From a3d0427e7578a84ae24b457d01c0a3b478f05d0a Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim <219906144+aibrahim-oai@users.noreply.github.com> Date: Fri, 20 Mar 2026 16:31:35 +0000 Subject: [PATCH] Extract sandbox runtime into codex-sandbox Move the cross-platform sandbox runtime out of codex-core into a new codex-sandbox crate and retarget direct consumers.\n\nCo-authored-by: Codex --- codex-rs/Cargo.lock | 43 +- codex-rs/Cargo.toml | 2 + codex-rs/app-server/Cargo.toml | 1 + .../app-server/src/bespoke_event_handling.rs | 2 +- .../app-server/src/codex_message_processor.rs | 57 +- codex-rs/app-server/src/command_exec.rs | 25 +- codex-rs/cli/Cargo.toml | 1 + codex-rs/cli/src/debug_sandbox.rs | 28 +- codex-rs/core/Cargo.toml | 1 + codex-rs/core/src/codex.rs | 7 +- codex-rs/core/src/codex_tests.rs | 31 +- codex-rs/core/src/config/mod.rs | 41 +- codex-rs/core/src/config/types.rs | 18 + codex-rs/core/src/error.rs | 41 + codex-rs/core/src/exec.rs | 1090 +---------------- codex-rs/core/src/landlock.rs | 173 +-- codex-rs/core/src/lib.rs | 15 +- codex-rs/core/src/sandboxing/mod.rs | 766 +----------- codex-rs/core/src/seatbelt.rs | 595 +-------- codex-rs/core/src/spawn.rs | 128 +- codex-rs/core/src/windows_sandbox.rs | 465 +------ .../core/src/windows_sandbox_read_grants.rs | 41 +- codex-rs/core/tests/common/lib.rs | 4 +- codex-rs/core/tests/suite/approvals.rs | 2 +- codex-rs/core/tests/suite/codex_delegate.rs | 2 +- .../core/tests/suite/compact_resume_fork.rs | 2 +- codex-rs/core/tests/suite/exec.rs | 20 +- .../core/tests/suite/request_permissions.rs | 2 +- codex-rs/core/tests/suite/seatbelt.rs | 6 +- .../core/tests/suite/text_encoding_fix.rs | 2 +- codex-rs/core/tests/suite/tools.rs | 2 +- codex-rs/exec/Cargo.toml | 1 + codex-rs/exec/tests/suite/sandbox.rs | 8 +- codex-rs/linux-sandbox/Cargo.toml | 2 +- codex-rs/linux-sandbox/src/bwrap.rs | 2 +- codex-rs/linux-sandbox/src/landlock.rs | 6 +- .../linux-sandbox/tests/suite/landlock.rs | 28 +- codex-rs/lmstudio/Cargo.toml | 1 + codex-rs/lmstudio/src/client.rs | 21 +- codex-rs/mcp-server/Cargo.toml | 1 + codex-rs/mcp-server/tests/suite/codex_tool.rs | 2 +- codex-rs/ollama/Cargo.toml | 1 + codex-rs/ollama/src/client.rs | 21 +- codex-rs/sandbox/BUILD.bazel | 16 + codex-rs/sandbox/Cargo.toml | 58 + codex-rs/sandbox/src/error.rs | 53 + codex-rs/sandbox/src/exec.rs | 1090 +++++++++++++++++ codex-rs/sandbox/src/exec_tests.rs | 697 +++++++++++ codex-rs/sandbox/src/landlock.rs | 170 +++ codex-rs/sandbox/src/landlock_tests.rs | 78 ++ codex-rs/sandbox/src/lib.rs | 90 ++ ...estricted_read_only_platform_defaults.sbpl | 199 +++ .../src/sandboxing/macos_permissions.rs | 154 +++ .../src/sandboxing/macos_permissions_tests.rs | 121 ++ codex-rs/sandbox/src/sandboxing/mod.rs | 754 ++++++++++++ codex-rs/sandbox/src/sandboxing/mod_tests.rs | 771 ++++++++++++ codex-rs/sandbox/src/seatbelt.rs | 594 +++++++++ .../sandbox/src/seatbelt_base_policy.sbpl | 108 ++ .../sandbox/src/seatbelt_network_policy.sbpl | 35 + codex-rs/sandbox/src/seatbelt_permissions.rs | 192 +++ .../sandbox/src/seatbelt_permissions_tests.rs | 154 +++ codex-rs/sandbox/src/seatbelt_tests.rs | 1064 ++++++++++++++++ codex-rs/sandbox/src/spawn.rs | 125 ++ codex-rs/sandbox/src/text_encoding.rs | 121 ++ codex-rs/sandbox/src/text_encoding_tests.rs | 340 +++++ codex-rs/sandbox/src/windows_sandbox.rs | 432 +++++++ .../src/windows_sandbox_read_grants.rs | 40 + .../src/windows_sandbox_read_grants_tests.rs | 57 + codex-rs/sandbox/src/windows_sandbox_tests.rs | 136 ++ codex-rs/tui/Cargo.toml | 1 + codex-rs/tui/src/app.rs | 52 +- codex-rs/tui/src/chatwidget.rs | 56 +- codex-rs/tui/src/lib.rs | 11 +- .../tui/src/onboarding/onboarding_screen.rs | 14 +- codex-rs/tui_app_server/Cargo.toml | 1 + codex-rs/tui_app_server/src/app.rs | 52 +- codex-rs/tui_app_server/src/chatwidget.rs | 52 +- codex-rs/tui_app_server/src/lib.rs | 11 +- .../src/onboarding/onboarding_screen.rs | 14 +- 79 files changed, 8205 insertions(+), 3415 deletions(-) create mode 100644 codex-rs/sandbox/BUILD.bazel create mode 100644 codex-rs/sandbox/Cargo.toml create mode 100644 codex-rs/sandbox/src/error.rs create mode 100644 codex-rs/sandbox/src/exec.rs create mode 100644 codex-rs/sandbox/src/exec_tests.rs create mode 100644 codex-rs/sandbox/src/landlock.rs create mode 100644 codex-rs/sandbox/src/landlock_tests.rs create mode 100644 codex-rs/sandbox/src/lib.rs create mode 100644 codex-rs/sandbox/src/restricted_read_only_platform_defaults.sbpl create mode 100644 codex-rs/sandbox/src/sandboxing/macos_permissions.rs create mode 100644 codex-rs/sandbox/src/sandboxing/macos_permissions_tests.rs create mode 100644 codex-rs/sandbox/src/sandboxing/mod.rs create mode 100644 codex-rs/sandbox/src/sandboxing/mod_tests.rs create mode 100644 codex-rs/sandbox/src/seatbelt.rs create mode 100644 codex-rs/sandbox/src/seatbelt_base_policy.sbpl create mode 100644 codex-rs/sandbox/src/seatbelt_network_policy.sbpl create mode 100644 codex-rs/sandbox/src/seatbelt_permissions.rs create mode 100644 codex-rs/sandbox/src/seatbelt_permissions_tests.rs create mode 100644 codex-rs/sandbox/src/seatbelt_tests.rs create mode 100644 codex-rs/sandbox/src/spawn.rs create mode 100644 codex-rs/sandbox/src/text_encoding.rs create mode 100644 codex-rs/sandbox/src/text_encoding_tests.rs create mode 100644 codex-rs/sandbox/src/windows_sandbox.rs create mode 100644 codex-rs/sandbox/src/windows_sandbox_read_grants.rs create mode 100644 codex-rs/sandbox/src/windows_sandbox_read_grants_tests.rs create mode 100644 codex-rs/sandbox/src/windows_sandbox_tests.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 13e6eaf597..4e55feafa2 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1436,6 +1436,7 @@ dependencies = [ "codex-otel", "codex-protocol", "codex-rmcp-client", + "codex-sandbox", "codex-shell-command", "codex-state", "codex-utils-absolute-path", @@ -1666,6 +1667,7 @@ dependencies = [ "codex-protocol", "codex-responses-api-proxy", "codex-rmcp-client", + "codex-sandbox", "codex-state", "codex-stdio-to-uds", "codex-terminal-detection", @@ -1858,6 +1860,7 @@ dependencies = [ "codex-otel", "codex-protocol", "codex-rmcp-client", + "codex-sandbox", "codex-secrets", "codex-shell-command", "codex-shell-escalation", @@ -1966,6 +1969,7 @@ dependencies = [ "codex-feedback", "codex-otel", "codex-protocol", + "codex-sandbox", "codex-utils-absolute-path", "codex-utils-cargo-bin", "codex-utils-cli", @@ -2155,8 +2159,8 @@ version = "0.0.0" dependencies = [ "cc", "clap", - "codex-core", "codex-protocol", + "codex-sandbox", "codex-utils-absolute-path", "landlock", "libc", @@ -2175,6 +2179,7 @@ name = "codex-lmstudio" version = "0.0.0" dependencies = [ "codex-core", + "codex-sandbox", "reqwest", "serde_json", "tokio", @@ -2230,6 +2235,7 @@ dependencies = [ "codex-core", "codex-features", "codex-protocol", + "codex-sandbox", "codex-shell-command", "codex-utils-cli", "codex-utils-json-to-toml", @@ -2288,6 +2294,7 @@ dependencies = [ "async-stream", "bytes", "codex-core", + "codex-sandbox", "futures", "pretty_assertions", "reqwest", @@ -2435,6 +2442,38 @@ dependencies = [ "which", ] +[[package]] +name = "codex-sandbox" +version = "0.0.0" +dependencies = [ + "anyhow", + "async-channel", + "chardetng", + "codex-features", + "codex-network-proxy", + "codex-otel", + "codex-protocol", + "codex-utils-absolute-path", + "codex-utils-home-dir", + "codex-utils-pty", + "codex-windows-sandbox", + "dirs", + "dunce", + "encoding_rs", + "landlock", + "libc", + "pretty_assertions", + "seccompiler", + "serde", + "serde_json", + "tempfile", + "thiserror 2.0.18", + "tokio", + "tokio-util", + "tracing", + "url", +] + [[package]] name = "codex-secrets" version = "0.0.0" @@ -2581,6 +2620,7 @@ dependencies = [ "codex-login", "codex-otel", "codex-protocol", + "codex-sandbox", "codex-shell-command", "codex-state", "codex-terminal-detection", @@ -2674,6 +2714,7 @@ dependencies = [ "codex-login", "codex-otel", "codex-protocol", + "codex-sandbox", "codex-shell-command", "codex-state", "codex-terminal-detection", diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 331174a802..8120a5616a 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -41,6 +41,7 @@ members = [ "protocol", "rmcp-client", "responses-api-proxy", + "sandbox", "stdio-to-uds", "otel", "tui", @@ -127,6 +128,7 @@ codex-process-hardening = { path = "process-hardening" } codex-protocol = { path = "protocol" } codex-responses-api-proxy = { path = "responses-api-proxy" } codex-rmcp-client = { path = "rmcp-client" } +codex-sandbox = { path = "sandbox" } codex-secrets = { path = "secrets" } codex-shell-command = { path = "shell-command" } codex-shell-escalation = { path = "shell-escalation" } diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index c6be85984d..e2cba94f83 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -46,6 +46,7 @@ codex-protocol = { workspace = true } codex-app-server-protocol = { workspace = true } codex-feedback = { workspace = true } codex-rmcp-client = { workspace = true } +codex-sandbox = { workspace = true } codex-state = { workspace = true } codex-utils-absolute-path = { workspace = true } codex-utils-json-to-toml = { workspace = true } diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index 6b69393474..3723b2fbed 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -109,7 +109,6 @@ use codex_core::ThreadManager; use codex_core::find_thread_name_by_id; use codex_core::review_format::format_review_findings_block; use codex_core::review_prompts; -use codex_core::sandboxing::intersect_permission_profiles; use codex_protocol::ThreadId; use codex_protocol::dynamic_tools::DynamicToolCallOutputContentItem as CoreDynamicToolCallOutputContentItem; use codex_protocol::dynamic_tools::DynamicToolResponse as CoreDynamicToolResponse; @@ -135,6 +134,7 @@ use codex_protocol::request_permissions::RequestPermissionProfile as CoreRequest use codex_protocol::request_permissions::RequestPermissionsResponse as CoreRequestPermissionsResponse; use codex_protocol::request_user_input::RequestUserInputAnswer as CoreRequestUserInputAnswer; use codex_protocol::request_user_input::RequestUserInputResponse as CoreRequestUserInputResponse; +use codex_sandbox::intersect_permission_profiles; use codex_shell_command::parse_command::shlex_join; use std::collections::HashMap; use std::convert::TryFrom; diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 06e2cd3ec3..93aa5bd7a1 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -200,12 +200,10 @@ use codex_core::config::types::McpServerTransportConfig; use codex_core::config_loader::CloudRequirementsLoadError; use codex_core::config_loader::CloudRequirementsLoadErrorCode; use codex_core::config_loader::CloudRequirementsLoader; +use codex_core::default_client::originator; use codex_core::default_client::set_default_client_residency_requirement; use codex_core::error::CodexErr; use codex_core::error::Result as CodexResult; -use codex_core::exec::ExecCapturePolicy; -use codex_core::exec::ExecExpiration; -use codex_core::exec::ExecParams; use codex_core::exec_env::create_env; use codex_core::find_archived_thread_path_by_id_str; use codex_core::find_thread_name_by_id; @@ -230,13 +228,9 @@ use codex_core::plugins::load_plugin_mcp_servers; use codex_core::read_head_for_summary; use codex_core::read_session_meta_line; use codex_core::rollout_date_parts; -use codex_core::sandboxing::SandboxPermissions; use codex_core::state_db::StateDbHandle; use codex_core::state_db::get_state_db; use codex_core::state_db::reconcile_rollout; -use codex_core::windows_sandbox::WindowsSandboxLevelExt; -use codex_core::windows_sandbox::WindowsSandboxSetupMode as CoreWindowsSandboxSetupMode; -use codex_core::windows_sandbox::WindowsSandboxSetupRequest; use codex_features::FEATURES; use codex_features::Feature; use codex_features::Stage; @@ -275,6 +269,16 @@ use codex_protocol::protocol::W3cTraceContext; use codex_protocol::user_input::MAX_USER_INPUT_TEXT_CHARS; use codex_protocol::user_input::UserInput as CoreInputItem; use codex_rmcp_client::perform_oauth_login_return_url; +use codex_sandbox::ExecCapturePolicy; +use codex_sandbox::ExecExpiration; +use codex_sandbox::ExecParams; +use codex_sandbox::SandboxPermissions; +use codex_sandbox::WindowsSandboxLevelExt; +use codex_sandbox::WindowsSandboxSetupMode as SandboxWindowsSandboxSetupMode; +use codex_sandbox::WindowsSandboxSetupRequest; +use codex_sandbox::build_exec_request; +use codex_sandbox::run_windows_sandbox_setup; +use codex_sandbox::windows_sandbox_mode_tag; use codex_state::StateRuntime; use codex_state::ThreadMetadata; use codex_state::ThreadMetadataBuilder; @@ -1661,7 +1665,10 @@ impl CodexMessageProcessor { }, None => None, }; - let windows_sandbox_level = WindowsSandboxLevel::from_config(&self.config); + let windows_sandbox_level = WindowsSandboxLevel::from_mode_and_features( + self.config.permissions.windows_sandbox_mode.map(Into::into), + &self.config.features, + ); let output_bytes_cap = if disable_output_cap { None } else { @@ -1745,7 +1752,7 @@ impl CodexMessageProcessor { None => None, }; - match codex_core::exec::build_exec_request( + match build_exec_request( exec_params, &effective_policy, &effective_file_system_sandbox_policy, @@ -3974,7 +3981,10 @@ impl CodexMessageProcessor { // Persist Windows sandbox mode. let mut cli_overrides = cli_overrides.unwrap_or_default(); if cfg!(windows) { - match WindowsSandboxLevel::from_config(&self.config) { + match WindowsSandboxLevel::from_mode_and_features( + self.config.permissions.windows_sandbox_mode.map(Into::into), + &self.config.features, + ) { WindowsSandboxLevel::Elevated => { cli_overrides .insert("windows.sandbox".to_string(), serde_json::json!("elevated")); @@ -7163,8 +7173,8 @@ impl CodexMessageProcessor { .await; let mode = match params.mode { - WindowsSandboxSetupMode::Elevated => CoreWindowsSandboxSetupMode::Elevated, - WindowsSandboxSetupMode::Unelevated => CoreWindowsSandboxSetupMode::Unelevated, + WindowsSandboxSetupMode::Elevated => SandboxWindowsSandboxSetupMode::Elevated, + WindowsSandboxSetupMode::Unelevated => SandboxWindowsSandboxSetupMode::Unelevated, }; let config = Arc::clone(&self.config); let cli_overrides = self.cli_overrides.clone(); @@ -7191,23 +7201,36 @@ impl CodexMessageProcessor { .await; let setup_result = match derived_config { Ok(config) => { + let active_profile = config.active_profile.clone(); + let codex_home = config.codex_home.clone(); let setup_request = WindowsSandboxSetupRequest { mode, policy: config.permissions.sandbox_policy.get().clone(), policy_cwd: config.cwd.clone(), command_cwd, env_map: std::env::vars().collect(), - codex_home: config.codex_home.clone(), - active_profile: config.active_profile.clone(), + codex_home: codex_home.clone(), + originator_tag: Some(originator().value), }; - codex_core::windows_sandbox::run_windows_sandbox_setup(setup_request).await + run_windows_sandbox_setup(setup_request).await?; + ConfigEditsBuilder::new(codex_home.as_path()) + .with_profile(active_profile.as_deref()) + .set_windows_sandbox_mode(windows_sandbox_mode_tag(mode)) + .clear_legacy_windows_sandbox_keys() + .apply() + .await + .map_err(|err| { + anyhow::anyhow!("failed to persist windows sandbox mode: {err}") + }) } Err(err) => Err(err.into()), }; let notification = WindowsSandboxSetupCompletedNotification { mode: match mode { - CoreWindowsSandboxSetupMode::Elevated => WindowsSandboxSetupMode::Elevated, - CoreWindowsSandboxSetupMode::Unelevated => WindowsSandboxSetupMode::Unelevated, + SandboxWindowsSandboxSetupMode::Elevated => WindowsSandboxSetupMode::Elevated, + SandboxWindowsSandboxSetupMode::Unelevated => { + WindowsSandboxSetupMode::Unelevated + } }, success: setup_result.is_ok(), error: setup_result.err().map(|err| err.to_string()), diff --git a/codex-rs/app-server/src/command_exec.rs b/codex-rs/app-server/src/command_exec.rs index e1a9cb3def..dc144c71bb 100644 --- a/codex-rs/app-server/src/command_exec.rs +++ b/codex-rs/app-server/src/command_exec.rs @@ -20,11 +20,14 @@ use codex_app_server_protocol::JSONRPCErrorError; use codex_app_server_protocol::ServerNotification; use codex_core::bytes_to_string_smart; use codex_core::config::StartedNetworkProxy; -use codex_core::exec::DEFAULT_EXEC_COMMAND_TIMEOUT_MS; -use codex_core::exec::ExecExpiration; -use codex_core::exec::IO_DRAIN_TIMEOUT_MS; -use codex_core::exec::SandboxType; -use codex_core::sandboxing::ExecRequest; +use codex_sandbox::DEFAULT_EXEC_COMMAND_TIMEOUT_MS; +use codex_sandbox::ExecCapturePolicy; +use codex_sandbox::ExecExpiration; +use codex_sandbox::ExecRequest; +use codex_sandbox::IO_DRAIN_TIMEOUT_MS; +use codex_sandbox::SandboxPermissions; +use codex_sandbox::SandboxType; +use codex_sandbox::execute_env; use codex_utils_pty::DEFAULT_OUTPUT_BYTES_CAP; use codex_utils_pty::ProcessHandle; use codex_utils_pty::SpawnedProcess; @@ -201,9 +204,7 @@ impl CommandExecManager { let sessions = Arc::clone(&self.sessions); tokio::spawn(async move { let _started_network_proxy = started_network_proxy; - match codex_core::sandboxing::execute_env(exec_request, /*stdout_stream*/ None) - .await - { + match execute_env(exec_request, /*stdout_stream*/ None).await { Ok(output) => { outgoing .send_response( @@ -733,11 +734,11 @@ mod tests { env: HashMap::new(), network: None, expiration: ExecExpiration::DefaultTimeout, - capture_policy: codex_core::exec::ExecCapturePolicy::ShellTool, + capture_policy: ExecCapturePolicy::ShellTool, sandbox: SandboxType::WindowsRestrictedToken, windows_sandbox_level: WindowsSandboxLevel::Disabled, windows_sandbox_private_desktop: false, - sandbox_permissions: codex_core::sandboxing::SandboxPermissions::UseDefault, + sandbox_permissions: SandboxPermissions::UseDefault, sandbox_policy: sandbox_policy.clone(), file_system_sandbox_policy: FileSystemSandboxPolicy::from(&sandbox_policy), network_sandbox_policy: NetworkSandboxPolicy::from(&sandbox_policy), @@ -846,11 +847,11 @@ mod tests { env: HashMap::new(), network: None, expiration: ExecExpiration::Cancellation(CancellationToken::new()), - capture_policy: codex_core::exec::ExecCapturePolicy::ShellTool, + capture_policy: ExecCapturePolicy::ShellTool, sandbox: SandboxType::None, windows_sandbox_level: WindowsSandboxLevel::Disabled, windows_sandbox_private_desktop: false, - sandbox_permissions: codex_core::sandboxing::SandboxPermissions::UseDefault, + sandbox_permissions: SandboxPermissions::UseDefault, sandbox_policy: sandbox_policy.clone(), file_system_sandbox_policy: FileSystemSandboxPolicy::from(&sandbox_policy), network_sandbox_policy: NetworkSandboxPolicy::from(&sandbox_policy), diff --git a/codex-rs/cli/Cargo.toml b/codex-rs/cli/Cargo.toml index c2fd1300c6..2eb536c84a 100644 --- a/codex-rs/cli/Cargo.toml +++ b/codex-rs/cli/Cargo.toml @@ -36,6 +36,7 @@ codex-mcp-server = { workspace = true } codex-protocol = { workspace = true } codex-responses-api-proxy = { workspace = true } codex-rmcp-client = { workspace = true } +codex-sandbox = { workspace = true } codex-state = { workspace = true } codex-stdio-to-uds = { workspace = true } codex-terminal-detection = { workspace = true } diff --git a/codex-rs/cli/src/debug_sandbox.rs b/codex-rs/cli/src/debug_sandbox.rs index c65b6dcad5..337dcb9b90 100644 --- a/codex-rs/cli/src/debug_sandbox.rs +++ b/codex-rs/cli/src/debug_sandbox.rs @@ -11,14 +11,18 @@ use codex_core::config::ConfigBuilder; use codex_core::config::ConfigOverrides; use codex_core::config::NetworkProxyAuditMetadata; use codex_core::exec_env::create_env; -use codex_core::landlock::create_linux_sandbox_command_args_for_policies; #[cfg(target_os = "macos")] -use codex_core::seatbelt::create_seatbelt_command_args_for_policies_with_extensions; -#[cfg(target_os = "macos")] -use codex_core::spawn::CODEX_SANDBOX_ENV_VAR; -use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; use codex_protocol::config_types::SandboxMode; +use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::permissions::NetworkSandboxPolicy; +#[cfg(target_os = "macos")] +use codex_sandbox::CODEX_SANDBOX_ENV_VAR; +use codex_sandbox::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; +use codex_sandbox::SandboxType; +use codex_sandbox::WindowsSandboxLevelExt; +use codex_sandbox::create_linux_sandbox_command_args_for_policies; +#[cfg(target_os = "macos")] +use codex_sandbox::create_seatbelt_command_args_for_policies_with_extensions; use codex_utils_cli::CliConfigOverrides; use tokio::process::Child; use tokio::process::Command as TokioCommand; @@ -102,13 +106,6 @@ pub async fn run_command_under_windows( .await } -enum SandboxType { - #[cfg(target_os = "macos")] - Seatbelt, - Landlock, - Windows, -} - async fn run_command_under_sandbox( full_auto: bool, command: Vec, @@ -143,8 +140,6 @@ async fn run_command_under_sandbox( if let SandboxType::Windows = sandbox_type { #[cfg(target_os = "windows")] { - use codex_core::windows_sandbox::WindowsSandboxLevelExt; - use codex_protocol::config_types::WindowsSandboxLevel; use codex_windows_sandbox::run_windows_sandbox_capture; use codex_windows_sandbox::run_windows_sandbox_capture_elevated; @@ -156,7 +151,10 @@ async fn run_command_under_sandbox( let command_vec = command.clone(); let base_dir = config.codex_home.clone(); let use_elevated = matches!( - WindowsSandboxLevel::from_config(&config), + WindowsSandboxLevel::from_mode_and_features( + config.permissions.windows_sandbox_mode.map(Into::into), + &config.features, + ), WindowsSandboxLevel::Elevated ); diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index d648655b24..262edcb3d5 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -47,6 +47,7 @@ codex-otel = { workspace = true } codex-artifacts = { workspace = true } codex-protocol = { workspace = true } codex-rmcp-client = { workspace = true } +codex-sandbox = { workspace = true } codex-state = { workspace = true } codex-terminal-detection = { workspace = true } codex-utils-absolute-path = { workspace = true } diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 12270bb6dd..08b79efe85 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -316,7 +316,6 @@ use crate::turn_timing::record_turn_ttfm_metric; use crate::turn_timing::record_turn_ttft_metric; use crate::unified_exec::UnifiedExecProcessManager; use crate::util::backoff; -use crate::windows_sandbox::WindowsSandboxLevelExt; use codex_async_utils::OrCancelExt; use codex_otel::SessionTelemetry; use codex_otel::TelemetryAuthMode; @@ -334,6 +333,7 @@ use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig; use codex_protocol::protocol::CodexErrorInfo; use codex_protocol::protocol::InitialHistory; use codex_protocol::user_input::UserInput; +use codex_sandbox::WindowsSandboxLevelExt; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_readiness::Readiness; use codex_utils_readiness::ReadinessFlag; @@ -580,7 +580,10 @@ impl Codex { sandbox_policy: config.permissions.sandbox_policy.clone(), file_system_sandbox_policy: config.permissions.file_system_sandbox_policy.clone(), network_sandbox_policy: config.permissions.network_sandbox_policy, - windows_sandbox_level: WindowsSandboxLevel::from_config(&config), + windows_sandbox_level: WindowsSandboxLevel::from_mode_and_features( + config.permissions.windows_sandbox_mode.map(Into::into), + &config.features, + ), cwd: config.cwd.clone(), codex_home: config.codex_home.clone(), thread_name: None, diff --git a/codex-rs/core/src/codex_tests.rs b/codex-rs/core/src/codex_tests.rs index a5412eff29..e332bc6808 100644 --- a/codex-rs/core/src/codex_tests.rs +++ b/codex-rs/core/src/codex_tests.rs @@ -74,6 +74,7 @@ use codex_protocol::protocol::ConversationAudioParams; use codex_protocol::protocol::RealtimeAudioFrame; use codex_protocol::protocol::Submission; use codex_protocol::protocol::W3cTraceContext; +use codex_sandbox::WindowsSandboxLevelExt; use core_test_support::tracing::install_test_tracing; use opentelemetry::trace::TraceContextExt; use opentelemetry::trace::TraceId; @@ -1650,7 +1651,10 @@ async fn set_rate_limits_retains_previous_credits() { sandbox_policy: config.permissions.sandbox_policy.clone(), file_system_sandbox_policy: config.permissions.file_system_sandbox_policy.clone(), network_sandbox_policy: config.permissions.network_sandbox_policy, - windows_sandbox_level: WindowsSandboxLevel::from_config(&config), + windows_sandbox_level: WindowsSandboxLevel::from_mode_and_features( + config.permissions.windows_sandbox_mode.map(Into::into), + &config.features, + ), cwd: config.cwd.clone(), codex_home: config.codex_home.clone(), thread_name: None, @@ -1748,7 +1752,10 @@ async fn set_rate_limits_updates_plan_type_when_present() { sandbox_policy: config.permissions.sandbox_policy.clone(), file_system_sandbox_policy: config.permissions.file_system_sandbox_policy.clone(), network_sandbox_policy: config.permissions.network_sandbox_policy, - windows_sandbox_level: WindowsSandboxLevel::from_config(&config), + windows_sandbox_level: WindowsSandboxLevel::from_mode_and_features( + config.permissions.windows_sandbox_mode.map(Into::into), + &config.features, + ), cwd: config.cwd.clone(), codex_home: config.codex_home.clone(), thread_name: None, @@ -2092,7 +2099,10 @@ pub(crate) async fn make_session_configuration_for_tests() -> SessionConfigurati sandbox_policy: config.permissions.sandbox_policy.clone(), file_system_sandbox_policy: config.permissions.file_system_sandbox_policy.clone(), network_sandbox_policy: config.permissions.network_sandbox_policy, - windows_sandbox_level: WindowsSandboxLevel::from_config(&config), + windows_sandbox_level: WindowsSandboxLevel::from_mode_and_features( + config.permissions.windows_sandbox_mode.map(Into::into), + &config.features, + ), cwd: config.cwd.clone(), codex_home: config.codex_home.clone(), thread_name: None, @@ -2323,7 +2333,10 @@ async fn session_new_fails_when_zsh_fork_enabled_without_zsh_path() { sandbox_policy: config.permissions.sandbox_policy.clone(), file_system_sandbox_policy: config.permissions.file_system_sandbox_policy.clone(), network_sandbox_policy: config.permissions.network_sandbox_policy, - windows_sandbox_level: WindowsSandboxLevel::from_config(&config), + windows_sandbox_level: WindowsSandboxLevel::from_mode_and_features( + config.permissions.windows_sandbox_mode.map(Into::into), + &config.features, + ), cwd: config.cwd.clone(), codex_home: config.codex_home.clone(), thread_name: None, @@ -2418,7 +2431,10 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { sandbox_policy: config.permissions.sandbox_policy.clone(), file_system_sandbox_policy: config.permissions.file_system_sandbox_policy.clone(), network_sandbox_policy: config.permissions.network_sandbox_policy, - windows_sandbox_level: WindowsSandboxLevel::from_config(&config), + windows_sandbox_level: WindowsSandboxLevel::from_mode_and_features( + config.permissions.windows_sandbox_mode.map(Into::into), + &config.features, + ), cwd: config.cwd.clone(), codex_home: config.codex_home.clone(), thread_name: None, @@ -3217,7 +3233,10 @@ pub(crate) async fn make_session_and_context_with_dynamic_tools_and_rx( sandbox_policy: config.permissions.sandbox_policy.clone(), file_system_sandbox_policy: config.permissions.file_system_sandbox_policy.clone(), network_sandbox_policy: config.permissions.network_sandbox_policy, - windows_sandbox_level: WindowsSandboxLevel::from_config(&config), + windows_sandbox_level: WindowsSandboxLevel::from_mode_and_features( + config.permissions.windows_sandbox_mode.map(Into::into), + &config.features, + ), cwd: config.cwd.clone(), codex_home: config.codex_home.clone(), thread_name: None, diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 48bde3f177..1331ed13b1 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -56,9 +56,6 @@ use crate::protocol::ReadOnlyAccess; use crate::protocol::SandboxPolicy; use crate::unified_exec::DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS; use crate::unified_exec::MIN_EMPTY_YIELD_TIME_MS; -use crate::windows_sandbox::WindowsSandboxLevelExt; -use crate::windows_sandbox::resolve_windows_sandbox_mode; -use crate::windows_sandbox::resolve_windows_sandbox_private_desktop; use codex_app_server_protocol::Tools; use codex_app_server_protocol::UserSavedConfig; use codex_features::Feature; @@ -101,6 +98,9 @@ use crate::config::permissions::compile_permission_profile; use crate::config::permissions::network_proxy_config_from_profile_network; use crate::config::profile::ConfigProfile; use codex_network_proxy::NetworkProxyConfig; +use codex_sandbox::WindowsSandboxLevelExt; +use codex_sandbox::resolve_windows_sandbox_mode; +use codex_sandbox::resolve_windows_sandbox_private_desktop; use toml::Value as TomlValue; use toml_edit::DocumentMut; use toml_edit::value; @@ -2208,9 +2208,29 @@ impl Config { feature_overrides, ); let features = ManagedFeatures::from_configured(configured_features, feature_requirements)?; - let windows_sandbox_mode = resolve_windows_sandbox_mode(&cfg, &config_profile); - let windows_sandbox_private_desktop = - resolve_windows_sandbox_private_desktop(&cfg, &config_profile); + let windows_sandbox_mode = resolve_windows_sandbox_mode( + config_profile + .windows + .as_ref() + .and_then(|windows| windows.sandbox) + .map(Into::into), + config_profile.features.as_ref(), + cfg.windows + .as_ref() + .and_then(|windows| windows.sandbox) + .map(Into::into), + cfg.features.as_ref(), + ) + .map(Into::into); + let windows_sandbox_private_desktop = resolve_windows_sandbox_private_desktop( + config_profile + .windows + .as_ref() + .and_then(|windows| windows.sandbox_private_desktop), + cfg.windows + .as_ref() + .and_then(|windows| windows.sandbox_private_desktop), + ); let resolved_cwd = normalize_for_native_workdir({ use std::env; @@ -2259,11 +2279,10 @@ impl Config { )); } - let windows_sandbox_level = match windows_sandbox_mode { - Some(WindowsSandboxModeToml::Elevated) => WindowsSandboxLevel::Elevated, - Some(WindowsSandboxModeToml::Unelevated) => WindowsSandboxLevel::RestrictedToken, - None => WindowsSandboxLevel::from_features(&features), - }; + let windows_sandbox_level = WindowsSandboxLevel::from_mode_and_features( + windows_sandbox_mode.map(Into::into), + &features, + ); let memories_root = memory_root(&codex_home); std::fs::create_dir_all(&memories_root)?; let memories_root = AbsolutePathBuf::from_absolute_path(&memories_root)?; diff --git a/codex-rs/core/src/config/types.rs b/codex-rs/core/src/config/types.rs index 3b20779cd5..cf25cb07ba 100644 --- a/codex-rs/core/src/config/types.rs +++ b/codex-rs/core/src/config/types.rs @@ -38,6 +38,24 @@ pub enum WindowsSandboxModeToml { Unelevated, } +impl From for codex_sandbox::WindowsSandboxMode { + fn from(value: WindowsSandboxModeToml) -> Self { + match value { + WindowsSandboxModeToml::Elevated => codex_sandbox::WindowsSandboxMode::Elevated, + WindowsSandboxModeToml::Unelevated => codex_sandbox::WindowsSandboxMode::Unelevated, + } + } +} + +impl From for WindowsSandboxModeToml { + fn from(value: codex_sandbox::WindowsSandboxMode) -> Self { + match value { + codex_sandbox::WindowsSandboxMode::Elevated => WindowsSandboxModeToml::Elevated, + codex_sandbox::WindowsSandboxMode::Unelevated => WindowsSandboxModeToml::Unelevated, + } + } +} + #[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)] #[schemars(deny_unknown_fields)] pub struct WindowsToml { diff --git a/codex-rs/core/src/error.rs b/codex-rs/core/src/error.rs index 80d60619dd..08b2e49c31 100644 --- a/codex-rs/core/src/error.rs +++ b/codex-rs/core/src/error.rs @@ -193,6 +193,47 @@ impl From for CodexErr { } } +impl From for SandboxErr { + fn from(err: codex_sandbox::error::SandboxErr) -> Self { + match err { + codex_sandbox::error::SandboxErr::Denied { output } => SandboxErr::Denied { + output, + network_policy_decision: None, + }, + #[cfg(target_os = "linux")] + codex_sandbox::error::SandboxErr::SeccompInstall(err) => { + SandboxErr::SeccompInstall(err) + } + #[cfg(target_os = "linux")] + codex_sandbox::error::SandboxErr::SeccompBackend(err) => { + SandboxErr::SeccompBackend(err) + } + codex_sandbox::error::SandboxErr::Timeout { output } => SandboxErr::Timeout { output }, + codex_sandbox::error::SandboxErr::Signal(signal) => SandboxErr::Signal(signal), + codex_sandbox::error::SandboxErr::LandlockRestrict => SandboxErr::LandlockRestrict, + } + } +} + +impl From for CodexErr { + fn from(err: codex_sandbox::error::CodexErr) -> Self { + match err { + codex_sandbox::error::CodexErr::Sandbox(err) => CodexErr::Sandbox(err.into()), + codex_sandbox::error::CodexErr::LandlockSandboxExecutableNotProvided => { + CodexErr::LandlockSandboxExecutableNotProvided + } + codex_sandbox::error::CodexErr::UnsupportedOperation(message) => { + CodexErr::UnsupportedOperation(message) + } + codex_sandbox::error::CodexErr::Io(err) => CodexErr::Io(err), + #[cfg(target_os = "linux")] + codex_sandbox::error::CodexErr::LandlockRuleset(err) => CodexErr::LandlockRuleset(err), + #[cfg(target_os = "linux")] + codex_sandbox::error::CodexErr::LandlockPathFd(err) => CodexErr::LandlockPathFd(err), + } + } +} + impl CodexErr { pub fn is_retryable(&self) -> bool { match self { diff --git a/codex-rs/core/src/exec.rs b/codex-rs/core/src/exec.rs index 9be0518fa0..36edda4962 100644 --- a/codex-rs/core/src/exec.rs +++ b/codex-rs/core/src/exec.rs @@ -1,216 +1,22 @@ -#[cfg(unix)] -use std::os::unix::process::ExitStatusExt; - -use std::collections::HashMap; -use std::io; -use std::path::Path; -use std::path::PathBuf; -use std::process::ExitStatus; -use std::time::Duration; -use std::time::Instant; - -use async_channel::Sender; -use tokio::io::AsyncRead; -use tokio::io::AsyncReadExt; -use tokio::io::BufReader; -use tokio::process::Child; -use tokio_util::sync::CancellationToken; - -use crate::error::CodexErr; use crate::error::Result; -use crate::error::SandboxErr; -use crate::protocol::Event; -use crate::protocol::EventMsg; -use crate::protocol::ExecCommandOutputDeltaEvent; -use crate::protocol::ExecOutputStream; use crate::protocol::SandboxPolicy; -use crate::sandboxing::CommandSpec; -use crate::sandboxing::ExecRequest; -use crate::sandboxing::SandboxManager; -use crate::sandboxing::SandboxPermissions; -use crate::spawn::SpawnChildRequest; -use crate::spawn::StdioPolicy; -use crate::spawn::spawn_child_async; -use crate::text_encoding::bytes_to_string_smart; -use crate::tools::sandboxing::SandboxablePreference; -use codex_network_proxy::NetworkProxy; -#[cfg(any(target_os = "windows", test))] -use codex_protocol::permissions::FileSystemSandboxKind; use codex_protocol::permissions::FileSystemSandboxPolicy; use codex_protocol::permissions::NetworkSandboxPolicy; -use codex_utils_pty::DEFAULT_OUTPUT_BYTES_CAP; -use codex_utils_pty::process_group::kill_child_process_group; +use std::path::Path; +use std::path::PathBuf; -pub const DEFAULT_EXEC_COMMAND_TIMEOUT_MS: u64 = 10_000; +pub(crate) use codex_sandbox::DEFAULT_EXEC_COMMAND_TIMEOUT_MS; +pub(crate) use codex_sandbox::ExecCapturePolicy; +pub(crate) use codex_sandbox::ExecExpiration; +pub(crate) use codex_sandbox::ExecParams; +pub(crate) use codex_sandbox::ExecToolCallOutput; +pub(crate) use codex_sandbox::IO_DRAIN_TIMEOUT_MS; +pub(crate) use codex_sandbox::MAX_EXEC_OUTPUT_DELTAS_PER_CALL; +pub(crate) use codex_sandbox::SandboxType; +pub(crate) use codex_sandbox::StdoutStream; +pub(crate) use codex_sandbox::StreamOutput; +pub(crate) use codex_sandbox::is_likely_sandbox_denied; -// Hardcode these since it does not seem worth including the libc crate just -// for these. -const SIGKILL_CODE: i32 = 9; -const TIMEOUT_CODE: i32 = 64; -const EXIT_CODE_SIGNAL_BASE: i32 = 128; // conventional shell: 128 + signal -const EXEC_TIMEOUT_EXIT_CODE: i32 = 124; // conventional timeout exit code - -// I/O buffer sizing -const READ_CHUNK_SIZE: usize = 8192; // bytes per read -const AGGREGATE_BUFFER_INITIAL_CAPACITY: usize = 8 * 1024; // 8 KiB - -/// Hard cap on bytes retained from exec stdout/stderr/aggregated output. -/// -/// This mirrors unified exec's output cap so a single runaway command cannot -/// OOM the process by dumping huge amounts of data to stdout/stderr. -const EXEC_OUTPUT_MAX_BYTES: usize = DEFAULT_OUTPUT_BYTES_CAP; - -/// Limit the number of ExecCommandOutputDelta events emitted per exec call. -/// Aggregation still collects full output; only the live event stream is capped. -pub(crate) const MAX_EXEC_OUTPUT_DELTAS_PER_CALL: usize = 10_000; - -// Wait for the stdout/stderr collection tasks but guard against them -// hanging forever. In the normal case, both pipes are closed once the child -// terminates so the tasks exit quickly. However, if the child process -// spawned grandchildren that inherited its stdout/stderr file descriptors -// those pipes may stay open after we `kill` the direct child on timeout. -// That would cause the `read_capped` tasks to block on `read()` -// indefinitely, effectively hanging the whole agent. -pub const IO_DRAIN_TIMEOUT_MS: u64 = 2_000; // 2 s should be plenty for local pipes - -#[derive(Debug)] -pub struct ExecParams { - pub command: Vec, - pub cwd: PathBuf, - pub expiration: ExecExpiration, - pub capture_policy: ExecCapturePolicy, - pub env: HashMap, - pub network: Option, - pub sandbox_permissions: SandboxPermissions, - pub windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel, - pub windows_sandbox_private_desktop: bool, - pub justification: Option, - pub arg0: Option, -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum ExecCapturePolicy { - /// Shell-like execs keep the historical output cap and timeout behavior. - #[default] - ShellTool, - /// Trusted internal helpers can buffer the full child output in memory - /// without the shell-oriented output cap or exec-expiration behavior. - 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 { - Timeout(Duration), - DefaultTimeout, - Cancellation(CancellationToken), -} - -impl From> for ExecExpiration { - fn from(timeout_ms: Option) -> Self { - timeout_ms.map_or(ExecExpiration::DefaultTimeout, |timeout_ms| { - ExecExpiration::Timeout(Duration::from_millis(timeout_ms)) - }) - } -} - -impl From for ExecExpiration { - fn from(timeout_ms: u64) -> Self { - ExecExpiration::Timeout(Duration::from_millis(timeout_ms)) - } -} - -impl ExecExpiration { - pub(crate) async fn wait(self) { - match self { - ExecExpiration::Timeout(duration) => tokio::time::sleep(duration).await, - ExecExpiration::DefaultTimeout => { - tokio::time::sleep(Duration::from_millis(DEFAULT_EXEC_COMMAND_TIMEOUT_MS)).await - } - ExecExpiration::Cancellation(cancel) => { - cancel.cancelled().await; - } - } - } - - /// If ExecExpiration is a timeout, returns the timeout in milliseconds. - pub(crate) fn timeout_ms(&self) -> Option { - match self { - ExecExpiration::Timeout(duration) => Some(duration.as_millis() as u64), - ExecExpiration::DefaultTimeout => Some(DEFAULT_EXEC_COMMAND_TIMEOUT_MS), - ExecExpiration::Cancellation(_) => None, - } - } -} - -impl ExecCapturePolicy { - fn retained_bytes_cap(self) -> Option { - match self { - Self::ShellTool => Some(EXEC_OUTPUT_MAX_BYTES), - Self::FullBuffer => None, - } - } - - fn io_drain_timeout(self) -> Duration { - Duration::from_millis(IO_DRAIN_TIMEOUT_MS) - } - - fn uses_expiration(self) -> bool { - match self { - Self::ShellTool => true, - Self::FullBuffer => false, - } - } -} - -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum SandboxType { - None, - - /// Only available on macOS. - MacosSeatbelt, - - /// Only available on Linux. - LinuxSeccomp, - - /// Only available on Windows. - WindowsRestrictedToken, -} - -impl SandboxType { - pub(crate) fn as_metric_tag(self) -> &'static str { - match self { - SandboxType::None => "none", - SandboxType::MacosSeatbelt => "seatbelt", - SandboxType::LinuxSeccomp => "seccomp", - SandboxType::WindowsRestrictedToken => "windows_sandbox", - } - } -} - -#[derive(Clone)] -pub struct StdoutStream { - pub sub_id: String, - pub call_id: String, - pub tx_event: Sender, -} - -#[allow(clippy::too_many_arguments)] pub async fn process_exec_tool_call( params: ExecParams, sandbox_policy: &SandboxPolicy, @@ -221,7 +27,7 @@ pub async fn process_exec_tool_call( use_legacy_landlock: bool, stdout_stream: Option, ) -> Result { - let exec_req = build_exec_request( + codex_sandbox::process_exec_tool_call( params, sandbox_policy, file_system_sandbox_policy, @@ -229,14 +35,12 @@ pub async fn process_exec_tool_call( sandbox_cwd, codex_linux_sandbox_exe, use_legacy_landlock, - )?; - - // Route through the sandboxing module for a single, unified execution path. - crate::sandboxing::execute_env(exec_req, stdout_stream).await + stdout_stream, + ) + .await + .map_err(Into::into) } -/// Transform a portable exec request into the concrete argv/env that should be -/// spawned under the requested sandbox policy. pub fn build_exec_request( params: ExecParams, sandbox_policy: &SandboxPolicy, @@ -245,858 +49,26 @@ pub fn build_exec_request( sandbox_cwd: &Path, 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( +) -> Result { + codex_sandbox::build_exec_request( + params, + sandbox_policy, file_system_sandbox_policy, network_sandbox_policy, - windows_sandbox_level, - enforce_managed_network, - ); - tracing::debug!("Sandbox type: {sandbox_type:?}"); - - let ExecParams { - command, - cwd, - mut env, - expiration, - capture_policy, - network, - sandbox_permissions, - windows_sandbox_level, - windows_sandbox_private_desktop, - justification, - arg0: _, - } = params; - if let Some(network) = network.as_ref() { - network.apply_to_env(&mut env); - } - let (program, args) = command.split_first().ok_or_else(|| { - CodexErr::Io(io::Error::new( - io::ErrorKind::InvalidInput, - "command args are empty", - )) - })?; - - let spec = CommandSpec { - program: program.clone(), - args: args.to_vec(), - cwd, - env, - expiration, - capture_policy, - sandbox_permissions, - additional_permissions: None, - justification, - }; - - let manager = SandboxManager::new(); - let exec_req = manager - .transform(crate::sandboxing::SandboxTransformRequest { - spec, - policy: sandbox_policy, - file_system_policy: file_system_sandbox_policy, - network_policy: network_sandbox_policy, - sandbox: sandbox_type, - enforce_managed_network, - network: network.as_ref(), - sandbox_policy_cwd: sandbox_cwd, - #[cfg(target_os = "macos")] - macos_seatbelt_profile_extensions: None, - codex_linux_sandbox_exe: codex_linux_sandbox_exe.as_ref(), - use_legacy_landlock, - windows_sandbox_level, - windows_sandbox_private_desktop, - }) - .map_err(CodexErr::from)?; - Ok(exec_req) + sandbox_cwd, + codex_linux_sandbox_exe, + use_legacy_landlock, + ) + .map_err(Into::into) } pub(crate) async fn execute_exec_request( - exec_request: ExecRequest, + exec_request: crate::sandboxing::ExecRequest, sandbox_policy: &SandboxPolicy, stdout_stream: Option, after_spawn: Option>, ) -> Result { - let ExecRequest { - command, - cwd, - env, - network, - expiration, - capture_policy, - sandbox, - windows_sandbox_level, - windows_sandbox_private_desktop, - sandbox_permissions, - sandbox_policy: _sandbox_policy_from_env, - file_system_sandbox_policy, - network_sandbox_policy, - justification, - arg0, - } = exec_request; - let _ = _sandbox_policy_from_env; - - let params = ExecParams { - command, - cwd, - expiration, - capture_policy, - env, - network: network.clone(), - sandbox_permissions, - windows_sandbox_level, - windows_sandbox_private_desktop, - justification, - arg0, - }; - - let start = Instant::now(); - let raw_output_result = exec( - params, - sandbox, - sandbox_policy, - &file_system_sandbox_policy, - network_sandbox_policy, - stdout_stream, - after_spawn, - ) - .await; - let duration = start.elapsed(); - finalize_exec_result(raw_output_result, sandbox, duration) + codex_sandbox::execute_exec_request(exec_request, sandbox_policy, stdout_stream, after_spawn) + .await + .map_err(Into::into) } - -#[cfg(target_os = "windows")] -fn extract_create_process_as_user_error_code(err: &str) -> Option { - let marker = "CreateProcessAsUserW failed: "; - let start = err.find(marker)? + marker.len(); - let tail = &err[start..]; - let digits: String = tail.chars().take_while(char::is_ascii_digit).collect(); - if digits.is_empty() { - None - } else { - Some(digits) - } -} - -#[cfg(target_os = "windows")] -fn windowsapps_path_kind(path: &str) -> &'static str { - let lower = path.to_ascii_lowercase(); - if lower.contains("\\program files\\windowsapps\\") { - return "windowsapps_package"; - } - if lower.contains("\\appdata\\local\\microsoft\\windowsapps\\") { - return "windowsapps_alias"; - } - if lower.contains("\\windowsapps\\") { - return "windowsapps_other"; - } - "other" -} - -#[cfg(target_os = "windows")] -fn record_windows_sandbox_spawn_failure( - command_path: Option<&str>, - windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel, - err: &str, -) { - let Some(error_code) = extract_create_process_as_user_error_code(err) else { - return; - }; - let path = command_path.unwrap_or("unknown"); - let exe = Path::new(path) - .file_name() - .and_then(|name| name.to_str()) - .unwrap_or("unknown") - .to_ascii_lowercase(); - let path_kind = windowsapps_path_kind(path); - let level = if matches!( - windows_sandbox_level, - codex_protocol::config_types::WindowsSandboxLevel::Elevated - ) { - "elevated" - } else { - "legacy" - }; - if let Some(metrics) = codex_otel::metrics::global() { - let _ = metrics.counter( - "codex.windows_sandbox.createprocessasuserw_failed", - /*inc*/ 1, - &[ - ("error_code", error_code.as_str()), - ("path_kind", path_kind), - ("exe", exe.as_str()), - ("level", level), - ], - ); - } -} - -#[cfg(target_os = "windows")] -async fn exec_windows_sandbox( - params: ExecParams, - sandbox_policy: &SandboxPolicy, -) -> Result { - use crate::config::find_codex_home; - use codex_protocol::config_types::WindowsSandboxLevel; - use codex_windows_sandbox::run_windows_sandbox_capture; - use codex_windows_sandbox::run_windows_sandbox_capture_elevated; - - let ExecParams { - command, - cwd, - mut env, - network, - expiration, - capture_policy, - windows_sandbox_level, - windows_sandbox_private_desktop, - .. - } = params; - if let Some(network) = network.as_ref() { - network.apply_to_env(&mut env); - } - - // TODO(iceweasel-oai): run_windows_sandbox_capture should support all - // variants of ExecExpiration, not just timeout. - let timeout_ms = if capture_policy.uses_expiration() { - expiration.timeout_ms() - } else { - None - }; - - let policy_str = serde_json::to_string(sandbox_policy).map_err(|err| { - CodexErr::Io(io::Error::other(format!( - "failed to serialize Windows sandbox policy: {err}" - ))) - })?; - let sandbox_cwd = cwd.clone(); - let codex_home = find_codex_home().map_err(|err| { - CodexErr::Io(io::Error::other(format!( - "windows sandbox: failed to resolve codex_home: {err}" - ))) - })?; - let command_path = command.first().cloned(); - let sandbox_level = windows_sandbox_level; - let use_elevated = matches!(sandbox_level, WindowsSandboxLevel::Elevated); - let spawn_res = tokio::task::spawn_blocking(move || { - if use_elevated { - run_windows_sandbox_capture_elevated( - policy_str.as_str(), - &sandbox_cwd, - codex_home.as_ref(), - command, - &cwd, - env, - timeout_ms, - windows_sandbox_private_desktop, - ) - } else { - run_windows_sandbox_capture( - policy_str.as_str(), - &sandbox_cwd, - codex_home.as_ref(), - command, - &cwd, - env, - timeout_ms, - windows_sandbox_private_desktop, - ) - } - }) - .await; - - let capture = match spawn_res { - Ok(Ok(v)) => v, - Ok(Err(err)) => { - record_windows_sandbox_spawn_failure( - command_path.as_deref(), - sandbox_level, - &err.to_string(), - ); - return Err(CodexErr::Io(io::Error::other(format!( - "windows sandbox: {err}" - )))); - } - Err(join_err) => { - return Err(CodexErr::Io(io::Error::other(format!( - "windows sandbox join error: {join_err}" - )))); - } - }; - - let exit_status = synthetic_exit_status(capture.exit_code); - let mut stdout_text = capture.stdout; - if let Some(max_bytes) = capture_policy.retained_bytes_cap() - && stdout_text.len() > max_bytes - { - stdout_text.truncate(max_bytes); - } - let mut stderr_text = capture.stderr; - if let Some(max_bytes) = capture_policy.retained_bytes_cap() - && stderr_text.len() > max_bytes - { - stderr_text.truncate(max_bytes); - } - let stdout = StreamOutput { - text: stdout_text, - truncated_after_lines: None, - }; - let stderr = StreamOutput { - text: stderr_text, - truncated_after_lines: None, - }; - let aggregated_output = aggregate_output(&stdout, &stderr, capture_policy.retained_bytes_cap()); - - Ok(RawExecToolCallOutput { - exit_status, - stdout, - stderr, - aggregated_output, - timed_out: capture.timed_out, - }) -} - -fn finalize_exec_result( - raw_output_result: std::result::Result, - sandbox_type: SandboxType, - duration: Duration, -) -> Result { - match raw_output_result { - Ok(raw_output) => { - #[allow(unused_mut)] - let mut timed_out = raw_output.timed_out; - - #[cfg(target_family = "unix")] - { - if let Some(signal) = raw_output.exit_status.signal() { - if signal == TIMEOUT_CODE { - timed_out = true; - } else { - return Err(CodexErr::Sandbox(SandboxErr::Signal(signal))); - } - } - } - - let mut exit_code = raw_output.exit_status.code().unwrap_or(-1); - if timed_out { - exit_code = EXEC_TIMEOUT_EXIT_CODE; - } - - let stdout = raw_output.stdout.from_utf8_lossy(); - let stderr = raw_output.stderr.from_utf8_lossy(); - let aggregated_output = raw_output.aggregated_output.from_utf8_lossy(); - let exec_output = ExecToolCallOutput { - exit_code, - stdout, - stderr, - aggregated_output, - duration, - timed_out, - }; - - if timed_out { - return Err(CodexErr::Sandbox(SandboxErr::Timeout { - output: Box::new(exec_output), - })); - } - - if is_likely_sandbox_denied(sandbox_type, &exec_output) { - return Err(CodexErr::Sandbox(SandboxErr::Denied { - output: Box::new(exec_output), - network_policy_decision: None, - })); - } - - Ok(exec_output) - } - Err(err) => { - tracing::error!("exec error: {err}"); - Err(err) - } - } -} - -pub(crate) mod errors { - use super::CodexErr; - use crate::sandboxing::SandboxTransformError; - - impl From for CodexErr { - fn from(err: SandboxTransformError) -> Self { - match err { - SandboxTransformError::MissingLinuxSandboxExecutable => { - CodexErr::LandlockSandboxExecutableNotProvided - } - #[cfg(not(target_os = "macos"))] - SandboxTransformError::SeatbeltUnavailable => CodexErr::UnsupportedOperation( - "seatbelt sandbox is only available on macOS".to_string(), - ), - } - } - } -} - -/// We don't have a fully deterministic way to tell if our command failed -/// because of the sandbox - a command in the user's zshrc file might hit an -/// error, but the command itself might fail or succeed for other reasons. -/// For now, we conservatively check for well known command failure exit codes and -/// also look for common sandbox denial keywords in the command output. -pub(crate) fn is_likely_sandbox_denied( - sandbox_type: SandboxType, - exec_output: &ExecToolCallOutput, -) -> bool { - if sandbox_type == SandboxType::None || exec_output.exit_code == 0 { - return false; - } - - // Quick rejects: well-known non-sandbox shell exit codes - // 2: misuse of shell builtins - // 126: permission denied - // 127: command not found - const SANDBOX_DENIED_KEYWORDS: [&str; 7] = [ - "operation not permitted", - "permission denied", - "read-only file system", - "seccomp", - "sandbox", - "landlock", - "failed to write file", - ]; - - let has_sandbox_keyword = [ - &exec_output.stderr.text, - &exec_output.stdout.text, - &exec_output.aggregated_output.text, - ] - .into_iter() - .any(|section| { - let lower = section.to_lowercase(); - SANDBOX_DENIED_KEYWORDS - .iter() - .any(|needle| lower.contains(needle)) - }); - - if has_sandbox_keyword { - return true; - } - - const QUICK_REJECT_EXIT_CODES: [i32; 3] = [2, 126, 127]; - if QUICK_REJECT_EXIT_CODES.contains(&exec_output.exit_code) { - return false; - } - - #[cfg(unix)] - { - const SIGSYS_CODE: i32 = libc::SIGSYS; - if sandbox_type == SandboxType::LinuxSeccomp - && exec_output.exit_code == EXIT_CODE_SIGNAL_BASE + SIGSYS_CODE - { - return true; - } - } - - false -} - -#[derive(Debug, Clone)] -pub struct StreamOutput { - pub text: T, - pub truncated_after_lines: Option, -} - -#[derive(Debug)] -struct RawExecToolCallOutput { - pub exit_status: ExitStatus, - pub stdout: StreamOutput>, - pub stderr: StreamOutput>, - pub aggregated_output: StreamOutput>, - pub timed_out: bool, -} - -impl StreamOutput { - pub fn new(text: String) -> Self { - Self { - text, - truncated_after_lines: None, - } - } -} - -impl StreamOutput> { - pub fn from_utf8_lossy(&self) -> StreamOutput { - StreamOutput { - text: bytes_to_string_smart(&self.text), - truncated_after_lines: self.truncated_after_lines, - } - } -} - -#[inline] -fn append_capped(dst: &mut Vec, src: &[u8], max_bytes: usize) { - if dst.len() >= max_bytes { - return; - } - let remaining = max_bytes.saturating_sub(dst.len()); - let take = remaining.min(src.len()); - dst.extend_from_slice(&src[..take]); -} - -fn aggregate_output( - stdout: &StreamOutput>, - stderr: &StreamOutput>, - max_bytes: Option, -) -> StreamOutput> { - let Some(max_bytes) = max_bytes else { - let total_len = stdout.text.len().saturating_add(stderr.text.len()); - let mut aggregated = Vec::with_capacity(total_len); - aggregated.extend_from_slice(&stdout.text); - aggregated.extend_from_slice(&stderr.text); - return StreamOutput { - text: aggregated, - truncated_after_lines: None, - }; - }; - - let total_len = stdout.text.len().saturating_add(stderr.text.len()); - let mut aggregated = Vec::with_capacity(total_len.min(max_bytes)); - - if total_len <= max_bytes { - aggregated.extend_from_slice(&stdout.text); - aggregated.extend_from_slice(&stderr.text); - return StreamOutput { - text: aggregated, - truncated_after_lines: None, - }; - } - - // Under contention, reserve 1/3 for stdout and 2/3 for stderr; rebalance unused stderr to stdout. - let want_stdout = stdout.text.len().min(max_bytes / 3); - let want_stderr = stderr.text.len(); - let stderr_take = want_stderr.min(max_bytes.saturating_sub(want_stdout)); - let remaining = max_bytes.saturating_sub(want_stdout + stderr_take); - let stdout_take = want_stdout + remaining.min(stdout.text.len().saturating_sub(want_stdout)); - - aggregated.extend_from_slice(&stdout.text[..stdout_take]); - aggregated.extend_from_slice(&stderr.text[..stderr_take]); - - StreamOutput { - text: aggregated, - truncated_after_lines: None, - } -} - -#[derive(Clone, Debug)] -pub struct ExecToolCallOutput { - pub exit_code: i32, - pub stdout: StreamOutput, - pub stderr: StreamOutput, - pub aggregated_output: StreamOutput, - pub duration: Duration, - pub timed_out: bool, -} - -impl Default for ExecToolCallOutput { - fn default() -> Self { - Self { - exit_code: 0, - stdout: StreamOutput::new(String::new()), - stderr: StreamOutput::new(String::new()), - aggregated_output: StreamOutput::new(String::new()), - duration: Duration::ZERO, - timed_out: false, - } - } -} - -#[cfg_attr(not(target_os = "windows"), allow(unused_variables))] -async fn exec( - params: ExecParams, - sandbox: SandboxType, - sandbox_policy: &SandboxPolicy, - file_system_sandbox_policy: &FileSystemSandboxPolicy, - network_sandbox_policy: NetworkSandboxPolicy, - stdout_stream: Option, - after_spawn: Option>, -) -> Result { - #[cfg(target_os = "windows")] - if sandbox == SandboxType::WindowsRestrictedToken { - let support = windows_restricted_token_sandbox_support( - sandbox, - params.windows_sandbox_level, - sandbox_policy, - file_system_sandbox_policy, - network_sandbox_policy, - ); - if let Some(reason) = support.unsupported_reason { - return Err(CodexErr::Io(io::Error::other(reason))); - } - return exec_windows_sandbox(params, sandbox_policy).await; - } - let ExecParams { - command, - cwd, - mut env, - network, - arg0, - expiration, - capture_policy, - windows_sandbox_level: _, - .. - } = params; - if let Some(network) = network.as_ref() { - network.apply_to_env(&mut env); - } - - let (program, args) = command.split_first().ok_or_else(|| { - CodexErr::Io(io::Error::new( - io::ErrorKind::InvalidInput, - "command args are empty", - )) - })?; - let arg0_ref = arg0.as_deref(); - let child = spawn_child_async(SpawnChildRequest { - program: PathBuf::from(program), - args: args.into(), - arg0: arg0_ref, - cwd, - network_sandbox_policy, - // The environment already has attempt-scoped proxy settings from - // apply_to_env_for_attempt above. Passing network here would reapply - // non-attempt proxy vars and drop attempt correlation metadata. - network: None, - stdio_policy: StdioPolicy::RedirectForShellTool, - env, - }) - .await?; - if let Some(after_spawn) = after_spawn { - after_spawn(); - } - consume_output(child, expiration, capture_policy, stdout_stream).await -} - -#[cfg_attr(not(target_os = "windows"), allow(dead_code))] -#[derive(Debug, PartialEq, Eq)] -struct WindowsRestrictedTokenSandboxSupport { - should_use: bool, - unsupported_reason: Option, -} - -#[cfg(any(target_os = "windows", test))] -fn windows_restricted_token_sandbox_support( - sandbox: SandboxType, - windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel, - sandbox_policy: &SandboxPolicy, - file_system_sandbox_policy: &FileSystemSandboxPolicy, - network_sandbox_policy: NetworkSandboxPolicy, -) -> WindowsRestrictedTokenSandboxSupport { - if sandbox != SandboxType::WindowsRestrictedToken { - return WindowsRestrictedTokenSandboxSupport { - should_use: false, - unsupported_reason: None, - }; - } - - // Windows currently reuses SandboxType::WindowsRestrictedToken for both - // the legacy restricted-token backend and the elevated setup/runner path. - // The sandbox level decides whether restricted read-only policies are - // supported. - let should_use = file_system_sandbox_policy.kind == FileSystemSandboxKind::Restricted - && !matches!( - sandbox_policy, - SandboxPolicy::DangerFullAccess | SandboxPolicy::ExternalSandbox { .. } - ) - && (matches!( - windows_sandbox_level, - codex_protocol::config_types::WindowsSandboxLevel::Elevated - ) || sandbox_policy.has_full_disk_read_access()); - - let unsupported_reason = if should_use { - None - } else { - Some(format!( - "windows sandbox backend cannot enforce file_system={:?}, network={network_sandbox_policy:?}, legacy_policy={sandbox_policy:?}; refusing to run unsandboxed", - file_system_sandbox_policy.kind, - )) - }; - - WindowsRestrictedTokenSandboxSupport { - should_use, - unsupported_reason, - } -} - -/// Consumes the output of a child process according to the configured capture -/// policy. -async fn consume_output( - mut child: Child, - expiration: ExecExpiration, - capture_policy: ExecCapturePolicy, - stdout_stream: Option, -) -> Result { - // Both stdout and stderr were configured with `Stdio::piped()` - // above, therefore `take()` should normally return `Some`. If it doesn't - // we treat it as an exceptional I/O error - - let stdout_reader = child.stdout.take().ok_or_else(|| { - CodexErr::Io(io::Error::other( - "stdout pipe was unexpectedly not available", - )) - })?; - let stderr_reader = child.stderr.take().ok_or_else(|| { - CodexErr::Io(io::Error::other( - "stderr pipe was unexpectedly not available", - )) - })?; - - let retained_bytes_cap = capture_policy.retained_bytes_cap(); - let stdout_handle = tokio::spawn(read_output( - BufReader::new(stdout_reader), - stdout_stream.clone(), - /*is_stderr*/ false, - retained_bytes_cap, - )); - let stderr_handle = tokio::spawn(read_output( - BufReader::new(stderr_reader), - stdout_stream.clone(), - /*is_stderr*/ true, - retained_bytes_cap, - )); - - let expiration_wait = async { - if capture_policy.uses_expiration() { - expiration.wait().await; - } else { - std::future::pending::<()>().await; - } - }; - tokio::pin!(expiration_wait); - let (exit_status, timed_out) = tokio::select! { - status_result = child.wait() => { - let exit_status = status_result?; - (exit_status, false) - } - _ = &mut expiration_wait => { - kill_child_process_group(&mut child)?; - child.start_kill()?; - (synthetic_exit_status(EXIT_CODE_SIGNAL_BASE + TIMEOUT_CODE), true) - } - _ = tokio::signal::ctrl_c() => { - kill_child_process_group(&mut child)?; - child.start_kill()?; - (synthetic_exit_status(EXIT_CODE_SIGNAL_BASE + SIGKILL_CODE), false) - } - }; - - // We need mutable bindings so we can `abort()` them on timeout. - use tokio::task::JoinHandle; - - async fn await_output( - handle: &mut JoinHandle>>>, - timeout: Duration, - ) -> std::io::Result>> { - match tokio::time::timeout(timeout, &mut *handle).await { - Ok(join_res) => match join_res { - Ok(io_res) => io_res, - Err(join_err) => Err(std::io::Error::other(join_err)), - }, - Err(_elapsed) => { - // Timeout: abort the task to avoid hanging on open pipes. - handle.abort(); - Ok(StreamOutput { - text: Vec::new(), - truncated_after_lines: None, - }) - } - } - } - - let mut stdout_handle = stdout_handle; - let mut stderr_handle = stderr_handle; - - let stdout = await_output(&mut stdout_handle, capture_policy.io_drain_timeout()).await?; - let stderr = await_output(&mut stderr_handle, capture_policy.io_drain_timeout()).await?; - let aggregated_output = aggregate_output(&stdout, &stderr, retained_bytes_cap); - - Ok(RawExecToolCallOutput { - exit_status, - stdout, - stderr, - aggregated_output, - timed_out, - }) -} - -async fn read_output( - mut reader: R, - stream: Option, - is_stderr: bool, - max_bytes: Option, -) -> io::Result>> { - let mut buf = Vec::with_capacity( - max_bytes.map_or(AGGREGATE_BUFFER_INITIAL_CAPACITY, |max_bytes| { - AGGREGATE_BUFFER_INITIAL_CAPACITY.min(max_bytes) - }), - ); - let mut tmp = [0u8; READ_CHUNK_SIZE]; - let mut emitted_deltas: usize = 0; - - loop { - let n = reader.read(&mut tmp).await?; - if n == 0 { - break; - } - - if let Some(stream) = &stream - && emitted_deltas < MAX_EXEC_OUTPUT_DELTAS_PER_CALL - { - let chunk = tmp[..n].to_vec(); - let msg = EventMsg::ExecCommandOutputDelta(ExecCommandOutputDeltaEvent { - call_id: stream.call_id.clone(), - stream: if is_stderr { - ExecOutputStream::Stderr - } else { - ExecOutputStream::Stdout - }, - chunk, - }); - let event = Event { - id: stream.sub_id.clone(), - msg, - }; - #[allow(clippy::let_unit_value)] - let _ = stream.tx_event.send(event).await; - emitted_deltas += 1; - } - - if let Some(max_bytes) = max_bytes { - append_capped(&mut buf, &tmp[..n], max_bytes); - } else { - buf.extend_from_slice(&tmp[..n]); - } - // Continue reading to EOF to avoid back-pressure - } - - Ok(StreamOutput { - text: buf, - truncated_after_lines: None, - }) -} - -#[cfg(unix)] -fn synthetic_exit_status(code: i32) -> ExitStatus { - use std::os::unix::process::ExitStatusExt; - std::process::ExitStatus::from_raw(code) -} - -#[cfg(windows)] -fn synthetic_exit_status(code: i32) -> ExitStatus { - use std::os::windows::process::ExitStatusExt; - // On Windows the raw status is a u32. Use a direct cast to avoid - // panicking on negative i32 values produced by prior narrowing casts. - std::process::ExitStatus::from_raw(code as u32) -} - -#[cfg(test)] -#[path = "exec_tests.rs"] -mod tests; diff --git a/codex-rs/core/src/landlock.rs b/codex-rs/core/src/landlock.rs index 19b3f7c6af..296cb65639 100644 --- a/codex-rs/core/src/landlock.rs +++ b/codex-rs/core/src/landlock.rs @@ -1,170 +1,3 @@ -use crate::protocol::SandboxPolicy; -use crate::spawn::SpawnChildRequest; -use crate::spawn::StdioPolicy; -use crate::spawn::spawn_child_async; -use codex_network_proxy::NetworkProxy; -use codex_protocol::permissions::FileSystemSandboxPolicy; -use codex_protocol::permissions::NetworkSandboxPolicy; -use std::collections::HashMap; -use std::path::Path; -use std::path::PathBuf; -use tokio::process::Child; - -/// Spawn a shell tool command under the Linux sandbox helper -/// (codex-linux-sandbox), which defaults to bubblewrap for filesystem -/// isolation plus seccomp for network restrictions. -/// -/// Unlike macOS Seatbelt where we directly embed the policy text, the Linux -/// helper is a separate executable. We pass the legacy [`SandboxPolicy`] plus -/// split filesystem/network policies as JSON so the helper can migrate -/// incrementally without breaking older call sites. -#[allow(clippy::too_many_arguments)] -pub async fn spawn_command_under_linux_sandbox

( - codex_linux_sandbox_exe: P, - command: Vec, - command_cwd: PathBuf, - sandbox_policy: &SandboxPolicy, - sandbox_policy_cwd: &Path, - use_legacy_landlock: bool, - stdio_policy: StdioPolicy, - network: Option<&NetworkProxy>, - env: HashMap, -) -> std::io::Result -where - P: AsRef, -{ - let file_system_sandbox_policy = - FileSystemSandboxPolicy::from_legacy_sandbox_policy(sandbox_policy, sandbox_policy_cwd); - let network_sandbox_policy = NetworkSandboxPolicy::from(sandbox_policy); - let args = create_linux_sandbox_command_args_for_policies( - command, - command_cwd.as_path(), - sandbox_policy, - &file_system_sandbox_policy, - network_sandbox_policy, - sandbox_policy_cwd, - use_legacy_landlock, - allow_network_for_proxy(/*enforce_managed_network*/ false), - ); - let arg0 = Some("codex-linux-sandbox"); - spawn_child_async(SpawnChildRequest { - program: codex_linux_sandbox_exe.as_ref().to_path_buf(), - args, - arg0, - cwd: command_cwd, - network_sandbox_policy, - network, - stdio_policy, - env, - }) - .await -} - -pub(crate) fn allow_network_for_proxy(enforce_managed_network: bool) -> bool { - // When managed network requirements are active, request proxy-only - // networking from the Linux sandbox helper. Without managed requirements, - // preserve existing behavior. - enforce_managed_network -} - -/// Converts the sandbox policies into the CLI invocation for -/// `codex-linux-sandbox`. -/// -/// The helper performs the actual sandboxing (bubblewrap by default + seccomp) after -/// parsing these arguments. Policy JSON flags are emitted before helper feature -/// flags so the argv order matches the helper's CLI shape. See -/// `docs/linux_sandbox.md` for the Linux semantics. -#[allow(clippy::too_many_arguments)] -pub fn create_linux_sandbox_command_args_for_policies( - command: Vec, - command_cwd: &Path, - sandbox_policy: &SandboxPolicy, - file_system_sandbox_policy: &FileSystemSandboxPolicy, - network_sandbox_policy: NetworkSandboxPolicy, - sandbox_policy_cwd: &Path, - use_legacy_landlock: bool, - allow_network_for_proxy: bool, -) -> Vec { - let sandbox_policy_json = serde_json::to_string(sandbox_policy) - .unwrap_or_else(|err| panic!("failed to serialize sandbox policy: {err}")); - let file_system_policy_json = serde_json::to_string(file_system_sandbox_policy) - .unwrap_or_else(|err| panic!("failed to serialize filesystem sandbox policy: {err}")); - let network_policy_json = serde_json::to_string(&network_sandbox_policy) - .unwrap_or_else(|err| panic!("failed to serialize network sandbox policy: {err}")); - let sandbox_policy_cwd = sandbox_policy_cwd - .to_str() - .unwrap_or_else(|| panic!("cwd must be valid UTF-8")) - .to_string(); - let command_cwd = command_cwd - .to_str() - .unwrap_or_else(|| panic!("command cwd must be valid UTF-8")) - .to_string(); - - let mut linux_cmd: Vec = vec![ - "--sandbox-policy-cwd".to_string(), - sandbox_policy_cwd, - "--command-cwd".to_string(), - command_cwd, - "--sandbox-policy".to_string(), - sandbox_policy_json, - "--file-system-sandbox-policy".to_string(), - file_system_policy_json, - "--network-sandbox-policy".to_string(), - network_policy_json, - ]; - if use_legacy_landlock { - linux_cmd.push("--use-legacy-landlock".to_string()); - } - if allow_network_for_proxy { - linux_cmd.push("--allow-network-for-proxy".to_string()); - } - linux_cmd.push("--".to_string()); - linux_cmd.extend(command); - linux_cmd -} - -/// Converts the sandbox cwd and execution options into the CLI invocation for -/// `codex-linux-sandbox`. -#[cfg(test)] -pub(crate) fn create_linux_sandbox_command_args( - command: Vec, - command_cwd: &Path, - sandbox_policy_cwd: &Path, - use_legacy_landlock: bool, - allow_network_for_proxy: bool, -) -> Vec { - let command_cwd = command_cwd - .to_str() - .unwrap_or_else(|| panic!("command cwd must be valid UTF-8")) - .to_string(); - let sandbox_policy_cwd = sandbox_policy_cwd - .to_str() - .unwrap_or_else(|| panic!("cwd must be valid UTF-8")) - .to_string(); - - let mut linux_cmd: Vec = vec![ - "--sandbox-policy-cwd".to_string(), - sandbox_policy_cwd, - "--command-cwd".to_string(), - command_cwd, - ]; - if use_legacy_landlock { - linux_cmd.push("--use-legacy-landlock".to_string()); - } - if allow_network_for_proxy { - linux_cmd.push("--allow-network-for-proxy".to_string()); - } - - // Separator so that command arguments starting with `-` are not parsed as - // options of the helper itself. - linux_cmd.push("--".to_string()); - - // Append the original tool command. - linux_cmd.extend(command); - - linux_cmd -} - -#[cfg(test)] -#[path = "landlock_tests.rs"] -mod tests; +pub(crate) use codex_sandbox::allow_network_for_proxy; +pub(crate) use codex_sandbox::create_linux_sandbox_command_args_for_policies; +pub(crate) use codex_sandbox::spawn_command_under_linux_sandbox; diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index 29436a0d7f..0cfc69ae13 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -35,7 +35,7 @@ pub mod custom_prompts; pub mod env; mod environment_context; pub mod error; -pub mod exec; +mod exec; pub mod exec_env; mod exec_policy; pub mod external_agent_config; @@ -45,7 +45,7 @@ pub mod git_info; mod guardian; mod hook_runtime; pub mod instructions; -pub mod landlock; +mod landlock; pub mod mcp; mod mcp_connection_manager; mod mcp_tool_approval_templates; @@ -68,7 +68,7 @@ pub mod path_utils; pub mod personality_migration; pub mod plugins; mod sandbox_tags; -pub mod sandboxing; +mod sandboxing; mod session_prefix; mod session_startup_prewarm; mod shell_detect; @@ -78,7 +78,8 @@ mod text_encoding; pub use codex_login::token_data; mod truncate; mod unified_exec; -pub mod windows_sandbox; +mod windows_sandbox; +mod windows_sandbox_read_grants; pub use client::X_RESPONSESAPI_INCLUDE_TIMING_METRICS_HEADER; pub use model_provider_info::DEFAULT_LMSTUDIO_PORT; pub use model_provider_info::DEFAULT_OLLAMA_PORT; @@ -96,7 +97,6 @@ pub mod review_prompts; mod seatbelt_permissions; mod thread_manager; pub mod web_search; -pub mod windows_sandbox_read_grants; pub use thread_manager::NewThread; pub use thread_manager::ThreadManager; #[deprecated(note = "use ThreadManager")] @@ -121,11 +121,11 @@ pub mod default_client { pub mod project_doc; mod rollout; pub(crate) mod safety; -pub mod seatbelt; +mod seatbelt; pub mod shell; pub mod shell_snapshot; pub mod skills; -pub mod spawn; +mod spawn; pub mod state_db; mod tools; pub mod turn_diff_tracker; @@ -180,7 +180,6 @@ pub use exec_policy::check_execpolicy_for_warnings; pub use exec_policy::format_exec_policy_error_with_source; pub use exec_policy::load_exec_policy; pub use file_watcher::FileWatcherEvent; -pub use safety::get_platform_sandbox; pub use tools::spec::parse_tool_input_schema; pub use turn_metadata::build_turn_metadata_header; pub mod compact; diff --git a/codex-rs/core/src/sandboxing/mod.rs b/codex-rs/core/src/sandboxing/mod.rs index 277ff2b241..2656a30804 100644 --- a/codex-rs/core/src/sandboxing/mod.rs +++ b/codex-rs/core/src/sandboxing/mod.rs @@ -1,756 +1,34 @@ -/* -Module: sandboxing - -Build platform wrappers and produce ExecRequest for execution. Owns low-level -sandbox placement and transformation of portable CommandSpec into a -ready‑to‑spawn environment. -*/ - -pub(crate) mod macos_permissions; - -use crate::exec::ExecCapturePolicy; -use crate::exec::ExecExpiration; +use crate::error::Result; use crate::exec::ExecToolCallOutput; -use crate::exec::SandboxType; use crate::exec::StdoutStream; -use crate::exec::execute_exec_request; -use crate::landlock::allow_network_for_proxy; -use crate::landlock::create_linux_sandbox_command_args_for_policies; -use crate::protocol::SandboxPolicy; -#[cfg(target_os = "macos")] -use crate::seatbelt::MACOS_PATH_TO_SEATBELT_EXECUTABLE; -#[cfg(target_os = "macos")] -use crate::seatbelt::create_seatbelt_command_args_for_policies_with_extensions; -#[cfg(target_os = "macos")] -use crate::spawn::CODEX_SANDBOX_ENV_VAR; -use crate::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; -use crate::tools::sandboxing::SandboxablePreference; -use codex_network_proxy::NetworkProxy; -use codex_protocol::config_types::WindowsSandboxLevel; -use codex_protocol::models::FileSystemPermissions; -use codex_protocol::models::MacOsSeatbeltProfileExtensions; -use codex_protocol::models::NetworkPermissions; -use codex_protocol::models::PermissionProfile; -pub use codex_protocol::models::SandboxPermissions; -use codex_protocol::permissions::FileSystemAccessMode; -use codex_protocol::permissions::FileSystemPath; -use codex_protocol::permissions::FileSystemSandboxEntry; -use codex_protocol::permissions::FileSystemSandboxKind; -use codex_protocol::permissions::FileSystemSandboxPolicy; -use codex_protocol::permissions::NetworkSandboxPolicy; -use codex_protocol::protocol::NetworkAccess; -use codex_protocol::protocol::ReadOnlyAccess; -use codex_utils_absolute_path::AbsolutePathBuf; -use dunce::canonicalize; -use macos_permissions::intersect_macos_seatbelt_profile_extensions; -use macos_permissions::merge_macos_seatbelt_profile_extensions; -use std::collections::HashMap; -use std::collections::HashSet; -use std::path::Path; -use std::path::PathBuf; -#[derive(Debug)] -pub struct CommandSpec { - pub program: String, - pub args: Vec, - pub cwd: PathBuf, - pub env: HashMap, - pub expiration: ExecExpiration, - pub capture_policy: ExecCapturePolicy, - pub sandbox_permissions: SandboxPermissions, - pub additional_permissions: Option, - pub justification: Option, -} +pub(crate) use codex_sandbox::CommandSpec; +pub(crate) use codex_sandbox::ExecRequest; +pub(crate) use codex_sandbox::SandboxManager; +pub(crate) use codex_sandbox::SandboxPermissions; +pub(crate) use codex_sandbox::SandboxPreference; +pub(crate) use codex_sandbox::SandboxTransformError; +pub(crate) use codex_sandbox::effective_file_system_sandbox_policy; +pub(crate) use codex_sandbox::intersect_permission_profiles; +pub(crate) use codex_sandbox::merge_permission_profiles; +pub(crate) use codex_sandbox::normalize_additional_permissions; +pub(crate) use codex_sandbox::sandboxing::SandboxTransformRequest; -#[derive(Debug)] -pub struct ExecRequest { - pub command: Vec, - pub cwd: PathBuf, - pub env: HashMap, - pub network: Option, - pub expiration: ExecExpiration, - pub capture_policy: ExecCapturePolicy, - pub sandbox: SandboxType, - pub windows_sandbox_level: WindowsSandboxLevel, - pub windows_sandbox_private_desktop: bool, - pub sandbox_permissions: SandboxPermissions, - pub sandbox_policy: SandboxPolicy, - pub file_system_sandbox_policy: FileSystemSandboxPolicy, - pub network_sandbox_policy: NetworkSandboxPolicy, - pub justification: Option, - pub arg0: Option, -} - -/// Bundled arguments for sandbox transformation. -/// -/// This keeps call sites self-documenting when several fields are optional. -pub(crate) struct SandboxTransformRequest<'a> { - pub spec: CommandSpec, - pub policy: &'a SandboxPolicy, - pub file_system_policy: &'a FileSystemSandboxPolicy, - pub network_policy: NetworkSandboxPolicy, - pub sandbox: SandboxType, - pub enforce_managed_network: bool, - // TODO(viyatb): Evaluate switching this to Option> - // to make shared ownership explicit across runtime/sandbox plumbing. - pub network: Option<&'a NetworkProxy>, - pub sandbox_policy_cwd: &'a Path, - #[cfg(target_os = "macos")] - pub macos_seatbelt_profile_extensions: Option<&'a MacOsSeatbeltProfileExtensions>, - pub codex_linux_sandbox_exe: Option<&'a PathBuf>, - pub use_legacy_landlock: bool, - pub windows_sandbox_level: WindowsSandboxLevel, - pub windows_sandbox_private_desktop: bool, -} - -pub enum SandboxPreference { - Auto, - Require, - Forbid, -} - -#[derive(Debug, thiserror::Error)] -pub(crate) enum SandboxTransformError { - #[error("missing codex-linux-sandbox executable path")] - MissingLinuxSandboxExecutable, - #[cfg(not(target_os = "macos"))] - #[error("seatbelt sandbox is only available on macOS")] - SeatbeltUnavailable, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) struct EffectiveSandboxPermissions { - pub(crate) sandbox_policy: SandboxPolicy, - pub(crate) macos_seatbelt_profile_extensions: Option, -} - -impl EffectiveSandboxPermissions { - pub(crate) fn new( - sandbox_policy: &SandboxPolicy, - macos_seatbelt_profile_extensions: Option<&MacOsSeatbeltProfileExtensions>, - additional_permissions: Option<&PermissionProfile>, - ) -> Self { - let Some(additional_permissions) = additional_permissions else { - return Self { - sandbox_policy: sandbox_policy.clone(), - macos_seatbelt_profile_extensions: macos_seatbelt_profile_extensions.cloned(), - }; - }; - - Self { - sandbox_policy: sandbox_policy_with_additional_permissions( - sandbox_policy, - additional_permissions, - ), - macos_seatbelt_profile_extensions: merge_macos_seatbelt_profile_extensions( - macos_seatbelt_profile_extensions, - additional_permissions.macos.as_ref(), - ), - } - } -} - -pub(crate) fn normalize_additional_permissions( - additional_permissions: PermissionProfile, -) -> Result { - let network = additional_permissions - .network - .filter(|network| !network.is_empty()); - let file_system = additional_permissions - .file_system - .map(|file_system| { - let read = file_system - .read - .map(|paths| normalize_permission_paths(paths, "file_system.read")); - let write = file_system - .write - .map(|paths| normalize_permission_paths(paths, "file_system.write")); - FileSystemPermissions { read, write } - }) - .filter(|file_system| !file_system.is_empty()); - let macos = additional_permissions.macos; - - Ok(PermissionProfile { - network, - file_system, - macos, - }) -} - -pub(crate) fn merge_permission_profiles( - base: Option<&PermissionProfile>, - permissions: Option<&PermissionProfile>, -) -> Option { - let Some(permissions) = permissions else { - return base.cloned(); - }; - - match base { - Some(base) => { - let network = match (base.network.as_ref(), permissions.network.as_ref()) { - ( - Some(NetworkPermissions { - enabled: Some(true), - }), - _, - ) - | ( - _, - Some(NetworkPermissions { - enabled: Some(true), - }), - ) => Some(NetworkPermissions { - enabled: Some(true), - }), - _ => None, - }; - let file_system = match (base.file_system.as_ref(), permissions.file_system.as_ref()) { - (Some(base), Some(permissions)) => Some(FileSystemPermissions { - read: merge_permission_paths(base.read.as_ref(), permissions.read.as_ref()), - write: merge_permission_paths(base.write.as_ref(), permissions.write.as_ref()), - }) - .filter(|file_system| !file_system.is_empty()), - (Some(base), None) => Some(base.clone()), - (None, Some(permissions)) => Some(permissions.clone()), - (None, None) => None, - }; - let macos = merge_macos_seatbelt_profile_extensions( - base.macos.as_ref(), - permissions.macos.as_ref(), - ); - - Some(PermissionProfile { - network, - file_system, - macos, - }) - .filter(|permissions| !permissions.is_empty()) - } - None => Some(permissions.clone()).filter(|permissions| !permissions.is_empty()), - } -} - -pub fn intersect_permission_profiles( - requested: PermissionProfile, - granted: PermissionProfile, -) -> PermissionProfile { - let file_system = requested - .file_system - .map(|requested_file_system| { - let granted_file_system = granted.file_system.unwrap_or_default(); - let read = requested_file_system - .read - .map(|requested_read| { - let granted_read = granted_file_system.read.unwrap_or_default(); - requested_read - .into_iter() - .filter(|path| granted_read.contains(path)) - .collect() - }) - .filter(|paths: &Vec<_>| !paths.is_empty()); - let write = requested_file_system - .write - .map(|requested_write| { - let granted_write = granted_file_system.write.unwrap_or_default(); - requested_write - .into_iter() - .filter(|path| granted_write.contains(path)) - .collect() - }) - .filter(|paths: &Vec<_>| !paths.is_empty()); - FileSystemPermissions { read, write } - }) - .filter(|file_system| !file_system.is_empty()); - let network = match (requested.network, granted.network) { - ( - Some(NetworkPermissions { - enabled: Some(true), - }), - Some(NetworkPermissions { - enabled: Some(true), - }), - ) => Some(NetworkPermissions { - enabled: Some(true), - }), - _ => None, - }; - - let macos = intersect_macos_seatbelt_profile_extensions(requested.macos, granted.macos); - - PermissionProfile { - network, - file_system, - macos, - } -} - -fn normalize_permission_paths( - paths: Vec, - _permission_kind: &str, -) -> Vec { - let mut out = Vec::with_capacity(paths.len()); - let mut seen = HashSet::new(); - - for path in paths { - let canonicalized = canonicalize(path.as_path()) - .ok() - .and_then(|path| AbsolutePathBuf::from_absolute_path(path).ok()) - .unwrap_or(path); - if seen.insert(canonicalized.clone()) { - out.push(canonicalized); - } - } - - out -} - -fn merge_permission_paths( - base: Option<&Vec>, - permissions: Option<&Vec>, -) -> Option> { - match (base, permissions) { - (Some(base), Some(permissions)) => { - let mut merged = Vec::with_capacity(base.len() + permissions.len()); - let mut seen = HashSet::with_capacity(base.len() + permissions.len()); - - for path in base.iter().chain(permissions.iter()) { - if seen.insert(path.clone()) { - merged.push(path.clone()); - } - } - - Some(merged).filter(|paths| !paths.is_empty()) - } - (Some(base), None) => Some(base.clone()), - (None, Some(permissions)) => Some(permissions.clone()), - (None, None) => None, - } -} - -fn dedup_absolute_paths(paths: Vec) -> Vec { - let mut out = Vec::with_capacity(paths.len()); - let mut seen = HashSet::new(); - for path in paths { - if seen.insert(path.to_path_buf()) { - out.push(path); - } - } - out -} - -fn additional_permission_roots( - additional_permissions: &PermissionProfile, -) -> (Vec, Vec) { - ( - dedup_absolute_paths( - additional_permissions - .file_system - .as_ref() - .and_then(|file_system| file_system.read.clone()) - .unwrap_or_default(), - ), - dedup_absolute_paths( - additional_permissions - .file_system - .as_ref() - .and_then(|file_system| file_system.write.clone()) - .unwrap_or_default(), - ), - ) -} - -fn merge_file_system_policy_with_additional_permissions( - file_system_policy: &FileSystemSandboxPolicy, - extra_reads: Vec, - extra_writes: Vec, -) -> FileSystemSandboxPolicy { - match file_system_policy.kind { - FileSystemSandboxKind::Restricted => { - let mut merged_policy = file_system_policy.clone(); - for path in extra_reads { - let entry = FileSystemSandboxEntry { - path: FileSystemPath::Path { path }, - access: FileSystemAccessMode::Read, - }; - if !merged_policy.entries.contains(&entry) { - merged_policy.entries.push(entry); - } - } - for path in extra_writes { - let entry = FileSystemSandboxEntry { - path: FileSystemPath::Path { path }, - access: FileSystemAccessMode::Write, - }; - if !merged_policy.entries.contains(&entry) { - merged_policy.entries.push(entry); - } - } - merged_policy - } - FileSystemSandboxKind::Unrestricted | FileSystemSandboxKind::ExternalSandbox => { - file_system_policy.clone() - } - } -} - -pub(crate) fn effective_file_system_sandbox_policy( - file_system_policy: &FileSystemSandboxPolicy, - additional_permissions: Option<&PermissionProfile>, -) -> FileSystemSandboxPolicy { - let Some(additional_permissions) = additional_permissions else { - return file_system_policy.clone(); - }; - - let (extra_reads, extra_writes) = additional_permission_roots(additional_permissions); - if extra_reads.is_empty() && extra_writes.is_empty() { - file_system_policy.clone() - } else { - merge_file_system_policy_with_additional_permissions( - file_system_policy, - extra_reads, - extra_writes, - ) - } -} - -fn merge_read_only_access_with_additional_reads( - read_only_access: &ReadOnlyAccess, - extra_reads: Vec, -) -> ReadOnlyAccess { - match read_only_access { - ReadOnlyAccess::FullAccess => ReadOnlyAccess::FullAccess, - ReadOnlyAccess::Restricted { - include_platform_defaults, - readable_roots, - } => { - let mut merged = readable_roots.clone(); - merged.extend(extra_reads); - ReadOnlyAccess::Restricted { - include_platform_defaults: *include_platform_defaults, - readable_roots: dedup_absolute_paths(merged), - } - } - } -} - -fn merge_network_access( - base_network_access: bool, - additional_permissions: &PermissionProfile, -) -> bool { - base_network_access - || additional_permissions - .network - .as_ref() - .and_then(|network| network.enabled) - .unwrap_or(false) -} - -fn sandbox_policy_with_additional_permissions( - sandbox_policy: &SandboxPolicy, - additional_permissions: &PermissionProfile, -) -> SandboxPolicy { - if additional_permissions.is_empty() { - return sandbox_policy.clone(); - } - - let (extra_reads, extra_writes) = additional_permission_roots(additional_permissions); - - match sandbox_policy { - SandboxPolicy::DangerFullAccess => SandboxPolicy::DangerFullAccess, - SandboxPolicy::ExternalSandbox { network_access } => SandboxPolicy::ExternalSandbox { - network_access: if merge_network_access( - network_access.is_enabled(), - additional_permissions, - ) { - NetworkAccess::Enabled - } else { - NetworkAccess::Restricted - }, - }, - SandboxPolicy::WorkspaceWrite { - writable_roots, - read_only_access, - network_access, - exclude_tmpdir_env_var, - exclude_slash_tmp, - } => { - let mut merged_writes = writable_roots.clone(); - merged_writes.extend(extra_writes); - SandboxPolicy::WorkspaceWrite { - writable_roots: dedup_absolute_paths(merged_writes), - read_only_access: merge_read_only_access_with_additional_reads( - read_only_access, - extra_reads, - ), - network_access: merge_network_access(*network_access, additional_permissions), - exclude_tmpdir_env_var: *exclude_tmpdir_env_var, - exclude_slash_tmp: *exclude_slash_tmp, - } - } - SandboxPolicy::ReadOnly { - access, - network_access, - } => { - if extra_writes.is_empty() { - SandboxPolicy::ReadOnly { - access: merge_read_only_access_with_additional_reads(access, extra_reads), - network_access: merge_network_access(*network_access, additional_permissions), - } - } else { - // todo(dylan) - for now, this grants more access than the request. We should restrict this, - // but we should add a new SandboxPolicy variant to handle this. While the feature is still - // UnderDevelopment, it's a useful approximation of the desired behavior. - SandboxPolicy::WorkspaceWrite { - writable_roots: dedup_absolute_paths(extra_writes), - read_only_access: merge_read_only_access_with_additional_reads( - access, - extra_reads, - ), - network_access: merge_network_access(*network_access, additional_permissions), - exclude_tmpdir_env_var: false, - exclude_slash_tmp: false, - } - } - } - } -} - -pub(crate) fn should_require_platform_sandbox( - file_system_policy: &FileSystemSandboxPolicy, - network_policy: NetworkSandboxPolicy, - has_managed_network_requirements: bool, -) -> bool { - if has_managed_network_requirements { - return true; - } - - if !network_policy.is_enabled() { - return !matches!( - file_system_policy.kind, - FileSystemSandboxKind::ExternalSandbox - ); - } - - match file_system_policy.kind { - FileSystemSandboxKind::Restricted => !file_system_policy.has_full_disk_write_access(), - FileSystemSandboxKind::Unrestricted | FileSystemSandboxKind::ExternalSandbox => false, - } -} - -#[derive(Default)] -pub struct SandboxManager; - -impl SandboxManager { - pub fn new() -> Self { - Self - } - - pub(crate) fn select_initial( - &self, - file_system_policy: &FileSystemSandboxPolicy, - network_policy: NetworkSandboxPolicy, - pref: SandboxablePreference, - windows_sandbox_level: WindowsSandboxLevel, - has_managed_network_requirements: bool, - ) -> SandboxType { - match pref { - SandboxablePreference::Forbid => SandboxType::None, - SandboxablePreference::Require => { - // Require a platform sandbox when available; on Windows this - // respects the experimental_windows_sandbox feature. - crate::safety::get_platform_sandbox( - windows_sandbox_level != WindowsSandboxLevel::Disabled, - ) - .unwrap_or(SandboxType::None) - } - SandboxablePreference::Auto => { - if should_require_platform_sandbox( - file_system_policy, - network_policy, - has_managed_network_requirements, - ) { - crate::safety::get_platform_sandbox( - windows_sandbox_level != WindowsSandboxLevel::Disabled, - ) - .unwrap_or(SandboxType::None) - } else { - SandboxType::None - } - } - } - } - - pub(crate) fn transform( - &self, - request: SandboxTransformRequest<'_>, - ) -> Result { - let SandboxTransformRequest { - mut spec, - policy, - file_system_policy, - network_policy, - sandbox, - enforce_managed_network, - network, - sandbox_policy_cwd, - #[cfg(target_os = "macos")] - macos_seatbelt_profile_extensions, - codex_linux_sandbox_exe, - use_legacy_landlock, - windows_sandbox_level, - windows_sandbox_private_desktop, - } = request; - #[cfg(not(target_os = "macos"))] - let macos_seatbelt_profile_extensions = None; - let additional_permissions = spec.additional_permissions.take(); - let EffectiveSandboxPermissions { - sandbox_policy: effective_policy, - macos_seatbelt_profile_extensions: _effective_macos_seatbelt_profile_extensions, - } = EffectiveSandboxPermissions::new( - policy, - macos_seatbelt_profile_extensions, - additional_permissions.as_ref(), - ); - let (effective_file_system_policy, effective_network_policy) = - if let Some(additional_permissions) = additional_permissions { - let (extra_reads, extra_writes) = - additional_permission_roots(&additional_permissions); - let file_system_sandbox_policy = - if extra_reads.is_empty() && extra_writes.is_empty() { - file_system_policy.clone() - } else { - merge_file_system_policy_with_additional_permissions( - file_system_policy, - extra_reads, - extra_writes, - ) - }; - let network_sandbox_policy = - if merge_network_access(network_policy.is_enabled(), &additional_permissions) { - NetworkSandboxPolicy::Enabled - } else { - NetworkSandboxPolicy::Restricted - }; - (file_system_sandbox_policy, network_sandbox_policy) - } else { - (file_system_policy.clone(), network_policy) - }; - let mut env = spec.env; - if !effective_network_policy.is_enabled() { - env.insert( - CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR.to_string(), - "1".to_string(), - ); - } - - let mut command = Vec::with_capacity(1 + spec.args.len()); - command.push(spec.program); - command.append(&mut spec.args); - - let (command, sandbox_env, arg0_override) = match sandbox { - SandboxType::None => (command, HashMap::new(), None), - #[cfg(target_os = "macos")] - SandboxType::MacosSeatbelt => { - let mut seatbelt_env = HashMap::new(); - seatbelt_env.insert(CODEX_SANDBOX_ENV_VAR.to_string(), "seatbelt".to_string()); - let mut args = create_seatbelt_command_args_for_policies_with_extensions( - command.clone(), - &effective_file_system_policy, - effective_network_policy, - sandbox_policy_cwd, - enforce_managed_network, - network, - _effective_macos_seatbelt_profile_extensions.as_ref(), - ); - let mut full_command = Vec::with_capacity(1 + args.len()); - full_command.push(MACOS_PATH_TO_SEATBELT_EXECUTABLE.to_string()); - full_command.append(&mut args); - (full_command, seatbelt_env, None) - } - #[cfg(not(target_os = "macos"))] - SandboxType::MacosSeatbelt => return Err(SandboxTransformError::SeatbeltUnavailable), - SandboxType::LinuxSeccomp => { - let exe = codex_linux_sandbox_exe - .ok_or(SandboxTransformError::MissingLinuxSandboxExecutable)?; - let allow_proxy_network = allow_network_for_proxy(enforce_managed_network); - let mut args = create_linux_sandbox_command_args_for_policies( - command.clone(), - spec.cwd.as_path(), - &effective_policy, - &effective_file_system_policy, - effective_network_policy, - sandbox_policy_cwd, - use_legacy_landlock, - allow_proxy_network, - ); - let mut full_command = Vec::with_capacity(1 + args.len()); - full_command.push(exe.to_string_lossy().to_string()); - full_command.append(&mut args); - ( - full_command, - HashMap::new(), - Some("codex-linux-sandbox".to_string()), - ) - } - // On Windows, the restricted token sandbox executes in-process via the - // codex-windows-sandbox crate. We leave the command unchanged here and - // branch during execution based on the sandbox type. - #[cfg(target_os = "windows")] - SandboxType::WindowsRestrictedToken => (command, HashMap::new(), None), - // When building for non-Windows targets, this variant is never constructed. - #[cfg(not(target_os = "windows"))] - SandboxType::WindowsRestrictedToken => (command, HashMap::new(), None), - }; - - env.extend(sandbox_env); - - Ok(ExecRequest { - command, - cwd: spec.cwd, - env, - network: network.cloned(), - expiration: spec.expiration, - capture_policy: spec.capture_policy, - sandbox, - windows_sandbox_level, - windows_sandbox_private_desktop, - sandbox_permissions: spec.sandbox_permissions, - sandbox_policy: effective_policy, - file_system_sandbox_policy: effective_file_system_policy, - network_sandbox_policy: effective_network_policy, - justification: spec.justification, - arg0: arg0_override, - }) - } - - pub fn denied(&self, sandbox: SandboxType, out: &ExecToolCallOutput) -> bool { - crate::exec::is_likely_sandbox_denied(sandbox, out) - } -} - -pub async fn execute_env( +pub(crate) async fn execute_env( exec_request: ExecRequest, stdout_stream: Option, -) -> crate::error::Result { - let effective_policy = exec_request.sandbox_policy.clone(); - execute_exec_request( - exec_request, - &effective_policy, - stdout_stream, - /*after_spawn*/ None, - ) - .await +) -> Result { + codex_sandbox::execute_env(exec_request, stdout_stream) + .await + .map_err(Into::into) } -pub async fn execute_exec_request_with_after_spawn( +pub(crate) async fn execute_exec_request_with_after_spawn( exec_request: ExecRequest, stdout_stream: Option, after_spawn: Option>, -) -> crate::error::Result { - let effective_policy = exec_request.sandbox_policy.clone(); - execute_exec_request(exec_request, &effective_policy, stdout_stream, after_spawn).await +) -> Result { + codex_sandbox::execute_exec_request_with_after_spawn(exec_request, stdout_stream, after_spawn) + .await + .map_err(Into::into) } - -#[cfg(test)] -#[path = "mod_tests.rs"] -mod tests; diff --git a/codex-rs/core/src/seatbelt.rs b/codex-rs/core/src/seatbelt.rs index 2d1e0a7b5d..ebfd73b2b4 100644 --- a/codex-rs/core/src/seatbelt.rs +++ b/codex-rs/core/src/seatbelt.rs @@ -1,594 +1,5 @@ #![cfg(target_os = "macos")] -use codex_network_proxy::NetworkProxy; -use codex_network_proxy::PROXY_URL_ENV_KEYS; -use codex_network_proxy::has_proxy_url_env_vars; -use codex_network_proxy::proxy_url_env_value; -use codex_utils_absolute_path::AbsolutePathBuf; -use std::collections::BTreeMap; -use std::collections::BTreeSet; -use std::collections::HashMap; -use std::ffi::CStr; -use std::path::Path; -use std::path::PathBuf; -use tokio::process::Child; -use tracing::warn; -use url::Url; - -use crate::protocol::SandboxPolicy; -use crate::seatbelt_permissions::MacOsSeatbeltProfileExtensions; -use crate::seatbelt_permissions::build_seatbelt_extensions; -use crate::spawn::CODEX_SANDBOX_ENV_VAR; -use crate::spawn::SpawnChildRequest; -use crate::spawn::StdioPolicy; -use crate::spawn::spawn_child_async; -use codex_protocol::permissions::FileSystemSandboxPolicy; -use codex_protocol::permissions::NetworkSandboxPolicy; - -const MACOS_SEATBELT_BASE_POLICY: &str = include_str!("seatbelt_base_policy.sbpl"); -const MACOS_SEATBELT_NETWORK_POLICY: &str = include_str!("seatbelt_network_policy.sbpl"); -const MACOS_RESTRICTED_READ_ONLY_PLATFORM_DEFAULTS: &str = - include_str!("restricted_read_only_platform_defaults.sbpl"); - -/// When working with `sandbox-exec`, only consider `sandbox-exec` in `/usr/bin` -/// to defend against an attacker trying to inject a malicious version on the -/// PATH. If /usr/bin/sandbox-exec has been tampered with, then the attacker -/// already has root access. -pub const MACOS_PATH_TO_SEATBELT_EXECUTABLE: &str = "/usr/bin/sandbox-exec"; - -pub async fn spawn_command_under_seatbelt( - command: Vec, - command_cwd: PathBuf, - sandbox_policy: &SandboxPolicy, - sandbox_policy_cwd: &Path, - stdio_policy: StdioPolicy, - network: Option<&NetworkProxy>, - mut env: HashMap, -) -> std::io::Result { - let args = create_seatbelt_command_args( - command, - sandbox_policy, - sandbox_policy_cwd, - /*enforce_managed_network*/ false, - network, - ); - let arg0 = None; - env.insert(CODEX_SANDBOX_ENV_VAR.to_string(), "seatbelt".to_string()); - spawn_child_async(SpawnChildRequest { - program: PathBuf::from(MACOS_PATH_TO_SEATBELT_EXECUTABLE), - args, - arg0, - cwd: command_cwd, - network_sandbox_policy: NetworkSandboxPolicy::from(sandbox_policy), - network, - stdio_policy, - env, - }) - .await -} - -fn is_loopback_host(host: &str) -> bool { - host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1" -} - -fn proxy_scheme_default_port(scheme: &str) -> u16 { - match scheme { - "https" => 443, - "socks5" | "socks5h" | "socks4" | "socks4a" => 1080, - _ => 80, - } -} - -fn proxy_loopback_ports_from_env(env: &HashMap) -> Vec { - let mut ports = BTreeSet::new(); - for key in PROXY_URL_ENV_KEYS { - let Some(proxy_url) = proxy_url_env_value(env, key) else { - continue; - }; - let trimmed = proxy_url.trim(); - if trimmed.is_empty() { - continue; - } - - let candidate = if trimmed.contains("://") { - trimmed.to_string() - } else { - format!("http://{trimmed}") - }; - let Ok(parsed) = Url::parse(&candidate) else { - continue; - }; - let Some(host) = parsed.host_str() else { - continue; - }; - if !is_loopback_host(host) { - continue; - } - - let scheme = parsed.scheme().to_ascii_lowercase(); - let port = parsed - .port() - .unwrap_or_else(|| proxy_scheme_default_port(scheme.as_str())); - ports.insert(port); - } - ports.into_iter().collect() -} - -#[derive(Debug, Default)] -struct ProxyPolicyInputs { - ports: Vec, - has_proxy_config: bool, - allow_local_binding: bool, - unix_domain_socket_policy: UnixDomainSocketPolicy, -} - -#[derive(Debug, Clone)] -// Keep allow-all and allowlist modes disjoint so we don't carry ignored state. -enum UnixDomainSocketPolicy { - AllowAll, - Restricted { allowed: Vec }, -} - -impl Default for UnixDomainSocketPolicy { - fn default() -> Self { - Self::Restricted { allowed: vec![] } - } -} - -#[derive(Debug, Clone)] -struct UnixSocketPathParam { - index: usize, - path: AbsolutePathBuf, -} - -fn proxy_policy_inputs(network: Option<&NetworkProxy>) -> ProxyPolicyInputs { - if let Some(network) = network { - let mut env = HashMap::new(); - network.apply_to_env(&mut env); - let unix_domain_socket_policy = if network.dangerously_allow_all_unix_sockets() { - UnixDomainSocketPolicy::AllowAll - } else { - let allowed = network - .allow_unix_sockets() - .iter() - .filter_map( - |socket_path| match normalize_path_for_sandbox(Path::new(socket_path)) { - Some(path) => Some((path.to_string_lossy().to_string(), path)), - None => { - warn!( - "ignoring network.allow_unix_sockets entry because it could not be normalized: {socket_path}" - ); - None - } - }, - ) - .collect::>() - .into_values() - .collect(); - UnixDomainSocketPolicy::Restricted { allowed } - }; - return ProxyPolicyInputs { - ports: proxy_loopback_ports_from_env(&env), - has_proxy_config: has_proxy_url_env_vars(&env), - allow_local_binding: network.allow_local_binding(), - unix_domain_socket_policy, - }; - } - - ProxyPolicyInputs::default() -} - -fn normalize_path_for_sandbox(path: &Path) -> Option { - // `AbsolutePathBuf::from_absolute_path()` normalizes relative paths against the current - // working directory, so keep the explicit check to avoid silently accepting relative entries. - if !path.is_absolute() { - return None; - } - - let absolute_path = AbsolutePathBuf::from_absolute_path(path).ok()?; - let normalized_path = absolute_path - .as_path() - .canonicalize() - .ok() - .and_then(|canonical_path| AbsolutePathBuf::from_absolute_path(canonical_path).ok()); - normalized_path.or(Some(absolute_path)) -} - -fn unix_socket_path_params(proxy: &ProxyPolicyInputs) -> Vec { - let mut deduped_paths: BTreeMap = BTreeMap::new(); - let UnixDomainSocketPolicy::Restricted { allowed } = &proxy.unix_domain_socket_policy else { - return vec![]; - }; - for path in allowed { - deduped_paths - .entry(path.to_string_lossy().to_string()) - .or_insert_with(|| path.clone()); - } - - deduped_paths - .into_values() - .enumerate() - .map(|(index, path)| UnixSocketPathParam { index, path }) - .collect() -} - -fn unix_socket_path_param_key(index: usize) -> String { - format!("UNIX_SOCKET_PATH_{index}") -} - -fn unix_socket_dir_params(proxy: &ProxyPolicyInputs) -> Vec<(String, PathBuf)> { - unix_socket_path_params(proxy) - .into_iter() - .map(|param| { - ( - unix_socket_path_param_key(param.index), - param.path.into_path_buf(), - ) - }) - .collect() -} - -/// Returns zero or more complete Seatbelt policy lines for unix socket rules. -/// When non-empty, the returned string is newline-terminated so callers can -/// append it directly to larger policy blocks. -fn unix_socket_policy(proxy: &ProxyPolicyInputs) -> String { - let socket_params = unix_socket_path_params(proxy); - let has_unix_socket_access = matches!( - proxy.unix_domain_socket_policy, - UnixDomainSocketPolicy::AllowAll - ) || !socket_params.is_empty(); - if !has_unix_socket_access { - return String::new(); - } - - let mut policy = String::new(); - policy.push_str("(allow system-socket (socket-domain AF_UNIX))\n"); - if matches!( - proxy.unix_domain_socket_policy, - UnixDomainSocketPolicy::AllowAll - ) { - // Keep AllowAll genuinely broad here; path qualifiers look narrower - // without a clear macOS behavioral benefit. - policy.push_str("(allow network-bind (local unix-socket))\n"); - policy.push_str("(allow network-outbound (remote unix-socket))\n"); - return policy; - } - - for param in socket_params { - let key = unix_socket_path_param_key(param.index); - // Use subpath so allowlists cover sockets created beneath approved directories. - policy.push_str(&format!( - "(allow network-bind (local unix-socket (subpath (param \"{key}\"))))\n" - )); - policy.push_str(&format!( - "(allow network-outbound (remote unix-socket (subpath (param \"{key}\"))))\n" - )); - } - policy -} - -#[cfg_attr(not(test), allow(dead_code))] -fn dynamic_network_policy( - sandbox_policy: &SandboxPolicy, - enforce_managed_network: bool, - proxy: &ProxyPolicyInputs, -) -> String { - dynamic_network_policy_for_network( - NetworkSandboxPolicy::from(sandbox_policy), - enforce_managed_network, - proxy, - ) -} - -fn dynamic_network_policy_for_network( - network_policy: NetworkSandboxPolicy, - enforce_managed_network: bool, - proxy: &ProxyPolicyInputs, -) -> String { - let should_use_restricted_network_policy = - !proxy.ports.is_empty() || proxy.has_proxy_config || enforce_managed_network; - if should_use_restricted_network_policy { - let mut policy = String::new(); - if proxy.allow_local_binding { - policy.push_str("; allow loopback local binding and loopback traffic\n"); - policy.push_str("(allow network-bind (local ip \"localhost:*\"))\n"); - policy.push_str("(allow network-inbound (local ip \"localhost:*\"))\n"); - policy.push_str("(allow network-outbound (remote ip \"localhost:*\"))\n"); - } - for port in &proxy.ports { - policy.push_str(&format!( - "(allow network-outbound (remote ip \"localhost:{port}\"))\n" - )); - } - let unix_socket_policy = unix_socket_policy(proxy); - if !unix_socket_policy.is_empty() { - policy.push_str("; allow unix domain sockets for local IPC\n"); - policy.push_str(&unix_socket_policy); - } - return format!("{policy}{MACOS_SEATBELT_NETWORK_POLICY}"); - } - - if proxy.has_proxy_config { - // Proxy configuration is present but we could not infer any valid loopback endpoints. - // Fail closed to avoid silently widening network access in proxy-enforced sessions. - return String::new(); - } - - if enforce_managed_network { - // Managed network requirements are active but no usable proxy endpoints - // are available. Fail closed for network access. - return String::new(); - } - - if network_policy.is_enabled() { - // No proxy env is configured: retain the existing full-network behavior. - format!( - "(allow network-outbound)\n(allow network-inbound)\n{MACOS_SEATBELT_NETWORK_POLICY}" - ) - } else { - String::new() - } -} - -#[cfg_attr(not(test), allow(dead_code))] -pub(crate) fn create_seatbelt_command_args( - command: Vec, - sandbox_policy: &SandboxPolicy, - sandbox_policy_cwd: &Path, - enforce_managed_network: bool, - network: Option<&NetworkProxy>, -) -> Vec { - create_seatbelt_command_args_with_extensions( - command, - sandbox_policy, - sandbox_policy_cwd, - enforce_managed_network, - network, - /*extensions*/ None, - ) -} - -fn root_absolute_path() -> AbsolutePathBuf { - match AbsolutePathBuf::from_absolute_path(Path::new("/")) { - Ok(path) => path, - Err(err) => panic!("root path must be absolute: {err}"), - } -} - -#[derive(Debug, Clone)] -struct SeatbeltAccessRoot { - root: AbsolutePathBuf, - excluded_subpaths: Vec, -} - -fn build_seatbelt_access_policy( - action: &str, - param_prefix: &str, - roots: Vec, -) -> (String, Vec<(String, PathBuf)>) { - let mut policy_components = Vec::new(); - let mut params = Vec::new(); - - for (index, access_root) in roots.into_iter().enumerate() { - let root = - normalize_path_for_sandbox(access_root.root.as_path()).unwrap_or(access_root.root); - let root_param = format!("{param_prefix}_{index}"); - params.push((root_param.clone(), root.into_path_buf())); - - if access_root.excluded_subpaths.is_empty() { - policy_components.push(format!("(subpath (param \"{root_param}\"))")); - continue; - } - - let mut require_parts = vec![format!("(subpath (param \"{root_param}\"))")]; - for (excluded_index, excluded_subpath) in - access_root.excluded_subpaths.into_iter().enumerate() - { - let excluded_subpath = - normalize_path_for_sandbox(excluded_subpath.as_path()).unwrap_or(excluded_subpath); - let excluded_param = format!("{param_prefix}_{index}_RO_{excluded_index}"); - params.push((excluded_param.clone(), excluded_subpath.into_path_buf())); - require_parts.push(format!( - "(require-not (subpath (param \"{excluded_param}\")))" - )); - } - policy_components.push(format!("(require-all {} )", require_parts.join(" "))); - } - - if policy_components.is_empty() { - (String::new(), Vec::new()) - } else { - ( - format!("(allow {action}\n{}\n)", policy_components.join(" ")), - params, - ) - } -} - -#[cfg_attr(not(test), allow(dead_code))] -pub(crate) fn create_seatbelt_command_args_with_extensions( - command: Vec, - sandbox_policy: &SandboxPolicy, - sandbox_policy_cwd: &Path, - enforce_managed_network: bool, - network: Option<&NetworkProxy>, - extensions: Option<&MacOsSeatbeltProfileExtensions>, -) -> Vec { - create_seatbelt_command_args_for_policies_with_extensions( - command, - &FileSystemSandboxPolicy::from_legacy_sandbox_policy(sandbox_policy, sandbox_policy_cwd), - NetworkSandboxPolicy::from(sandbox_policy), - sandbox_policy_cwd, - enforce_managed_network, - network, - extensions, - ) -} - -pub fn create_seatbelt_command_args_for_policies_with_extensions( - command: Vec, - file_system_sandbox_policy: &FileSystemSandboxPolicy, - network_sandbox_policy: NetworkSandboxPolicy, - sandbox_policy_cwd: &Path, - enforce_managed_network: bool, - network: Option<&NetworkProxy>, - extensions: Option<&MacOsSeatbeltProfileExtensions>, -) -> Vec { - let unreadable_roots = - file_system_sandbox_policy.get_unreadable_roots_with_cwd(sandbox_policy_cwd); - let (file_write_policy, file_write_dir_params) = - if file_system_sandbox_policy.has_full_disk_write_access() { - if unreadable_roots.is_empty() { - // Allegedly, this is more permissive than `(allow file-write*)`. - ( - r#"(allow file-write* (regex #"^/"))"#.to_string(), - Vec::new(), - ) - } else { - build_seatbelt_access_policy( - "file-write*", - "WRITABLE_ROOT", - vec![SeatbeltAccessRoot { - root: root_absolute_path(), - excluded_subpaths: unreadable_roots.clone(), - }], - ) - } - } else { - build_seatbelt_access_policy( - "file-write*", - "WRITABLE_ROOT", - file_system_sandbox_policy - .get_writable_roots_with_cwd(sandbox_policy_cwd) - .into_iter() - .map(|root| SeatbeltAccessRoot { - root: root.root, - excluded_subpaths: root.read_only_subpaths, - }) - .collect(), - ) - }; - - let (file_read_policy, file_read_dir_params) = - if file_system_sandbox_policy.has_full_disk_read_access() { - if unreadable_roots.is_empty() { - ( - "; allow read-only file operations\n(allow file-read*)".to_string(), - Vec::new(), - ) - } else { - let (policy, params) = build_seatbelt_access_policy( - "file-read*", - "READABLE_ROOT", - vec![SeatbeltAccessRoot { - root: root_absolute_path(), - excluded_subpaths: unreadable_roots, - }], - ); - ( - format!("; allow read-only file operations\n{policy}"), - params, - ) - } - } else { - let (policy, params) = build_seatbelt_access_policy( - "file-read*", - "READABLE_ROOT", - file_system_sandbox_policy - .get_readable_roots_with_cwd(sandbox_policy_cwd) - .into_iter() - .map(|root| SeatbeltAccessRoot { - excluded_subpaths: unreadable_roots - .iter() - .filter(|path| path.as_path().starts_with(root.as_path())) - .cloned() - .collect(), - root, - }) - .collect(), - ); - if policy.is_empty() { - (String::new(), params) - } else { - ( - format!("; allow read-only file operations\n{policy}"), - params, - ) - } - }; - - let proxy = proxy_policy_inputs(network); - let network_policy = - dynamic_network_policy_for_network(network_sandbox_policy, enforce_managed_network, &proxy); - let seatbelt_extensions = extensions.map_or_else( - || { - // Backward-compatibility default when no extension profile is provided. - build_seatbelt_extensions(&MacOsSeatbeltProfileExtensions::default()) - }, - build_seatbelt_extensions, - ); - - let include_platform_defaults = file_system_sandbox_policy.include_platform_defaults(); - let mut policy_sections = vec![ - MACOS_SEATBELT_BASE_POLICY.to_string(), - file_read_policy, - file_write_policy, - network_policy, - ]; - if include_platform_defaults { - policy_sections.push(MACOS_RESTRICTED_READ_ONLY_PLATFORM_DEFAULTS.to_string()); - } - if !seatbelt_extensions.policy.is_empty() { - policy_sections.push(seatbelt_extensions.policy.clone()); - } - - let full_policy = policy_sections.join("\n"); - - let dir_params = [ - file_read_dir_params, - file_write_dir_params, - macos_dir_params(), - unix_socket_dir_params(&proxy), - seatbelt_extensions.dir_params, - ] - .concat(); - - let mut seatbelt_args: Vec = vec!["-p".to_string(), full_policy]; - let definition_args = dir_params - .into_iter() - .map(|(key, value)| format!("-D{key}={value}", value = value.to_string_lossy())); - seatbelt_args.extend(definition_args); - seatbelt_args.push("--".to_string()); - seatbelt_args.extend(command); - seatbelt_args -} - -/// Wraps libc::confstr to return a String. -fn confstr(name: libc::c_int) -> Option { - let mut buf = vec![0_i8; (libc::PATH_MAX as usize) + 1]; - let len = unsafe { libc::confstr(name, buf.as_mut_ptr(), buf.len()) }; - if len == 0 { - return None; - } - // confstr guarantees NUL-termination when len > 0. - let cstr = unsafe { CStr::from_ptr(buf.as_ptr()) }; - cstr.to_str().ok().map(ToString::to_string) -} - -/// Wraps confstr to return a canonicalized PathBuf. -fn confstr_path(name: libc::c_int) -> Option { - let s = confstr(name)?; - let path = PathBuf::from(s); - path.canonicalize().ok().or(Some(path)) -} - -fn macos_dir_params() -> Vec<(String, PathBuf)> { - if let Some(p) = confstr_path(libc::_CS_DARWIN_USER_CACHE_DIR) { - return vec![("DARWIN_USER_CACHE_DIR".to_string(), p)]; - } - vec![] -} - -#[cfg(test)] -#[path = "seatbelt_tests.rs"] -mod tests; +pub(crate) use codex_sandbox::MACOS_PATH_TO_SEATBELT_EXECUTABLE; +pub(crate) use codex_sandbox::create_seatbelt_command_args_for_policies_with_extensions; +pub(crate) use codex_sandbox::spawn_command_under_seatbelt; diff --git a/codex-rs/core/src/spawn.rs b/codex-rs/core/src/spawn.rs index 575a2f777c..aa30900cbc 100644 --- a/codex-rs/core/src/spawn.rs +++ b/codex-rs/core/src/spawn.rs @@ -1,125 +1,3 @@ -use codex_network_proxy::NetworkProxy; -use std::collections::HashMap; -use std::path::PathBuf; -use std::process::Stdio; -use tokio::process::Child; -use tokio::process::Command; -use tracing::trace; - -use codex_protocol::permissions::NetworkSandboxPolicy; - -/// Experimental environment variable that will be set to some non-empty value -/// if both of the following are true: -/// -/// 1. The process was spawned by Codex as part of a shell tool call. -/// 2. NetworkSandboxPolicy is restricted for the tool call. -/// -/// We may try to have just one environment variable for all sandboxing -/// attributes, so this may change in the future. -pub const CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR: &str = "CODEX_SANDBOX_NETWORK_DISABLED"; - -/// Should be set when the process is spawned under a sandbox. Currently, the -/// value is "seatbelt" for macOS, but it may change in the future to -/// accommodate sandboxing configuration and other sandboxing mechanisms. -pub const CODEX_SANDBOX_ENV_VAR: &str = "CODEX_SANDBOX"; - -#[derive(Debug, Clone, Copy)] -pub enum StdioPolicy { - RedirectForShellTool, - Inherit, -} - -/// Spawns the appropriate child process for the ExecParams and SandboxPolicy, -/// ensuring the args and environment variables used to create the `Command` -/// (and `Child`) honor the configuration. -/// -/// For now, we take `NetworkSandboxPolicy` as a parameter to spawn_child() -/// because we need to determine whether to set the -/// `CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR` environment variable. -pub(crate) struct SpawnChildRequest<'a> { - pub program: PathBuf, - pub args: Vec, - pub arg0: Option<&'a str>, - pub cwd: PathBuf, - pub network_sandbox_policy: NetworkSandboxPolicy, - pub network: Option<&'a NetworkProxy>, - pub stdio_policy: StdioPolicy, - pub env: HashMap, -} - -pub(crate) async fn spawn_child_async(request: SpawnChildRequest<'_>) -> std::io::Result { - let SpawnChildRequest { - program, - args, - arg0, - cwd, - network_sandbox_policy, - network, - stdio_policy, - mut env, - } = request; - - trace!( - "spawn_child_async: {program:?} {args:?} {arg0:?} {cwd:?} {network_sandbox_policy:?} {stdio_policy:?} {env:?}" - ); - - let mut cmd = Command::new(&program); - #[cfg(unix)] - cmd.arg0(arg0.map_or_else(|| program.to_string_lossy().to_string(), String::from)); - cmd.args(args); - cmd.current_dir(cwd); - if let Some(network) = network { - network.apply_to_env(&mut env); - } - cmd.env_clear(); - cmd.envs(env); - - if !network_sandbox_policy.is_enabled() { - cmd.env(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR, "1"); - } - - // If this Codex process dies (including being killed via SIGKILL), we want - // any child processes that were spawned as part of a `"shell"` tool call - // to also be terminated. - - #[cfg(unix)] - unsafe { - let detach_from_tty = matches!(stdio_policy, StdioPolicy::RedirectForShellTool); - #[cfg(target_os = "linux")] - let parent_pid = libc::getpid(); - cmd.pre_exec(move || { - if detach_from_tty { - codex_utils_pty::process_group::detach_from_tty()?; - } - - // This relies on prctl(2), so it only works on Linux. - #[cfg(target_os = "linux")] - { - // This prctl call effectively requests, "deliver SIGTERM when my - // current parent dies." - codex_utils_pty::process_group::set_parent_death_signal(parent_pid)?; - } - Ok(()) - }); - } - - match stdio_policy { - StdioPolicy::RedirectForShellTool => { - // Do not create a file descriptor for stdin because otherwise some - // commands may hang forever waiting for input. For example, ripgrep has - // a heuristic where it may try to read from stdin as explained here: - // https://github.com/BurntSushi/ripgrep/blob/e2362d4d5185d02fa857bf381e7bd52e66fafc73/crates/core/flags/hiargs.rs#L1101-L1103 - cmd.stdin(Stdio::null()); - - cmd.stdout(Stdio::piped()).stderr(Stdio::piped()); - } - StdioPolicy::Inherit => { - // Inherit stdin, stdout, and stderr from the parent process. - cmd.stdin(Stdio::inherit()) - .stdout(Stdio::inherit()) - .stderr(Stdio::inherit()); - } - } - - cmd.kill_on_drop(true).spawn() -} +pub(crate) use codex_sandbox::CODEX_SANDBOX_ENV_VAR; +pub(crate) use codex_sandbox::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; +pub(crate) use codex_sandbox::StdioPolicy; diff --git a/codex-rs/core/src/windows_sandbox.rs b/codex-rs/core/src/windows_sandbox.rs index 1fdf3ee338..2277b42ea3 100644 --- a/codex-rs/core/src/windows_sandbox.rs +++ b/codex-rs/core/src/windows_sandbox.rs @@ -1,448 +1,17 @@ -use crate::config::Config; -use crate::config::ConfigToml; -use crate::config::edit::ConfigEditsBuilder; -use crate::config::profile::ConfigProfile; -use crate::config::types::WindowsSandboxModeToml; -use crate::default_client::originator; -use crate::protocol::SandboxPolicy; -use codex_features::Feature; -use codex_features::Features; -use codex_features::FeaturesToml; -use codex_otel::sanitize_metric_tag_value; -use codex_protocol::config_types::WindowsSandboxLevel; -use std::collections::BTreeMap; -use std::collections::HashMap; -use std::path::Path; -use std::path::PathBuf; -use std::time::Instant; - -/// Kill switch for the elevated sandbox NUX on Windows. -/// -/// When false, revert to the previous sandbox NUX, which only -/// prompts users to enable the legacy sandbox feature. -pub const ELEVATED_SANDBOX_NUX_ENABLED: bool = true; - -pub trait WindowsSandboxLevelExt { - fn from_config(config: &Config) -> WindowsSandboxLevel; - fn from_features(features: &Features) -> WindowsSandboxLevel; -} - -impl WindowsSandboxLevelExt for WindowsSandboxLevel { - fn from_config(config: &Config) -> WindowsSandboxLevel { - match config.permissions.windows_sandbox_mode { - Some(WindowsSandboxModeToml::Elevated) => WindowsSandboxLevel::Elevated, - Some(WindowsSandboxModeToml::Unelevated) => WindowsSandboxLevel::RestrictedToken, - None => Self::from_features(&config.features), - } - } - - fn from_features(features: &Features) -> WindowsSandboxLevel { - if features.enabled(Feature::WindowsSandboxElevated) { - return WindowsSandboxLevel::Elevated; - } - if features.enabled(Feature::WindowsSandbox) { - WindowsSandboxLevel::RestrictedToken - } else { - WindowsSandboxLevel::Disabled - } - } -} - -pub fn windows_sandbox_level_from_config(config: &Config) -> WindowsSandboxLevel { - WindowsSandboxLevel::from_config(config) -} - -pub fn windows_sandbox_level_from_features(features: &Features) -> WindowsSandboxLevel { - WindowsSandboxLevel::from_features(features) -} - -pub fn resolve_windows_sandbox_mode( - cfg: &ConfigToml, - profile: &ConfigProfile, -) -> Option { - if let Some(mode) = legacy_windows_sandbox_mode(profile.features.as_ref()) { - return Some(mode); - } - if legacy_windows_sandbox_keys_present(profile.features.as_ref()) { - return None; - } - - profile - .windows - .as_ref() - .and_then(|windows| windows.sandbox) - .or_else(|| cfg.windows.as_ref().and_then(|windows| windows.sandbox)) - .or_else(|| legacy_windows_sandbox_mode(cfg.features.as_ref())) -} - -pub fn resolve_windows_sandbox_private_desktop(cfg: &ConfigToml, profile: &ConfigProfile) -> bool { - profile - .windows - .as_ref() - .and_then(|windows| windows.sandbox_private_desktop) - .or_else(|| { - cfg.windows - .as_ref() - .and_then(|windows| windows.sandbox_private_desktop) - }) - .unwrap_or(true) -} - -fn legacy_windows_sandbox_keys_present(features: Option<&FeaturesToml>) -> bool { - let Some(entries) = features.map(|features| &features.entries) else { - return false; - }; - entries.contains_key(Feature::WindowsSandboxElevated.key()) - || entries.contains_key(Feature::WindowsSandbox.key()) - || entries.contains_key("enable_experimental_windows_sandbox") -} - -pub fn legacy_windows_sandbox_mode( - features: Option<&FeaturesToml>, -) -> Option { - let entries = features.map(|features| &features.entries)?; - legacy_windows_sandbox_mode_from_entries(entries) -} - -pub fn legacy_windows_sandbox_mode_from_entries( - entries: &BTreeMap, -) -> Option { - if entries - .get(Feature::WindowsSandboxElevated.key()) - .copied() - .unwrap_or(false) - { - return Some(WindowsSandboxModeToml::Elevated); - } - if entries - .get(Feature::WindowsSandbox.key()) - .copied() - .unwrap_or(false) - || entries - .get("enable_experimental_windows_sandbox") - .copied() - .unwrap_or(false) - { - Some(WindowsSandboxModeToml::Unelevated) - } else { - None - } -} - -#[cfg(target_os = "windows")] -pub fn sandbox_setup_is_complete(codex_home: &Path) -> bool { - codex_windows_sandbox::sandbox_setup_is_complete(codex_home) -} - -#[cfg(not(target_os = "windows"))] -pub fn sandbox_setup_is_complete(_codex_home: &Path) -> bool { - false -} - -#[cfg(target_os = "windows")] -pub fn elevated_setup_failure_details(err: &anyhow::Error) -> Option<(String, String)> { - let failure = codex_windows_sandbox::extract_setup_failure(err)?; - let code = failure.code.as_str().to_string(); - let message = codex_windows_sandbox::sanitize_setup_metric_tag_value(&failure.message); - Some((code, message)) -} - -#[cfg(not(target_os = "windows"))] -pub fn elevated_setup_failure_details(_err: &anyhow::Error) -> Option<(String, String)> { - None -} - -#[cfg(target_os = "windows")] -pub fn elevated_setup_failure_metric_name(err: &anyhow::Error) -> &'static str { - if codex_windows_sandbox::extract_setup_failure(err).is_some_and(|failure| { - matches!( - failure.code, - codex_windows_sandbox::SetupErrorCode::OrchestratorHelperLaunchCanceled - ) - }) { - "codex.windows_sandbox.elevated_setup_canceled" - } else { - "codex.windows_sandbox.elevated_setup_failure" - } -} - -#[cfg(not(target_os = "windows"))] -pub fn elevated_setup_failure_metric_name(_err: &anyhow::Error) -> &'static str { - panic!("elevated_setup_failure_metric_name is only supported on Windows") -} - -#[cfg(target_os = "windows")] -pub fn run_elevated_setup( - policy: &SandboxPolicy, - policy_cwd: &Path, - command_cwd: &Path, - env_map: &HashMap, - codex_home: &Path, -) -> anyhow::Result<()> { - codex_windows_sandbox::run_elevated_setup( - policy, - policy_cwd, - command_cwd, - env_map, - codex_home, - /*read_roots_override*/ None, - /*write_roots_override*/ None, - ) -} - -#[cfg(not(target_os = "windows"))] -pub fn run_elevated_setup( - _policy: &SandboxPolicy, - _policy_cwd: &Path, - _command_cwd: &Path, - _env_map: &HashMap, - _codex_home: &Path, -) -> anyhow::Result<()> { - anyhow::bail!("elevated Windows sandbox setup is only supported on Windows") -} - -#[cfg(target_os = "windows")] -pub fn run_legacy_setup_preflight( - policy: &SandboxPolicy, - policy_cwd: &Path, - command_cwd: &Path, - env_map: &HashMap, - codex_home: &Path, -) -> anyhow::Result<()> { - codex_windows_sandbox::run_windows_sandbox_legacy_preflight( - policy, - policy_cwd, - codex_home, - command_cwd, - env_map, - ) -} - -#[cfg(target_os = "windows")] -pub fn run_setup_refresh_with_extra_read_roots( - policy: &SandboxPolicy, - policy_cwd: &Path, - command_cwd: &Path, - env_map: &HashMap, - codex_home: &Path, - extra_read_roots: Vec, -) -> anyhow::Result<()> { - codex_windows_sandbox::run_setup_refresh_with_extra_read_roots( - policy, - policy_cwd, - command_cwd, - env_map, - codex_home, - extra_read_roots, - ) -} - -#[cfg(not(target_os = "windows"))] -pub fn run_legacy_setup_preflight( - _policy: &SandboxPolicy, - _policy_cwd: &Path, - _command_cwd: &Path, - _env_map: &HashMap, - _codex_home: &Path, -) -> anyhow::Result<()> { - anyhow::bail!("legacy Windows sandbox setup is only supported on Windows") -} - -#[cfg(not(target_os = "windows"))] -pub fn run_setup_refresh_with_extra_read_roots( - _policy: &SandboxPolicy, - _policy_cwd: &Path, - _command_cwd: &Path, - _env_map: &HashMap, - _codex_home: &Path, - _extra_read_roots: Vec, -) -> anyhow::Result<()> { - anyhow::bail!("Windows sandbox read-root refresh is only supported on Windows") -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum WindowsSandboxSetupMode { - Elevated, - Unelevated, -} - -#[derive(Debug, Clone)] -pub struct WindowsSandboxSetupRequest { - pub mode: WindowsSandboxSetupMode, - pub policy: SandboxPolicy, - pub policy_cwd: PathBuf, - pub command_cwd: PathBuf, - pub env_map: HashMap, - pub codex_home: PathBuf, - pub active_profile: Option, -} - -pub async fn run_windows_sandbox_setup(request: WindowsSandboxSetupRequest) -> anyhow::Result<()> { - let start = Instant::now(); - let mode = request.mode; - let originator_tag = sanitize_metric_tag_value(originator().value.as_str()); - let result = run_windows_sandbox_setup_and_persist(request).await; - - match result { - Ok(()) => { - emit_windows_sandbox_setup_success_metrics( - mode, - originator_tag.as_str(), - start.elapsed(), - ); - Ok(()) - } - Err(err) => { - emit_windows_sandbox_setup_failure_metrics( - mode, - originator_tag.as_str(), - start.elapsed(), - &err, - ); - Err(err) - } - } -} - -async fn run_windows_sandbox_setup_and_persist( - request: WindowsSandboxSetupRequest, -) -> anyhow::Result<()> { - let mode = request.mode; - let policy = request.policy; - let policy_cwd = request.policy_cwd; - let command_cwd = request.command_cwd; - let env_map = request.env_map; - let codex_home = request.codex_home; - let active_profile = request.active_profile; - let setup_codex_home = codex_home.clone(); - - let setup_result = tokio::task::spawn_blocking(move || -> anyhow::Result<()> { - match mode { - WindowsSandboxSetupMode::Elevated => { - if !sandbox_setup_is_complete(setup_codex_home.as_path()) { - run_elevated_setup( - &policy, - policy_cwd.as_path(), - command_cwd.as_path(), - &env_map, - setup_codex_home.as_path(), - )?; - } - } - WindowsSandboxSetupMode::Unelevated => { - run_legacy_setup_preflight( - &policy, - policy_cwd.as_path(), - command_cwd.as_path(), - &env_map, - setup_codex_home.as_path(), - )?; - } - } - Ok(()) - }) - .await - .map_err(|join_err| anyhow::anyhow!("windows sandbox setup task failed: {join_err}"))?; - - setup_result?; - - ConfigEditsBuilder::new(codex_home.as_path()) - .with_profile(active_profile.as_deref()) - .set_windows_sandbox_mode(windows_sandbox_setup_mode_tag(mode)) - .clear_legacy_windows_sandbox_keys() - .apply() - .await - .map_err(|err| anyhow::anyhow!("failed to persist windows sandbox mode: {err}")) -} - -fn emit_windows_sandbox_setup_success_metrics( - mode: WindowsSandboxSetupMode, - originator_tag: &str, - duration: std::time::Duration, -) { - let Some(metrics) = codex_otel::metrics::global() else { - return; - }; - let mode_tag = windows_sandbox_setup_mode_tag(mode); - let _ = metrics.record_duration( - "codex.windows_sandbox.setup_duration_ms", - duration, - &[ - ("result", "success"), - ("originator", originator_tag), - ("mode", mode_tag), - ], - ); - let _ = metrics.counter( - "codex.windows_sandbox.setup_success", - /*inc*/ 1, - &[("originator", originator_tag), ("mode", mode_tag)], - ); -} - -fn emit_windows_sandbox_setup_failure_metrics( - mode: WindowsSandboxSetupMode, - originator_tag: &str, - duration: std::time::Duration, - _err: &anyhow::Error, -) { - let Some(metrics) = codex_otel::metrics::global() else { - return; - }; - let mode_tag = windows_sandbox_setup_mode_tag(mode); - let _ = metrics.record_duration( - "codex.windows_sandbox.setup_duration_ms", - duration, - &[ - ("result", "failure"), - ("originator", originator_tag), - ("mode", mode_tag), - ], - ); - let _ = metrics.counter( - "codex.windows_sandbox.setup_failure", - /*inc*/ 1, - &[("originator", originator_tag), ("mode", mode_tag)], - ); - - if matches!(mode, WindowsSandboxSetupMode::Elevated) { - #[cfg(target_os = "windows")] - { - let mut failure_tags: Vec<(&str, &str)> = vec![("originator", originator_tag)]; - let mut code_tag: Option = None; - let mut message_tag: Option = None; - if let Some((code, message)) = elevated_setup_failure_details(_err) { - code_tag = Some(code); - message_tag = Some(message); - } - if let Some(code) = code_tag.as_deref() { - failure_tags.push(("code", code)); - } - if let Some(message) = message_tag.as_deref() { - failure_tags.push(("message", message)); - } - let _ = metrics.counter( - elevated_setup_failure_metric_name(_err), - /*inc*/ 1, - &failure_tags, - ); - } - } else { - let _ = metrics.counter( - "codex.windows_sandbox.legacy_setup_preflight_failed", - /*inc*/ 1, - &[("originator", originator_tag)], - ); - } -} - -fn windows_sandbox_setup_mode_tag(mode: WindowsSandboxSetupMode) -> &'static str { - match mode { - WindowsSandboxSetupMode::Elevated => "elevated", - WindowsSandboxSetupMode::Unelevated => "unelevated", - } -} - -#[cfg(test)] -#[path = "windows_sandbox_tests.rs"] -mod tests; +pub(crate) use codex_sandbox::ELEVATED_SANDBOX_NUX_ENABLED; +pub(crate) use codex_sandbox::WindowsSandboxLevelExt; +pub(crate) use codex_sandbox::WindowsSandboxMode; +pub(crate) use codex_sandbox::WindowsSandboxSetupMode; +pub(crate) use codex_sandbox::WindowsSandboxSetupRequest; +pub(crate) use codex_sandbox::elevated_setup_failure_details; +pub(crate) use codex_sandbox::elevated_setup_failure_metric_name; +pub(crate) use codex_sandbox::legacy_windows_sandbox_mode; +pub(crate) use codex_sandbox::legacy_windows_sandbox_mode_from_entries; +pub(crate) use codex_sandbox::resolve_windows_sandbox_mode; +pub(crate) use codex_sandbox::resolve_windows_sandbox_private_desktop; +pub(crate) use codex_sandbox::run_elevated_setup; +pub(crate) use codex_sandbox::run_legacy_setup_preflight; +pub(crate) use codex_sandbox::run_setup_refresh_with_extra_read_roots; +pub(crate) use codex_sandbox::run_windows_sandbox_setup; +pub(crate) use codex_sandbox::sandbox_setup_is_complete; +pub(crate) use codex_sandbox::windows_sandbox_mode_tag; diff --git a/codex-rs/core/src/windows_sandbox_read_grants.rs b/codex-rs/core/src/windows_sandbox_read_grants.rs index ec08e55cfd..2e6ae90e5a 100644 --- a/codex-rs/core/src/windows_sandbox_read_grants.rs +++ b/codex-rs/core/src/windows_sandbox_read_grants.rs @@ -1,40 +1 @@ -use crate::protocol::SandboxPolicy; -use crate::windows_sandbox::run_setup_refresh_with_extra_read_roots; -use anyhow::Result; -use std::collections::HashMap; -use std::path::Path; -use std::path::PathBuf; - -pub fn grant_read_root_non_elevated( - policy: &SandboxPolicy, - policy_cwd: &Path, - command_cwd: &Path, - env_map: &HashMap, - codex_home: &Path, - read_root: &Path, -) -> Result { - if !read_root.is_absolute() { - anyhow::bail!("path must be absolute: {}", read_root.display()); - } - if !read_root.exists() { - anyhow::bail!("path does not exist: {}", read_root.display()); - } - if !read_root.is_dir() { - anyhow::bail!("path must be a directory: {}", read_root.display()); - } - - let canonical_root = dunce::canonicalize(read_root)?; - run_setup_refresh_with_extra_read_roots( - policy, - policy_cwd, - command_cwd, - env_map, - codex_home, - vec![canonical_root.clone()], - )?; - Ok(canonical_root) -} - -#[cfg(test)] -#[path = "windows_sandbox_read_grants_tests.rs"] -mod tests; +pub(crate) use codex_sandbox::grant_read_root_non_elevated; diff --git a/codex-rs/core/tests/common/lib.rs b/codex-rs/core/tests/common/lib.rs index 6209ded404..b456b582e6 100644 --- a/codex-rs/core/tests/common/lib.rs +++ b/codex-rs/core/tests/common/lib.rs @@ -282,11 +282,11 @@ where } pub fn sandbox_env_var() -> &'static str { - codex_core::spawn::CODEX_SANDBOX_ENV_VAR + codex_sandbox::CODEX_SANDBOX_ENV_VAR } pub fn sandbox_network_env_var() -> &'static str { - codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR + codex_sandbox::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR } pub fn format_with_current_shell(command: &str) -> Vec { diff --git a/codex-rs/core/tests/suite/approvals.rs b/codex-rs/core/tests/suite/approvals.rs index f77697d017..1b2077f8f4 100644 --- a/codex-rs/core/tests/suite/approvals.rs +++ b/codex-rs/core/tests/suite/approvals.rs @@ -9,7 +9,6 @@ use codex_core::config_loader::NetworkConstraints; use codex_core::config_loader::NetworkRequirementsToml; use codex_core::config_loader::RequirementSource; use codex_core::config_loader::Sourced; -use codex_core::sandboxing::SandboxPermissions; use codex_features::Feature; use codex_protocol::approvals::NetworkApprovalProtocol; use codex_protocol::approvals::NetworkPolicyAmendment; @@ -23,6 +22,7 @@ use codex_protocol::protocol::Op; use codex_protocol::protocol::ReviewDecision; use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; +use codex_sandbox::SandboxPermissions; use core_test_support::responses::ev_apply_patch_function_call; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; diff --git a/codex-rs/core/tests/suite/codex_delegate.rs b/codex-rs/core/tests/suite/codex_delegate.rs index e71d99b620..cf646459a8 100644 --- a/codex-rs/core/tests/suite/codex_delegate.rs +++ b/codex-rs/core/tests/suite/codex_delegate.rs @@ -1,5 +1,4 @@ use codex_core::config::Constrained; -use codex_core::sandboxing::SandboxPermissions; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; @@ -7,6 +6,7 @@ use codex_protocol::protocol::ReviewDecision; use codex_protocol::protocol::ReviewRequest; use codex_protocol::protocol::ReviewTarget; use codex_protocol::protocol::SandboxPolicy; +use codex_sandbox::SandboxPermissions; use core_test_support::responses::ev_apply_patch_function_call; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; diff --git a/codex-rs/core/tests/suite/compact_resume_fork.rs b/codex-rs/core/tests/suite/compact_resume_fork.rs index fafbced0b7..c9a446133a 100644 --- a/codex-rs/core/tests/suite/compact_resume_fork.rs +++ b/codex-rs/core/tests/suite/compact_resume_fork.rs @@ -15,11 +15,11 @@ use codex_core::CodexThread; use codex_core::ThreadManager; use codex_core::compact::SUMMARIZATION_PROMPT; use codex_core::config::Config; -use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; use codex_protocol::protocol::WarningEvent; use codex_protocol::user_input::UserInput; +use codex_sandbox::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; use core_test_support::context_snapshot; use core_test_support::context_snapshot::ContextSnapshotOptions; use core_test_support::context_snapshot::ContextSnapshotRenderMode; diff --git a/codex-rs/core/tests/suite/exec.rs b/codex-rs/core/tests/suite/exec.rs index 069e824ee5..e55fcfd947 100644 --- a/codex-rs/core/tests/suite/exec.rs +++ b/codex-rs/core/tests/suite/exec.rs @@ -3,23 +3,21 @@ use std::collections::HashMap; use std::string::ToString; -use codex_core::exec::ExecCapturePolicy; -use codex_core::exec::ExecParams; -use codex_core::exec::ExecToolCallOutput; -use codex_core::exec::SandboxType; -use codex_core::exec::process_exec_tool_call; -use codex_core::sandboxing::SandboxPermissions; -use codex_core::spawn::CODEX_SANDBOX_ENV_VAR; use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::permissions::FileSystemSandboxPolicy; use codex_protocol::permissions::NetworkSandboxPolicy; use codex_protocol::protocol::SandboxPolicy; +use codex_sandbox::CODEX_SANDBOX_ENV_VAR; +use codex_sandbox::ExecCapturePolicy; +use codex_sandbox::ExecParams; +use codex_sandbox::ExecToolCallOutput; +use codex_sandbox::SandboxPermissions; +use codex_sandbox::SandboxType; +use codex_sandbox::error::Result; +use codex_sandbox::get_platform_sandbox; +use codex_sandbox::process_exec_tool_call; use tempfile::TempDir; -use codex_core::error::Result; - -use codex_core::get_platform_sandbox; - fn skip_test() -> bool { if std::env::var(CODEX_SANDBOX_ENV_VAR) == Ok("seatbelt".to_string()) { eprintln!("{CODEX_SANDBOX_ENV_VAR} is set to 'seatbelt', skipping test."); diff --git a/codex-rs/core/tests/suite/request_permissions.rs b/codex-rs/core/tests/suite/request_permissions.rs index b1aaac65b4..9df09745ad 100644 --- a/codex-rs/core/tests/suite/request_permissions.rs +++ b/codex-rs/core/tests/suite/request_permissions.rs @@ -2,7 +2,6 @@ use anyhow::Result; use codex_core::config::Constrained; -use codex_core::sandboxing::SandboxPermissions; use codex_features::Feature; use codex_protocol::models::FileSystemPermissions; use codex_protocol::models::PermissionProfile; @@ -17,6 +16,7 @@ use codex_protocol::request_permissions::PermissionGrantScope; use codex_protocol::request_permissions::RequestPermissionProfile; use codex_protocol::request_permissions::RequestPermissionsResponse; use codex_protocol::user_input::UserInput; +use codex_sandbox::SandboxPermissions; use codex_utils_absolute_path::AbsolutePathBuf; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; diff --git a/codex-rs/core/tests/suite/seatbelt.rs b/codex-rs/core/tests/suite/seatbelt.rs index cfb91caeed..12f936a42e 100644 --- a/codex-rs/core/tests/suite/seatbelt.rs +++ b/codex-rs/core/tests/suite/seatbelt.rs @@ -7,10 +7,10 @@ use std::collections::HashMap; use std::path::Path; use std::path::PathBuf; -use codex_core::seatbelt::spawn_command_under_seatbelt; -use codex_core::spawn::CODEX_SANDBOX_ENV_VAR; -use codex_core::spawn::StdioPolicy; use codex_protocol::protocol::SandboxPolicy; +use codex_sandbox::CODEX_SANDBOX_ENV_VAR; +use codex_sandbox::StdioPolicy; +use codex_sandbox::spawn_command_under_seatbelt; use tempfile::TempDir; struct TestScenario { diff --git a/codex-rs/core/tests/suite/text_encoding_fix.rs b/codex-rs/core/tests/suite/text_encoding_fix.rs index ecebb1e429..6451fa4ffb 100644 --- a/codex-rs/core/tests/suite/text_encoding_fix.rs +++ b/codex-rs/core/tests/suite/text_encoding_fix.rs @@ -3,7 +3,7 @@ //! These tests simulate VSCode's shell preview on Windows/WSL where the output //! may be encoded with a legacy code page before it reaches Codex. -use codex_core::exec::StreamOutput; +use codex_sandbox::StreamOutput; use pretty_assertions::assert_eq; #[test] diff --git a/codex-rs/core/tests/suite/tools.rs b/codex-rs/core/tests/suite/tools.rs index af8d70f220..19fee167f5 100644 --- a/codex-rs/core/tests/suite/tools.rs +++ b/codex-rs/core/tests/suite/tools.rs @@ -7,10 +7,10 @@ use std::time::Instant; use anyhow::Context; use anyhow::Result; -use codex_core::sandboxing::SandboxPermissions; use codex_features::Feature; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::SandboxPolicy; +use codex_sandbox::SandboxPermissions; use core_test_support::assert_regex_match; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; diff --git a/codex-rs/exec/Cargo.toml b/codex-rs/exec/Cargo.toml index 3785235606..cc9a64bf8c 100644 --- a/codex-rs/exec/Cargo.toml +++ b/codex-rs/exec/Cargo.toml @@ -26,6 +26,7 @@ codex-core = { workspace = true } codex-feedback = { workspace = true } codex-otel = { workspace = true } codex-protocol = { workspace = true } +codex-sandbox = { workspace = true } codex-utils-absolute-path = { workspace = true } codex-utils-cli = { workspace = true } codex-utils-elapsed = { workspace = true } diff --git a/codex-rs/exec/tests/suite/sandbox.rs b/codex-rs/exec/tests/suite/sandbox.rs index e6dd37927b..a104d8fd4b 100644 --- a/codex-rs/exec/tests/suite/sandbox.rs +++ b/codex-rs/exec/tests/suite/sandbox.rs @@ -1,6 +1,10 @@ #![cfg(unix)] -use codex_core::spawn::StdioPolicy; use codex_protocol::protocol::SandboxPolicy; +use codex_sandbox::StdioPolicy; +#[cfg(target_os = "linux")] +use codex_sandbox::spawn_command_under_linux_sandbox; +#[cfg(target_os = "macos")] +use codex_sandbox::spawn_command_under_seatbelt; use codex_utils_absolute_path::AbsolutePathBuf; use std::collections::HashMap; use std::future::Future; @@ -20,7 +24,6 @@ async fn spawn_command_under_sandbox( stdio_policy: StdioPolicy, env: HashMap, ) -> std::io::Result { - use codex_core::seatbelt::spawn_command_under_seatbelt; spawn_command_under_seatbelt( command, command_cwd, @@ -42,7 +45,6 @@ async fn spawn_command_under_sandbox( stdio_policy: StdioPolicy, env: HashMap, ) -> std::io::Result { - use codex_core::landlock::spawn_command_under_linux_sandbox; let codex_linux_sandbox_exe = codex_utils_cargo_bin::cargo_bin("codex-exec") .map_err(|err| io::Error::new(io::ErrorKind::NotFound, err))?; spawn_command_under_linux_sandbox( diff --git a/codex-rs/linux-sandbox/Cargo.toml b/codex-rs/linux-sandbox/Cargo.toml index 88da2d7479..060274ba82 100644 --- a/codex-rs/linux-sandbox/Cargo.toml +++ b/codex-rs/linux-sandbox/Cargo.toml @@ -17,8 +17,8 @@ workspace = true [target.'cfg(target_os = "linux")'.dependencies] clap = { workspace = true, features = ["derive"] } -codex-core = { workspace = true } codex-protocol = { workspace = true } +codex-sandbox = { workspace = true } codex-utils-absolute-path = { workspace = true } landlock = { workspace = true } libc = { workspace = true } diff --git a/codex-rs/linux-sandbox/src/bwrap.rs b/codex-rs/linux-sandbox/src/bwrap.rs index 05e7b58e2c..3bfd0ddbac 100644 --- a/codex-rs/linux-sandbox/src/bwrap.rs +++ b/codex-rs/linux-sandbox/src/bwrap.rs @@ -16,8 +16,8 @@ use std::os::fd::AsRawFd; use std::path::Path; use std::path::PathBuf; -use codex_core::error::Result; use codex_protocol::protocol::FileSystemSandboxPolicy; +use codex_sandbox::error::Result; use codex_utils_absolute_path::AbsolutePathBuf; /// Linux "platform defaults" that keep common system binaries and dynamic diff --git a/codex-rs/linux-sandbox/src/landlock.rs b/codex-rs/linux-sandbox/src/landlock.rs index 307f956a4d..b361f9e061 100644 --- a/codex-rs/linux-sandbox/src/landlock.rs +++ b/codex-rs/linux-sandbox/src/landlock.rs @@ -5,11 +5,11 @@ use std::collections::BTreeMap; use std::path::Path; -use codex_core::error::CodexErr; -use codex_core::error::Result; -use codex_core::error::SandboxErr; use codex_protocol::protocol::NetworkSandboxPolicy; use codex_protocol::protocol::SandboxPolicy; +use codex_sandbox::error::CodexErr; +use codex_sandbox::error::Result; +use codex_sandbox::error::SandboxErr; use codex_utils_absolute_path::AbsolutePathBuf; use landlock::ABI; diff --git a/codex-rs/linux-sandbox/tests/suite/landlock.rs b/codex-rs/linux-sandbox/tests/suite/landlock.rs index 8e273783b8..3426136b0b 100644 --- a/codex-rs/linux-sandbox/tests/suite/landlock.rs +++ b/codex-rs/linux-sandbox/tests/suite/landlock.rs @@ -1,14 +1,7 @@ #![cfg(target_os = "linux")] #![allow(clippy::unwrap_used)] use codex_core::config::types::ShellEnvironmentPolicy; -use codex_core::error::CodexErr; -use codex_core::error::Result; -use codex_core::error::SandboxErr; -use codex_core::exec::ExecCapturePolicy; -use codex_core::exec::ExecParams; -use codex_core::exec::process_exec_tool_call; use codex_core::exec_env::create_env; -use codex_core::sandboxing::SandboxPermissions; use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::permissions::FileSystemAccessMode; use codex_protocol::permissions::FileSystemPath; @@ -18,6 +11,14 @@ use codex_protocol::permissions::FileSystemSpecialPath; use codex_protocol::permissions::NetworkSandboxPolicy; use codex_protocol::protocol::ReadOnlyAccess; use codex_protocol::protocol::SandboxPolicy; +use codex_sandbox::ExecCapturePolicy; +use codex_sandbox::ExecParams; +use codex_sandbox::ExecToolCallOutput; +use codex_sandbox::SandboxPermissions; +use codex_sandbox::error::CodexErr; +use codex_sandbox::error::Result; +use codex_sandbox::error::SandboxErr; +use codex_sandbox::process_exec_tool_call; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; use std::collections::HashMap; @@ -63,7 +64,7 @@ async fn run_cmd_output( cmd: &[&str], writable_roots: &[PathBuf], timeout_ms: u64, -) -> codex_core::exec::ExecToolCallOutput { +) -> ExecToolCallOutput { run_cmd_result_with_writable_roots(cmd, writable_roots, timeout_ms, false, false) .await .expect("sandboxed command should execute") @@ -75,7 +76,7 @@ async fn run_cmd_result_with_writable_roots( timeout_ms: u64, use_legacy_landlock: bool, network_access: bool, -) -> Result { +) -> Result { let sandbox_policy = SandboxPolicy::WorkspaceWrite { writable_roots: writable_roots .iter() @@ -110,7 +111,7 @@ async fn run_cmd_result_with_policies( network_sandbox_policy: NetworkSandboxPolicy, timeout_ms: u64, use_legacy_landlock: bool, -) -> Result { +) -> Result { let cwd = std::env::current_dir().expect("cwd should exist"); let sandbox_cwd = cwd.clone(); let params = ExecParams { @@ -142,7 +143,7 @@ async fn run_cmd_result_with_policies( .await } -fn is_bwrap_unavailable_output(output: &codex_core::exec::ExecToolCallOutput) -> bool { +fn is_bwrap_unavailable_output(output: &ExecToolCallOutput) -> bool { output.stderr.text.contains(BWRAP_UNAVAILABLE_ERR) || (output .stderr @@ -174,10 +175,7 @@ async fn should_skip_bwrap_tests() -> bool { } } -fn expect_denied( - result: Result, - context: &str, -) -> codex_core::exec::ExecToolCallOutput { +fn expect_denied(result: Result, context: &str) -> ExecToolCallOutput { match result { Ok(output) => { assert_ne!(output.exit_code, 0, "{context}: expected nonzero exit code"); diff --git a/codex-rs/lmstudio/Cargo.toml b/codex-rs/lmstudio/Cargo.toml index 5f4849638a..e2e258a090 100644 --- a/codex-rs/lmstudio/Cargo.toml +++ b/codex-rs/lmstudio/Cargo.toml @@ -11,6 +11,7 @@ path = "src/lib.rs" [dependencies] codex-core = { path = "../core" } +codex-sandbox = { workspace = true } reqwest = { version = "0.12", features = ["json", "stream"] } serde_json = "1" tokio = { version = "1", features = ["rt"] } diff --git a/codex-rs/lmstudio/src/client.rs b/codex-rs/lmstudio/src/client.rs index 1d0c04c1ac..7c7a6b945b 100644 --- a/codex-rs/lmstudio/src/client.rs +++ b/codex-rs/lmstudio/src/client.rs @@ -1,5 +1,6 @@ use codex_core::LMSTUDIO_OSS_PROVIDER_ID; use codex_core::config::Config; +use codex_sandbox::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; use std::io; use std::path::Path; @@ -210,10 +211,10 @@ mod tests { #[tokio::test] async fn test_fetch_models_happy_path() { - if std::env::var(codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { + if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { tracing::info!( "{} is set; skipping test_fetch_models_happy_path", - codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR + CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR ); return; } @@ -242,10 +243,10 @@ mod tests { #[tokio::test] async fn test_fetch_models_no_data_array() { - if std::env::var(codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { + if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { tracing::info!( "{} is set; skipping test_fetch_models_no_data_array", - codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR + CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR ); return; } @@ -273,10 +274,10 @@ mod tests { #[tokio::test] async fn test_fetch_models_server_error() { - if std::env::var(codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { + if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { tracing::info!( "{} is set; skipping test_fetch_models_server_error", - codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR + CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR ); return; } @@ -301,10 +302,10 @@ mod tests { #[tokio::test] async fn test_check_server_happy_path() { - if std::env::var(codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { + if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { tracing::info!( "{} is set; skipping test_check_server_happy_path", - codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR + CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR ); return; } @@ -325,10 +326,10 @@ mod tests { #[tokio::test] async fn test_check_server_error() { - if std::env::var(codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { + if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { tracing::info!( "{} is set; skipping test_check_server_error", - codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR + CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR ); return; } diff --git a/codex-rs/mcp-server/Cargo.toml b/codex-rs/mcp-server/Cargo.toml index 4c05f27c10..cc2f3c4769 100644 --- a/codex-rs/mcp-server/Cargo.toml +++ b/codex-rs/mcp-server/Cargo.toml @@ -21,6 +21,7 @@ codex-arg0 = { workspace = true } codex-core = { workspace = true } codex-features = { workspace = true } codex-protocol = { workspace = true } +codex-sandbox = { workspace = true } codex-shell-command = { workspace = true } codex-utils-cli = { workspace = true } codex-utils-json-to-toml = { workspace = true } diff --git a/codex-rs/mcp-server/tests/suite/codex_tool.rs b/codex-rs/mcp-server/tests/suite/codex_tool.rs index c6df62dbf1..b3ecd3bc8e 100644 --- a/codex-rs/mcp-server/tests/suite/codex_tool.rs +++ b/codex-rs/mcp-server/tests/suite/codex_tool.rs @@ -3,7 +3,6 @@ use std::env; use std::path::Path; use std::path::PathBuf; -use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; use codex_mcp_server::CodexToolCallParam; use codex_mcp_server::ExecApprovalElicitRequestParams; use codex_mcp_server::ExecApprovalResponse; @@ -11,6 +10,7 @@ use codex_mcp_server::PatchApprovalElicitRequestParams; use codex_mcp_server::PatchApprovalResponse; use codex_protocol::protocol::FileChange; use codex_protocol::protocol::ReviewDecision; +use codex_sandbox::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; use codex_shell_command::parse_command; use pretty_assertions::assert_eq; use rmcp::model::JsonRpcResponse; diff --git a/codex-rs/ollama/Cargo.toml b/codex-rs/ollama/Cargo.toml index 56e8d6e5d8..f022633516 100644 --- a/codex-rs/ollama/Cargo.toml +++ b/codex-rs/ollama/Cargo.toml @@ -15,6 +15,7 @@ workspace = true async-stream = { workspace = true } bytes = { workspace = true } codex-core = { workspace = true } +codex-sandbox = { workspace = true } futures = { workspace = true } reqwest = { workspace = true, features = ["json", "stream"] } semver = { workspace = true } diff --git a/codex-rs/ollama/src/client.rs b/codex-rs/ollama/src/client.rs index a0ab2d04fb..0343d3bd7d 100644 --- a/codex-rs/ollama/src/client.rs +++ b/codex-rs/ollama/src/client.rs @@ -14,6 +14,7 @@ use crate::url::is_openai_compatible_base_url; use codex_core::ModelProviderInfo; use codex_core::OLLAMA_OSS_PROVIDER_ID; use codex_core::config::Config; +use codex_sandbox::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; const OLLAMA_CONNECTION_ERROR: &str = "No running Ollama server detected. Start it with: `ollama serve` (after installing). Install instructions: https://github.com/ollama/ollama?tab=readme-ov-file#ollama"; @@ -265,10 +266,10 @@ mod tests { // Happy-path tests using a mock HTTP server; skip if sandbox network is disabled. #[tokio::test] async fn test_fetch_models_happy_path() { - if std::env::var(codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { + if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { tracing::info!( "{} is set; skipping test_fetch_models_happy_path", - codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR + CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR ); return; } @@ -296,10 +297,10 @@ mod tests { #[tokio::test] async fn test_fetch_version() { - if std::env::var(codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { + if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { tracing::info!( "{} is set; skipping test_fetch_version", - codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR + CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR ); return; } @@ -332,10 +333,10 @@ mod tests { #[tokio::test] async fn test_probe_server_happy_path_openai_compat_and_native() { - if std::env::var(codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { + if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { tracing::info!( "{} set; skipping test_probe_server_happy_path_openai_compat_and_native", - codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR + CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR ); return; } @@ -369,10 +370,10 @@ mod tests { #[tokio::test] async fn test_try_from_oss_provider_ok_when_server_running() { - if std::env::var(codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { + if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { tracing::info!( "{} set; skipping test_try_from_oss_provider_ok_when_server_running", - codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR + CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR ); return; } @@ -393,10 +394,10 @@ mod tests { #[tokio::test] async fn test_try_from_oss_provider_err_when_server_missing() { - if std::env::var(codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { + if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { tracing::info!( "{} set; skipping test_try_from_oss_provider_err_when_server_missing", - codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR + CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR ); return; } diff --git a/codex-rs/sandbox/BUILD.bazel b/codex-rs/sandbox/BUILD.bazel new file mode 100644 index 0000000000..e54ce00a1e --- /dev/null +++ b/codex-rs/sandbox/BUILD.bazel @@ -0,0 +1,16 @@ +load("//:defs.bzl", "codex_rust_crate") + +codex_rust_crate( + name = "sandbox", + crate_name = "codex_sandbox", + compile_data = glob( + include = ["**"], + exclude = [ + "**/* *", + "BUILD.bazel", + "Cargo.toml", + ], + allow_empty = True, + ), + test_tags = ["no-sandbox"], +) diff --git a/codex-rs/sandbox/Cargo.toml b/codex-rs/sandbox/Cargo.toml new file mode 100644 index 0000000000..7cad7462e2 --- /dev/null +++ b/codex-rs/sandbox/Cargo.toml @@ -0,0 +1,58 @@ +[package] +edition.workspace = true +license.workspace = true +name = "codex-sandbox" +version.workspace = true + +[lib] +doctest = false +name = "codex_sandbox" +path = "src/lib.rs" + +[lints] +workspace = true + +[dependencies] +anyhow = { workspace = true } +async-channel = { workspace = true } +chardetng = { workspace = true } +codex-features = { workspace = true } +codex-network-proxy = { workspace = true } +codex-otel = { workspace = true } +codex-protocol = { workspace = true } +codex-utils-absolute-path = { workspace = true } +codex-utils-home-dir = { workspace = true } +codex-utils-pty = { workspace = true } +codex-windows-sandbox = { workspace = true } +dirs = { workspace = true } +dunce = { workspace = true } +encoding_rs = { workspace = true } +libc = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +thiserror = { workspace = true } +tokio = { workspace = true, features = [ + "io-std", + "macros", + "process", + "rt-multi-thread", + "signal", +] } +tokio-util = { workspace = true, features = ["rt"] } +tracing = { workspace = true, features = ["log"] } +url = { workspace = true } + +[target.'cfg(target_os = "linux")'.dependencies] +landlock = { workspace = true } +seccompiler = { workspace = true } + +[dev-dependencies] +pretty_assertions = { workspace = true } +tempfile = { workspace = true } +tokio = { workspace = true, features = [ + "io-std", + "macros", + "process", + "rt-multi-thread", + "signal", +] } diff --git a/codex-rs/sandbox/src/error.rs b/codex-rs/sandbox/src/error.rs new file mode 100644 index 0000000000..0c14635d50 --- /dev/null +++ b/codex-rs/sandbox/src/error.rs @@ -0,0 +1,53 @@ +use crate::exec::ExecToolCallOutput; +use thiserror::Error; + +pub type Result = std::result::Result; + +#[derive(Error, Debug)] +pub enum SandboxErr { + #[error( + "sandbox denied exec error, exit code: {}, stdout: {}, stderr: {}", + .output.exit_code, .output.stdout.text, .output.stderr.text + )] + Denied { output: Box }, + + #[cfg(target_os = "linux")] + #[error("seccomp setup error")] + SeccompInstall(#[from] seccompiler::Error), + + #[cfg(target_os = "linux")] + #[error("seccomp backend error")] + SeccompBackend(#[from] seccompiler::BackendError), + + #[error("command timed out")] + Timeout { output: Box }, + + #[error("command was killed by a signal")] + Signal(i32), + + #[error("Landlock was not able to fully enforce all sandbox rules")] + LandlockRestrict, +} + +#[derive(Error, Debug)] +pub enum CodexErr { + #[error("sandbox error: {0}")] + Sandbox(#[from] SandboxErr), + + #[error("codex-linux-sandbox was required but not provided")] + LandlockSandboxExecutableNotProvided, + + #[error("unsupported operation: {0}")] + UnsupportedOperation(String), + + #[error(transparent)] + Io(#[from] std::io::Error), + + #[cfg(target_os = "linux")] + #[error(transparent)] + LandlockRuleset(#[from] landlock::RulesetError), + + #[cfg(target_os = "linux")] + #[error(transparent)] + LandlockPathFd(#[from] landlock::PathFdError), +} diff --git a/codex-rs/sandbox/src/exec.rs b/codex-rs/sandbox/src/exec.rs new file mode 100644 index 0000000000..4c7eff1a63 --- /dev/null +++ b/codex-rs/sandbox/src/exec.rs @@ -0,0 +1,1090 @@ +#[cfg(unix)] +use std::os::unix::process::ExitStatusExt; + +use std::collections::HashMap; +use std::io; +use std::path::Path; +use std::path::PathBuf; +use std::process::ExitStatus; +use std::time::Duration; +use std::time::Instant; + +use async_channel::Sender; +use tokio::io::AsyncRead; +use tokio::io::AsyncReadExt; +use tokio::io::BufReader; +use tokio::process::Child; +use tokio_util::sync::CancellationToken; + +use crate::SandboxPreference; +use crate::error::CodexErr; +use crate::error::Result; +use crate::error::SandboxErr; +use crate::protocol::Event; +use crate::protocol::EventMsg; +use crate::protocol::ExecCommandOutputDeltaEvent; +use crate::protocol::ExecOutputStream; +use crate::protocol::SandboxPolicy; +use crate::sandboxing::CommandSpec; +use crate::sandboxing::ExecRequest; +use crate::sandboxing::SandboxManager; +use crate::sandboxing::SandboxPermissions; +use crate::spawn::SpawnChildRequest; +use crate::spawn::StdioPolicy; +use crate::spawn::spawn_child_async; +use crate::text_encoding::bytes_to_string_smart; +use codex_network_proxy::NetworkProxy; +#[cfg(any(target_os = "windows", test))] +use codex_protocol::permissions::FileSystemSandboxKind; +use codex_protocol::permissions::FileSystemSandboxPolicy; +use codex_protocol::permissions::NetworkSandboxPolicy; +use codex_utils_pty::DEFAULT_OUTPUT_BYTES_CAP; +use codex_utils_pty::process_group::kill_child_process_group; + +pub const DEFAULT_EXEC_COMMAND_TIMEOUT_MS: u64 = 10_000; + +// Hardcode these since it does not seem worth including the libc crate just +// for these. +const SIGKILL_CODE: i32 = 9; +const TIMEOUT_CODE: i32 = 64; +const EXIT_CODE_SIGNAL_BASE: i32 = 128; // conventional shell: 128 + signal +const EXEC_TIMEOUT_EXIT_CODE: i32 = 124; // conventional timeout exit code + +// I/O buffer sizing +const READ_CHUNK_SIZE: usize = 8192; // bytes per read +const AGGREGATE_BUFFER_INITIAL_CAPACITY: usize = 8 * 1024; // 8 KiB + +/// Hard cap on bytes retained from exec stdout/stderr/aggregated output. +/// +/// This mirrors unified exec's output cap so a single runaway command cannot +/// OOM the process by dumping huge amounts of data to stdout/stderr. +const EXEC_OUTPUT_MAX_BYTES: usize = DEFAULT_OUTPUT_BYTES_CAP; + +/// Limit the number of ExecCommandOutputDelta events emitted per exec call. +/// Aggregation still collects full output; only the live event stream is capped. +pub const MAX_EXEC_OUTPUT_DELTAS_PER_CALL: usize = 10_000; + +// Wait for the stdout/stderr collection tasks but guard against them +// hanging forever. In the normal case, both pipes are closed once the child +// terminates so the tasks exit quickly. However, if the child process +// spawned grandchildren that inherited its stdout/stderr file descriptors +// those pipes may stay open after we `kill` the direct child on timeout. +// That would cause the `read_capped` tasks to block on `read()` +// indefinitely, effectively hanging the whole agent. +pub const IO_DRAIN_TIMEOUT_MS: u64 = 2_000; // 2 s should be plenty for local pipes + +#[derive(Debug)] +pub struct ExecParams { + pub command: Vec, + pub cwd: PathBuf, + pub expiration: ExecExpiration, + pub capture_policy: ExecCapturePolicy, + pub env: HashMap, + pub network: Option, + pub sandbox_permissions: SandboxPermissions, + pub windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel, + pub windows_sandbox_private_desktop: bool, + pub justification: Option, + pub arg0: Option, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ExecCapturePolicy { + /// Shell-like execs keep the historical output cap and timeout behavior. + #[default] + ShellTool, + /// Trusted internal helpers can buffer the full child output in memory + /// without the shell-oriented output cap or exec-expiration behavior. + 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, + SandboxPreference::Auto, + windows_sandbox_level, + enforce_managed_network, + ) +} + +/// Mechanism to terminate an exec invocation before it finishes naturally. +#[derive(Clone, Debug)] +pub enum ExecExpiration { + Timeout(Duration), + DefaultTimeout, + Cancellation(CancellationToken), +} + +impl From> for ExecExpiration { + fn from(timeout_ms: Option) -> Self { + timeout_ms.map_or(ExecExpiration::DefaultTimeout, |timeout_ms| { + ExecExpiration::Timeout(Duration::from_millis(timeout_ms)) + }) + } +} + +impl From for ExecExpiration { + fn from(timeout_ms: u64) -> Self { + ExecExpiration::Timeout(Duration::from_millis(timeout_ms)) + } +} + +impl ExecExpiration { + pub(crate) async fn wait(self) { + match self { + ExecExpiration::Timeout(duration) => tokio::time::sleep(duration).await, + ExecExpiration::DefaultTimeout => { + tokio::time::sleep(Duration::from_millis(DEFAULT_EXEC_COMMAND_TIMEOUT_MS)).await + } + ExecExpiration::Cancellation(cancel) => { + cancel.cancelled().await; + } + } + } + + /// If ExecExpiration is a timeout, returns the timeout in milliseconds. + pub fn timeout_ms(&self) -> Option { + match self { + ExecExpiration::Timeout(duration) => Some(duration.as_millis() as u64), + ExecExpiration::DefaultTimeout => Some(DEFAULT_EXEC_COMMAND_TIMEOUT_MS), + ExecExpiration::Cancellation(_) => None, + } + } +} + +impl ExecCapturePolicy { + fn retained_bytes_cap(self) -> Option { + match self { + Self::ShellTool => Some(EXEC_OUTPUT_MAX_BYTES), + Self::FullBuffer => None, + } + } + + fn io_drain_timeout(self) -> Duration { + Duration::from_millis(IO_DRAIN_TIMEOUT_MS) + } + + fn uses_expiration(self) -> bool { + match self { + Self::ShellTool => true, + Self::FullBuffer => false, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum SandboxType { + None, + + /// Only available on macOS. + MacosSeatbelt, + + /// Only available on Linux. + LinuxSeccomp, + + /// Only available on Windows. + WindowsRestrictedToken, +} + +#[derive(Clone)] +pub struct StdoutStream { + pub sub_id: String, + pub call_id: String, + pub tx_event: Sender, +} + +#[allow(clippy::too_many_arguments)] +pub async fn process_exec_tool_call( + params: ExecParams, + sandbox_policy: &SandboxPolicy, + file_system_sandbox_policy: &FileSystemSandboxPolicy, + network_sandbox_policy: NetworkSandboxPolicy, + sandbox_cwd: &Path, + codex_linux_sandbox_exe: &Option, + use_legacy_landlock: bool, + stdout_stream: Option, +) -> Result { + let exec_req = build_exec_request( + params, + sandbox_policy, + file_system_sandbox_policy, + network_sandbox_policy, + sandbox_cwd, + codex_linux_sandbox_exe, + use_legacy_landlock, + )?; + + // Route through the sandboxing module for a single, unified execution path. + crate::sandboxing::execute_env(exec_req, stdout_stream).await +} + +/// Transform a portable exec request into the concrete argv/env that should be +/// spawned under the requested sandbox policy. +pub fn build_exec_request( + params: ExecParams, + sandbox_policy: &SandboxPolicy, + file_system_sandbox_policy: &FileSystemSandboxPolicy, + network_sandbox_policy: NetworkSandboxPolicy, + sandbox_cwd: &Path, + 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, + cwd, + mut env, + expiration, + capture_policy, + network, + sandbox_permissions, + windows_sandbox_level, + windows_sandbox_private_desktop, + justification, + arg0: _, + } = params; + if let Some(network) = network.as_ref() { + network.apply_to_env(&mut env); + } + let (program, args) = command.split_first().ok_or_else(|| { + CodexErr::Io(io::Error::new( + io::ErrorKind::InvalidInput, + "command args are empty", + )) + })?; + + let spec = CommandSpec { + program: program.clone(), + args: args.to_vec(), + cwd, + env, + expiration, + capture_policy, + sandbox_permissions, + additional_permissions: None, + justification, + }; + + let manager = SandboxManager::new(); + let exec_req = manager + .transform(crate::sandboxing::SandboxTransformRequest { + spec, + policy: sandbox_policy, + file_system_policy: file_system_sandbox_policy, + network_policy: network_sandbox_policy, + sandbox: sandbox_type, + enforce_managed_network, + network: network.as_ref(), + sandbox_policy_cwd: sandbox_cwd, + #[cfg(target_os = "macos")] + macos_seatbelt_profile_extensions: None, + codex_linux_sandbox_exe: codex_linux_sandbox_exe.as_ref(), + use_legacy_landlock, + windows_sandbox_level, + windows_sandbox_private_desktop, + }) + .map_err(CodexErr::from)?; + Ok(exec_req) +} + +pub async fn execute_exec_request( + exec_request: ExecRequest, + sandbox_policy: &SandboxPolicy, + stdout_stream: Option, + after_spawn: Option>, +) -> Result { + let ExecRequest { + command, + cwd, + env, + network, + expiration, + capture_policy, + sandbox, + windows_sandbox_level, + windows_sandbox_private_desktop, + sandbox_permissions, + sandbox_policy: _sandbox_policy_from_env, + file_system_sandbox_policy, + network_sandbox_policy, + justification, + arg0, + } = exec_request; + let _ = _sandbox_policy_from_env; + + let params = ExecParams { + command, + cwd, + expiration, + capture_policy, + env, + network: network.clone(), + sandbox_permissions, + windows_sandbox_level, + windows_sandbox_private_desktop, + justification, + arg0, + }; + + let start = Instant::now(); + let raw_output_result = exec( + params, + sandbox, + sandbox_policy, + &file_system_sandbox_policy, + network_sandbox_policy, + stdout_stream, + after_spawn, + ) + .await; + let duration = start.elapsed(); + finalize_exec_result(raw_output_result, sandbox, duration) +} + +#[cfg(target_os = "windows")] +fn extract_create_process_as_user_error_code(err: &str) -> Option { + let marker = "CreateProcessAsUserW failed: "; + let start = err.find(marker)? + marker.len(); + let tail = &err[start..]; + let digits: String = tail.chars().take_while(char::is_ascii_digit).collect(); + if digits.is_empty() { + None + } else { + Some(digits) + } +} + +#[cfg(target_os = "windows")] +fn windowsapps_path_kind(path: &str) -> &'static str { + let lower = path.to_ascii_lowercase(); + if lower.contains("\\program files\\windowsapps\\") { + return "windowsapps_package"; + } + if lower.contains("\\appdata\\local\\microsoft\\windowsapps\\") { + return "windowsapps_alias"; + } + if lower.contains("\\windowsapps\\") { + return "windowsapps_other"; + } + "other" +} + +#[cfg(target_os = "windows")] +fn record_windows_sandbox_spawn_failure( + command_path: Option<&str>, + windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel, + err: &str, +) { + let Some(error_code) = extract_create_process_as_user_error_code(err) else { + return; + }; + let path = command_path.unwrap_or("unknown"); + let exe = Path::new(path) + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or("unknown") + .to_ascii_lowercase(); + let path_kind = windowsapps_path_kind(path); + let level = if matches!( + windows_sandbox_level, + codex_protocol::config_types::WindowsSandboxLevel::Elevated + ) { + "elevated" + } else { + "legacy" + }; + if let Some(metrics) = codex_otel::metrics::global() { + let _ = metrics.counter( + "codex.windows_sandbox.createprocessasuserw_failed", + /*inc*/ 1, + &[ + ("error_code", error_code.as_str()), + ("path_kind", path_kind), + ("exe", exe.as_str()), + ("level", level), + ], + ); + } +} + +#[cfg(target_os = "windows")] +async fn exec_windows_sandbox( + params: ExecParams, + sandbox_policy: &SandboxPolicy, +) -> Result { + use codex_protocol::config_types::WindowsSandboxLevel; + use codex_utils_home_dir::find_codex_home; + use codex_windows_sandbox::run_windows_sandbox_capture; + use codex_windows_sandbox::run_windows_sandbox_capture_elevated; + + let ExecParams { + command, + cwd, + mut env, + network, + expiration, + capture_policy, + windows_sandbox_level, + windows_sandbox_private_desktop, + .. + } = params; + if let Some(network) = network.as_ref() { + network.apply_to_env(&mut env); + } + + // TODO(iceweasel-oai): run_windows_sandbox_capture should support all + // variants of ExecExpiration, not just timeout. + let timeout_ms = if capture_policy.uses_expiration() { + expiration.timeout_ms() + } else { + None + }; + + let policy_str = serde_json::to_string(sandbox_policy).map_err(|err| { + CodexErr::Io(io::Error::other(format!( + "failed to serialize Windows sandbox policy: {err}" + ))) + })?; + let sandbox_cwd = cwd.clone(); + let codex_home = find_codex_home().map_err(|err| { + CodexErr::Io(io::Error::other(format!( + "windows sandbox: failed to resolve codex_home: {err}" + ))) + })?; + let command_path = command.first().cloned(); + let sandbox_level = windows_sandbox_level; + let use_elevated = matches!(sandbox_level, WindowsSandboxLevel::Elevated); + let spawn_res = tokio::task::spawn_blocking(move || { + if use_elevated { + run_windows_sandbox_capture_elevated( + policy_str.as_str(), + &sandbox_cwd, + codex_home.as_ref(), + command, + &cwd, + env, + timeout_ms, + windows_sandbox_private_desktop, + ) + } else { + run_windows_sandbox_capture( + policy_str.as_str(), + &sandbox_cwd, + codex_home.as_ref(), + command, + &cwd, + env, + timeout_ms, + windows_sandbox_private_desktop, + ) + } + }) + .await; + + let capture = match spawn_res { + Ok(Ok(v)) => v, + Ok(Err(err)) => { + record_windows_sandbox_spawn_failure( + command_path.as_deref(), + sandbox_level, + &err.to_string(), + ); + return Err(CodexErr::Io(io::Error::other(format!( + "windows sandbox: {err}" + )))); + } + Err(join_err) => { + return Err(CodexErr::Io(io::Error::other(format!( + "windows sandbox join error: {join_err}" + )))); + } + }; + + let exit_status = synthetic_exit_status(capture.exit_code); + let mut stdout_text = capture.stdout; + if let Some(max_bytes) = capture_policy.retained_bytes_cap() + && stdout_text.len() > max_bytes + { + stdout_text.truncate(max_bytes); + } + let mut stderr_text = capture.stderr; + if let Some(max_bytes) = capture_policy.retained_bytes_cap() + && stderr_text.len() > max_bytes + { + stderr_text.truncate(max_bytes); + } + let stdout = StreamOutput { + text: stdout_text, + truncated_after_lines: None, + }; + let stderr = StreamOutput { + text: stderr_text, + truncated_after_lines: None, + }; + let aggregated_output = aggregate_output(&stdout, &stderr, capture_policy.retained_bytes_cap()); + + Ok(RawExecToolCallOutput { + exit_status, + stdout, + stderr, + aggregated_output, + timed_out: capture.timed_out, + }) +} + +fn finalize_exec_result( + raw_output_result: std::result::Result, + sandbox_type: SandboxType, + duration: Duration, +) -> Result { + match raw_output_result { + Ok(raw_output) => { + #[allow(unused_mut)] + let mut timed_out = raw_output.timed_out; + + #[cfg(target_family = "unix")] + { + if let Some(signal) = raw_output.exit_status.signal() { + if signal == TIMEOUT_CODE { + timed_out = true; + } else { + return Err(CodexErr::Sandbox(SandboxErr::Signal(signal))); + } + } + } + + let mut exit_code = raw_output.exit_status.code().unwrap_or(-1); + if timed_out { + exit_code = EXEC_TIMEOUT_EXIT_CODE; + } + + let stdout = raw_output.stdout.from_utf8_lossy(); + let stderr = raw_output.stderr.from_utf8_lossy(); + let aggregated_output = raw_output.aggregated_output.from_utf8_lossy(); + let exec_output = ExecToolCallOutput { + exit_code, + stdout, + stderr, + aggregated_output, + duration, + timed_out, + }; + + if timed_out { + return Err(CodexErr::Sandbox(SandboxErr::Timeout { + output: Box::new(exec_output), + })); + } + + if is_likely_sandbox_denied(sandbox_type, &exec_output) { + return Err(CodexErr::Sandbox(SandboxErr::Denied { + output: Box::new(exec_output), + })); + } + + Ok(exec_output) + } + Err(err) => { + tracing::error!("exec error: {err}"); + Err(err) + } + } +} + +pub(crate) mod errors { + use super::CodexErr; + use crate::sandboxing::SandboxTransformError; + + impl From for CodexErr { + fn from(err: SandboxTransformError) -> Self { + match err { + SandboxTransformError::MissingLinuxSandboxExecutable => { + CodexErr::LandlockSandboxExecutableNotProvided + } + #[cfg(not(target_os = "macos"))] + SandboxTransformError::SeatbeltUnavailable => CodexErr::UnsupportedOperation( + "seatbelt sandbox is only available on macOS".to_string(), + ), + } + } + } +} + +/// We don't have a fully deterministic way to tell if our command failed +/// because of the sandbox - a command in the user's zshrc file might hit an +/// error, but the command itself might fail or succeed for other reasons. +/// For now, we conservatively check for well known command failure exit codes and +/// also look for common sandbox denial keywords in the command output. +pub fn is_likely_sandbox_denied( + sandbox_type: SandboxType, + exec_output: &ExecToolCallOutput, +) -> bool { + if sandbox_type == SandboxType::None || exec_output.exit_code == 0 { + return false; + } + + // Quick rejects: well-known non-sandbox shell exit codes + // 2: misuse of shell builtins + // 126: permission denied + // 127: command not found + const SANDBOX_DENIED_KEYWORDS: [&str; 7] = [ + "operation not permitted", + "permission denied", + "read-only file system", + "seccomp", + "sandbox", + "landlock", + "failed to write file", + ]; + + let has_sandbox_keyword = [ + &exec_output.stderr.text, + &exec_output.stdout.text, + &exec_output.aggregated_output.text, + ] + .into_iter() + .any(|section| { + let lower = section.to_lowercase(); + SANDBOX_DENIED_KEYWORDS + .iter() + .any(|needle| lower.contains(needle)) + }); + + if has_sandbox_keyword { + return true; + } + + const QUICK_REJECT_EXIT_CODES: [i32; 3] = [2, 126, 127]; + if QUICK_REJECT_EXIT_CODES.contains(&exec_output.exit_code) { + return false; + } + + #[cfg(unix)] + { + const SIGSYS_CODE: i32 = libc::SIGSYS; + if sandbox_type == SandboxType::LinuxSeccomp + && exec_output.exit_code == EXIT_CODE_SIGNAL_BASE + SIGSYS_CODE + { + return true; + } + } + + false +} + +#[derive(Debug, Clone)] +pub struct StreamOutput { + pub text: T, + pub truncated_after_lines: Option, +} + +#[derive(Debug)] +struct RawExecToolCallOutput { + pub exit_status: ExitStatus, + pub stdout: StreamOutput>, + pub stderr: StreamOutput>, + pub aggregated_output: StreamOutput>, + pub timed_out: bool, +} + +impl StreamOutput { + pub fn new(text: String) -> Self { + Self { + text, + truncated_after_lines: None, + } + } +} + +impl StreamOutput> { + pub fn from_utf8_lossy(&self) -> StreamOutput { + StreamOutput { + text: bytes_to_string_smart(&self.text), + truncated_after_lines: self.truncated_after_lines, + } + } +} + +#[inline] +fn append_capped(dst: &mut Vec, src: &[u8], max_bytes: usize) { + if dst.len() >= max_bytes { + return; + } + let remaining = max_bytes.saturating_sub(dst.len()); + let take = remaining.min(src.len()); + dst.extend_from_slice(&src[..take]); +} + +fn aggregate_output( + stdout: &StreamOutput>, + stderr: &StreamOutput>, + max_bytes: Option, +) -> StreamOutput> { + let Some(max_bytes) = max_bytes else { + let total_len = stdout.text.len().saturating_add(stderr.text.len()); + let mut aggregated = Vec::with_capacity(total_len); + aggregated.extend_from_slice(&stdout.text); + aggregated.extend_from_slice(&stderr.text); + return StreamOutput { + text: aggregated, + truncated_after_lines: None, + }; + }; + + let total_len = stdout.text.len().saturating_add(stderr.text.len()); + let mut aggregated = Vec::with_capacity(total_len.min(max_bytes)); + + if total_len <= max_bytes { + aggregated.extend_from_slice(&stdout.text); + aggregated.extend_from_slice(&stderr.text); + return StreamOutput { + text: aggregated, + truncated_after_lines: None, + }; + } + + // Under contention, reserve 1/3 for stdout and 2/3 for stderr; rebalance unused stderr to stdout. + let want_stdout = stdout.text.len().min(max_bytes / 3); + let want_stderr = stderr.text.len(); + let stderr_take = want_stderr.min(max_bytes.saturating_sub(want_stdout)); + let remaining = max_bytes.saturating_sub(want_stdout + stderr_take); + let stdout_take = want_stdout + remaining.min(stdout.text.len().saturating_sub(want_stdout)); + + aggregated.extend_from_slice(&stdout.text[..stdout_take]); + aggregated.extend_from_slice(&stderr.text[..stderr_take]); + + StreamOutput { + text: aggregated, + truncated_after_lines: None, + } +} + +#[derive(Clone, Debug)] +pub struct ExecToolCallOutput { + pub exit_code: i32, + pub stdout: StreamOutput, + pub stderr: StreamOutput, + pub aggregated_output: StreamOutput, + pub duration: Duration, + pub timed_out: bool, +} + +impl Default for ExecToolCallOutput { + fn default() -> Self { + Self { + exit_code: 0, + stdout: StreamOutput::new(String::new()), + stderr: StreamOutput::new(String::new()), + aggregated_output: StreamOutput::new(String::new()), + duration: Duration::ZERO, + timed_out: false, + } + } +} + +#[cfg_attr(not(target_os = "windows"), allow(unused_variables))] +async fn exec( + params: ExecParams, + sandbox: SandboxType, + sandbox_policy: &SandboxPolicy, + file_system_sandbox_policy: &FileSystemSandboxPolicy, + network_sandbox_policy: NetworkSandboxPolicy, + stdout_stream: Option, + after_spawn: Option>, +) -> Result { + #[cfg(target_os = "windows")] + if sandbox == SandboxType::WindowsRestrictedToken { + let support = windows_restricted_token_sandbox_support( + sandbox, + params.windows_sandbox_level, + sandbox_policy, + file_system_sandbox_policy, + network_sandbox_policy, + ); + if let Some(reason) = support.unsupported_reason { + return Err(CodexErr::Io(io::Error::other(reason))); + } + return exec_windows_sandbox(params, sandbox_policy).await; + } + let ExecParams { + command, + cwd, + mut env, + network, + arg0, + expiration, + capture_policy, + windows_sandbox_level: _, + .. + } = params; + if let Some(network) = network.as_ref() { + network.apply_to_env(&mut env); + } + + let (program, args) = command.split_first().ok_or_else(|| { + CodexErr::Io(io::Error::new( + io::ErrorKind::InvalidInput, + "command args are empty", + )) + })?; + let arg0_ref = arg0.as_deref(); + let child = spawn_child_async(SpawnChildRequest { + program: PathBuf::from(program), + args: args.into(), + arg0: arg0_ref, + cwd, + network_sandbox_policy, + // The environment already has attempt-scoped proxy settings from + // apply_to_env_for_attempt above. Passing network here would reapply + // non-attempt proxy vars and drop attempt correlation metadata. + network: None, + stdio_policy: StdioPolicy::RedirectForShellTool, + env, + }) + .await?; + if let Some(after_spawn) = after_spawn { + after_spawn(); + } + consume_output(child, expiration, capture_policy, stdout_stream).await +} + +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +#[derive(Debug, PartialEq, Eq)] +struct WindowsRestrictedTokenSandboxSupport { + should_use: bool, + unsupported_reason: Option, +} + +#[cfg(any(target_os = "windows", test))] +fn windows_restricted_token_sandbox_support( + sandbox: SandboxType, + windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel, + sandbox_policy: &SandboxPolicy, + file_system_sandbox_policy: &FileSystemSandboxPolicy, + network_sandbox_policy: NetworkSandboxPolicy, +) -> WindowsRestrictedTokenSandboxSupport { + if sandbox != SandboxType::WindowsRestrictedToken { + return WindowsRestrictedTokenSandboxSupport { + should_use: false, + unsupported_reason: None, + }; + } + + // Windows currently reuses SandboxType::WindowsRestrictedToken for both + // the legacy restricted-token backend and the elevated setup/runner path. + // The sandbox level decides whether restricted read-only policies are + // supported. + let should_use = file_system_sandbox_policy.kind == FileSystemSandboxKind::Restricted + && !matches!( + sandbox_policy, + SandboxPolicy::DangerFullAccess | SandboxPolicy::ExternalSandbox { .. } + ) + && (matches!( + windows_sandbox_level, + codex_protocol::config_types::WindowsSandboxLevel::Elevated + ) || sandbox_policy.has_full_disk_read_access()); + + let unsupported_reason = if should_use { + None + } else { + Some(format!( + "windows sandbox backend cannot enforce file_system={:?}, network={network_sandbox_policy:?}, legacy_policy={sandbox_policy:?}; refusing to run unsandboxed", + file_system_sandbox_policy.kind, + )) + }; + + WindowsRestrictedTokenSandboxSupport { + should_use, + unsupported_reason, + } +} + +/// Consumes the output of a child process according to the configured capture +/// policy. +async fn consume_output( + mut child: Child, + expiration: ExecExpiration, + capture_policy: ExecCapturePolicy, + stdout_stream: Option, +) -> Result { + // Both stdout and stderr were configured with `Stdio::piped()` + // above, therefore `take()` should normally return `Some`. If it doesn't + // we treat it as an exceptional I/O error + + let stdout_reader = child.stdout.take().ok_or_else(|| { + CodexErr::Io(io::Error::other( + "stdout pipe was unexpectedly not available", + )) + })?; + let stderr_reader = child.stderr.take().ok_or_else(|| { + CodexErr::Io(io::Error::other( + "stderr pipe was unexpectedly not available", + )) + })?; + + let retained_bytes_cap = capture_policy.retained_bytes_cap(); + let stdout_handle = tokio::spawn(read_output( + BufReader::new(stdout_reader), + stdout_stream.clone(), + /*is_stderr*/ false, + retained_bytes_cap, + )); + let stderr_handle = tokio::spawn(read_output( + BufReader::new(stderr_reader), + stdout_stream.clone(), + /*is_stderr*/ true, + retained_bytes_cap, + )); + + let expiration_wait = async { + if capture_policy.uses_expiration() { + expiration.wait().await; + } else { + std::future::pending::<()>().await; + } + }; + tokio::pin!(expiration_wait); + let (exit_status, timed_out) = tokio::select! { + status_result = child.wait() => { + let exit_status = status_result?; + (exit_status, false) + } + _ = &mut expiration_wait => { + kill_child_process_group(&mut child)?; + child.start_kill()?; + (synthetic_exit_status(EXIT_CODE_SIGNAL_BASE + TIMEOUT_CODE), true) + } + _ = tokio::signal::ctrl_c() => { + kill_child_process_group(&mut child)?; + child.start_kill()?; + (synthetic_exit_status(EXIT_CODE_SIGNAL_BASE + SIGKILL_CODE), false) + } + }; + + // We need mutable bindings so we can `abort()` them on timeout. + use tokio::task::JoinHandle; + + async fn await_output( + handle: &mut JoinHandle>>>, + timeout: Duration, + ) -> std::io::Result>> { + match tokio::time::timeout(timeout, &mut *handle).await { + Ok(join_res) => match join_res { + Ok(io_res) => io_res, + Err(join_err) => Err(std::io::Error::other(join_err)), + }, + Err(_elapsed) => { + // Timeout: abort the task to avoid hanging on open pipes. + handle.abort(); + Ok(StreamOutput { + text: Vec::new(), + truncated_after_lines: None, + }) + } + } + } + + let mut stdout_handle = stdout_handle; + let mut stderr_handle = stderr_handle; + + let stdout = await_output(&mut stdout_handle, capture_policy.io_drain_timeout()).await?; + let stderr = await_output(&mut stderr_handle, capture_policy.io_drain_timeout()).await?; + let aggregated_output = aggregate_output(&stdout, &stderr, retained_bytes_cap); + + Ok(RawExecToolCallOutput { + exit_status, + stdout, + stderr, + aggregated_output, + timed_out, + }) +} + +async fn read_output( + mut reader: R, + stream: Option, + is_stderr: bool, + max_bytes: Option, +) -> io::Result>> { + let mut buf = Vec::with_capacity( + max_bytes.map_or(AGGREGATE_BUFFER_INITIAL_CAPACITY, |max_bytes| { + AGGREGATE_BUFFER_INITIAL_CAPACITY.min(max_bytes) + }), + ); + let mut tmp = [0u8; READ_CHUNK_SIZE]; + let mut emitted_deltas: usize = 0; + + loop { + let n = reader.read(&mut tmp).await?; + if n == 0 { + break; + } + + if let Some(stream) = &stream + && emitted_deltas < MAX_EXEC_OUTPUT_DELTAS_PER_CALL + { + let chunk = tmp[..n].to_vec(); + let msg = EventMsg::ExecCommandOutputDelta(ExecCommandOutputDeltaEvent { + call_id: stream.call_id.clone(), + stream: if is_stderr { + ExecOutputStream::Stderr + } else { + ExecOutputStream::Stdout + }, + chunk, + }); + let event = Event { + id: stream.sub_id.clone(), + msg, + }; + #[allow(clippy::let_unit_value)] + let _ = stream.tx_event.send(event).await; + emitted_deltas += 1; + } + + if let Some(max_bytes) = max_bytes { + append_capped(&mut buf, &tmp[..n], max_bytes); + } else { + buf.extend_from_slice(&tmp[..n]); + } + // Continue reading to EOF to avoid back-pressure + } + + Ok(StreamOutput { + text: buf, + truncated_after_lines: None, + }) +} + +#[cfg(unix)] +fn synthetic_exit_status(code: i32) -> ExitStatus { + use std::os::unix::process::ExitStatusExt; + std::process::ExitStatus::from_raw(code) +} + +#[cfg(windows)] +fn synthetic_exit_status(code: i32) -> ExitStatus { + use std::os::windows::process::ExitStatusExt; + // On Windows the raw status is a u32. Use a direct cast to avoid + // panicking on negative i32 values produced by prior narrowing casts. + std::process::ExitStatus::from_raw(code as u32) +} + +#[cfg(test)] +#[path = "exec_tests.rs"] +mod tests; diff --git a/codex-rs/sandbox/src/exec_tests.rs b/codex-rs/sandbox/src/exec_tests.rs new file mode 100644 index 0000000000..fc312ec88e --- /dev/null +++ b/codex-rs/sandbox/src/exec_tests.rs @@ -0,0 +1,697 @@ +use super::*; +use codex_protocol::config_types::WindowsSandboxLevel; +use pretty_assertions::assert_eq; +use std::collections::HashMap; +use std::time::Duration; +use tokio::io::AsyncWriteExt; + +fn make_exec_output( + exit_code: i32, + stdout: &str, + stderr: &str, + aggregated: &str, +) -> ExecToolCallOutput { + ExecToolCallOutput { + exit_code, + stdout: StreamOutput::new(stdout.to_string()), + stderr: StreamOutput::new(stderr.to_string()), + aggregated_output: StreamOutput::new(aggregated.to_string()), + duration: Duration::from_millis(1), + timed_out: false, + } +} + +#[test] +fn sandbox_detection_requires_keywords() { + let output = make_exec_output(1, "", "", ""); + assert!(!is_likely_sandbox_denied( + SandboxType::LinuxSeccomp, + &output + )); +} + +#[test] +fn sandbox_detection_identifies_keyword_in_stderr() { + let output = make_exec_output(1, "", "Operation not permitted", ""); + assert!(is_likely_sandbox_denied(SandboxType::LinuxSeccomp, &output)); +} + +#[test] +fn sandbox_detection_respects_quick_reject_exit_codes() { + let output = make_exec_output(127, "", "command not found", ""); + assert!(!is_likely_sandbox_denied( + SandboxType::LinuxSeccomp, + &output + )); +} + +#[test] +fn sandbox_detection_ignores_non_sandbox_mode() { + let output = make_exec_output(1, "", "Operation not permitted", ""); + assert!(!is_likely_sandbox_denied(SandboxType::None, &output)); +} + +#[test] +fn sandbox_detection_ignores_network_policy_text_in_non_sandbox_mode() { + let output = make_exec_output( + 0, + "", + "", + r#"CODEX_NETWORK_POLICY_DECISION {"decision":"ask","reason":"not_allowed","source":"decider","protocol":"http","host":"google.com","port":80}"#, + ); + assert!(!is_likely_sandbox_denied(SandboxType::None, &output)); +} + +#[test] +fn sandbox_detection_uses_aggregated_output() { + let output = make_exec_output( + 101, + "", + "", + "cargo failed: Read-only file system when writing target", + ); + assert!(is_likely_sandbox_denied( + SandboxType::MacosSeatbelt, + &output + )); +} + +#[test] +fn sandbox_detection_ignores_network_policy_text_with_zero_exit_code() { + let output = make_exec_output( + 0, + "", + "", + r#"CODEX_NETWORK_POLICY_DECISION {"decision":"ask","source":"decider","protocol":"http","host":"google.com","port":80}"#, + ); + + assert!(!is_likely_sandbox_denied( + SandboxType::LinuxSeccomp, + &output + )); +} + +#[tokio::test] +async fn read_output_limits_retained_bytes_for_shell_capture() { + let (mut writer, reader) = tokio::io::duplex(1024); + let bytes = vec![b'a'; EXEC_OUTPUT_MAX_BYTES.saturating_add(128 * 1024)]; + tokio::spawn(async move { + writer.write_all(&bytes).await.expect("write"); + }); + + let out = read_output(reader, None, false, Some(EXEC_OUTPUT_MAX_BYTES)) + .await + .expect("read"); + assert_eq!(out.text.len(), EXEC_OUTPUT_MAX_BYTES); +} + +#[test] +fn aggregate_output_prefers_stderr_on_contention() { + let stdout = StreamOutput { + text: vec![b'a'; EXEC_OUTPUT_MAX_BYTES], + truncated_after_lines: None, + }; + let stderr = StreamOutput { + text: vec![b'b'; EXEC_OUTPUT_MAX_BYTES], + truncated_after_lines: None, + }; + + let aggregated = aggregate_output(&stdout, &stderr, Some(EXEC_OUTPUT_MAX_BYTES)); + let stdout_cap = EXEC_OUTPUT_MAX_BYTES / 3; + let stderr_cap = EXEC_OUTPUT_MAX_BYTES.saturating_sub(stdout_cap); + + assert_eq!(aggregated.text.len(), EXEC_OUTPUT_MAX_BYTES); + assert_eq!(aggregated.text[..stdout_cap], vec![b'a'; stdout_cap]); + assert_eq!(aggregated.text[stdout_cap..], vec![b'b'; stderr_cap]); +} + +#[test] +fn aggregate_output_fills_remaining_capacity_with_stderr() { + let stdout_len = EXEC_OUTPUT_MAX_BYTES / 10; + let stdout = StreamOutput { + text: vec![b'a'; stdout_len], + truncated_after_lines: None, + }; + let stderr = StreamOutput { + text: vec![b'b'; EXEC_OUTPUT_MAX_BYTES], + truncated_after_lines: None, + }; + + let aggregated = aggregate_output(&stdout, &stderr, Some(EXEC_OUTPUT_MAX_BYTES)); + let stderr_cap = EXEC_OUTPUT_MAX_BYTES.saturating_sub(stdout_len); + + assert_eq!(aggregated.text.len(), EXEC_OUTPUT_MAX_BYTES); + assert_eq!(aggregated.text[..stdout_len], vec![b'a'; stdout_len]); + assert_eq!(aggregated.text[stdout_len..], vec![b'b'; stderr_cap]); +} + +#[test] +fn aggregate_output_rebalances_when_stderr_is_small() { + let stdout = StreamOutput { + text: vec![b'a'; EXEC_OUTPUT_MAX_BYTES], + truncated_after_lines: None, + }; + let stderr = StreamOutput { + text: vec![b'b'; 1], + truncated_after_lines: None, + }; + + let aggregated = aggregate_output(&stdout, &stderr, Some(EXEC_OUTPUT_MAX_BYTES)); + let stdout_len = EXEC_OUTPUT_MAX_BYTES.saturating_sub(1); + + assert_eq!(aggregated.text.len(), EXEC_OUTPUT_MAX_BYTES); + assert_eq!(aggregated.text[..stdout_len], vec![b'a'; stdout_len]); + assert_eq!(aggregated.text[stdout_len..], vec![b'b'; 1]); +} + +#[test] +fn aggregate_output_keeps_stdout_then_stderr_when_under_cap() { + let stdout = StreamOutput { + text: vec![b'a'; 4], + truncated_after_lines: None, + }; + let stderr = StreamOutput { + text: vec![b'b'; 3], + truncated_after_lines: None, + }; + + let aggregated = aggregate_output(&stdout, &stderr, Some(EXEC_OUTPUT_MAX_BYTES)); + let mut expected = Vec::new(); + expected.extend_from_slice(&stdout.text); + expected.extend_from_slice(&stderr.text); + + assert_eq!(aggregated.text, expected); + assert_eq!(aggregated.truncated_after_lines, None); +} + +#[tokio::test] +async fn read_output_retains_all_bytes_for_full_buffer_capture() { + let (mut writer, reader) = tokio::io::duplex(1024); + let bytes = vec![b'a'; EXEC_OUTPUT_MAX_BYTES.saturating_add(128 * 1024)]; + let expected_len = bytes.len(); + // The duplex pipe is smaller than `bytes`, so the writer must run concurrently + // with `read_output()` or `write_all()` will block once the buffer fills up. + tokio::spawn(async move { + writer.write_all(&bytes).await.expect("write"); + }); + + let out = read_output(reader, None, false, None).await.expect("read"); + assert_eq!(out.text.len(), expected_len); +} + +#[test] +fn aggregate_output_keeps_all_bytes_when_uncapped() { + let stdout = StreamOutput { + text: vec![b'a'; EXEC_OUTPUT_MAX_BYTES], + truncated_after_lines: None, + }; + let stderr = StreamOutput { + text: vec![b'b'; EXEC_OUTPUT_MAX_BYTES], + truncated_after_lines: None, + }; + + let aggregated = aggregate_output(&stdout, &stderr, None); + + assert_eq!(aggregated.text.len(), EXEC_OUTPUT_MAX_BYTES * 2); + assert_eq!( + aggregated.text[..EXEC_OUTPUT_MAX_BYTES], + vec![b'a'; EXEC_OUTPUT_MAX_BYTES] + ); + assert_eq!( + aggregated.text[EXEC_OUTPUT_MAX_BYTES..], + vec![b'b'; EXEC_OUTPUT_MAX_BYTES] + ); +} + +#[test] +fn full_buffer_capture_policy_disables_caps_and_exec_expiration() { + assert_eq!(ExecCapturePolicy::FullBuffer.retained_bytes_cap(), None); + assert_eq!( + ExecCapturePolicy::FullBuffer.io_drain_timeout(), + Duration::from_millis(IO_DRAIN_TIMEOUT_MS) + ); + assert!(!ExecCapturePolicy::FullBuffer.uses_expiration()); +} + +#[tokio::test] +async fn exec_full_buffer_capture_ignores_expiration() -> Result<()> { + #[cfg(windows)] + let command = vec![ + "powershell.exe".to_string(), + "-NonInteractive".to_string(), + "-NoLogo".to_string(), + "-Command".to_string(), + "Start-Sleep -Milliseconds 50; [Console]::Out.Write('hello')".to_string(), + ]; + #[cfg(not(windows))] + let command = vec![ + "/bin/sh".to_string(), + "-c".to_string(), + "sleep 0.05; printf hello".to_string(), + ]; + + let env: HashMap = std::env::vars().collect(); + let output = exec( + ExecParams { + command, + cwd: std::env::current_dir()?, + expiration: 1.into(), + capture_policy: ExecCapturePolicy::FullBuffer, + env, + network: None, + sandbox_permissions: SandboxPermissions::UseDefault, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + windows_sandbox_private_desktop: false, + justification: None, + arg0: None, + }, + SandboxType::None, + &SandboxPolicy::DangerFullAccess, + &FileSystemSandboxPolicy::unrestricted(), + NetworkSandboxPolicy::Enabled, + /*stdout_stream*/ None, + /*after_spawn*/ None, + ) + .await?; + + assert_eq!(output.stdout.from_utf8_lossy().text.trim(), "hello"); + assert!(!output.timed_out); + + Ok(()) +} + +#[cfg(unix)] +#[tokio::test] +async fn exec_full_buffer_capture_keeps_io_drain_timeout_when_descendant_holds_pipe_open() +-> Result<()> { + let output = tokio::time::timeout( + Duration::from_millis(IO_DRAIN_TIMEOUT_MS * 3), + exec( + ExecParams { + command: vec![ + "/bin/sh".to_string(), + "-c".to_string(), + "printf hello; sleep 30 &".to_string(), + ], + cwd: std::env::current_dir()?, + expiration: 1.into(), + capture_policy: ExecCapturePolicy::FullBuffer, + env: std::env::vars().collect(), + network: None, + sandbox_permissions: SandboxPermissions::UseDefault, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + windows_sandbox_private_desktop: false, + justification: None, + arg0: None, + }, + SandboxType::None, + &SandboxPolicy::DangerFullAccess, + &FileSystemSandboxPolicy::unrestricted(), + NetworkSandboxPolicy::Enabled, + /*stdout_stream*/ None, + /*after_spawn*/ None, + ), + ) + .await + .expect("full-buffer exec should return once the I/O drain guard fires")?; + + assert!(!output.timed_out); + + Ok(()) +} + +#[tokio::test] +async fn process_exec_tool_call_preserves_full_buffer_capture_policy() -> Result<()> { + let byte_count = EXEC_OUTPUT_MAX_BYTES.saturating_add(128 * 1024); + #[cfg(windows)] + let command = vec![ + "powershell.exe".to_string(), + "-NonInteractive".to_string(), + "-NoLogo".to_string(), + "-Command".to_string(), + format!("Start-Sleep -Milliseconds 50; [Console]::Out.Write('a' * {byte_count})"), + ]; + #[cfg(not(windows))] + let command = vec![ + "/bin/sh".to_string(), + "-c".to_string(), + format!("sleep 0.05; head -c {byte_count} /dev/zero | tr '\\0' 'a'"), + ]; + + let cwd = std::env::current_dir()?; + let sandbox_policy = SandboxPolicy::DangerFullAccess; + let output = process_exec_tool_call( + ExecParams { + command, + cwd: cwd.clone(), + expiration: 1.into(), + capture_policy: ExecCapturePolicy::FullBuffer, + env: std::env::vars().collect(), + network: None, + sandbox_permissions: SandboxPermissions::UseDefault, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + windows_sandbox_private_desktop: false, + justification: None, + arg0: None, + }, + &sandbox_policy, + &FileSystemSandboxPolicy::from(&sandbox_policy), + NetworkSandboxPolicy::Enabled, + cwd.as_path(), + &None, + false, + None, + ) + .await?; + + assert!(!output.timed_out); + assert_eq!(output.stdout.text.len(), byte_count); + + Ok(()) +} + +#[test] +fn windows_restricted_token_skips_external_sandbox_policies() { + let policy = SandboxPolicy::ExternalSandbox { + network_access: codex_protocol::protocol::NetworkAccess::Restricted, + }; + let file_system_policy = FileSystemSandboxPolicy::restricted(vec![]); + + assert_eq!( + windows_restricted_token_sandbox_support( + SandboxType::WindowsRestrictedToken, + WindowsSandboxLevel::Disabled, + &policy, + &file_system_policy, + NetworkSandboxPolicy::Restricted, + ), + WindowsRestrictedTokenSandboxSupport { + should_use: false, + unsupported_reason: Some( + "windows sandbox backend cannot enforce file_system=Restricted, network=Restricted, legacy_policy=ExternalSandbox { network_access: Restricted }; refusing to run unsandboxed".to_string() + ), + } + ); +} + +#[test] +fn windows_restricted_token_runs_for_legacy_restricted_policies() { + let policy = SandboxPolicy::new_read_only_policy(); + let file_system_policy = FileSystemSandboxPolicy::restricted(vec![]); + + assert_eq!( + windows_restricted_token_sandbox_support( + SandboxType::WindowsRestrictedToken, + WindowsSandboxLevel::Disabled, + &policy, + &file_system_policy, + NetworkSandboxPolicy::Restricted, + ), + WindowsRestrictedTokenSandboxSupport { + should_use: true, + unsupported_reason: None, + } + ); +} + +#[test] +fn windows_restricted_token_rejects_network_only_restrictions() { + let policy = SandboxPolicy::ExternalSandbox { + network_access: codex_protocol::protocol::NetworkAccess::Restricted, + }; + let file_system_policy = FileSystemSandboxPolicy::unrestricted(); + + assert_eq!( + windows_restricted_token_sandbox_support( + SandboxType::WindowsRestrictedToken, + WindowsSandboxLevel::Disabled, + &policy, + &file_system_policy, + NetworkSandboxPolicy::Restricted, + ), + WindowsRestrictedTokenSandboxSupport { + should_use: false, + unsupported_reason: Some( + "windows sandbox backend cannot enforce file_system=Unrestricted, network=Restricted, legacy_policy=ExternalSandbox { network_access: Restricted }; refusing to run unsandboxed".to_string() + ), + } + ); +} + +#[test] +fn windows_restricted_token_allows_legacy_restricted_policies() { + let policy = SandboxPolicy::new_read_only_policy(); + let file_system_policy = FileSystemSandboxPolicy::restricted(vec![]); + + assert_eq!( + windows_restricted_token_sandbox_support( + SandboxType::WindowsRestrictedToken, + WindowsSandboxLevel::Disabled, + &policy, + &file_system_policy, + NetworkSandboxPolicy::Restricted, + ), + WindowsRestrictedTokenSandboxSupport { + should_use: true, + unsupported_reason: None, + } + ); +} + +#[test] +fn windows_restricted_token_rejects_restricted_read_only_policies() { + let policy = SandboxPolicy::ReadOnly { + access: codex_protocol::protocol::ReadOnlyAccess::Restricted { + include_platform_defaults: true, + readable_roots: vec![], + }, + network_access: false, + }; + let file_system_policy = FileSystemSandboxPolicy::from(&policy); + + assert_eq!( + windows_restricted_token_sandbox_support( + SandboxType::WindowsRestrictedToken, + WindowsSandboxLevel::Disabled, + &policy, + &file_system_policy, + NetworkSandboxPolicy::Restricted, + ), + WindowsRestrictedTokenSandboxSupport { + should_use: false, + unsupported_reason: Some( + "windows sandbox backend cannot enforce file_system=Restricted, network=Restricted, legacy_policy=ReadOnly { access: Restricted { include_platform_defaults: true, readable_roots: [] }, network_access: false }; refusing to run unsandboxed".to_string() + ), + }, + "restricted-token should fail closed for restricted read-only policies" + ); +} + +#[test] +fn windows_restricted_token_allows_legacy_workspace_write_policies() { + let policy = SandboxPolicy::WorkspaceWrite { + writable_roots: vec![], + read_only_access: codex_protocol::protocol::ReadOnlyAccess::FullAccess, + network_access: false, + exclude_tmpdir_env_var: false, + exclude_slash_tmp: false, + }; + let file_system_policy = FileSystemSandboxPolicy::from(&policy); + + assert_eq!( + windows_restricted_token_sandbox_support( + SandboxType::WindowsRestrictedToken, + WindowsSandboxLevel::Disabled, + &policy, + &file_system_policy, + NetworkSandboxPolicy::Restricted, + ), + WindowsRestrictedTokenSandboxSupport { + should_use: true, + unsupported_reason: None, + } + ); +} + +#[test] +fn windows_elevated_sandbox_allows_restricted_read_only_policies() { + let policy = SandboxPolicy::ReadOnly { + access: codex_protocol::protocol::ReadOnlyAccess::Restricted { + include_platform_defaults: true, + readable_roots: vec![], + }, + network_access: false, + }; + let file_system_policy = FileSystemSandboxPolicy::from(&policy); + + assert_eq!( + windows_restricted_token_sandbox_support( + SandboxType::WindowsRestrictedToken, + WindowsSandboxLevel::Elevated, + &policy, + &file_system_policy, + NetworkSandboxPolicy::Restricted, + ), + WindowsRestrictedTokenSandboxSupport { + should_use: true, + unsupported_reason: None, + }, + "elevated Windows sandbox should keep restricted read-only support enabled" + ); +} + +#[test] +fn process_exec_tool_call_uses_platform_sandbox_for_network_only_restrictions() { + let expected = crate::get_platform_sandbox(false).unwrap_or(SandboxType::None); + + assert_eq!( + select_process_exec_tool_sandbox_type( + &FileSystemSandboxPolicy::unrestricted(), + NetworkSandboxPolicy::Restricted, + WindowsSandboxLevel::Disabled, + false, + ), + expected + ); +} + +#[cfg(unix)] +#[test] +fn sandbox_detection_flags_sigsys_exit_code() { + let exit_code = EXIT_CODE_SIGNAL_BASE + libc::SIGSYS; + let output = make_exec_output(exit_code, "", "", ""); + assert!(is_likely_sandbox_denied(SandboxType::LinuxSeccomp, &output)); +} + +#[cfg(unix)] +#[tokio::test] +async fn kill_child_process_group_kills_grandchildren_on_timeout() -> Result<()> { + // On Linux/macOS, /bin/bash is typically present; on FreeBSD/OpenBSD, + // prefer /bin/sh to avoid NotFound errors. + #[cfg(any(target_os = "freebsd", target_os = "openbsd"))] + let command = vec![ + "/bin/sh".to_string(), + "-c".to_string(), + "sleep 60 & echo $!; sleep 60".to_string(), + ]; + #[cfg(all(unix, not(any(target_os = "freebsd", target_os = "openbsd"))))] + let command = vec![ + "/bin/bash".to_string(), + "-c".to_string(), + "sleep 60 & echo $!; sleep 60".to_string(), + ]; + let env: HashMap = std::env::vars().collect(); + let params = ExecParams { + command, + cwd: std::env::current_dir()?, + expiration: 500.into(), + capture_policy: ExecCapturePolicy::ShellTool, + env, + network: None, + sandbox_permissions: SandboxPermissions::UseDefault, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + windows_sandbox_private_desktop: false, + justification: None, + arg0: None, + }; + + let output = exec( + params, + SandboxType::None, + &SandboxPolicy::new_read_only_policy(), + &FileSystemSandboxPolicy::from(&SandboxPolicy::new_read_only_policy()), + NetworkSandboxPolicy::Restricted, + None, + None, + ) + .await?; + assert!(output.timed_out); + + let stdout = output.stdout.from_utf8_lossy().text; + let pid_line = stdout.lines().next().unwrap_or("").trim(); + let pid: i32 = pid_line.parse().map_err(|error| { + io::Error::new( + io::ErrorKind::InvalidData, + format!("Failed to parse pid from stdout '{pid_line}': {error}"), + ) + })?; + + let mut killed = false; + for _ in 0..20 { + // Use kill(pid, 0) to check if the process is alive. + if unsafe { libc::kill(pid, 0) } == -1 + && let Some(libc::ESRCH) = std::io::Error::last_os_error().raw_os_error() + { + killed = true; + break; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + + assert!(killed, "grandchild process with pid {pid} is still alive"); + Ok(()) +} + +#[tokio::test] +async fn process_exec_tool_call_respects_cancellation_token() -> Result<()> { + let command = long_running_command(); + let cwd = std::env::current_dir()?; + let env: HashMap = std::env::vars().collect(); + let cancel_token = CancellationToken::new(); + let cancel_tx = cancel_token.clone(); + let params = ExecParams { + command, + cwd: cwd.clone(), + expiration: ExecExpiration::Cancellation(cancel_token), + capture_policy: ExecCapturePolicy::ShellTool, + env, + network: None, + sandbox_permissions: SandboxPermissions::UseDefault, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + windows_sandbox_private_desktop: false, + justification: None, + arg0: None, + }; + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(1_000)).await; + cancel_tx.cancel(); + }); + let result = process_exec_tool_call( + params, + &SandboxPolicy::DangerFullAccess, + &FileSystemSandboxPolicy::from(&SandboxPolicy::DangerFullAccess), + NetworkSandboxPolicy::Enabled, + cwd.as_path(), + &None, + false, + None, + ) + .await; + let output = match result { + Err(CodexErr::Sandbox(SandboxErr::Timeout { output })) => output, + other => panic!("expected timeout error, got {other:?}"), + }; + assert!(output.timed_out); + assert_eq!(output.exit_code, EXEC_TIMEOUT_EXIT_CODE); + Ok(()) +} + +#[cfg(unix)] +fn long_running_command() -> Vec { + vec![ + "/bin/sh".to_string(), + "-c".to_string(), + "sleep 30".to_string(), + ] +} + +#[cfg(windows)] +fn long_running_command() -> Vec { + vec![ + "powershell.exe".to_string(), + "-NonInteractive".to_string(), + "-NoLogo".to_string(), + "-Command".to_string(), + "Start-Sleep -Seconds 30".to_string(), + ] +} diff --git a/codex-rs/sandbox/src/landlock.rs b/codex-rs/sandbox/src/landlock.rs new file mode 100644 index 0000000000..6ad2c8bc32 --- /dev/null +++ b/codex-rs/sandbox/src/landlock.rs @@ -0,0 +1,170 @@ +use crate::protocol::SandboxPolicy; +use crate::spawn::SpawnChildRequest; +use crate::spawn::StdioPolicy; +use crate::spawn::spawn_child_async; +use codex_network_proxy::NetworkProxy; +use codex_protocol::permissions::FileSystemSandboxPolicy; +use codex_protocol::permissions::NetworkSandboxPolicy; +use std::collections::HashMap; +use std::path::Path; +use std::path::PathBuf; +use tokio::process::Child; + +/// Spawn a shell tool command under the Linux sandbox helper +/// (codex-linux-sandbox), which defaults to bubblewrap for filesystem +/// isolation plus seccomp for network restrictions. +/// +/// Unlike macOS Seatbelt where we directly embed the policy text, the Linux +/// helper is a separate executable. We pass the legacy [`SandboxPolicy`] plus +/// split filesystem/network policies as JSON so the helper can migrate +/// incrementally without breaking older call sites. +#[allow(clippy::too_many_arguments)] +pub async fn spawn_command_under_linux_sandbox

( + codex_linux_sandbox_exe: P, + command: Vec, + command_cwd: PathBuf, + sandbox_policy: &SandboxPolicy, + sandbox_policy_cwd: &Path, + use_legacy_landlock: bool, + stdio_policy: StdioPolicy, + network: Option<&NetworkProxy>, + env: HashMap, +) -> std::io::Result +where + P: AsRef, +{ + let file_system_sandbox_policy = + FileSystemSandboxPolicy::from_legacy_sandbox_policy(sandbox_policy, sandbox_policy_cwd); + let network_sandbox_policy = NetworkSandboxPolicy::from(sandbox_policy); + let args = create_linux_sandbox_command_args_for_policies( + command, + command_cwd.as_path(), + sandbox_policy, + &file_system_sandbox_policy, + network_sandbox_policy, + sandbox_policy_cwd, + use_legacy_landlock, + allow_network_for_proxy(/*enforce_managed_network*/ false), + ); + let arg0 = Some("codex-linux-sandbox"); + spawn_child_async(SpawnChildRequest { + program: codex_linux_sandbox_exe.as_ref().to_path_buf(), + args, + arg0, + cwd: command_cwd, + network_sandbox_policy, + network, + stdio_policy, + env, + }) + .await +} + +pub fn allow_network_for_proxy(enforce_managed_network: bool) -> bool { + // When managed network requirements are active, request proxy-only + // networking from the Linux sandbox helper. Without managed requirements, + // preserve existing behavior. + enforce_managed_network +} + +/// Converts the sandbox policies into the CLI invocation for +/// `codex-linux-sandbox`. +/// +/// The helper performs the actual sandboxing (bubblewrap by default + seccomp) after +/// parsing these arguments. Policy JSON flags are emitted before helper feature +/// flags so the argv order matches the helper's CLI shape. See +/// `docs/linux_sandbox.md` for the Linux semantics. +#[allow(clippy::too_many_arguments)] +pub fn create_linux_sandbox_command_args_for_policies( + command: Vec, + command_cwd: &Path, + sandbox_policy: &SandboxPolicy, + file_system_sandbox_policy: &FileSystemSandboxPolicy, + network_sandbox_policy: NetworkSandboxPolicy, + sandbox_policy_cwd: &Path, + use_legacy_landlock: bool, + allow_network_for_proxy: bool, +) -> Vec { + let sandbox_policy_json = serde_json::to_string(sandbox_policy) + .unwrap_or_else(|err| panic!("failed to serialize sandbox policy: {err}")); + let file_system_policy_json = serde_json::to_string(file_system_sandbox_policy) + .unwrap_or_else(|err| panic!("failed to serialize filesystem sandbox policy: {err}")); + let network_policy_json = serde_json::to_string(&network_sandbox_policy) + .unwrap_or_else(|err| panic!("failed to serialize network sandbox policy: {err}")); + let sandbox_policy_cwd = sandbox_policy_cwd + .to_str() + .unwrap_or_else(|| panic!("cwd must be valid UTF-8")) + .to_string(); + let command_cwd = command_cwd + .to_str() + .unwrap_or_else(|| panic!("command cwd must be valid UTF-8")) + .to_string(); + + let mut linux_cmd: Vec = vec![ + "--sandbox-policy-cwd".to_string(), + sandbox_policy_cwd, + "--command-cwd".to_string(), + command_cwd, + "--sandbox-policy".to_string(), + sandbox_policy_json, + "--file-system-sandbox-policy".to_string(), + file_system_policy_json, + "--network-sandbox-policy".to_string(), + network_policy_json, + ]; + if use_legacy_landlock { + linux_cmd.push("--use-legacy-landlock".to_string()); + } + if allow_network_for_proxy { + linux_cmd.push("--allow-network-for-proxy".to_string()); + } + linux_cmd.push("--".to_string()); + linux_cmd.extend(command); + linux_cmd +} + +/// Converts the sandbox cwd and execution options into the CLI invocation for +/// `codex-linux-sandbox`. +#[cfg(test)] +pub(crate) fn create_linux_sandbox_command_args( + command: Vec, + command_cwd: &Path, + sandbox_policy_cwd: &Path, + use_legacy_landlock: bool, + allow_network_for_proxy: bool, +) -> Vec { + let command_cwd = command_cwd + .to_str() + .unwrap_or_else(|| panic!("command cwd must be valid UTF-8")) + .to_string(); + let sandbox_policy_cwd = sandbox_policy_cwd + .to_str() + .unwrap_or_else(|| panic!("cwd must be valid UTF-8")) + .to_string(); + + let mut linux_cmd: Vec = vec![ + "--sandbox-policy-cwd".to_string(), + sandbox_policy_cwd, + "--command-cwd".to_string(), + command_cwd, + ]; + if use_legacy_landlock { + linux_cmd.push("--use-legacy-landlock".to_string()); + } + if allow_network_for_proxy { + linux_cmd.push("--allow-network-for-proxy".to_string()); + } + + // Separator so that command arguments starting with `-` are not parsed as + // options of the helper itself. + linux_cmd.push("--".to_string()); + + // Append the original tool command. + linux_cmd.extend(command); + + linux_cmd +} + +#[cfg(test)] +#[path = "landlock_tests.rs"] +mod tests; diff --git a/codex-rs/sandbox/src/landlock_tests.rs b/codex-rs/sandbox/src/landlock_tests.rs new file mode 100644 index 0000000000..454878cd51 --- /dev/null +++ b/codex-rs/sandbox/src/landlock_tests.rs @@ -0,0 +1,78 @@ +use super::*; +use pretty_assertions::assert_eq; + +#[test] +fn legacy_landlock_flag_is_included_when_requested() { + let command = vec!["/bin/true".to_string()]; + let command_cwd = Path::new("/tmp/link"); + let cwd = Path::new("/tmp"); + + let default_bwrap = + create_linux_sandbox_command_args(command.clone(), command_cwd, cwd, false, false); + assert_eq!( + default_bwrap.contains(&"--use-legacy-landlock".to_string()), + false + ); + + let legacy_landlock = create_linux_sandbox_command_args(command, command_cwd, cwd, true, false); + assert_eq!( + legacy_landlock.contains(&"--use-legacy-landlock".to_string()), + true + ); +} + +#[test] +fn proxy_flag_is_included_when_requested() { + let command = vec!["/bin/true".to_string()]; + let command_cwd = Path::new("/tmp/link"); + let cwd = Path::new("/tmp"); + + let args = create_linux_sandbox_command_args(command, command_cwd, cwd, true, true); + assert_eq!( + args.contains(&"--allow-network-for-proxy".to_string()), + true + ); +} + +#[test] +fn split_policy_flags_are_included() { + let command = vec!["/bin/true".to_string()]; + let command_cwd = Path::new("/tmp/link"); + let cwd = Path::new("/tmp"); + let sandbox_policy = SandboxPolicy::new_read_only_policy(); + let file_system_sandbox_policy = FileSystemSandboxPolicy::from(&sandbox_policy); + let network_sandbox_policy = NetworkSandboxPolicy::from(&sandbox_policy); + + let args = create_linux_sandbox_command_args_for_policies( + command, + command_cwd, + &sandbox_policy, + &file_system_sandbox_policy, + network_sandbox_policy, + cwd, + true, + false, + ); + + assert_eq!( + args.windows(2) + .any(|window| { window[0] == "--file-system-sandbox-policy" && !window[1].is_empty() }), + true + ); + assert_eq!( + args.windows(2) + .any(|window| window[0] == "--network-sandbox-policy" && window[1] == "\"restricted\""), + true + ); + assert_eq!( + args.windows(2) + .any(|window| window[0] == "--command-cwd" && window[1] == "/tmp/link"), + true + ); +} + +#[test] +fn proxy_network_requires_managed_requirements() { + assert_eq!(allow_network_for_proxy(false), false); + assert_eq!(allow_network_for_proxy(true), true); +} diff --git a/codex-rs/sandbox/src/lib.rs b/codex-rs/sandbox/src/lib.rs new file mode 100644 index 0000000000..5aac673cf1 --- /dev/null +++ b/codex-rs/sandbox/src/lib.rs @@ -0,0 +1,90 @@ +#![deny(clippy::print_stdout, clippy::print_stderr)] + +pub mod error; +pub mod exec; +pub mod landlock; +pub mod sandboxing; +pub mod seatbelt; +pub mod spawn; +pub mod windows_sandbox; +pub mod windows_sandbox_read_grants; + +pub use exec::DEFAULT_EXEC_COMMAND_TIMEOUT_MS; +pub use exec::ExecCapturePolicy; +pub use exec::ExecExpiration; +pub use exec::ExecParams; +pub use exec::ExecToolCallOutput; +pub use exec::IO_DRAIN_TIMEOUT_MS; +pub use exec::MAX_EXEC_OUTPUT_DELTAS_PER_CALL; +pub use exec::SandboxType; +pub use exec::StdoutStream; +pub use exec::StreamOutput; +pub use exec::build_exec_request; +pub use exec::execute_exec_request; +pub use exec::is_likely_sandbox_denied; +pub use exec::process_exec_tool_call; +pub use landlock::allow_network_for_proxy; +pub use landlock::create_linux_sandbox_command_args_for_policies; +pub use landlock::spawn_command_under_linux_sandbox; +pub use sandboxing::CommandSpec; +pub use sandboxing::ExecRequest; +pub use sandboxing::SandboxManager; +pub use sandboxing::SandboxPermissions; +pub use sandboxing::SandboxPreference; +pub use sandboxing::SandboxTransformError; +pub use sandboxing::effective_file_system_sandbox_policy; +pub use sandboxing::execute_env; +pub use sandboxing::execute_exec_request_with_after_spawn; +pub use sandboxing::intersect_permission_profiles; +pub use sandboxing::merge_permission_profiles; +pub use sandboxing::normalize_additional_permissions; +pub use spawn::CODEX_SANDBOX_ENV_VAR; +pub use spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; +pub use spawn::StdioPolicy; +pub use windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED; +pub use windows_sandbox::WindowsSandboxLevelExt; +pub use windows_sandbox::WindowsSandboxMode; +pub use windows_sandbox::WindowsSandboxSetupMode; +pub use windows_sandbox::WindowsSandboxSetupRequest; +pub use windows_sandbox::elevated_setup_failure_details; +pub use windows_sandbox::elevated_setup_failure_metric_name; +pub use windows_sandbox::legacy_windows_sandbox_mode; +pub use windows_sandbox::legacy_windows_sandbox_mode_from_entries; +pub use windows_sandbox::resolve_windows_sandbox_mode; +pub use windows_sandbox::resolve_windows_sandbox_private_desktop; +pub use windows_sandbox::run_elevated_setup; +pub use windows_sandbox::run_legacy_setup_preflight; +pub use windows_sandbox::run_setup_refresh_with_extra_read_roots; +pub use windows_sandbox::run_windows_sandbox_setup; +pub use windows_sandbox::sandbox_setup_is_complete; +pub use windows_sandbox::windows_sandbox_mode_tag; +pub use windows_sandbox_read_grants::grant_read_root_non_elevated; + +#[cfg(target_os = "macos")] +pub use seatbelt::MACOS_PATH_TO_SEATBELT_EXECUTABLE; +#[cfg(target_os = "macos")] +pub use seatbelt::create_seatbelt_command_args_for_policies_with_extensions; +#[cfg(target_os = "macos")] +pub use seatbelt::spawn_command_under_seatbelt; + +mod seatbelt_permissions; + +pub fn get_platform_sandbox(windows_sandbox_enabled: bool) -> Option { + if cfg!(target_os = "macos") { + Some(SandboxType::MacosSeatbelt) + } else if cfg!(target_os = "linux") { + Some(SandboxType::LinuxSeccomp) + } else if cfg!(target_os = "windows") { + if windows_sandbox_enabled { + Some(SandboxType::WindowsRestrictedToken) + } else { + None + } + } else { + None + } +} + +pub(crate) use codex_protocol::protocol; + +mod text_encoding; diff --git a/codex-rs/sandbox/src/restricted_read_only_platform_defaults.sbpl b/codex-rs/sandbox/src/restricted_read_only_platform_defaults.sbpl new file mode 100644 index 0000000000..0e3a7bb2f2 --- /dev/null +++ b/codex-rs/sandbox/src/restricted_read_only_platform_defaults.sbpl @@ -0,0 +1,199 @@ +; macOS platform defaults included via `ReadOnlyAccess::Restricted::include_platform_defaults` + +; Read access to standard system paths +(allow file-read* file-test-existence + (subpath "/Library/Apple") + (subpath "/Library/Filesystems/NetFSPlugins") + (subpath "/Library/Preferences/Logging") + (subpath "/private/var/db/DarwinDirectory/local/recordStore.data") + (subpath "/private/var/db/timezone") + (subpath "/usr/lib") + (subpath "/usr/share") + (subpath "/Library/Preferences") + (subpath "/var/db") + (subpath "/private/var/db")) + +; Map system frameworks + dylibs for loader. +(allow file-map-executable + (subpath "/Library/Apple/System/Library/Frameworks") + (subpath "/Library/Apple/System/Library/PrivateFrameworks") + (subpath "/Library/Apple/usr/lib") + (subpath "/System/Library/Extensions") + (subpath "/System/Library/Frameworks") + (subpath "/System/Library/PrivateFrameworks") + (subpath "/System/Library/SubFrameworks") + (subpath "/System/iOSSupport/System/Library/Frameworks") + (subpath "/System/iOSSupport/System/Library/PrivateFrameworks") + (subpath "/System/iOSSupport/System/Library/SubFrameworks") + (subpath "/usr/lib")) + +; System Framework and AppKit resources +(allow file-read* file-test-existence + (subpath "/Library/Apple/System/Library/Frameworks") + (subpath "/Library/Apple/System/Library/PrivateFrameworks") + (subpath "/Library/Apple/usr/lib") + (subpath "/System/Library/Frameworks") + (subpath "/System/Library/PrivateFrameworks") + (subpath "/System/Library/SubFrameworks") + (subpath "/System/iOSSupport/System/Library/Frameworks") + (subpath "/System/iOSSupport/System/Library/PrivateFrameworks") + (subpath "/System/iOSSupport/System/Library/SubFrameworks") + (subpath "/usr/lib")) + +; Allow guarded vnodes. +(allow system-mac-syscall (mac-policy-name "vnguard")) + +; Determine whether a container is expected. +(allow system-mac-syscall + (require-all + (mac-policy-name "Sandbox") + (mac-syscall-number 67))) + +; Allow resolution of standard system symlinks. +(allow file-read-metadata file-test-existence + (literal "/etc") + (literal "/tmp") + (literal "/var") + (literal "/private/etc/localtime")) + +; Allow stat'ing of firmlink parent path components. +(allow file-read-metadata file-test-existence + (path-ancestors "/System/Volumes/Data/private")) + +; Allow processes to get their current working directory. +(allow file-read* file-test-existence + (literal "/")) + +; Allow FSIOC_CAS_BSDFLAGS as alternate chflags. +(allow system-fsctl (fsctl-command FSIOC_CAS_BSDFLAGS)) + +; Allow access to standard special files. +(allow file-read* file-test-existence + (literal "/dev/autofs_nowait") + (literal "/dev/random") + (literal "/dev/urandom") + (literal "/private/etc/master.passwd") + (literal "/private/etc/passwd") + (literal "/private/etc/protocols") + (literal "/private/etc/services")) + +; Allow null/zero read/write. +(allow file-read* file-test-existence file-write-data + (literal "/dev/null") + (literal "/dev/zero")) + +; Allow read/write access to the file descriptors. +(allow file-read-data file-test-existence file-write-data + (subpath "/dev/fd")) + +; Provide access to debugger helpers. +(allow file-read* file-test-existence file-write-data file-ioctl + (literal "/dev/dtracehelper")) + +; Scratch space so tools can create temp files. +(allow file-read* file-test-existence file-write* (subpath "/tmp")) +(allow file-read* file-write* (subpath "/private/tmp")) +(allow file-read* file-write* (subpath "/var/tmp")) +(allow file-read* file-write* (subpath "/private/var/tmp")) + +; Allow reading standard config directories. +(allow file-read* (subpath "/etc")) +(allow file-read* (subpath "/private/etc")) + +(allow file-read* file-test-existence + (literal "/System/Library/CoreServices") + (literal "/System/Library/CoreServices/.SystemVersionPlatform.plist") + (literal "/System/Library/CoreServices/SystemVersion.plist")) + +; Some processes read /var metadata during startup. +(allow file-read-metadata (subpath "/var")) +(allow file-read-metadata (subpath "/private/var")) + +; IOKit access for root domain services. +(allow iokit-open + (iokit-registry-entry-class "RootDomainUserClient")) + +; macOS Standard library queries opendirectoryd at startup +(allow mach-lookup (global-name "com.apple.system.opendirectoryd.libinfo")) + +; Allow IPC to analytics, logging, trust, and other system agents. +(allow mach-lookup + (global-name "com.apple.analyticsd") + (global-name "com.apple.analyticsd.messagetracer") + (global-name "com.apple.appsleep") + (global-name "com.apple.bsd.dirhelper") + (global-name "com.apple.cfprefsd.agent") + (global-name "com.apple.cfprefsd.daemon") + (global-name "com.apple.diagnosticd") + (global-name "com.apple.dt.automationmode.reader") + (global-name "com.apple.espd") + (global-name "com.apple.logd") + (global-name "com.apple.logd.events") + (global-name "com.apple.runningboard") + (global-name "com.apple.secinitd") + (global-name "com.apple.system.DirectoryService.libinfo_v1") + (global-name "com.apple.system.logger") + (global-name "com.apple.system.notification_center") + (global-name "com.apple.system.opendirectoryd.membership") + (global-name "com.apple.trustd") + (global-name "com.apple.trustd.agent") + (global-name "com.apple.xpc.activity.unmanaged") + (local-name "com.apple.cfprefsd.agent")) + +; Allow IPC to the syslog socket for logging. +(allow network-outbound (literal "/private/var/run/syslog")) + +; macOS Notifications +(allow ipc-posix-shm-read* + (ipc-posix-name "apple.shm.notification_center")) + +; Regulatory domain support. +(allow file-read* + (literal "/private/var/db/eligibilityd/eligibility.plist")) + +; Audio and power management services. +(allow mach-lookup (global-name "com.apple.audio.audiohald")) +(allow mach-lookup (global-name "com.apple.audio.AudioComponentRegistrar")) +(allow mach-lookup (global-name "com.apple.PowerManagement.control")) + +; Allow reading the minimum system runtime so exec works. +(allow file-read-data (subpath "/bin")) +(allow file-read-metadata (subpath "/bin")) +(allow file-read-data (subpath "/sbin")) +(allow file-read-metadata (subpath "/sbin")) +(allow file-read-data (subpath "/usr/bin")) +(allow file-read-metadata (subpath "/usr/bin")) +(allow file-read-data (subpath "/usr/sbin")) +(allow file-read-metadata (subpath "/usr/sbin")) +(allow file-read-data (subpath "/usr/libexec")) +(allow file-read-metadata (subpath "/usr/libexec")) + +(allow file-read* (subpath "/Library/Preferences")) +(allow file-read* (subpath "/opt/homebrew/lib")) +(allow file-read* (subpath "/usr/local/lib")) +(allow file-read* (subpath "/Applications")) + +; Terminal basics and device handles. +(allow file-read* (regex "^/dev/fd/(0|1|2)$")) +(allow file-write* (regex "^/dev/fd/(1|2)$")) +(allow file-read* file-write* (literal "/dev/null")) +(allow file-read* file-write* (literal "/dev/tty")) +(allow file-read-metadata (literal "/dev")) +(allow file-read-metadata (regex "^/dev/.*$")) +(allow file-read-metadata (literal "/dev/stdin")) +(allow file-read-metadata (literal "/dev/stdout")) +(allow file-read-metadata (literal "/dev/stderr")) +(allow file-read-metadata (regex "^/dev/tty[^/]*$")) +(allow file-read-metadata (regex "^/dev/pty[^/]*$")) +(allow file-read* file-write* (regex "^/dev/ttys[0-9]+$")) +(allow file-read* file-write* (literal "/dev/ptmx")) +(allow file-ioctl (regex "^/dev/ttys[0-9]+$")) + +; Allow metadata traversal for firmlink parents. +(allow file-read-metadata (literal "/System/Volumes") (vnode-type DIRECTORY)) +(allow file-read-metadata (literal "/System/Volumes/Data") (vnode-type DIRECTORY)) +(allow file-read-metadata (literal "/System/Volumes/Data/Users") (vnode-type DIRECTORY)) + +; App sandbox extensions +(allow file-read* (extension "com.apple.app-sandbox.read")) +(allow file-read* file-write* (extension "com.apple.app-sandbox.read-write")) diff --git a/codex-rs/sandbox/src/sandboxing/macos_permissions.rs b/codex-rs/sandbox/src/sandboxing/macos_permissions.rs new file mode 100644 index 0000000000..1a409d4bdf --- /dev/null +++ b/codex-rs/sandbox/src/sandboxing/macos_permissions.rs @@ -0,0 +1,154 @@ +use std::collections::BTreeSet; + +use codex_protocol::models::MacOsAutomationPermission; +use codex_protocol::models::MacOsContactsPermission; +use codex_protocol::models::MacOsPreferencesPermission; +use codex_protocol::models::MacOsSeatbeltProfileExtensions; + +/// Merges macOS seatbelt profile extensions by taking the permissive union of +/// each permission field. +pub(crate) fn merge_macos_seatbelt_profile_extensions( + base: Option<&MacOsSeatbeltProfileExtensions>, + permissions: Option<&MacOsSeatbeltProfileExtensions>, +) -> Option { + let Some(permissions) = permissions else { + return base.cloned(); + }; + + match base { + Some(base) => Some(MacOsSeatbeltProfileExtensions { + macos_preferences: union_macos_preferences_permission( + &base.macos_preferences, + &permissions.macos_preferences, + ), + macos_automation: union_macos_automation_permission( + &base.macos_automation, + &permissions.macos_automation, + ), + macos_launch_services: base.macos_launch_services || permissions.macos_launch_services, + macos_accessibility: base.macos_accessibility || permissions.macos_accessibility, + macos_calendar: base.macos_calendar || permissions.macos_calendar, + macos_reminders: base.macos_reminders || permissions.macos_reminders, + macos_contacts: union_macos_contacts_permission( + &base.macos_contacts, + &permissions.macos_contacts, + ), + }), + None => Some(permissions.clone()), + } +} + +pub(crate) fn intersect_macos_seatbelt_profile_extensions( + requested: Option, + granted: Option, +) -> Option { + match (requested, granted) { + (Some(requested), Some(granted)) => { + let macos_automation = intersect_macos_automation_permission( + &requested.macos_automation, + &granted.macos_automation, + ); + + Some(MacOsSeatbeltProfileExtensions { + macos_preferences: requested.macos_preferences.min(granted.macos_preferences), + macos_automation, + macos_launch_services: requested.macos_launch_services + && granted.macos_launch_services, + macos_accessibility: requested.macos_accessibility && granted.macos_accessibility, + macos_calendar: requested.macos_calendar && granted.macos_calendar, + macos_reminders: requested.macos_reminders && granted.macos_reminders, + macos_contacts: requested.macos_contacts.min(granted.macos_contacts), + }) + } + _ => None, + } +} + +/// Unions two preferences permissions by keeping the more permissive one. +/// +/// The larger rank wins: `None < ReadOnly < ReadWrite`. When both sides have +/// the same rank, this keeps `base`. +fn union_macos_preferences_permission( + base: &MacOsPreferencesPermission, + requested: &MacOsPreferencesPermission, +) -> MacOsPreferencesPermission { + if base < requested { + requested.clone() + } else { + base.clone() + } +} + +fn union_macos_contacts_permission( + base: &MacOsContactsPermission, + requested: &MacOsContactsPermission, +) -> MacOsContactsPermission { + if base < requested { + requested.clone() + } else { + base.clone() + } +} + +/// Unions two automation permissions by keeping the more permissive result. +/// +/// `All` wins over everything, `None` yields to the other side, and two bundle +/// ID allowlists are unioned together. +fn union_macos_automation_permission( + base: &MacOsAutomationPermission, + requested: &MacOsAutomationPermission, +) -> MacOsAutomationPermission { + match (base, requested) { + (MacOsAutomationPermission::All, _) | (_, MacOsAutomationPermission::All) => { + MacOsAutomationPermission::All + } + (MacOsAutomationPermission::None, _) => requested.clone(), + (_, MacOsAutomationPermission::None) => base.clone(), + ( + MacOsAutomationPermission::BundleIds(base_bundle_ids), + MacOsAutomationPermission::BundleIds(requested_bundle_ids), + ) => MacOsAutomationPermission::BundleIds( + base_bundle_ids + .iter() + .chain(requested_bundle_ids.iter()) + .cloned() + .collect::>() + .into_iter() + .collect(), + ), + } +} + +fn intersect_macos_automation_permission( + requested: &MacOsAutomationPermission, + granted: &MacOsAutomationPermission, +) -> MacOsAutomationPermission { + match (requested, granted) { + (_, MacOsAutomationPermission::None) | (MacOsAutomationPermission::None, _) => { + MacOsAutomationPermission::None + } + (MacOsAutomationPermission::All, granted) => granted.clone(), + (MacOsAutomationPermission::BundleIds(requested), MacOsAutomationPermission::All) => { + MacOsAutomationPermission::BundleIds(requested.clone()) + } + ( + MacOsAutomationPermission::BundleIds(requested), + MacOsAutomationPermission::BundleIds(granted), + ) => { + let bundle_ids = requested + .iter() + .filter(|bundle_id| granted.contains(bundle_id)) + .cloned() + .collect::>(); + if bundle_ids.is_empty() { + MacOsAutomationPermission::None + } else { + MacOsAutomationPermission::BundleIds(bundle_ids) + } + } + } +} + +#[cfg(all(test, target_os = "macos"))] +#[path = "macos_permissions_tests.rs"] +mod tests; diff --git a/codex-rs/sandbox/src/sandboxing/macos_permissions_tests.rs b/codex-rs/sandbox/src/sandboxing/macos_permissions_tests.rs new file mode 100644 index 0000000000..97a2a2c753 --- /dev/null +++ b/codex-rs/sandbox/src/sandboxing/macos_permissions_tests.rs @@ -0,0 +1,121 @@ +use super::intersect_macos_automation_permission; +use super::intersect_macos_seatbelt_profile_extensions; +use super::merge_macos_seatbelt_profile_extensions; +use super::union_macos_automation_permission; +use super::union_macos_contacts_permission; +use super::union_macos_preferences_permission; +use codex_protocol::models::MacOsAutomationPermission; +use codex_protocol::models::MacOsContactsPermission; +use codex_protocol::models::MacOsPreferencesPermission; +use codex_protocol::models::MacOsSeatbeltProfileExtensions; +use pretty_assertions::assert_eq; + +#[test] +fn merge_extensions_widens_permissions() { + let base = MacOsSeatbeltProfileExtensions { + macos_preferences: MacOsPreferencesPermission::ReadOnly, + macos_automation: MacOsAutomationPermission::BundleIds(vec![ + "com.apple.Calendar".to_string(), + ]), + macos_launch_services: false, + macos_accessibility: false, + macos_calendar: false, + macos_reminders: false, + macos_contacts: MacOsContactsPermission::ReadOnly, + }; + let requested = MacOsSeatbeltProfileExtensions { + macos_preferences: MacOsPreferencesPermission::ReadWrite, + macos_automation: MacOsAutomationPermission::BundleIds(vec![ + "com.apple.Notes".to_string(), + "com.apple.Calendar".to_string(), + ]), + macos_launch_services: true, + macos_accessibility: true, + macos_calendar: true, + macos_reminders: true, + macos_contacts: MacOsContactsPermission::ReadWrite, + }; + + let merged = + merge_macos_seatbelt_profile_extensions(Some(&base), Some(&requested)).expect("merge"); + + assert_eq!( + merged, + MacOsSeatbeltProfileExtensions { + macos_preferences: MacOsPreferencesPermission::ReadWrite, + macos_automation: MacOsAutomationPermission::BundleIds(vec![ + "com.apple.Calendar".to_string(), + "com.apple.Notes".to_string(), + ]), + macos_launch_services: true, + macos_accessibility: true, + macos_calendar: true, + macos_reminders: true, + macos_contacts: MacOsContactsPermission::ReadWrite, + } + ); +} + +#[test] +fn union_macos_preferences_permission_does_not_downgrade() { + let base = MacOsPreferencesPermission::ReadWrite; + let requested = MacOsPreferencesPermission::ReadOnly; + + let merged = union_macos_preferences_permission(&base, &requested); + + assert_eq!(merged, MacOsPreferencesPermission::ReadWrite); +} + +#[test] +fn union_macos_automation_permission_all_is_dominant() { + let base = MacOsAutomationPermission::BundleIds(vec!["com.apple.Notes".to_string()]); + let requested = MacOsAutomationPermission::All; + + let merged = union_macos_automation_permission(&base, &requested); + + assert_eq!(merged, MacOsAutomationPermission::All); +} + +#[test] +fn intersect_macos_automation_permission_keeps_common_bundle_ids() { + let requested = MacOsAutomationPermission::BundleIds(vec![ + "com.apple.Notes".to_string(), + "com.apple.Calendar".to_string(), + ]); + let granted = MacOsAutomationPermission::BundleIds(vec!["com.apple.Notes".to_string()]); + + let intersected = intersect_macos_automation_permission(&requested, &granted); + + assert_eq!( + intersected, + MacOsAutomationPermission::BundleIds(vec!["com.apple.Notes".to_string()]) + ); +} + +#[test] +fn intersect_macos_seatbelt_profile_extensions_preserves_default_grant() { + let requested = MacOsSeatbeltProfileExtensions { + macos_preferences: MacOsPreferencesPermission::ReadWrite, + macos_automation: MacOsAutomationPermission::BundleIds(vec!["com.apple.Notes".to_string()]), + macos_launch_services: false, + macos_accessibility: true, + macos_calendar: true, + macos_reminders: false, + macos_contacts: MacOsContactsPermission::None, + }; + let granted = MacOsSeatbeltProfileExtensions::default(); + + let intersected = intersect_macos_seatbelt_profile_extensions(Some(requested), Some(granted)); + + assert_eq!(intersected, Some(MacOsSeatbeltProfileExtensions::default())); +} + +#[test] +fn union_macos_contacts_permission_does_not_downgrade() { + let base = MacOsContactsPermission::ReadWrite; + let requested = MacOsContactsPermission::ReadOnly; + + let merged = union_macos_contacts_permission(&base, &requested); + + assert_eq!(merged, MacOsContactsPermission::ReadWrite); +} diff --git a/codex-rs/sandbox/src/sandboxing/mod.rs b/codex-rs/sandbox/src/sandboxing/mod.rs new file mode 100644 index 0000000000..dde529b8c3 --- /dev/null +++ b/codex-rs/sandbox/src/sandboxing/mod.rs @@ -0,0 +1,754 @@ +/* +Module: sandboxing + +Build platform wrappers and produce ExecRequest for execution. Owns low-level +sandbox placement and transformation of portable CommandSpec into a +ready‑to‑spawn environment. +*/ + +pub(crate) mod macos_permissions; + +use crate::exec::ExecCapturePolicy; +use crate::exec::ExecExpiration; +use crate::exec::ExecToolCallOutput; +use crate::exec::SandboxType; +use crate::exec::StdoutStream; +use crate::exec::execute_exec_request; +use crate::landlock::allow_network_for_proxy; +use crate::landlock::create_linux_sandbox_command_args_for_policies; +use crate::protocol::SandboxPolicy; +#[cfg(target_os = "macos")] +use crate::seatbelt::MACOS_PATH_TO_SEATBELT_EXECUTABLE; +#[cfg(target_os = "macos")] +use crate::seatbelt::create_seatbelt_command_args_for_policies_with_extensions; +#[cfg(target_os = "macos")] +use crate::spawn::CODEX_SANDBOX_ENV_VAR; +use crate::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; +use codex_network_proxy::NetworkProxy; +use codex_protocol::config_types::WindowsSandboxLevel; +use codex_protocol::models::FileSystemPermissions; +use codex_protocol::models::MacOsSeatbeltProfileExtensions; +use codex_protocol::models::NetworkPermissions; +use codex_protocol::models::PermissionProfile; +pub use codex_protocol::models::SandboxPermissions; +use codex_protocol::permissions::FileSystemAccessMode; +use codex_protocol::permissions::FileSystemPath; +use codex_protocol::permissions::FileSystemSandboxEntry; +use codex_protocol::permissions::FileSystemSandboxKind; +use codex_protocol::permissions::FileSystemSandboxPolicy; +use codex_protocol::permissions::NetworkSandboxPolicy; +use codex_protocol::protocol::NetworkAccess; +use codex_protocol::protocol::ReadOnlyAccess; +use codex_utils_absolute_path::AbsolutePathBuf; +use dunce::canonicalize; +use macos_permissions::intersect_macos_seatbelt_profile_extensions; +use macos_permissions::merge_macos_seatbelt_profile_extensions; +use std::collections::HashMap; +use std::collections::HashSet; +use std::path::Path; +use std::path::PathBuf; + +#[derive(Debug)] +pub struct CommandSpec { + pub program: String, + pub args: Vec, + pub cwd: PathBuf, + pub env: HashMap, + pub expiration: ExecExpiration, + pub capture_policy: ExecCapturePolicy, + pub sandbox_permissions: SandboxPermissions, + pub additional_permissions: Option, + pub justification: Option, +} + +#[derive(Debug)] +pub struct ExecRequest { + pub command: Vec, + pub cwd: PathBuf, + pub env: HashMap, + pub network: Option, + pub expiration: ExecExpiration, + pub capture_policy: ExecCapturePolicy, + pub sandbox: SandboxType, + pub windows_sandbox_level: WindowsSandboxLevel, + pub windows_sandbox_private_desktop: bool, + pub sandbox_permissions: SandboxPermissions, + pub sandbox_policy: SandboxPolicy, + pub file_system_sandbox_policy: FileSystemSandboxPolicy, + pub network_sandbox_policy: NetworkSandboxPolicy, + pub justification: Option, + pub arg0: Option, +} + +/// Bundled arguments for sandbox transformation. +/// +/// This keeps call sites self-documenting when several fields are optional. +pub struct SandboxTransformRequest<'a> { + pub spec: CommandSpec, + pub policy: &'a SandboxPolicy, + pub file_system_policy: &'a FileSystemSandboxPolicy, + pub network_policy: NetworkSandboxPolicy, + pub sandbox: SandboxType, + pub enforce_managed_network: bool, + // TODO(viyatb): Evaluate switching this to Option> + // to make shared ownership explicit across runtime/sandbox plumbing. + pub network: Option<&'a NetworkProxy>, + pub sandbox_policy_cwd: &'a Path, + #[cfg(target_os = "macos")] + pub macos_seatbelt_profile_extensions: Option<&'a MacOsSeatbeltProfileExtensions>, + pub codex_linux_sandbox_exe: Option<&'a PathBuf>, + pub use_legacy_landlock: bool, + pub windows_sandbox_level: WindowsSandboxLevel, + pub windows_sandbox_private_desktop: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SandboxPreference { + Auto, + Require, + Forbid, +} + +#[derive(Debug, thiserror::Error)] +pub enum SandboxTransformError { + #[error("missing codex-linux-sandbox executable path")] + MissingLinuxSandboxExecutable, + #[cfg(not(target_os = "macos"))] + #[error("seatbelt sandbox is only available on macOS")] + SeatbeltUnavailable, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct EffectiveSandboxPermissions { + pub(crate) sandbox_policy: SandboxPolicy, + pub(crate) macos_seatbelt_profile_extensions: Option, +} + +impl EffectiveSandboxPermissions { + pub(crate) fn new( + sandbox_policy: &SandboxPolicy, + macos_seatbelt_profile_extensions: Option<&MacOsSeatbeltProfileExtensions>, + additional_permissions: Option<&PermissionProfile>, + ) -> Self { + let Some(additional_permissions) = additional_permissions else { + return Self { + sandbox_policy: sandbox_policy.clone(), + macos_seatbelt_profile_extensions: macos_seatbelt_profile_extensions.cloned(), + }; + }; + + Self { + sandbox_policy: sandbox_policy_with_additional_permissions( + sandbox_policy, + additional_permissions, + ), + macos_seatbelt_profile_extensions: merge_macos_seatbelt_profile_extensions( + macos_seatbelt_profile_extensions, + additional_permissions.macos.as_ref(), + ), + } + } +} + +pub fn normalize_additional_permissions( + additional_permissions: PermissionProfile, +) -> Result { + let network = additional_permissions + .network + .filter(|network| !network.is_empty()); + let file_system = additional_permissions + .file_system + .map(|file_system| { + let read = file_system + .read + .map(|paths| normalize_permission_paths(paths, "file_system.read")); + let write = file_system + .write + .map(|paths| normalize_permission_paths(paths, "file_system.write")); + FileSystemPermissions { read, write } + }) + .filter(|file_system| !file_system.is_empty()); + let macos = additional_permissions.macos; + + Ok(PermissionProfile { + network, + file_system, + macos, + }) +} + +pub fn merge_permission_profiles( + base: Option<&PermissionProfile>, + permissions: Option<&PermissionProfile>, +) -> Option { + let Some(permissions) = permissions else { + return base.cloned(); + }; + + match base { + Some(base) => { + let network = match (base.network.as_ref(), permissions.network.as_ref()) { + ( + Some(NetworkPermissions { + enabled: Some(true), + }), + _, + ) + | ( + _, + Some(NetworkPermissions { + enabled: Some(true), + }), + ) => Some(NetworkPermissions { + enabled: Some(true), + }), + _ => None, + }; + let file_system = match (base.file_system.as_ref(), permissions.file_system.as_ref()) { + (Some(base), Some(permissions)) => Some(FileSystemPermissions { + read: merge_permission_paths(base.read.as_ref(), permissions.read.as_ref()), + write: merge_permission_paths(base.write.as_ref(), permissions.write.as_ref()), + }) + .filter(|file_system| !file_system.is_empty()), + (Some(base), None) => Some(base.clone()), + (None, Some(permissions)) => Some(permissions.clone()), + (None, None) => None, + }; + let macos = merge_macos_seatbelt_profile_extensions( + base.macos.as_ref(), + permissions.macos.as_ref(), + ); + + Some(PermissionProfile { + network, + file_system, + macos, + }) + .filter(|permissions| !permissions.is_empty()) + } + None => Some(permissions.clone()).filter(|permissions| !permissions.is_empty()), + } +} + +pub fn intersect_permission_profiles( + requested: PermissionProfile, + granted: PermissionProfile, +) -> PermissionProfile { + let file_system = requested + .file_system + .map(|requested_file_system| { + let granted_file_system = granted.file_system.unwrap_or_default(); + let read = requested_file_system + .read + .map(|requested_read| { + let granted_read = granted_file_system.read.unwrap_or_default(); + requested_read + .into_iter() + .filter(|path| granted_read.contains(path)) + .collect() + }) + .filter(|paths: &Vec<_>| !paths.is_empty()); + let write = requested_file_system + .write + .map(|requested_write| { + let granted_write = granted_file_system.write.unwrap_or_default(); + requested_write + .into_iter() + .filter(|path| granted_write.contains(path)) + .collect() + }) + .filter(|paths: &Vec<_>| !paths.is_empty()); + FileSystemPermissions { read, write } + }) + .filter(|file_system| !file_system.is_empty()); + let network = match (requested.network, granted.network) { + ( + Some(NetworkPermissions { + enabled: Some(true), + }), + Some(NetworkPermissions { + enabled: Some(true), + }), + ) => Some(NetworkPermissions { + enabled: Some(true), + }), + _ => None, + }; + + let macos = intersect_macos_seatbelt_profile_extensions(requested.macos, granted.macos); + + PermissionProfile { + network, + file_system, + macos, + } +} + +fn normalize_permission_paths( + paths: Vec, + _permission_kind: &str, +) -> Vec { + let mut out = Vec::with_capacity(paths.len()); + let mut seen = HashSet::new(); + + for path in paths { + let canonicalized = canonicalize(path.as_path()) + .ok() + .and_then(|path| AbsolutePathBuf::from_absolute_path(path).ok()) + .unwrap_or(path); + if seen.insert(canonicalized.clone()) { + out.push(canonicalized); + } + } + + out +} + +fn merge_permission_paths( + base: Option<&Vec>, + permissions: Option<&Vec>, +) -> Option> { + match (base, permissions) { + (Some(base), Some(permissions)) => { + let mut merged = Vec::with_capacity(base.len() + permissions.len()); + let mut seen = HashSet::with_capacity(base.len() + permissions.len()); + + for path in base.iter().chain(permissions.iter()) { + if seen.insert(path.clone()) { + merged.push(path.clone()); + } + } + + Some(merged).filter(|paths| !paths.is_empty()) + } + (Some(base), None) => Some(base.clone()), + (None, Some(permissions)) => Some(permissions.clone()), + (None, None) => None, + } +} + +fn dedup_absolute_paths(paths: Vec) -> Vec { + let mut out = Vec::with_capacity(paths.len()); + let mut seen = HashSet::new(); + for path in paths { + if seen.insert(path.to_path_buf()) { + out.push(path); + } + } + out +} + +fn additional_permission_roots( + additional_permissions: &PermissionProfile, +) -> (Vec, Vec) { + ( + dedup_absolute_paths( + additional_permissions + .file_system + .as_ref() + .and_then(|file_system| file_system.read.clone()) + .unwrap_or_default(), + ), + dedup_absolute_paths( + additional_permissions + .file_system + .as_ref() + .and_then(|file_system| file_system.write.clone()) + .unwrap_or_default(), + ), + ) +} + +fn merge_file_system_policy_with_additional_permissions( + file_system_policy: &FileSystemSandboxPolicy, + extra_reads: Vec, + extra_writes: Vec, +) -> FileSystemSandboxPolicy { + match file_system_policy.kind { + FileSystemSandboxKind::Restricted => { + let mut merged_policy = file_system_policy.clone(); + for path in extra_reads { + let entry = FileSystemSandboxEntry { + path: FileSystemPath::Path { path }, + access: FileSystemAccessMode::Read, + }; + if !merged_policy.entries.contains(&entry) { + merged_policy.entries.push(entry); + } + } + for path in extra_writes { + let entry = FileSystemSandboxEntry { + path: FileSystemPath::Path { path }, + access: FileSystemAccessMode::Write, + }; + if !merged_policy.entries.contains(&entry) { + merged_policy.entries.push(entry); + } + } + merged_policy + } + FileSystemSandboxKind::Unrestricted | FileSystemSandboxKind::ExternalSandbox => { + file_system_policy.clone() + } + } +} + +pub fn effective_file_system_sandbox_policy( + file_system_policy: &FileSystemSandboxPolicy, + additional_permissions: Option<&PermissionProfile>, +) -> FileSystemSandboxPolicy { + let Some(additional_permissions) = additional_permissions else { + return file_system_policy.clone(); + }; + + let (extra_reads, extra_writes) = additional_permission_roots(additional_permissions); + if extra_reads.is_empty() && extra_writes.is_empty() { + file_system_policy.clone() + } else { + merge_file_system_policy_with_additional_permissions( + file_system_policy, + extra_reads, + extra_writes, + ) + } +} + +fn merge_read_only_access_with_additional_reads( + read_only_access: &ReadOnlyAccess, + extra_reads: Vec, +) -> ReadOnlyAccess { + match read_only_access { + ReadOnlyAccess::FullAccess => ReadOnlyAccess::FullAccess, + ReadOnlyAccess::Restricted { + include_platform_defaults, + readable_roots, + } => { + let mut merged = readable_roots.clone(); + merged.extend(extra_reads); + ReadOnlyAccess::Restricted { + include_platform_defaults: *include_platform_defaults, + readable_roots: dedup_absolute_paths(merged), + } + } + } +} + +fn merge_network_access( + base_network_access: bool, + additional_permissions: &PermissionProfile, +) -> bool { + base_network_access + || additional_permissions + .network + .as_ref() + .and_then(|network| network.enabled) + .unwrap_or(false) +} + +fn sandbox_policy_with_additional_permissions( + sandbox_policy: &SandboxPolicy, + additional_permissions: &PermissionProfile, +) -> SandboxPolicy { + if additional_permissions.is_empty() { + return sandbox_policy.clone(); + } + + let (extra_reads, extra_writes) = additional_permission_roots(additional_permissions); + + match sandbox_policy { + SandboxPolicy::DangerFullAccess => SandboxPolicy::DangerFullAccess, + SandboxPolicy::ExternalSandbox { network_access } => SandboxPolicy::ExternalSandbox { + network_access: if merge_network_access( + network_access.is_enabled(), + additional_permissions, + ) { + NetworkAccess::Enabled + } else { + NetworkAccess::Restricted + }, + }, + SandboxPolicy::WorkspaceWrite { + writable_roots, + read_only_access, + network_access, + exclude_tmpdir_env_var, + exclude_slash_tmp, + } => { + let mut merged_writes = writable_roots.clone(); + merged_writes.extend(extra_writes); + SandboxPolicy::WorkspaceWrite { + writable_roots: dedup_absolute_paths(merged_writes), + read_only_access: merge_read_only_access_with_additional_reads( + read_only_access, + extra_reads, + ), + network_access: merge_network_access(*network_access, additional_permissions), + exclude_tmpdir_env_var: *exclude_tmpdir_env_var, + exclude_slash_tmp: *exclude_slash_tmp, + } + } + SandboxPolicy::ReadOnly { + access, + network_access, + } => { + if extra_writes.is_empty() { + SandboxPolicy::ReadOnly { + access: merge_read_only_access_with_additional_reads(access, extra_reads), + network_access: merge_network_access(*network_access, additional_permissions), + } + } else { + // todo(dylan) - for now, this grants more access than the request. We should restrict this, + // but we should add a new SandboxPolicy variant to handle this. While the feature is still + // UnderDevelopment, it's a useful approximation of the desired behavior. + SandboxPolicy::WorkspaceWrite { + writable_roots: dedup_absolute_paths(extra_writes), + read_only_access: merge_read_only_access_with_additional_reads( + access, + extra_reads, + ), + network_access: merge_network_access(*network_access, additional_permissions), + exclude_tmpdir_env_var: false, + exclude_slash_tmp: false, + } + } + } + } +} + +pub(crate) fn should_require_platform_sandbox( + file_system_policy: &FileSystemSandboxPolicy, + network_policy: NetworkSandboxPolicy, + has_managed_network_requirements: bool, +) -> bool { + if has_managed_network_requirements { + return true; + } + + if !network_policy.is_enabled() { + return !matches!( + file_system_policy.kind, + FileSystemSandboxKind::ExternalSandbox + ); + } + + match file_system_policy.kind { + FileSystemSandboxKind::Restricted => !file_system_policy.has_full_disk_write_access(), + FileSystemSandboxKind::Unrestricted | FileSystemSandboxKind::ExternalSandbox => false, + } +} + +#[derive(Default)] +pub struct SandboxManager; + +impl SandboxManager { + pub fn new() -> Self { + Self + } + + pub fn select_initial( + &self, + file_system_policy: &FileSystemSandboxPolicy, + network_policy: NetworkSandboxPolicy, + pref: SandboxPreference, + windows_sandbox_level: WindowsSandboxLevel, + has_managed_network_requirements: bool, + ) -> SandboxType { + match pref { + SandboxPreference::Forbid => SandboxType::None, + SandboxPreference::Require => { + // Require a platform sandbox when available; on Windows this + // respects the experimental_windows_sandbox feature. + crate::get_platform_sandbox(windows_sandbox_level != WindowsSandboxLevel::Disabled) + .unwrap_or(SandboxType::None) + } + SandboxPreference::Auto => { + if should_require_platform_sandbox( + file_system_policy, + network_policy, + has_managed_network_requirements, + ) { + crate::get_platform_sandbox( + windows_sandbox_level != WindowsSandboxLevel::Disabled, + ) + .unwrap_or(SandboxType::None) + } else { + SandboxType::None + } + } + } + } + + pub fn transform( + &self, + request: SandboxTransformRequest<'_>, + ) -> Result { + let SandboxTransformRequest { + mut spec, + policy, + file_system_policy, + network_policy, + sandbox, + enforce_managed_network, + network, + sandbox_policy_cwd, + #[cfg(target_os = "macos")] + macos_seatbelt_profile_extensions, + codex_linux_sandbox_exe, + use_legacy_landlock, + windows_sandbox_level, + windows_sandbox_private_desktop, + } = request; + #[cfg(not(target_os = "macos"))] + let macos_seatbelt_profile_extensions = None; + let additional_permissions = spec.additional_permissions.take(); + let EffectiveSandboxPermissions { + sandbox_policy: effective_policy, + macos_seatbelt_profile_extensions: _effective_macos_seatbelt_profile_extensions, + } = EffectiveSandboxPermissions::new( + policy, + macos_seatbelt_profile_extensions, + additional_permissions.as_ref(), + ); + let (effective_file_system_policy, effective_network_policy) = + if let Some(additional_permissions) = additional_permissions { + let (extra_reads, extra_writes) = + additional_permission_roots(&additional_permissions); + let file_system_sandbox_policy = + if extra_reads.is_empty() && extra_writes.is_empty() { + file_system_policy.clone() + } else { + merge_file_system_policy_with_additional_permissions( + file_system_policy, + extra_reads, + extra_writes, + ) + }; + let network_sandbox_policy = + if merge_network_access(network_policy.is_enabled(), &additional_permissions) { + NetworkSandboxPolicy::Enabled + } else { + NetworkSandboxPolicy::Restricted + }; + (file_system_sandbox_policy, network_sandbox_policy) + } else { + (file_system_policy.clone(), network_policy) + }; + let mut env = spec.env; + if !effective_network_policy.is_enabled() { + env.insert( + CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR.to_string(), + "1".to_string(), + ); + } + + let mut command = Vec::with_capacity(1 + spec.args.len()); + command.push(spec.program); + command.append(&mut spec.args); + + let (command, sandbox_env, arg0_override) = match sandbox { + SandboxType::None => (command, HashMap::new(), None), + #[cfg(target_os = "macos")] + SandboxType::MacosSeatbelt => { + let mut seatbelt_env = HashMap::new(); + seatbelt_env.insert(CODEX_SANDBOX_ENV_VAR.to_string(), "seatbelt".to_string()); + let mut args = create_seatbelt_command_args_for_policies_with_extensions( + command.clone(), + &effective_file_system_policy, + effective_network_policy, + sandbox_policy_cwd, + enforce_managed_network, + network, + _effective_macos_seatbelt_profile_extensions.as_ref(), + ); + let mut full_command = Vec::with_capacity(1 + args.len()); + full_command.push(MACOS_PATH_TO_SEATBELT_EXECUTABLE.to_string()); + full_command.append(&mut args); + (full_command, seatbelt_env, None) + } + #[cfg(not(target_os = "macos"))] + SandboxType::MacosSeatbelt => return Err(SandboxTransformError::SeatbeltUnavailable), + SandboxType::LinuxSeccomp => { + let exe = codex_linux_sandbox_exe + .ok_or(SandboxTransformError::MissingLinuxSandboxExecutable)?; + let allow_proxy_network = allow_network_for_proxy(enforce_managed_network); + let mut args = create_linux_sandbox_command_args_for_policies( + command.clone(), + spec.cwd.as_path(), + &effective_policy, + &effective_file_system_policy, + effective_network_policy, + sandbox_policy_cwd, + use_legacy_landlock, + allow_proxy_network, + ); + let mut full_command = Vec::with_capacity(1 + args.len()); + full_command.push(exe.to_string_lossy().to_string()); + full_command.append(&mut args); + ( + full_command, + HashMap::new(), + Some("codex-linux-sandbox".to_string()), + ) + } + // On Windows, the restricted token sandbox executes in-process via the + // codex-windows-sandbox crate. We leave the command unchanged here and + // branch during execution based on the sandbox type. + #[cfg(target_os = "windows")] + SandboxType::WindowsRestrictedToken => (command, HashMap::new(), None), + // When building for non-Windows targets, this variant is never constructed. + #[cfg(not(target_os = "windows"))] + SandboxType::WindowsRestrictedToken => (command, HashMap::new(), None), + }; + + env.extend(sandbox_env); + + Ok(ExecRequest { + command, + cwd: spec.cwd, + env, + network: network.cloned(), + expiration: spec.expiration, + capture_policy: spec.capture_policy, + sandbox, + windows_sandbox_level, + windows_sandbox_private_desktop, + sandbox_permissions: spec.sandbox_permissions, + sandbox_policy: effective_policy, + file_system_sandbox_policy: effective_file_system_policy, + network_sandbox_policy: effective_network_policy, + justification: spec.justification, + arg0: arg0_override, + }) + } + + pub fn denied(&self, sandbox: SandboxType, out: &ExecToolCallOutput) -> bool { + crate::is_likely_sandbox_denied(sandbox, out) + } +} + +pub async fn execute_env( + exec_request: ExecRequest, + stdout_stream: Option, +) -> crate::error::Result { + let effective_policy = exec_request.sandbox_policy.clone(); + execute_exec_request( + exec_request, + &effective_policy, + stdout_stream, + /*after_spawn*/ None, + ) + .await +} + +pub async fn execute_exec_request_with_after_spawn( + exec_request: ExecRequest, + stdout_stream: Option, + after_spawn: Option>, +) -> crate::error::Result { + let effective_policy = exec_request.sandbox_policy.clone(); + execute_exec_request(exec_request, &effective_policy, stdout_stream, after_spawn).await +} + +#[cfg(test)] +#[path = "mod_tests.rs"] +mod tests; diff --git a/codex-rs/sandbox/src/sandboxing/mod_tests.rs b/codex-rs/sandbox/src/sandboxing/mod_tests.rs new file mode 100644 index 0000000000..7731898dac --- /dev/null +++ b/codex-rs/sandbox/src/sandboxing/mod_tests.rs @@ -0,0 +1,771 @@ +#[cfg(target_os = "macos")] +use super::EffectiveSandboxPermissions; +use super::SandboxManager; +use super::SandboxPreference; +use super::effective_file_system_sandbox_policy; +#[cfg(target_os = "macos")] +use super::intersect_permission_profiles; +use super::merge_file_system_policy_with_additional_permissions; +use super::normalize_additional_permissions; +use super::sandbox_policy_with_additional_permissions; +use super::should_require_platform_sandbox; +use crate::exec::SandboxType; +use crate::protocol::NetworkAccess; +use crate::protocol::ReadOnlyAccess; +use crate::protocol::SandboxPolicy; +use codex_protocol::config_types::WindowsSandboxLevel; +use codex_protocol::models::FileSystemPermissions; +#[cfg(target_os = "macos")] +use codex_protocol::models::MacOsAutomationPermission; +#[cfg(target_os = "macos")] +use codex_protocol::models::MacOsContactsPermission; +#[cfg(target_os = "macos")] +use codex_protocol::models::MacOsPreferencesPermission; +#[cfg(target_os = "macos")] +use codex_protocol::models::MacOsSeatbeltProfileExtensions; +use codex_protocol::models::NetworkPermissions; +use codex_protocol::models::PermissionProfile; +use codex_protocol::permissions::FileSystemAccessMode; +use codex_protocol::permissions::FileSystemPath; +use codex_protocol::permissions::FileSystemSandboxEntry; +use codex_protocol::permissions::FileSystemSandboxPolicy; +use codex_protocol::permissions::FileSystemSpecialPath; +use codex_protocol::permissions::NetworkSandboxPolicy; +use codex_utils_absolute_path::AbsolutePathBuf; +use dunce::canonicalize; +use pretty_assertions::assert_eq; +use std::collections::HashMap; +#[cfg(unix)] +use std::path::Path; +use tempfile::TempDir; + +#[cfg(unix)] +fn symlink_dir(original: &Path, link: &Path) -> std::io::Result<()> { + std::os::unix::fs::symlink(original, link) +} + +#[test] +fn danger_full_access_defaults_to_no_sandbox_without_network_requirements() { + let manager = SandboxManager::new(); + let sandbox = manager.select_initial( + &FileSystemSandboxPolicy::unrestricted(), + NetworkSandboxPolicy::Enabled, + SandboxPreference::Auto, + WindowsSandboxLevel::Disabled, + false, + ); + assert_eq!(sandbox, SandboxType::None); +} + +#[test] +fn danger_full_access_uses_platform_sandbox_with_network_requirements() { + let manager = SandboxManager::new(); + let expected = crate::get_platform_sandbox(false).unwrap_or(SandboxType::None); + let sandbox = manager.select_initial( + &FileSystemSandboxPolicy::unrestricted(), + NetworkSandboxPolicy::Enabled, + SandboxPreference::Auto, + WindowsSandboxLevel::Disabled, + true, + ); + assert_eq!(sandbox, expected); +} + +#[test] +fn restricted_file_system_uses_platform_sandbox_without_managed_network() { + let manager = SandboxManager::new(); + let expected = crate::get_platform_sandbox(false).unwrap_or(SandboxType::None); + let sandbox = manager.select_initial( + &FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::Root, + }, + access: FileSystemAccessMode::Read, + }]), + NetworkSandboxPolicy::Enabled, + SandboxPreference::Auto, + WindowsSandboxLevel::Disabled, + false, + ); + assert_eq!(sandbox, expected); +} + +#[test] +fn full_access_restricted_policy_skips_platform_sandbox_when_network_is_enabled() { + let policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::Root, + }, + access: FileSystemAccessMode::Write, + }]); + + assert_eq!( + should_require_platform_sandbox(&policy, NetworkSandboxPolicy::Enabled, false), + false + ); +} + +#[test] +fn root_write_policy_with_carveouts_still_uses_platform_sandbox() { + let blocked = AbsolutePathBuf::resolve_path_against_base( + "blocked", + std::env::current_dir().expect("current dir"), + ) + .expect("blocked path"); + let policy = FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::Root, + }, + access: FileSystemAccessMode::Write, + }, + FileSystemSandboxEntry { + path: FileSystemPath::Path { path: blocked }, + access: FileSystemAccessMode::None, + }, + ]); + + assert_eq!( + should_require_platform_sandbox(&policy, NetworkSandboxPolicy::Enabled, false), + true + ); +} + +#[test] +fn full_access_restricted_policy_still_uses_platform_sandbox_for_restricted_network() { + let policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::Root, + }, + access: FileSystemAccessMode::Write, + }]); + + assert_eq!( + should_require_platform_sandbox(&policy, NetworkSandboxPolicy::Restricted, false), + true + ); +} + +#[test] +fn transform_preserves_unrestricted_file_system_policy_for_restricted_network() { + let manager = SandboxManager::new(); + let cwd = std::env::current_dir().expect("current dir"); + let exec_request = manager + .transform(super::SandboxTransformRequest { + spec: super::CommandSpec { + program: "true".to_string(), + args: Vec::new(), + cwd: cwd.clone(), + env: HashMap::new(), + expiration: crate::exec::ExecExpiration::DefaultTimeout, + capture_policy: crate::exec::ExecCapturePolicy::ShellTool, + sandbox_permissions: super::SandboxPermissions::UseDefault, + additional_permissions: None, + justification: None, + }, + policy: &SandboxPolicy::ExternalSandbox { + network_access: crate::protocol::NetworkAccess::Restricted, + }, + file_system_policy: &FileSystemSandboxPolicy::unrestricted(), + network_policy: NetworkSandboxPolicy::Restricted, + sandbox: SandboxType::None, + enforce_managed_network: false, + network: None, + sandbox_policy_cwd: cwd.as_path(), + #[cfg(target_os = "macos")] + macos_seatbelt_profile_extensions: None, + codex_linux_sandbox_exe: None, + use_legacy_landlock: false, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + windows_sandbox_private_desktop: false, + }) + .expect("transform"); + + assert_eq!( + exec_request.file_system_sandbox_policy, + FileSystemSandboxPolicy::unrestricted() + ); + assert_eq!( + exec_request.network_sandbox_policy, + NetworkSandboxPolicy::Restricted + ); +} + +#[test] +fn normalize_additional_permissions_preserves_network() { + let temp_dir = TempDir::new().expect("create temp dir"); + let path = AbsolutePathBuf::from_absolute_path( + canonicalize(temp_dir.path()).expect("canonicalize temp dir"), + ) + .expect("absolute temp dir"); + let permissions = normalize_additional_permissions(PermissionProfile { + network: Some(NetworkPermissions { + enabled: Some(true), + }), + file_system: Some(FileSystemPermissions { + read: Some(vec![path.clone()]), + write: Some(vec![path.clone()]), + }), + ..Default::default() + }) + .expect("permissions"); + + assert_eq!( + permissions.network, + Some(NetworkPermissions { + enabled: Some(true), + }) + ); + assert_eq!( + permissions.file_system, + Some(FileSystemPermissions { + read: Some(vec![path.clone()]), + write: Some(vec![path]), + }) + ); +} + +#[cfg(unix)] +#[test] +fn normalize_additional_permissions_canonicalizes_symlinked_write_paths() { + let temp_dir = TempDir::new().expect("create temp dir"); + let real_root = temp_dir.path().join("real"); + let link_root = temp_dir.path().join("link"); + let write_dir = real_root.join("write"); + std::fs::create_dir_all(&write_dir).expect("create write dir"); + symlink_dir(&real_root, &link_root).expect("create symlinked root"); + + let link_write_dir = + AbsolutePathBuf::from_absolute_path(link_root.join("write")).expect("link write dir"); + let expected_write_dir = AbsolutePathBuf::from_absolute_path( + write_dir.canonicalize().expect("canonicalize write dir"), + ) + .expect("absolute canonical write dir"); + + let permissions = normalize_additional_permissions(PermissionProfile { + file_system: Some(FileSystemPermissions { + read: Some(vec![]), + write: Some(vec![link_write_dir]), + }), + ..Default::default() + }) + .expect("permissions"); + + assert_eq!( + permissions.file_system, + Some(FileSystemPermissions { + read: Some(vec![]), + write: Some(vec![expected_write_dir]), + }) + ); +} + +#[test] +fn normalize_additional_permissions_drops_empty_nested_profiles() { + let permissions = normalize_additional_permissions(PermissionProfile { + network: Some(NetworkPermissions { enabled: None }), + file_system: Some(FileSystemPermissions { + read: None, + write: None, + }), + macos: None, + }) + .expect("permissions"); + + assert_eq!(permissions, PermissionProfile::default()); +} + +#[cfg(target_os = "macos")] +#[test] +fn normalize_additional_permissions_preserves_default_macos_preferences_permission() { + let permissions = normalize_additional_permissions(PermissionProfile { + macos: Some(MacOsSeatbeltProfileExtensions::default()), + ..Default::default() + }) + .expect("permissions"); + + assert_eq!( + permissions, + PermissionProfile { + macos: Some(MacOsSeatbeltProfileExtensions::default()), + ..Default::default() + } + ); +} + +#[cfg(target_os = "macos")] +#[test] +fn intersect_permission_profiles_preserves_default_macos_grants() { + let requested = PermissionProfile { + file_system: Some(FileSystemPermissions { + read: Some(Vec::from(["/tmp/requested" + .try_into() + .expect("absolute path")])), + write: None, + }), + macos: Some(MacOsSeatbeltProfileExtensions { + macos_preferences: MacOsPreferencesPermission::ReadWrite, + macos_automation: MacOsAutomationPermission::BundleIds(vec![ + "com.apple.Notes".to_string(), + ]), + macos_launch_services: false, + macos_accessibility: true, + macos_calendar: true, + macos_reminders: false, + macos_contacts: MacOsContactsPermission::None, + }), + ..Default::default() + }; + let granted = PermissionProfile { + file_system: Some(FileSystemPermissions { + read: Some(Vec::new()), + write: None, + }), + macos: Some(MacOsSeatbeltProfileExtensions::default()), + ..Default::default() + }; + + assert_eq!( + intersect_permission_profiles(requested, granted), + PermissionProfile { + macos: Some(MacOsSeatbeltProfileExtensions::default()), + ..Default::default() + } + ); +} + +#[cfg(target_os = "macos")] +#[test] +fn normalize_additional_permissions_preserves_macos_permissions() { + let permissions = normalize_additional_permissions(PermissionProfile { + macos: Some(MacOsSeatbeltProfileExtensions { + macos_preferences: MacOsPreferencesPermission::ReadWrite, + macos_automation: MacOsAutomationPermission::BundleIds(vec![ + "com.apple.Notes".to_string(), + ]), + macos_launch_services: true, + macos_accessibility: true, + macos_calendar: true, + macos_reminders: false, + macos_contacts: MacOsContactsPermission::None, + }), + ..Default::default() + }) + .expect("permissions"); + + assert_eq!( + permissions.macos, + Some(MacOsSeatbeltProfileExtensions { + macos_preferences: MacOsPreferencesPermission::ReadWrite, + macos_automation: MacOsAutomationPermission::BundleIds(vec![ + "com.apple.Notes".to_string(), + ]), + macos_launch_services: true, + macos_accessibility: true, + macos_calendar: true, + macos_reminders: false, + macos_contacts: MacOsContactsPermission::None, + }) + ); +} + +#[test] +fn read_only_additional_permissions_can_enable_network_without_writes() { + let temp_dir = TempDir::new().expect("create temp dir"); + let path = AbsolutePathBuf::from_absolute_path( + canonicalize(temp_dir.path()).expect("canonicalize temp dir"), + ) + .expect("absolute temp dir"); + let policy = sandbox_policy_with_additional_permissions( + &SandboxPolicy::ReadOnly { + access: ReadOnlyAccess::Restricted { + include_platform_defaults: true, + readable_roots: vec![path.clone()], + }, + network_access: false, + }, + &PermissionProfile { + network: Some(NetworkPermissions { + enabled: Some(true), + }), + file_system: Some(FileSystemPermissions { + read: Some(vec![path.clone()]), + write: Some(Vec::new()), + }), + ..Default::default() + }, + ); + + assert_eq!( + policy, + SandboxPolicy::ReadOnly { + access: ReadOnlyAccess::Restricted { + include_platform_defaults: true, + readable_roots: vec![path], + }, + network_access: true, + } + ); +} +#[cfg(target_os = "macos")] +#[test] +fn effective_permissions_merge_macos_extensions_with_additional_permissions() { + let temp_dir = TempDir::new().expect("create temp dir"); + let path = AbsolutePathBuf::from_absolute_path( + canonicalize(temp_dir.path()).expect("canonicalize temp dir"), + ) + .expect("absolute temp dir"); + let effective_permissions = EffectiveSandboxPermissions::new( + &SandboxPolicy::ReadOnly { + access: ReadOnlyAccess::Restricted { + include_platform_defaults: true, + readable_roots: vec![path.clone()], + }, + network_access: false, + }, + Some(&MacOsSeatbeltProfileExtensions { + macos_preferences: MacOsPreferencesPermission::ReadOnly, + macos_automation: MacOsAutomationPermission::BundleIds(vec![ + "com.apple.Calendar".to_string(), + ]), + macos_launch_services: false, + macos_accessibility: false, + macos_calendar: false, + macos_reminders: false, + macos_contacts: MacOsContactsPermission::None, + }), + Some(&PermissionProfile { + file_system: Some(FileSystemPermissions { + read: Some(vec![path]), + write: Some(Vec::new()), + }), + macos: Some(MacOsSeatbeltProfileExtensions { + macos_preferences: MacOsPreferencesPermission::ReadWrite, + macos_automation: MacOsAutomationPermission::BundleIds(vec![ + "com.apple.Notes".to_string(), + ]), + macos_launch_services: true, + macos_accessibility: true, + macos_calendar: true, + macos_reminders: false, + macos_contacts: MacOsContactsPermission::None, + }), + ..Default::default() + }), + ); + + assert_eq!( + effective_permissions.macos_seatbelt_profile_extensions, + Some(MacOsSeatbeltProfileExtensions { + macos_preferences: MacOsPreferencesPermission::ReadWrite, + macos_automation: MacOsAutomationPermission::BundleIds(vec![ + "com.apple.Calendar".to_string(), + "com.apple.Notes".to_string(), + ]), + macos_launch_services: true, + macos_accessibility: true, + macos_calendar: true, + macos_reminders: false, + macos_contacts: MacOsContactsPermission::None, + }) + ); +} + +#[test] +fn external_sandbox_additional_permissions_can_enable_network() { + let temp_dir = TempDir::new().expect("create temp dir"); + let path = AbsolutePathBuf::from_absolute_path( + canonicalize(temp_dir.path()).expect("canonicalize temp dir"), + ) + .expect("absolute temp dir"); + let policy = sandbox_policy_with_additional_permissions( + &SandboxPolicy::ExternalSandbox { + network_access: NetworkAccess::Restricted, + }, + &PermissionProfile { + network: Some(NetworkPermissions { + enabled: Some(true), + }), + file_system: Some(FileSystemPermissions { + read: Some(vec![path]), + write: Some(Vec::new()), + }), + ..Default::default() + }, + ); + + assert_eq!( + policy, + SandboxPolicy::ExternalSandbox { + network_access: NetworkAccess::Enabled, + } + ); +} + +#[test] +fn transform_additional_permissions_enable_network_for_external_sandbox() { + let manager = SandboxManager::new(); + let cwd = std::env::current_dir().expect("current dir"); + let temp_dir = TempDir::new().expect("create temp dir"); + let path = AbsolutePathBuf::from_absolute_path( + canonicalize(temp_dir.path()).expect("canonicalize temp dir"), + ) + .expect("absolute temp dir"); + let exec_request = manager + .transform(super::SandboxTransformRequest { + spec: super::CommandSpec { + program: "true".to_string(), + args: Vec::new(), + cwd: cwd.clone(), + env: HashMap::new(), + expiration: crate::exec::ExecExpiration::DefaultTimeout, + capture_policy: crate::exec::ExecCapturePolicy::ShellTool, + sandbox_permissions: super::SandboxPermissions::WithAdditionalPermissions, + additional_permissions: Some(PermissionProfile { + network: Some(NetworkPermissions { + enabled: Some(true), + }), + file_system: Some(FileSystemPermissions { + read: Some(vec![path]), + write: Some(Vec::new()), + }), + ..Default::default() + }), + justification: None, + }, + policy: &SandboxPolicy::ExternalSandbox { + network_access: NetworkAccess::Restricted, + }, + file_system_policy: &FileSystemSandboxPolicy::unrestricted(), + network_policy: NetworkSandboxPolicy::Restricted, + sandbox: SandboxType::None, + enforce_managed_network: false, + network: None, + sandbox_policy_cwd: cwd.as_path(), + #[cfg(target_os = "macos")] + macos_seatbelt_profile_extensions: None, + codex_linux_sandbox_exe: None, + use_legacy_landlock: false, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + windows_sandbox_private_desktop: false, + }) + .expect("transform"); + + assert_eq!( + exec_request.sandbox_policy, + SandboxPolicy::ExternalSandbox { + network_access: NetworkAccess::Enabled, + } + ); + assert_eq!( + exec_request.network_sandbox_policy, + NetworkSandboxPolicy::Enabled + ); +} + +#[test] +fn transform_additional_permissions_preserves_denied_entries() { + let manager = SandboxManager::new(); + let cwd = std::env::current_dir().expect("current dir"); + let temp_dir = TempDir::new().expect("create temp dir"); + let workspace_root = AbsolutePathBuf::from_absolute_path( + canonicalize(temp_dir.path()).expect("canonicalize temp dir"), + ) + .expect("absolute temp dir"); + let allowed_path = workspace_root.join("allowed").expect("allowed path"); + let denied_path = workspace_root.join("denied").expect("denied path"); + let exec_request = manager + .transform(super::SandboxTransformRequest { + spec: super::CommandSpec { + program: "true".to_string(), + args: Vec::new(), + cwd: cwd.clone(), + env: HashMap::new(), + expiration: crate::exec::ExecExpiration::DefaultTimeout, + capture_policy: crate::exec::ExecCapturePolicy::ShellTool, + sandbox_permissions: super::SandboxPermissions::WithAdditionalPermissions, + additional_permissions: Some(PermissionProfile { + file_system: Some(FileSystemPermissions { + read: None, + write: Some(vec![allowed_path.clone()]), + }), + ..Default::default() + }), + justification: None, + }, + policy: &SandboxPolicy::ReadOnly { + access: ReadOnlyAccess::FullAccess, + network_access: false, + }, + file_system_policy: &FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::Root, + }, + access: FileSystemAccessMode::Read, + }, + FileSystemSandboxEntry { + path: FileSystemPath::Path { + path: denied_path.clone(), + }, + access: FileSystemAccessMode::None, + }, + ]), + network_policy: NetworkSandboxPolicy::Restricted, + sandbox: SandboxType::None, + enforce_managed_network: false, + network: None, + sandbox_policy_cwd: cwd.as_path(), + #[cfg(target_os = "macos")] + macos_seatbelt_profile_extensions: None, + codex_linux_sandbox_exe: None, + use_legacy_landlock: false, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + windows_sandbox_private_desktop: false, + }) + .expect("transform"); + + assert_eq!( + exec_request.file_system_sandbox_policy, + FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::Root, + }, + access: FileSystemAccessMode::Read, + }, + FileSystemSandboxEntry { + path: FileSystemPath::Path { path: denied_path }, + access: FileSystemAccessMode::None, + }, + FileSystemSandboxEntry { + path: FileSystemPath::Path { path: allowed_path }, + access: FileSystemAccessMode::Write, + }, + ]) + ); + assert_eq!( + exec_request.network_sandbox_policy, + NetworkSandboxPolicy::Restricted + ); +} + +#[test] +fn merge_file_system_policy_with_additional_permissions_preserves_unreadable_roots() { + let temp_dir = TempDir::new().expect("create temp dir"); + let cwd = AbsolutePathBuf::from_absolute_path( + canonicalize(temp_dir.path()).expect("canonicalize temp dir"), + ) + .expect("absolute temp dir"); + let allowed_path = cwd.join("allowed").expect("allowed path"); + let denied_path = cwd.join("denied").expect("denied path"); + let merged_policy = merge_file_system_policy_with_additional_permissions( + &FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::Root, + }, + access: FileSystemAccessMode::Read, + }, + FileSystemSandboxEntry { + path: FileSystemPath::Path { + path: denied_path.clone(), + }, + access: FileSystemAccessMode::None, + }, + ]), + vec![allowed_path.clone()], + Vec::new(), + ); + + assert_eq!( + merged_policy.entries.contains(&FileSystemSandboxEntry { + path: FileSystemPath::Path { path: denied_path }, + access: FileSystemAccessMode::None, + }), + true + ); + assert_eq!( + merged_policy.entries.contains(&FileSystemSandboxEntry { + path: FileSystemPath::Path { path: allowed_path }, + access: FileSystemAccessMode::Read, + }), + true + ); +} + +#[test] +fn effective_file_system_sandbox_policy_returns_base_policy_without_additional_permissions() { + let temp_dir = TempDir::new().expect("create temp dir"); + let cwd = AbsolutePathBuf::from_absolute_path( + canonicalize(temp_dir.path()).expect("canonicalize temp dir"), + ) + .expect("absolute temp dir"); + let denied_path = cwd.join("denied").expect("denied path"); + let base_policy = FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::Root, + }, + access: FileSystemAccessMode::Read, + }, + FileSystemSandboxEntry { + path: FileSystemPath::Path { path: denied_path }, + access: FileSystemAccessMode::None, + }, + ]); + + let effective_policy = effective_file_system_sandbox_policy(&base_policy, None); + + assert_eq!(effective_policy, base_policy); +} + +#[test] +fn effective_file_system_sandbox_policy_merges_additional_write_roots() { + let temp_dir = TempDir::new().expect("create temp dir"); + let cwd = AbsolutePathBuf::from_absolute_path( + canonicalize(temp_dir.path()).expect("canonicalize temp dir"), + ) + .expect("absolute temp dir"); + let allowed_path = cwd.join("allowed").expect("allowed path"); + let denied_path = cwd.join("denied").expect("denied path"); + let base_policy = FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::Root, + }, + access: FileSystemAccessMode::Read, + }, + FileSystemSandboxEntry { + path: FileSystemPath::Path { + path: denied_path.clone(), + }, + access: FileSystemAccessMode::None, + }, + ]); + let additional_permissions = PermissionProfile { + file_system: Some(FileSystemPermissions { + read: Some(vec![]), + write: Some(vec![allowed_path.clone()]), + }), + ..Default::default() + }; + + let effective_policy = + effective_file_system_sandbox_policy(&base_policy, Some(&additional_permissions)); + + assert_eq!( + effective_policy.entries.contains(&FileSystemSandboxEntry { + path: FileSystemPath::Path { path: denied_path }, + access: FileSystemAccessMode::None, + }), + true + ); + assert_eq!( + effective_policy.entries.contains(&FileSystemSandboxEntry { + path: FileSystemPath::Path { path: allowed_path }, + access: FileSystemAccessMode::Write, + }), + true + ); +} diff --git a/codex-rs/sandbox/src/seatbelt.rs b/codex-rs/sandbox/src/seatbelt.rs new file mode 100644 index 0000000000..2d1e0a7b5d --- /dev/null +++ b/codex-rs/sandbox/src/seatbelt.rs @@ -0,0 +1,594 @@ +#![cfg(target_os = "macos")] + +use codex_network_proxy::NetworkProxy; +use codex_network_proxy::PROXY_URL_ENV_KEYS; +use codex_network_proxy::has_proxy_url_env_vars; +use codex_network_proxy::proxy_url_env_value; +use codex_utils_absolute_path::AbsolutePathBuf; +use std::collections::BTreeMap; +use std::collections::BTreeSet; +use std::collections::HashMap; +use std::ffi::CStr; +use std::path::Path; +use std::path::PathBuf; +use tokio::process::Child; +use tracing::warn; +use url::Url; + +use crate::protocol::SandboxPolicy; +use crate::seatbelt_permissions::MacOsSeatbeltProfileExtensions; +use crate::seatbelt_permissions::build_seatbelt_extensions; +use crate::spawn::CODEX_SANDBOX_ENV_VAR; +use crate::spawn::SpawnChildRequest; +use crate::spawn::StdioPolicy; +use crate::spawn::spawn_child_async; +use codex_protocol::permissions::FileSystemSandboxPolicy; +use codex_protocol::permissions::NetworkSandboxPolicy; + +const MACOS_SEATBELT_BASE_POLICY: &str = include_str!("seatbelt_base_policy.sbpl"); +const MACOS_SEATBELT_NETWORK_POLICY: &str = include_str!("seatbelt_network_policy.sbpl"); +const MACOS_RESTRICTED_READ_ONLY_PLATFORM_DEFAULTS: &str = + include_str!("restricted_read_only_platform_defaults.sbpl"); + +/// When working with `sandbox-exec`, only consider `sandbox-exec` in `/usr/bin` +/// to defend against an attacker trying to inject a malicious version on the +/// PATH. If /usr/bin/sandbox-exec has been tampered with, then the attacker +/// already has root access. +pub const MACOS_PATH_TO_SEATBELT_EXECUTABLE: &str = "/usr/bin/sandbox-exec"; + +pub async fn spawn_command_under_seatbelt( + command: Vec, + command_cwd: PathBuf, + sandbox_policy: &SandboxPolicy, + sandbox_policy_cwd: &Path, + stdio_policy: StdioPolicy, + network: Option<&NetworkProxy>, + mut env: HashMap, +) -> std::io::Result { + let args = create_seatbelt_command_args( + command, + sandbox_policy, + sandbox_policy_cwd, + /*enforce_managed_network*/ false, + network, + ); + let arg0 = None; + env.insert(CODEX_SANDBOX_ENV_VAR.to_string(), "seatbelt".to_string()); + spawn_child_async(SpawnChildRequest { + program: PathBuf::from(MACOS_PATH_TO_SEATBELT_EXECUTABLE), + args, + arg0, + cwd: command_cwd, + network_sandbox_policy: NetworkSandboxPolicy::from(sandbox_policy), + network, + stdio_policy, + env, + }) + .await +} + +fn is_loopback_host(host: &str) -> bool { + host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1" +} + +fn proxy_scheme_default_port(scheme: &str) -> u16 { + match scheme { + "https" => 443, + "socks5" | "socks5h" | "socks4" | "socks4a" => 1080, + _ => 80, + } +} + +fn proxy_loopback_ports_from_env(env: &HashMap) -> Vec { + let mut ports = BTreeSet::new(); + for key in PROXY_URL_ENV_KEYS { + let Some(proxy_url) = proxy_url_env_value(env, key) else { + continue; + }; + let trimmed = proxy_url.trim(); + if trimmed.is_empty() { + continue; + } + + let candidate = if trimmed.contains("://") { + trimmed.to_string() + } else { + format!("http://{trimmed}") + }; + let Ok(parsed) = Url::parse(&candidate) else { + continue; + }; + let Some(host) = parsed.host_str() else { + continue; + }; + if !is_loopback_host(host) { + continue; + } + + let scheme = parsed.scheme().to_ascii_lowercase(); + let port = parsed + .port() + .unwrap_or_else(|| proxy_scheme_default_port(scheme.as_str())); + ports.insert(port); + } + ports.into_iter().collect() +} + +#[derive(Debug, Default)] +struct ProxyPolicyInputs { + ports: Vec, + has_proxy_config: bool, + allow_local_binding: bool, + unix_domain_socket_policy: UnixDomainSocketPolicy, +} + +#[derive(Debug, Clone)] +// Keep allow-all and allowlist modes disjoint so we don't carry ignored state. +enum UnixDomainSocketPolicy { + AllowAll, + Restricted { allowed: Vec }, +} + +impl Default for UnixDomainSocketPolicy { + fn default() -> Self { + Self::Restricted { allowed: vec![] } + } +} + +#[derive(Debug, Clone)] +struct UnixSocketPathParam { + index: usize, + path: AbsolutePathBuf, +} + +fn proxy_policy_inputs(network: Option<&NetworkProxy>) -> ProxyPolicyInputs { + if let Some(network) = network { + let mut env = HashMap::new(); + network.apply_to_env(&mut env); + let unix_domain_socket_policy = if network.dangerously_allow_all_unix_sockets() { + UnixDomainSocketPolicy::AllowAll + } else { + let allowed = network + .allow_unix_sockets() + .iter() + .filter_map( + |socket_path| match normalize_path_for_sandbox(Path::new(socket_path)) { + Some(path) => Some((path.to_string_lossy().to_string(), path)), + None => { + warn!( + "ignoring network.allow_unix_sockets entry because it could not be normalized: {socket_path}" + ); + None + } + }, + ) + .collect::>() + .into_values() + .collect(); + UnixDomainSocketPolicy::Restricted { allowed } + }; + return ProxyPolicyInputs { + ports: proxy_loopback_ports_from_env(&env), + has_proxy_config: has_proxy_url_env_vars(&env), + allow_local_binding: network.allow_local_binding(), + unix_domain_socket_policy, + }; + } + + ProxyPolicyInputs::default() +} + +fn normalize_path_for_sandbox(path: &Path) -> Option { + // `AbsolutePathBuf::from_absolute_path()` normalizes relative paths against the current + // working directory, so keep the explicit check to avoid silently accepting relative entries. + if !path.is_absolute() { + return None; + } + + let absolute_path = AbsolutePathBuf::from_absolute_path(path).ok()?; + let normalized_path = absolute_path + .as_path() + .canonicalize() + .ok() + .and_then(|canonical_path| AbsolutePathBuf::from_absolute_path(canonical_path).ok()); + normalized_path.or(Some(absolute_path)) +} + +fn unix_socket_path_params(proxy: &ProxyPolicyInputs) -> Vec { + let mut deduped_paths: BTreeMap = BTreeMap::new(); + let UnixDomainSocketPolicy::Restricted { allowed } = &proxy.unix_domain_socket_policy else { + return vec![]; + }; + for path in allowed { + deduped_paths + .entry(path.to_string_lossy().to_string()) + .or_insert_with(|| path.clone()); + } + + deduped_paths + .into_values() + .enumerate() + .map(|(index, path)| UnixSocketPathParam { index, path }) + .collect() +} + +fn unix_socket_path_param_key(index: usize) -> String { + format!("UNIX_SOCKET_PATH_{index}") +} + +fn unix_socket_dir_params(proxy: &ProxyPolicyInputs) -> Vec<(String, PathBuf)> { + unix_socket_path_params(proxy) + .into_iter() + .map(|param| { + ( + unix_socket_path_param_key(param.index), + param.path.into_path_buf(), + ) + }) + .collect() +} + +/// Returns zero or more complete Seatbelt policy lines for unix socket rules. +/// When non-empty, the returned string is newline-terminated so callers can +/// append it directly to larger policy blocks. +fn unix_socket_policy(proxy: &ProxyPolicyInputs) -> String { + let socket_params = unix_socket_path_params(proxy); + let has_unix_socket_access = matches!( + proxy.unix_domain_socket_policy, + UnixDomainSocketPolicy::AllowAll + ) || !socket_params.is_empty(); + if !has_unix_socket_access { + return String::new(); + } + + let mut policy = String::new(); + policy.push_str("(allow system-socket (socket-domain AF_UNIX))\n"); + if matches!( + proxy.unix_domain_socket_policy, + UnixDomainSocketPolicy::AllowAll + ) { + // Keep AllowAll genuinely broad here; path qualifiers look narrower + // without a clear macOS behavioral benefit. + policy.push_str("(allow network-bind (local unix-socket))\n"); + policy.push_str("(allow network-outbound (remote unix-socket))\n"); + return policy; + } + + for param in socket_params { + let key = unix_socket_path_param_key(param.index); + // Use subpath so allowlists cover sockets created beneath approved directories. + policy.push_str(&format!( + "(allow network-bind (local unix-socket (subpath (param \"{key}\"))))\n" + )); + policy.push_str(&format!( + "(allow network-outbound (remote unix-socket (subpath (param \"{key}\"))))\n" + )); + } + policy +} + +#[cfg_attr(not(test), allow(dead_code))] +fn dynamic_network_policy( + sandbox_policy: &SandboxPolicy, + enforce_managed_network: bool, + proxy: &ProxyPolicyInputs, +) -> String { + dynamic_network_policy_for_network( + NetworkSandboxPolicy::from(sandbox_policy), + enforce_managed_network, + proxy, + ) +} + +fn dynamic_network_policy_for_network( + network_policy: NetworkSandboxPolicy, + enforce_managed_network: bool, + proxy: &ProxyPolicyInputs, +) -> String { + let should_use_restricted_network_policy = + !proxy.ports.is_empty() || proxy.has_proxy_config || enforce_managed_network; + if should_use_restricted_network_policy { + let mut policy = String::new(); + if proxy.allow_local_binding { + policy.push_str("; allow loopback local binding and loopback traffic\n"); + policy.push_str("(allow network-bind (local ip \"localhost:*\"))\n"); + policy.push_str("(allow network-inbound (local ip \"localhost:*\"))\n"); + policy.push_str("(allow network-outbound (remote ip \"localhost:*\"))\n"); + } + for port in &proxy.ports { + policy.push_str(&format!( + "(allow network-outbound (remote ip \"localhost:{port}\"))\n" + )); + } + let unix_socket_policy = unix_socket_policy(proxy); + if !unix_socket_policy.is_empty() { + policy.push_str("; allow unix domain sockets for local IPC\n"); + policy.push_str(&unix_socket_policy); + } + return format!("{policy}{MACOS_SEATBELT_NETWORK_POLICY}"); + } + + if proxy.has_proxy_config { + // Proxy configuration is present but we could not infer any valid loopback endpoints. + // Fail closed to avoid silently widening network access in proxy-enforced sessions. + return String::new(); + } + + if enforce_managed_network { + // Managed network requirements are active but no usable proxy endpoints + // are available. Fail closed for network access. + return String::new(); + } + + if network_policy.is_enabled() { + // No proxy env is configured: retain the existing full-network behavior. + format!( + "(allow network-outbound)\n(allow network-inbound)\n{MACOS_SEATBELT_NETWORK_POLICY}" + ) + } else { + String::new() + } +} + +#[cfg_attr(not(test), allow(dead_code))] +pub(crate) fn create_seatbelt_command_args( + command: Vec, + sandbox_policy: &SandboxPolicy, + sandbox_policy_cwd: &Path, + enforce_managed_network: bool, + network: Option<&NetworkProxy>, +) -> Vec { + create_seatbelt_command_args_with_extensions( + command, + sandbox_policy, + sandbox_policy_cwd, + enforce_managed_network, + network, + /*extensions*/ None, + ) +} + +fn root_absolute_path() -> AbsolutePathBuf { + match AbsolutePathBuf::from_absolute_path(Path::new("/")) { + Ok(path) => path, + Err(err) => panic!("root path must be absolute: {err}"), + } +} + +#[derive(Debug, Clone)] +struct SeatbeltAccessRoot { + root: AbsolutePathBuf, + excluded_subpaths: Vec, +} + +fn build_seatbelt_access_policy( + action: &str, + param_prefix: &str, + roots: Vec, +) -> (String, Vec<(String, PathBuf)>) { + let mut policy_components = Vec::new(); + let mut params = Vec::new(); + + for (index, access_root) in roots.into_iter().enumerate() { + let root = + normalize_path_for_sandbox(access_root.root.as_path()).unwrap_or(access_root.root); + let root_param = format!("{param_prefix}_{index}"); + params.push((root_param.clone(), root.into_path_buf())); + + if access_root.excluded_subpaths.is_empty() { + policy_components.push(format!("(subpath (param \"{root_param}\"))")); + continue; + } + + let mut require_parts = vec![format!("(subpath (param \"{root_param}\"))")]; + for (excluded_index, excluded_subpath) in + access_root.excluded_subpaths.into_iter().enumerate() + { + let excluded_subpath = + normalize_path_for_sandbox(excluded_subpath.as_path()).unwrap_or(excluded_subpath); + let excluded_param = format!("{param_prefix}_{index}_RO_{excluded_index}"); + params.push((excluded_param.clone(), excluded_subpath.into_path_buf())); + require_parts.push(format!( + "(require-not (subpath (param \"{excluded_param}\")))" + )); + } + policy_components.push(format!("(require-all {} )", require_parts.join(" "))); + } + + if policy_components.is_empty() { + (String::new(), Vec::new()) + } else { + ( + format!("(allow {action}\n{}\n)", policy_components.join(" ")), + params, + ) + } +} + +#[cfg_attr(not(test), allow(dead_code))] +pub(crate) fn create_seatbelt_command_args_with_extensions( + command: Vec, + sandbox_policy: &SandboxPolicy, + sandbox_policy_cwd: &Path, + enforce_managed_network: bool, + network: Option<&NetworkProxy>, + extensions: Option<&MacOsSeatbeltProfileExtensions>, +) -> Vec { + create_seatbelt_command_args_for_policies_with_extensions( + command, + &FileSystemSandboxPolicy::from_legacy_sandbox_policy(sandbox_policy, sandbox_policy_cwd), + NetworkSandboxPolicy::from(sandbox_policy), + sandbox_policy_cwd, + enforce_managed_network, + network, + extensions, + ) +} + +pub fn create_seatbelt_command_args_for_policies_with_extensions( + command: Vec, + file_system_sandbox_policy: &FileSystemSandboxPolicy, + network_sandbox_policy: NetworkSandboxPolicy, + sandbox_policy_cwd: &Path, + enforce_managed_network: bool, + network: Option<&NetworkProxy>, + extensions: Option<&MacOsSeatbeltProfileExtensions>, +) -> Vec { + let unreadable_roots = + file_system_sandbox_policy.get_unreadable_roots_with_cwd(sandbox_policy_cwd); + let (file_write_policy, file_write_dir_params) = + if file_system_sandbox_policy.has_full_disk_write_access() { + if unreadable_roots.is_empty() { + // Allegedly, this is more permissive than `(allow file-write*)`. + ( + r#"(allow file-write* (regex #"^/"))"#.to_string(), + Vec::new(), + ) + } else { + build_seatbelt_access_policy( + "file-write*", + "WRITABLE_ROOT", + vec![SeatbeltAccessRoot { + root: root_absolute_path(), + excluded_subpaths: unreadable_roots.clone(), + }], + ) + } + } else { + build_seatbelt_access_policy( + "file-write*", + "WRITABLE_ROOT", + file_system_sandbox_policy + .get_writable_roots_with_cwd(sandbox_policy_cwd) + .into_iter() + .map(|root| SeatbeltAccessRoot { + root: root.root, + excluded_subpaths: root.read_only_subpaths, + }) + .collect(), + ) + }; + + let (file_read_policy, file_read_dir_params) = + if file_system_sandbox_policy.has_full_disk_read_access() { + if unreadable_roots.is_empty() { + ( + "; allow read-only file operations\n(allow file-read*)".to_string(), + Vec::new(), + ) + } else { + let (policy, params) = build_seatbelt_access_policy( + "file-read*", + "READABLE_ROOT", + vec![SeatbeltAccessRoot { + root: root_absolute_path(), + excluded_subpaths: unreadable_roots, + }], + ); + ( + format!("; allow read-only file operations\n{policy}"), + params, + ) + } + } else { + let (policy, params) = build_seatbelt_access_policy( + "file-read*", + "READABLE_ROOT", + file_system_sandbox_policy + .get_readable_roots_with_cwd(sandbox_policy_cwd) + .into_iter() + .map(|root| SeatbeltAccessRoot { + excluded_subpaths: unreadable_roots + .iter() + .filter(|path| path.as_path().starts_with(root.as_path())) + .cloned() + .collect(), + root, + }) + .collect(), + ); + if policy.is_empty() { + (String::new(), params) + } else { + ( + format!("; allow read-only file operations\n{policy}"), + params, + ) + } + }; + + let proxy = proxy_policy_inputs(network); + let network_policy = + dynamic_network_policy_for_network(network_sandbox_policy, enforce_managed_network, &proxy); + let seatbelt_extensions = extensions.map_or_else( + || { + // Backward-compatibility default when no extension profile is provided. + build_seatbelt_extensions(&MacOsSeatbeltProfileExtensions::default()) + }, + build_seatbelt_extensions, + ); + + let include_platform_defaults = file_system_sandbox_policy.include_platform_defaults(); + let mut policy_sections = vec![ + MACOS_SEATBELT_BASE_POLICY.to_string(), + file_read_policy, + file_write_policy, + network_policy, + ]; + if include_platform_defaults { + policy_sections.push(MACOS_RESTRICTED_READ_ONLY_PLATFORM_DEFAULTS.to_string()); + } + if !seatbelt_extensions.policy.is_empty() { + policy_sections.push(seatbelt_extensions.policy.clone()); + } + + let full_policy = policy_sections.join("\n"); + + let dir_params = [ + file_read_dir_params, + file_write_dir_params, + macos_dir_params(), + unix_socket_dir_params(&proxy), + seatbelt_extensions.dir_params, + ] + .concat(); + + let mut seatbelt_args: Vec = vec!["-p".to_string(), full_policy]; + let definition_args = dir_params + .into_iter() + .map(|(key, value)| format!("-D{key}={value}", value = value.to_string_lossy())); + seatbelt_args.extend(definition_args); + seatbelt_args.push("--".to_string()); + seatbelt_args.extend(command); + seatbelt_args +} + +/// Wraps libc::confstr to return a String. +fn confstr(name: libc::c_int) -> Option { + let mut buf = vec![0_i8; (libc::PATH_MAX as usize) + 1]; + let len = unsafe { libc::confstr(name, buf.as_mut_ptr(), buf.len()) }; + if len == 0 { + return None; + } + // confstr guarantees NUL-termination when len > 0. + let cstr = unsafe { CStr::from_ptr(buf.as_ptr()) }; + cstr.to_str().ok().map(ToString::to_string) +} + +/// Wraps confstr to return a canonicalized PathBuf. +fn confstr_path(name: libc::c_int) -> Option { + let s = confstr(name)?; + let path = PathBuf::from(s); + path.canonicalize().ok().or(Some(path)) +} + +fn macos_dir_params() -> Vec<(String, PathBuf)> { + if let Some(p) = confstr_path(libc::_CS_DARWIN_USER_CACHE_DIR) { + return vec![("DARWIN_USER_CACHE_DIR".to_string(), p)]; + } + vec![] +} + +#[cfg(test)] +#[path = "seatbelt_tests.rs"] +mod tests; diff --git a/codex-rs/sandbox/src/seatbelt_base_policy.sbpl b/codex-rs/sandbox/src/seatbelt_base_policy.sbpl new file mode 100644 index 0000000000..72b13c96cd --- /dev/null +++ b/codex-rs/sandbox/src/seatbelt_base_policy.sbpl @@ -0,0 +1,108 @@ +(version 1) + +; inspired by Chrome's sandbox policy: +; https://source.chromium.org/chromium/chromium/src/+/main:sandbox/policy/mac/common.sb;l=273-319;drc=7b3962fe2e5fc9e2ee58000dc8fbf3429d84d3bd +; https://source.chromium.org/chromium/chromium/src/+/main:sandbox/policy/mac/renderer.sb;l=64;drc=7b3962fe2e5fc9e2ee58000dc8fbf3429d84d3bd + +; start with closed-by-default +(deny default) + +; child processes inherit the policy of their parent +(allow process-exec) +(allow process-fork) +(allow signal (target same-sandbox)) + +; process-info +(allow process-info* (target same-sandbox)) + +(allow file-write-data + (require-all + (path "/dev/null") + (vnode-type CHARACTER-DEVICE))) + +; sysctls permitted. +(allow sysctl-read + (sysctl-name "hw.activecpu") + (sysctl-name "hw.busfrequency_compat") + (sysctl-name "hw.byteorder") + (sysctl-name "hw.cacheconfig") + (sysctl-name "hw.cachelinesize_compat") + (sysctl-name "hw.cpufamily") + (sysctl-name "hw.cpufrequency_compat") + (sysctl-name "hw.cputype") + (sysctl-name "hw.l1dcachesize_compat") + (sysctl-name "hw.l1icachesize_compat") + (sysctl-name "hw.l2cachesize_compat") + (sysctl-name "hw.l3cachesize_compat") + (sysctl-name "hw.logicalcpu_max") + (sysctl-name "hw.machine") + (sysctl-name "hw.model") + (sysctl-name "hw.memsize") + (sysctl-name "hw.ncpu") + (sysctl-name "hw.nperflevels") + ; Chrome locks these CPU feature detection down a bit more tightly, + ; but mostly for fingerprinting concerns which isn't an issue for codex. + (sysctl-name-prefix "hw.optional.arm.") + (sysctl-name-prefix "hw.optional.armv8_") + (sysctl-name "hw.packages") + (sysctl-name "hw.pagesize_compat") + (sysctl-name "hw.pagesize") + (sysctl-name "hw.physicalcpu") + (sysctl-name "hw.physicalcpu_max") + (sysctl-name "hw.logicalcpu") + (sysctl-name "hw.cpufrequency") + (sysctl-name "hw.tbfrequency_compat") + (sysctl-name "hw.vectorunit") + (sysctl-name "machdep.cpu.brand_string") + (sysctl-name "kern.argmax") + (sysctl-name "kern.hostname") + (sysctl-name "kern.maxfilesperproc") + (sysctl-name "kern.maxproc") + (sysctl-name "kern.osproductversion") + (sysctl-name "kern.osrelease") + (sysctl-name "kern.ostype") + (sysctl-name "kern.osvariant_status") + (sysctl-name "kern.osversion") + (sysctl-name "kern.secure_kernel") + (sysctl-name "kern.usrstack64") + (sysctl-name "kern.version") + (sysctl-name "sysctl.proc_cputype") + (sysctl-name "vm.loadavg") + (sysctl-name-prefix "hw.perflevel") + (sysctl-name-prefix "kern.proc.pgrp.") + (sysctl-name-prefix "kern.proc.pid.") + (sysctl-name-prefix "net.routetable.") +) + +; Allow Java to read some CPU info. This is misclassified as a "write" because +; userspace passes a memory buffer to the sysctl, but conceptually it is a read. +(allow sysctl-write + (sysctl-name "kern.grade_cputype")) + +; IOKit +(allow iokit-open + (iokit-registry-entry-class "RootDomainUserClient") +) + +; needed to look up user info, see https://crbug.com/792228 +(allow mach-lookup + (global-name "com.apple.system.opendirectoryd.libinfo") +) + +; Needed for python multiprocessing on MacOS for the SemLock +(allow ipc-posix-sem) + +(allow mach-lookup + (global-name "com.apple.PowerManagement.control") +) + +; allow openpty() +(allow pseudo-tty) +(allow file-read* file-write* file-ioctl (literal "/dev/ptmx")) +(allow file-read* file-write* + (require-all + (regex #"^/dev/ttys[0-9]+") + (extension "com.apple.sandbox.pty"))) +; PTYs created before entering seatbelt may lack the extension; allow ioctl +; on those slave ttys so interactive shells detect a TTY and remain functional. +(allow file-ioctl (regex #"^/dev/ttys[0-9]+")) diff --git a/codex-rs/sandbox/src/seatbelt_network_policy.sbpl b/codex-rs/sandbox/src/seatbelt_network_policy.sbpl new file mode 100644 index 0000000000..a0801d093b --- /dev/null +++ b/codex-rs/sandbox/src/seatbelt_network_policy.sbpl @@ -0,0 +1,35 @@ +; when network access is enabled, these policies are added after those in seatbelt_base_policy.sbpl +; proxy-specific allow rules are injected by codex-core based on environment. +; Ref https://source.chromium.org/chromium/chromium/src/+/main:sandbox/policy/mac/network.sb;drc=f8f264d5e4e7509c913f4c60c2639d15905a07e4 + +; allow only safe AF_SYSTEM sockets used for local platform services. +(allow system-socket + (require-all + (socket-domain AF_SYSTEM) + (socket-protocol 2) + ) +) + +(allow mach-lookup + ; Used to look up the _CS_DARWIN_USER_CACHE_DIR in the sandbox. + (global-name "com.apple.bsd.dirhelper") + (global-name "com.apple.system.opendirectoryd.membership") + + ; Communicate with the security server for TLS certificate information. + (global-name "com.apple.SecurityServer") + (global-name "com.apple.networkd") + (global-name "com.apple.ocspd") + (global-name "com.apple.trustd.agent") + + ; Read network configuration. + (global-name "com.apple.SystemConfiguration.DNSConfiguration") + (global-name "com.apple.SystemConfiguration.configd") +) + +(allow sysctl-read + (sysctl-name-regex #"^net.routetable") +) + +(allow file-write* + (subpath (param "DARWIN_USER_CACHE_DIR")) +) diff --git a/codex-rs/sandbox/src/seatbelt_permissions.rs b/codex-rs/sandbox/src/seatbelt_permissions.rs new file mode 100644 index 0000000000..5cbfd65094 --- /dev/null +++ b/codex-rs/sandbox/src/seatbelt_permissions.rs @@ -0,0 +1,192 @@ +#![cfg(target_os = "macos")] + +use std::collections::BTreeSet; +use std::path::PathBuf; + +pub use codex_protocol::models::MacOsAutomationPermission; +pub use codex_protocol::models::MacOsContactsPermission; +pub use codex_protocol::models::MacOsPreferencesPermission; +pub use codex_protocol::models::MacOsSeatbeltProfileExtensions; + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub(crate) struct SeatbeltExtensionPolicy { + pub(crate) policy: String, + pub(crate) dir_params: Vec<(String, PathBuf)>, +} + +fn normalized_extensions( + extensions: &MacOsSeatbeltProfileExtensions, +) -> MacOsSeatbeltProfileExtensions { + let mut normalized = extensions.clone(); + if let MacOsAutomationPermission::BundleIds(bundle_ids) = &extensions.macos_automation { + let bundle_ids = normalize_bundle_ids(bundle_ids); + normalized.macos_automation = if bundle_ids.is_empty() { + MacOsAutomationPermission::None + } else { + MacOsAutomationPermission::BundleIds(bundle_ids) + }; + } + + normalized +} + +pub(crate) fn build_seatbelt_extensions( + extensions: &MacOsSeatbeltProfileExtensions, +) -> SeatbeltExtensionPolicy { + let extensions = normalized_extensions(extensions); + let mut clauses = Vec::new(); + + match extensions.macos_preferences { + MacOsPreferencesPermission::None => {} + MacOsPreferencesPermission::ReadOnly => { + clauses.push( + "(allow ipc-posix-shm-read* (ipc-posix-name-prefix \"apple.cfprefs.\"))" + .to_string(), + ); + clauses.push( + "(allow mach-lookup\n (global-name \"com.apple.cfprefsd.daemon\")\n (global-name \"com.apple.cfprefsd.agent\")\n (local-name \"com.apple.cfprefsd.agent\"))" + .to_string(), + ); + clauses.push("(allow user-preference-read)".to_string()); + } + MacOsPreferencesPermission::ReadWrite => { + clauses.push( + "(allow ipc-posix-shm-read* (ipc-posix-name-prefix \"apple.cfprefs.\"))" + .to_string(), + ); + clauses.push( + "(allow mach-lookup\n (global-name \"com.apple.cfprefsd.daemon\")\n (global-name \"com.apple.cfprefsd.agent\")\n (local-name \"com.apple.cfprefsd.agent\"))" + .to_string(), + ); + clauses.push("(allow user-preference-read)".to_string()); + clauses.push("(allow user-preference-write)".to_string()); + clauses.push( + "(allow ipc-posix-shm-write-data (ipc-posix-name-prefix \"apple.cfprefs.\"))" + .to_string(), + ); + clauses.push( + "(allow ipc-posix-shm-write-create (ipc-posix-name-prefix \"apple.cfprefs.\"))" + .to_string(), + ); + } + } + + match extensions.macos_automation { + MacOsAutomationPermission::None => {} + MacOsAutomationPermission::All => { + clauses.push( + "(allow mach-lookup\n (global-name \"com.apple.coreservices.appleevents\"))" + .to_string(), + ); + clauses.push("(allow appleevent-send)".to_string()); + } + MacOsAutomationPermission::BundleIds(bundle_ids) => { + if !bundle_ids.is_empty() { + clauses.push( + "(allow mach-lookup\n (global-name \"com.apple.coreservices.appleevents\"))" + .to_string(), + ); + let destinations = bundle_ids + .iter() + .map(|bundle_id| format!(" (appleevent-destination \"{bundle_id}\")")) + .collect::>() + .join("\n"); + clauses.push(format!("(allow appleevent-send\n{destinations}\n)")); + } + } + } + + if extensions.macos_launch_services { + clauses.push( + "(allow mach-lookup\n (global-name \"com.apple.coreservices.launchservicesd\")\n (global-name \"com.apple.lsd.mapdb\")\n (global-name \"com.apple.coreservices.quarantine-resolver\")\n (global-name \"com.apple.lsd.modifydb\"))" + .to_string(), + ); + clauses.push("(allow lsopen)".to_string()); + } + + if extensions.macos_accessibility { + clauses.push("(allow mach-lookup (local-name \"com.apple.axserver\"))".to_string()); + } + + if extensions.macos_calendar { + clauses.push("(allow mach-lookup (global-name \"com.apple.CalendarAgent\"))".to_string()); + } + + if extensions.macos_reminders { + clauses.push( + "(allow mach-lookup\n (global-name \"com.apple.CalendarAgent\")\n (global-name \"com.apple.remindd\"))" + .to_string(), + ); + } + + let mut dir_params = Vec::new(); + match extensions.macos_contacts { + MacOsContactsPermission::None => {} + MacOsContactsPermission::ReadOnly => { + clauses.push( + "(allow file-read* file-test-existence\n (subpath \"/System/Library/Address Book Plug-Ins\")\n (subpath (param \"ADDRESSBOOK_DIR\")))" + .to_string(), + ); + clauses.push( + "(allow mach-lookup\n (global-name \"com.apple.tccd\")\n (global-name \"com.apple.tccd.system\")\n (global-name \"com.apple.contactsd.persistence\")\n (global-name \"com.apple.AddressBook.ContactsAccountsService\")\n (global-name \"com.apple.contacts.account-caching\")\n (global-name \"com.apple.accountsd.accountmanager\"))" + .to_string(), + ); + if let Some(addressbook_dir) = addressbook_dir() { + dir_params.push(("ADDRESSBOOK_DIR".to_string(), addressbook_dir)); + } + } + MacOsContactsPermission::ReadWrite => { + clauses.push( + "(allow file-read* file-write*\n (subpath \"/System/Library/Address Book Plug-Ins\")\n (subpath (param \"ADDRESSBOOK_DIR\"))\n (subpath \"/var/folders\")\n (subpath \"/private/var/folders\"))" + .to_string(), + ); + clauses.push( + "(allow mach-lookup\n (global-name \"com.apple.tccd\")\n (global-name \"com.apple.tccd.system\")\n (global-name \"com.apple.contactsd.persistence\")\n (global-name \"com.apple.AddressBook.ContactsAccountsService\")\n (global-name \"com.apple.contacts.account-caching\")\n (global-name \"com.apple.accountsd.accountmanager\")\n (global-name \"com.apple.securityd.xpc\"))" + .to_string(), + ); + if let Some(addressbook_dir) = addressbook_dir() { + dir_params.push(("ADDRESSBOOK_DIR".to_string(), addressbook_dir)); + } + } + } + + if clauses.is_empty() { + SeatbeltExtensionPolicy::default() + } else { + SeatbeltExtensionPolicy { + policy: format!( + "; macOS permission profile extensions\n{}\n", + clauses.join("\n") + ), + dir_params, + } + } +} + +fn addressbook_dir() -> Option { + Some(dirs::home_dir()?.join("Library/Application Support/AddressBook")) +} + +fn normalize_bundle_ids(bundle_ids: &[String]) -> Vec { + let mut unique = BTreeSet::new(); + for bundle_id in bundle_ids { + let candidate = bundle_id.trim(); + if is_valid_bundle_id(candidate) { + unique.insert(candidate.to_string()); + } + } + unique.into_iter().collect() +} + +fn is_valid_bundle_id(bundle_id: &str) -> bool { + if bundle_id.len() < 3 || !bundle_id.contains('.') { + return false; + } + bundle_id + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_') +} + +#[cfg(test)] +#[path = "seatbelt_permissions_tests.rs"] +mod tests; diff --git a/codex-rs/sandbox/src/seatbelt_permissions_tests.rs b/codex-rs/sandbox/src/seatbelt_permissions_tests.rs new file mode 100644 index 0000000000..b52ccdfcb2 --- /dev/null +++ b/codex-rs/sandbox/src/seatbelt_permissions_tests.rs @@ -0,0 +1,154 @@ +use super::MacOsAutomationPermission; +use super::MacOsContactsPermission; +use super::MacOsPreferencesPermission; +use super::MacOsSeatbeltProfileExtensions; +use super::build_seatbelt_extensions; + +#[test] +fn preferences_read_only_emits_read_clauses_only() { + let policy = build_seatbelt_extensions(&MacOsSeatbeltProfileExtensions { + macos_preferences: MacOsPreferencesPermission::ReadOnly, + ..Default::default() + }); + assert!(policy.policy.contains("(allow user-preference-read)")); + assert!(!policy.policy.contains("(allow user-preference-write)")); +} + +#[test] +fn preferences_read_write_emits_write_clauses() { + let policy = build_seatbelt_extensions(&MacOsSeatbeltProfileExtensions { + macos_preferences: MacOsPreferencesPermission::ReadWrite, + ..Default::default() + }); + assert!(policy.policy.contains("(allow user-preference-read)")); + assert!(policy.policy.contains("(allow user-preference-write)")); + assert!( + policy.policy.contains( + "(allow ipc-posix-shm-write-create (ipc-posix-name-prefix \"apple.cfprefs.\"))" + ) + ); +} + +#[test] +fn automation_all_emits_unscoped_appleevents() { + let policy = build_seatbelt_extensions(&MacOsSeatbeltProfileExtensions { + macos_automation: MacOsAutomationPermission::All, + ..Default::default() + }); + assert!(policy.policy.contains("(allow appleevent-send)")); + assert!(policy.policy.contains("com.apple.coreservices.appleevents")); +} + +#[test] +fn automation_bundle_ids_are_normalized_and_scoped() { + let policy = build_seatbelt_extensions(&MacOsSeatbeltProfileExtensions { + macos_automation: MacOsAutomationPermission::BundleIds(vec![ + " com.apple.Notes ".to_string(), + "com.apple.Calendar".to_string(), + "bad bundle".to_string(), + "com.apple.Notes".to_string(), + ]), + ..Default::default() + }); + assert!( + policy + .policy + .contains("(appleevent-destination \"com.apple.Calendar\")") + ); + assert!( + policy + .policy + .contains("(appleevent-destination \"com.apple.Notes\")") + ); + assert!(!policy.policy.contains("bad bundle")); + assert!(policy.policy.contains("com.apple.coreservices.appleevents")); +} + +#[test] +fn launch_services_emit_launch_clauses() { + let policy = build_seatbelt_extensions(&MacOsSeatbeltProfileExtensions { + macos_launch_services: true, + ..Default::default() + }); + assert!( + policy + .policy + .contains("com.apple.coreservices.launchservicesd") + ); + assert!(policy.policy.contains("com.apple.lsd.mapdb")); + assert!( + policy + .policy + .contains("com.apple.coreservices.quarantine-resolver") + ); + assert!(policy.policy.contains("com.apple.lsd.modifydb")); + assert!(policy.policy.contains("(allow lsopen)")); +} + +#[test] +fn accessibility_and_calendar_emit_mach_lookups() { + let policy = build_seatbelt_extensions(&MacOsSeatbeltProfileExtensions { + macos_accessibility: true, + macos_calendar: true, + ..Default::default() + }); + assert!(policy.policy.contains("com.apple.axserver")); + assert!(policy.policy.contains("com.apple.CalendarAgent")); +} + +#[test] +fn reminders_emit_calendar_agent_and_remindd_lookups() { + let policy = build_seatbelt_extensions(&MacOsSeatbeltProfileExtensions { + macos_reminders: true, + ..Default::default() + }); + assert!(policy.policy.contains("com.apple.CalendarAgent")); + assert!(policy.policy.contains("com.apple.remindd")); +} + +#[test] +fn contacts_read_only_emit_contacts_read_clauses() { + let policy = build_seatbelt_extensions(&MacOsSeatbeltProfileExtensions { + macos_contacts: MacOsContactsPermission::ReadOnly, + ..Default::default() + }); + + assert!( + policy + .policy + .contains("(subpath \"/System/Library/Address Book Plug-Ins\")") + ); + assert!( + policy + .policy + .contains("(subpath (param \"ADDRESSBOOK_DIR\"))") + ); + assert!(policy.policy.contains("com.apple.contactsd.persistence")); + assert!(policy.policy.contains("com.apple.accountsd.accountmanager")); + assert!(!policy.policy.contains("com.apple.securityd.xpc")); + assert!( + policy + .dir_params + .iter() + .any(|(key, _)| key == "ADDRESSBOOK_DIR") + ); +} + +#[test] +fn contacts_read_write_emit_write_clauses() { + let policy = build_seatbelt_extensions(&MacOsSeatbeltProfileExtensions { + macos_contacts: MacOsContactsPermission::ReadWrite, + ..Default::default() + }); + + assert!(policy.policy.contains("(subpath \"/var/folders\")")); + assert!(policy.policy.contains("(subpath \"/private/var/folders\")")); + assert!(policy.policy.contains("com.apple.securityd.xpc")); +} + +#[test] +fn default_extensions_emit_preferences_read_only_policy() { + let policy = build_seatbelt_extensions(&MacOsSeatbeltProfileExtensions::default()); + assert!(policy.policy.contains("(allow user-preference-read)")); + assert!(!policy.policy.contains("(allow user-preference-write)")); +} diff --git a/codex-rs/sandbox/src/seatbelt_tests.rs b/codex-rs/sandbox/src/seatbelt_tests.rs new file mode 100644 index 0000000000..bab1362017 --- /dev/null +++ b/codex-rs/sandbox/src/seatbelt_tests.rs @@ -0,0 +1,1064 @@ +use super::MACOS_SEATBELT_BASE_POLICY; +use super::ProxyPolicyInputs; +use super::UnixDomainSocketPolicy; +use super::create_seatbelt_command_args; +use super::create_seatbelt_command_args_for_policies_with_extensions; +use super::create_seatbelt_command_args_with_extensions; +use super::dynamic_network_policy; +use super::macos_dir_params; +use super::normalize_path_for_sandbox; +use super::unix_socket_dir_params; +use super::unix_socket_policy; +use crate::protocol::ReadOnlyAccess; +use crate::protocol::SandboxPolicy; +use crate::seatbelt::MACOS_PATH_TO_SEATBELT_EXECUTABLE; +use crate::seatbelt_permissions::MacOsAutomationPermission; +use crate::seatbelt_permissions::MacOsContactsPermission; +use crate::seatbelt_permissions::MacOsPreferencesPermission; +use crate::seatbelt_permissions::MacOsSeatbeltProfileExtensions; +use codex_protocol::permissions::FileSystemAccessMode; +use codex_protocol::permissions::FileSystemPath; +use codex_protocol::permissions::FileSystemSandboxEntry; +use codex_protocol::permissions::FileSystemSandboxPolicy; +use codex_protocol::permissions::NetworkSandboxPolicy; +use codex_utils_absolute_path::AbsolutePathBuf; +use pretty_assertions::assert_eq; +use std::fs; +use std::path::Path; +use std::path::PathBuf; +use std::process::Command; +use tempfile::TempDir; + +fn assert_seatbelt_denied(stderr: &[u8], path: &Path) { + let stderr = String::from_utf8_lossy(stderr); + let expected = format!("bash: {}: Operation not permitted\n", path.display()); + assert!( + stderr == expected + || stderr.contains("sandbox-exec: sandbox_apply: Operation not permitted"), + "unexpected stderr: {stderr}" + ); +} + +fn absolute_path(path: &str) -> AbsolutePathBuf { + AbsolutePathBuf::from_absolute_path(Path::new(path)).expect("absolute path") +} + +fn seatbelt_policy_arg(args: &[String]) -> &str { + let policy_index = args + .iter() + .position(|arg| arg == "-p") + .expect("seatbelt args should include -p"); + args.get(policy_index + 1) + .expect("seatbelt args should include policy text") +} + +#[test] +fn base_policy_allows_node_cpu_sysctls() { + assert!( + MACOS_SEATBELT_BASE_POLICY.contains("(sysctl-name \"machdep.cpu.brand_string\")"), + "base policy must allow CPU brand lookup for os.cpus()" + ); + assert!( + MACOS_SEATBELT_BASE_POLICY.contains("(sysctl-name \"hw.model\")"), + "base policy must allow hardware model lookup for os.cpus()" + ); +} + +#[test] +fn create_seatbelt_args_routes_network_through_proxy_ports() { + let policy = dynamic_network_policy( + &SandboxPolicy::new_read_only_policy(), + false, + &ProxyPolicyInputs { + ports: vec![43128, 48081], + has_proxy_config: true, + allow_local_binding: false, + ..ProxyPolicyInputs::default() + }, + ); + + assert!( + policy.contains("(allow network-outbound (remote ip \"localhost:43128\"))"), + "expected HTTP proxy port allow rule in policy:\n{policy}" + ); + assert!( + policy.contains("(allow network-outbound (remote ip \"localhost:48081\"))"), + "expected SOCKS proxy port allow rule in policy:\n{policy}" + ); + assert!( + !policy.contains("\n(allow network-outbound)\n"), + "policy should not include blanket outbound allowance when proxy ports are present:\n{policy}" + ); + assert!( + !policy.contains("(allow network-bind (local ip \"localhost:*\"))"), + "policy should not allow loopback binding unless explicitly enabled:\n{policy}" + ); + assert!( + !policy.contains("(allow network-inbound (local ip \"localhost:*\"))"), + "policy should not allow loopback inbound unless explicitly enabled:\n{policy}" + ); +} + +#[test] +fn explicit_unreadable_paths_are_excluded_from_full_disk_read_and_write_access() { + let unreadable = absolute_path("/tmp/codex-unreadable"); + let file_system_policy = FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: crate::protocol::FileSystemSpecialPath::Root, + }, + access: FileSystemAccessMode::Write, + }, + FileSystemSandboxEntry { + path: FileSystemPath::Path { path: unreadable }, + access: FileSystemAccessMode::None, + }, + ]); + + let args = create_seatbelt_command_args_for_policies_with_extensions( + vec!["/bin/true".to_string()], + &file_system_policy, + NetworkSandboxPolicy::Restricted, + Path::new("/"), + false, + None, + None, + ); + + let policy = seatbelt_policy_arg(&args); + let unreadable_roots = file_system_policy.get_unreadable_roots_with_cwd(Path::new("/")); + let unreadable_root = unreadable_roots.first().expect("expected unreadable root"); + assert!( + policy.contains("(require-not (subpath (param \"READABLE_ROOT_0_RO_0\")))"), + "expected read carveout in policy:\n{policy}" + ); + assert!( + policy.contains("(require-not (subpath (param \"WRITABLE_ROOT_0_RO_0\")))"), + "expected write carveout in policy:\n{policy}" + ); + assert!( + args.iter() + .any(|arg| arg == &format!("-DREADABLE_ROOT_0_RO_0={}", unreadable_root.display())), + "expected read carveout parameter in args: {args:#?}" + ); + assert!( + args.iter() + .any(|arg| arg == &format!("-DWRITABLE_ROOT_0_RO_0={}", unreadable_root.display())), + "expected write carveout parameter in args: {args:#?}" + ); +} + +#[test] +fn explicit_unreadable_paths_are_excluded_from_readable_roots() { + let root = absolute_path("/tmp/codex-readable"); + let unreadable = absolute_path("/tmp/codex-readable/private"); + let file_system_policy = FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry { + path: FileSystemPath::Path { path: root }, + access: FileSystemAccessMode::Read, + }, + FileSystemSandboxEntry { + path: FileSystemPath::Path { path: unreadable }, + access: FileSystemAccessMode::None, + }, + ]); + + let args = create_seatbelt_command_args_for_policies_with_extensions( + vec!["/bin/true".to_string()], + &file_system_policy, + NetworkSandboxPolicy::Restricted, + Path::new("/"), + false, + None, + None, + ); + + let policy = seatbelt_policy_arg(&args); + let readable_roots = file_system_policy.get_readable_roots_with_cwd(Path::new("/")); + let readable_root = readable_roots.first().expect("expected readable root"); + let unreadable_roots = file_system_policy.get_unreadable_roots_with_cwd(Path::new("/")); + let unreadable_root = unreadable_roots.first().expect("expected unreadable root"); + assert!( + policy.contains("(require-not (subpath (param \"READABLE_ROOT_0_RO_0\")))"), + "expected read carveout in policy:\n{policy}" + ); + assert!( + args.iter() + .any(|arg| arg == &format!("-DREADABLE_ROOT_0={}", readable_root.display())), + "expected readable root parameter in args: {args:#?}" + ); + assert!( + args.iter() + .any(|arg| arg == &format!("-DREADABLE_ROOT_0_RO_0={}", unreadable_root.display())), + "expected read carveout parameter in args: {args:#?}" + ); +} + +#[test] +fn seatbelt_args_include_macos_permission_extensions() { + let cwd = std::env::temp_dir(); + let args = create_seatbelt_command_args_with_extensions( + vec!["echo".to_string(), "ok".to_string()], + &SandboxPolicy::new_read_only_policy(), + cwd.as_path(), + false, + None, + Some(&MacOsSeatbeltProfileExtensions { + macos_preferences: MacOsPreferencesPermission::ReadWrite, + macos_automation: MacOsAutomationPermission::BundleIds(vec![ + "com.apple.Notes".to_string(), + ]), + macos_launch_services: true, + macos_accessibility: true, + macos_calendar: true, + macos_reminders: false, + macos_contacts: MacOsContactsPermission::None, + }), + ); + let policy = &args[1]; + + assert!(policy.contains("(allow user-preference-write)")); + assert!(policy.contains("(appleevent-destination \"com.apple.Notes\")")); + assert!(policy.contains("com.apple.axserver")); + assert!(policy.contains("com.apple.CalendarAgent")); +} + +#[test] +fn bundle_id_automation_keeps_lsopen_denied() { + let tmp = TempDir::new().expect("tempdir"); + let cwd = tmp.path().join("cwd"); + fs::create_dir_all(&cwd).expect("create cwd"); + + let args = create_seatbelt_command_args_with_extensions( + vec![ + "/usr/bin/python3".to_string(), + "-c".to_string(), + r#"import ctypes +import os +import sys +lib = ctypes.CDLL("/usr/lib/libsandbox.1.dylib") +lib.sandbox_check.restype = ctypes.c_int +allowed = lib.sandbox_check(os.getpid(), b"lsopen", 0) == 0 +sys.exit(0 if allowed else 13) +"# + .to_string(), + ], + &SandboxPolicy::new_read_only_policy(), + cwd.as_path(), + false, + None, + Some(&MacOsSeatbeltProfileExtensions { + macos_automation: MacOsAutomationPermission::BundleIds(vec![ + "com.apple.Notes".to_string(), + ]), + ..Default::default() + }), + ); + + let output = Command::new(MACOS_PATH_TO_SEATBELT_EXECUTABLE) + .args(&args) + .current_dir(&cwd) + .output() + .expect("execute seatbelt command"); + + let stderr = String::from_utf8_lossy(&output.stderr); + if stderr.contains("sandbox-exec: sandbox_apply: Operation not permitted") { + return; + } + + assert_eq!( + Some(13), + output.status.code(), + "lsopen should remain denied even with bundle-scoped automation\nstdout: {}\nstderr: {stderr}", + String::from_utf8_lossy(&output.stdout), + ); +} + +#[test] +fn seatbelt_args_without_extension_profile_keep_legacy_preferences_read_access() { + let cwd = std::env::temp_dir(); + let args = create_seatbelt_command_args( + vec!["echo".to_string(), "ok".to_string()], + &SandboxPolicy::new_read_only_policy(), + cwd.as_path(), + false, + None, + ); + let policy = &args[1]; + assert!(policy.contains("(allow user-preference-read)")); + assert!(!policy.contains("(allow user-preference-write)")); +} + +#[test] +fn seatbelt_legacy_workspace_write_nested_readable_root_stays_writable() { + let tmp = TempDir::new().expect("tempdir"); + let cwd = tmp.path().join("workspace"); + fs::create_dir_all(cwd.join("docs")).expect("create docs"); + let docs = AbsolutePathBuf::from_absolute_path(cwd.join("docs")).expect("absolute docs"); + let args = create_seatbelt_command_args( + vec!["/bin/true".to_string()], + &SandboxPolicy::WorkspaceWrite { + writable_roots: vec![], + read_only_access: ReadOnlyAccess::Restricted { + include_platform_defaults: true, + readable_roots: vec![docs.clone()], + }, + network_access: false, + exclude_tmpdir_env_var: true, + exclude_slash_tmp: true, + }, + cwd.as_path(), + false, + None, + ); + + let docs_param = format!("-DWRITABLE_ROOT_0_RO_0={}", docs.as_path().display()); + assert!( + !seatbelt_policy_arg(&args).contains("WRITABLE_ROOT_0_RO_0"), + "legacy workspace-write readable roots under cwd should not become seatbelt carveouts:\n{args:#?}" + ); + assert!( + !args.iter().any(|arg| arg == &docs_param), + "unexpected seatbelt carveout parameter for redundant legacy readable root: {args:#?}" + ); +} + +#[test] +fn seatbelt_args_default_extension_profile_keeps_preferences_read_access() { + let cwd = std::env::temp_dir(); + let args = create_seatbelt_command_args_with_extensions( + vec!["echo".to_string(), "ok".to_string()], + &SandboxPolicy::new_read_only_policy(), + cwd.as_path(), + false, + None, + Some(&MacOsSeatbeltProfileExtensions::default()), + ); + let policy = &args[1]; + assert!(!policy.contains("appleevent-send")); + assert!(!policy.contains("com.apple.axserver")); + assert!(!policy.contains("com.apple.CalendarAgent")); + assert!(policy.contains("(allow user-preference-read)")); + assert!(!policy.contains("user-preference-write")); +} + +#[test] +fn create_seatbelt_args_allows_local_binding_when_explicitly_enabled() { + let policy = dynamic_network_policy( + &SandboxPolicy::new_read_only_policy(), + false, + &ProxyPolicyInputs { + ports: vec![43128], + has_proxy_config: true, + allow_local_binding: true, + ..ProxyPolicyInputs::default() + }, + ); + + assert!( + policy.contains("(allow network-bind (local ip \"localhost:*\"))"), + "policy should allow loopback local binding when explicitly enabled:\n{policy}" + ); + assert!( + policy.contains("(allow network-inbound (local ip \"localhost:*\"))"), + "policy should allow loopback inbound when explicitly enabled:\n{policy}" + ); + assert!( + policy.contains("(allow network-outbound (remote ip \"localhost:*\"))"), + "policy should allow loopback outbound when explicitly enabled:\n{policy}" + ); + assert!( + !policy.contains("\n(allow network-outbound)\n"), + "policy should keep proxy-routed behavior without blanket outbound allowance:\n{policy}" + ); +} + +#[test] +fn dynamic_network_policy_preserves_restricted_policy_when_proxy_config_without_ports() { + let policy = dynamic_network_policy( + &SandboxPolicy::WorkspaceWrite { + writable_roots: vec![], + read_only_access: Default::default(), + network_access: true, + exclude_tmpdir_env_var: false, + exclude_slash_tmp: false, + }, + false, + &ProxyPolicyInputs { + ports: vec![], + has_proxy_config: true, + allow_local_binding: false, + ..ProxyPolicyInputs::default() + }, + ); + + assert!( + policy.contains("(socket-domain AF_SYSTEM)"), + "policy should keep the restricted network profile when proxy config is present without ports:\n{policy}" + ); + assert!( + !policy.contains("\n(allow network-outbound)\n"), + "policy should not include blanket outbound allowance when proxy config is present without ports:\n{policy}" + ); + assert!( + !policy.contains("(allow network-outbound (remote ip \"localhost:"), + "policy should not include proxy port allowance when proxy config is present without ports:\n{policy}" + ); +} + +#[test] +fn dynamic_network_policy_preserves_restricted_policy_for_managed_network_without_proxy_config() { + let policy = dynamic_network_policy( + &SandboxPolicy::WorkspaceWrite { + writable_roots: vec![], + read_only_access: Default::default(), + network_access: true, + exclude_tmpdir_env_var: false, + exclude_slash_tmp: false, + }, + true, + &ProxyPolicyInputs { + ports: vec![], + has_proxy_config: false, + allow_local_binding: false, + ..ProxyPolicyInputs::default() + }, + ); + + assert!( + policy.contains("(socket-domain AF_SYSTEM)"), + "policy should keep the restricted network profile when managed network is active without proxy endpoints:\n{policy}" + ); + assert!( + !policy.contains("\n(allow network-outbound)\n"), + "policy should not include blanket outbound allowance when managed network is active without proxy endpoints:\n{policy}" + ); +} + +#[test] +fn create_seatbelt_args_allowlists_unix_socket_paths() { + let policy = dynamic_network_policy( + &SandboxPolicy::new_read_only_policy(), + false, + &ProxyPolicyInputs { + ports: vec![43128], + has_proxy_config: true, + allow_local_binding: false, + unix_domain_socket_policy: UnixDomainSocketPolicy::Restricted { + allowed: vec![absolute_path("/tmp/example.sock")], + }, + }, + ); + + assert!( + policy.contains("(allow system-socket (socket-domain AF_UNIX))"), + "policy should allow AF_UNIX socket creation for configured unix sockets:\n{policy}" + ); + assert!( + policy.contains( + "(allow network-bind (local unix-socket (subpath (param \"UNIX_SOCKET_PATH_0\"))))" + ), + "policy should allow binding explicitly configured unix sockets:\n{policy}" + ); + assert!( + policy.contains( + "(allow network-outbound (remote unix-socket (subpath (param \"UNIX_SOCKET_PATH_0\"))))" + ), + "policy should allow connecting to explicitly configured unix sockets:\n{policy}" + ); + assert!( + !policy.contains("(allow network* (subpath"), + "policy should no longer use the generic subpath unix-socket rules:\n{policy}" + ); +} + +#[test] +fn unix_socket_policy_non_empty_output_is_newline_terminated() { + let allowlist_policy = unix_socket_policy(&ProxyPolicyInputs { + unix_domain_socket_policy: UnixDomainSocketPolicy::Restricted { + allowed: vec![absolute_path("/tmp/example.sock")], + }, + ..ProxyPolicyInputs::default() + }); + assert!( + allowlist_policy.ends_with('\n'), + "allowlist unix socket policy should end with a newline:\n{allowlist_policy}" + ); + + let allow_all_policy = unix_socket_policy(&ProxyPolicyInputs { + unix_domain_socket_policy: UnixDomainSocketPolicy::AllowAll, + ..ProxyPolicyInputs::default() + }); + assert!( + allow_all_policy.ends_with('\n'), + "allow-all unix socket policy should end with a newline:\n{allow_all_policy}" + ); +} + +#[test] +fn unix_socket_dir_params_use_stable_param_names() { + let params = unix_socket_dir_params(&ProxyPolicyInputs { + unix_domain_socket_policy: UnixDomainSocketPolicy::Restricted { + allowed: vec![ + absolute_path("/tmp/b.sock"), + absolute_path("/tmp/a.sock"), + absolute_path("/tmp/a.sock"), + ], + }, + ..ProxyPolicyInputs::default() + }); + + assert_eq!( + params, + vec![ + ( + "UNIX_SOCKET_PATH_0".to_string(), + PathBuf::from("/tmp/a.sock") + ), + ( + "UNIX_SOCKET_PATH_1".to_string(), + PathBuf::from("/tmp/b.sock") + ), + ] + ); +} + +#[test] +fn normalize_path_for_sandbox_rejects_relative_paths() { + assert_eq!(normalize_path_for_sandbox(Path::new("relative.sock")), None); +} + +#[test] +fn create_seatbelt_args_allows_all_unix_sockets_when_enabled() { + let policy = dynamic_network_policy( + &SandboxPolicy::new_read_only_policy(), + false, + &ProxyPolicyInputs { + ports: vec![43128], + has_proxy_config: true, + allow_local_binding: false, + unix_domain_socket_policy: UnixDomainSocketPolicy::AllowAll, + }, + ); + + assert!( + policy.contains("(allow system-socket (socket-domain AF_UNIX))"), + "policy should allow AF_UNIX socket creation when unix sockets are enabled:\n{policy}" + ); + assert!( + policy.contains("(allow network-bind (local unix-socket))"), + "policy should allow binding unix sockets when enabled:\n{policy}" + ); + assert!( + policy.contains("(allow network-outbound (remote unix-socket))"), + "policy should allow connecting to unix sockets when enabled:\n{policy}" + ); + assert!( + !policy.contains("(allow network* (subpath"), + "policy should no longer use the generic subpath unix-socket rules:\n{policy}" + ); +} + +#[test] +fn create_seatbelt_args_full_network_with_proxy_is_still_proxy_only() { + let policy = dynamic_network_policy( + &SandboxPolicy::WorkspaceWrite { + writable_roots: vec![], + read_only_access: Default::default(), + network_access: true, + exclude_tmpdir_env_var: false, + exclude_slash_tmp: false, + }, + false, + &ProxyPolicyInputs { + ports: vec![43128], + has_proxy_config: true, + allow_local_binding: false, + ..ProxyPolicyInputs::default() + }, + ); + + assert!( + policy.contains("(allow network-outbound (remote ip \"localhost:43128\"))"), + "expected proxy endpoint allow rule in policy:\n{policy}" + ); + assert!( + !policy.contains("\n(allow network-outbound)\n"), + "policy should not include blanket outbound allowance when proxy is configured:\n{policy}" + ); + assert!( + !policy.contains("\n(allow network-inbound)\n"), + "policy should not include blanket inbound allowance when proxy is configured:\n{policy}" + ); +} + +#[test] +fn create_seatbelt_args_with_read_only_git_and_codex_subpaths() { + // Create a temporary workspace with two writable roots: one containing + // top-level .git and .codex directories and one without them. + let tmp = TempDir::new().expect("tempdir"); + let PopulatedTmp { + vulnerable_root, + vulnerable_root_canonical, + dot_git_canonical, + dot_codex_canonical, + empty_root, + empty_root_canonical, + } = populate_tmpdir(tmp.path()); + let cwd = tmp.path().join("cwd"); + fs::create_dir_all(&cwd).expect("create cwd"); + + // Build a policy that only includes the two test roots as writable and + // does not automatically include defaults TMPDIR or /tmp. + let policy = SandboxPolicy::WorkspaceWrite { + writable_roots: vec![vulnerable_root, empty_root] + .into_iter() + .map(|p| p.try_into().unwrap()) + .collect(), + read_only_access: Default::default(), + network_access: false, + exclude_tmpdir_env_var: true, + exclude_slash_tmp: true, + }; + + // Create the Seatbelt command to wrap a shell command that tries to + // write to .codex/config.toml in the vulnerable root. + let shell_command: Vec = [ + "bash", + "-c", + "echo 'sandbox_mode = \"danger-full-access\"' > \"$1\"", + "bash", + dot_codex_canonical + .join("config.toml") + .to_string_lossy() + .as_ref(), + ] + .iter() + .map(std::string::ToString::to_string) + .collect(); + let args = create_seatbelt_command_args(shell_command.clone(), &policy, &cwd, false, None); + + // Build the expected policy text using a raw string for readability. + // Note that the policy includes: + // - the base policy, + // - read-only access to the filesystem, + // - write access to WRITABLE_ROOT_0 (but not its .git or .codex), WRITABLE_ROOT_1, and cwd as WRITABLE_ROOT_2. + let expected_policy = format!( + r#"{MACOS_SEATBELT_BASE_POLICY} +; allow read-only file operations +(allow file-read*) +(allow file-write* +(subpath (param "WRITABLE_ROOT_0")) (require-all (subpath (param "WRITABLE_ROOT_1")) (require-not (subpath (param "WRITABLE_ROOT_1_RO_0"))) (require-not (subpath (param "WRITABLE_ROOT_1_RO_1"))) ) (subpath (param "WRITABLE_ROOT_2")) +) + +; macOS permission profile extensions +(allow ipc-posix-shm-read* (ipc-posix-name-prefix "apple.cfprefs.")) +(allow mach-lookup + (global-name "com.apple.cfprefsd.daemon") + (global-name "com.apple.cfprefsd.agent") + (local-name "com.apple.cfprefsd.agent")) +(allow user-preference-read) +"#, + ); + + assert_eq!(seatbelt_policy_arg(&args), expected_policy); + + let expected_definitions = [ + format!( + "-DWRITABLE_ROOT_0={}", + cwd.canonicalize() + .expect("canonicalize cwd") + .to_string_lossy() + ), + format!( + "-DWRITABLE_ROOT_1={}", + vulnerable_root_canonical.to_string_lossy() + ), + format!( + "-DWRITABLE_ROOT_1_RO_0={}", + dot_git_canonical.to_string_lossy() + ), + format!( + "-DWRITABLE_ROOT_1_RO_1={}", + dot_codex_canonical.to_string_lossy() + ), + format!( + "-DWRITABLE_ROOT_2={}", + empty_root_canonical.to_string_lossy() + ), + ]; + for expected_definition in expected_definitions { + assert!( + args.contains(&expected_definition), + "expected definition arg `{expected_definition}` in {args:#?}" + ); + } + for (key, value) in macos_dir_params() { + let expected_definition = format!("-D{key}={}", value.to_string_lossy()); + assert!( + args.contains(&expected_definition), + "expected definition arg `{expected_definition}` in {args:#?}" + ); + } + + let command_index = args + .iter() + .position(|arg| arg == "--") + .expect("seatbelt args should include command separator"); + assert_eq!(args[command_index + 1..], shell_command); + + // Verify that .codex/config.toml cannot be modified under the generated + // Seatbelt policy. + let config_toml = dot_codex_canonical.join("config.toml"); + let output = Command::new(MACOS_PATH_TO_SEATBELT_EXECUTABLE) + .args(&args) + .current_dir(&cwd) + .output() + .expect("execute seatbelt command"); + assert_eq!( + "sandbox_mode = \"read-only\"\n", + String::from_utf8_lossy(&fs::read(&config_toml).expect("read config.toml")), + "config.toml should contain its original contents because it should not have been modified" + ); + assert!( + !output.status.success(), + "command to write {} should fail under seatbelt", + &config_toml.display() + ); + assert_seatbelt_denied(&output.stderr, &config_toml); + + // Create a similar Seatbelt command that tries to write to a file in + // the .git folder, which should also be blocked. + let pre_commit_hook = dot_git_canonical.join("hooks").join("pre-commit"); + let shell_command_git: Vec = [ + "bash", + "-c", + "echo 'pwned!' > \"$1\"", + "bash", + pre_commit_hook.to_string_lossy().as_ref(), + ] + .iter() + .map(std::string::ToString::to_string) + .collect(); + let write_hooks_file_args = + create_seatbelt_command_args(shell_command_git, &policy, &cwd, false, None); + let output = Command::new(MACOS_PATH_TO_SEATBELT_EXECUTABLE) + .args(&write_hooks_file_args) + .current_dir(&cwd) + .output() + .expect("execute seatbelt command"); + assert!( + !fs::exists(&pre_commit_hook).expect("exists pre-commit hook"), + "{} should not exist because it should not have been created", + pre_commit_hook.display() + ); + assert!( + !output.status.success(), + "command to write {} should fail under seatbelt", + &pre_commit_hook.display() + ); + assert_seatbelt_denied(&output.stderr, &pre_commit_hook); + + // Verify that writing a file to the folder containing .git and .codex is allowed. + let allowed_file = vulnerable_root_canonical.join("allowed.txt"); + let shell_command_allowed: Vec = [ + "bash", + "-c", + "echo 'this is allowed' > \"$1\"", + "bash", + allowed_file.to_string_lossy().as_ref(), + ] + .iter() + .map(std::string::ToString::to_string) + .collect(); + let write_allowed_file_args = + create_seatbelt_command_args(shell_command_allowed, &policy, &cwd, false, None); + let output = Command::new(MACOS_PATH_TO_SEATBELT_EXECUTABLE) + .args(&write_allowed_file_args) + .current_dir(&cwd) + .output() + .expect("execute seatbelt command"); + let stderr = String::from_utf8_lossy(&output.stderr); + if !output.status.success() + && stderr.contains("sandbox-exec: sandbox_apply: Operation not permitted") + { + return; + } + assert!( + output.status.success(), + "command to write {} should succeed under seatbelt", + &allowed_file.display() + ); + assert_eq!( + "this is allowed\n", + String::from_utf8_lossy(&fs::read(&allowed_file).expect("read allowed.txt")), + "{} should contain the written text", + allowed_file.display() + ); +} + +#[test] +fn create_seatbelt_args_with_read_only_git_pointer_file() { + let tmp = TempDir::new().expect("tempdir"); + let worktree_root = tmp.path().join("worktree_root"); + fs::create_dir_all(&worktree_root).expect("create worktree_root"); + let gitdir = worktree_root.join("actual-gitdir"); + fs::create_dir_all(&gitdir).expect("create gitdir"); + let gitdir_config = gitdir.join("config"); + let gitdir_config_contents = "[core]\n"; + fs::write(&gitdir_config, gitdir_config_contents).expect("write gitdir config"); + + let dot_git = worktree_root.join(".git"); + let dot_git_contents = format!("gitdir: {}\n", gitdir.to_string_lossy()); + fs::write(&dot_git, &dot_git_contents).expect("write .git pointer"); + + let cwd = tmp.path().join("cwd"); + fs::create_dir_all(&cwd).expect("create cwd"); + + let policy = SandboxPolicy::WorkspaceWrite { + writable_roots: vec![worktree_root.try_into().expect("worktree_root is absolute")], + read_only_access: Default::default(), + network_access: false, + exclude_tmpdir_env_var: true, + exclude_slash_tmp: true, + }; + + let shell_command: Vec = [ + "bash", + "-c", + "echo 'pwned!' > \"$1\"", + "bash", + dot_git.to_string_lossy().as_ref(), + ] + .iter() + .map(std::string::ToString::to_string) + .collect(); + let args = create_seatbelt_command_args(shell_command, &policy, &cwd, false, None); + + let output = Command::new(MACOS_PATH_TO_SEATBELT_EXECUTABLE) + .args(&args) + .current_dir(&cwd) + .output() + .expect("execute seatbelt command"); + + assert_eq!( + dot_git_contents, + String::from_utf8_lossy(&fs::read(&dot_git).expect("read .git pointer")), + ".git pointer file should not be modified under seatbelt" + ); + assert!( + !output.status.success(), + "command to write {} should fail under seatbelt", + dot_git.display() + ); + assert_seatbelt_denied(&output.stderr, &dot_git); + + let shell_command_gitdir: Vec = [ + "bash", + "-c", + "echo 'pwned!' > \"$1\"", + "bash", + gitdir_config.to_string_lossy().as_ref(), + ] + .iter() + .map(std::string::ToString::to_string) + .collect(); + let gitdir_args = + create_seatbelt_command_args(shell_command_gitdir, &policy, &cwd, false, None); + let output = Command::new(MACOS_PATH_TO_SEATBELT_EXECUTABLE) + .args(&gitdir_args) + .current_dir(&cwd) + .output() + .expect("execute seatbelt command"); + + assert_eq!( + gitdir_config_contents, + String::from_utf8_lossy(&fs::read(&gitdir_config).expect("read gitdir config")), + "gitdir config should contain its original contents because it should not have been modified" + ); + assert!( + !output.status.success(), + "command to write {} should fail under seatbelt", + gitdir_config.display() + ); + assert_seatbelt_denied(&output.stderr, &gitdir_config); +} + +#[test] +fn create_seatbelt_args_for_cwd_as_git_repo() { + // Create a temporary workspace with two writable roots: one containing + // top-level .git and .codex directories and one without them. + let tmp = TempDir::new().expect("tempdir"); + let PopulatedTmp { + vulnerable_root, + vulnerable_root_canonical, + dot_git_canonical, + dot_codex_canonical, + .. + } = populate_tmpdir(tmp.path()); + + // Build a policy that does not specify any writable_roots, but does + // use the default ones (cwd and TMPDIR) and verifies the `.git` and + // `.codex` checks are done properly for cwd. + let policy = SandboxPolicy::WorkspaceWrite { + writable_roots: vec![], + read_only_access: Default::default(), + network_access: false, + exclude_tmpdir_env_var: false, + exclude_slash_tmp: false, + }; + + let shell_command: Vec = [ + "bash", + "-c", + "echo 'sandbox_mode = \"danger-full-access\"' > \"$1\"", + "bash", + dot_codex_canonical + .join("config.toml") + .to_string_lossy() + .as_ref(), + ] + .iter() + .map(std::string::ToString::to_string) + .collect(); + let args = create_seatbelt_command_args( + shell_command.clone(), + &policy, + vulnerable_root.as_path(), + false, + None, + ); + + let tmpdir_env_var = std::env::var("TMPDIR") + .ok() + .map(PathBuf::from) + .and_then(|p| p.canonicalize().ok()) + .map(|p| p.to_string_lossy().to_string()); + + let tempdir_policy_entry = if tmpdir_env_var.is_some() { + r#" (subpath (param "WRITABLE_ROOT_2"))"# + } else { + "" + }; + + // Build the expected policy text using a raw string for readability. + // Note that the policy includes: + // - the base policy, + // - read-only access to the filesystem, + // - write access to WRITABLE_ROOT_0 (but not its .git or .codex), WRITABLE_ROOT_1, and cwd as WRITABLE_ROOT_2. + let expected_policy = format!( + r#"{MACOS_SEATBELT_BASE_POLICY} +; allow read-only file operations +(allow file-read*) +(allow file-write* +(require-all (subpath (param "WRITABLE_ROOT_0")) (require-not (subpath (param "WRITABLE_ROOT_0_RO_0"))) (require-not (subpath (param "WRITABLE_ROOT_0_RO_1"))) ) (subpath (param "WRITABLE_ROOT_1")){tempdir_policy_entry} +) + +; macOS permission profile extensions +(allow ipc-posix-shm-read* (ipc-posix-name-prefix "apple.cfprefs.")) +(allow mach-lookup + (global-name "com.apple.cfprefsd.daemon") + (global-name "com.apple.cfprefsd.agent") + (local-name "com.apple.cfprefsd.agent")) +(allow user-preference-read) +"#, + ); + + let mut expected_args = vec![ + "-p".to_string(), + expected_policy, + format!( + "-DWRITABLE_ROOT_0={}", + vulnerable_root_canonical.to_string_lossy() + ), + format!( + "-DWRITABLE_ROOT_0_RO_0={}", + dot_git_canonical.to_string_lossy() + ), + format!( + "-DWRITABLE_ROOT_0_RO_1={}", + dot_codex_canonical.to_string_lossy() + ), + format!( + "-DWRITABLE_ROOT_1={}", + PathBuf::from("/tmp") + .canonicalize() + .expect("canonicalize /tmp") + .to_string_lossy() + ), + ]; + + if let Some(p) = tmpdir_env_var { + expected_args.push(format!("-DWRITABLE_ROOT_2={p}")); + } + + expected_args.extend( + macos_dir_params() + .into_iter() + .map(|(key, value)| format!("-D{key}={value}", value = value.to_string_lossy())), + ); + + expected_args.push("--".to_string()); + expected_args.extend(shell_command); + + assert_eq!(expected_args, args); +} + +struct PopulatedTmp { + /// Path containing a .git and .codex subfolder. + /// For the purposes of this test, we consider this a "vulnerable" root + /// because a bad actor could write to .git/hooks/pre-commit so an + /// unsuspecting user would run code as privileged the next time they + /// ran `git commit` themselves, or modified .codex/config.toml to + /// contain `sandbox_mode = "danger-full-access"` so the agent would + /// have full privileges the next time it ran in that repo. + vulnerable_root: PathBuf, + vulnerable_root_canonical: PathBuf, + dot_git_canonical: PathBuf, + dot_codex_canonical: PathBuf, + + /// Path without .git or .codex subfolders. + empty_root: PathBuf, + /// Canonicalized version of `empty_root`. + empty_root_canonical: PathBuf, +} + +fn populate_tmpdir(tmp: &Path) -> PopulatedTmp { + let vulnerable_root = tmp.join("vulnerable_root"); + fs::create_dir_all(&vulnerable_root).expect("create vulnerable_root"); + + // TODO(mbolin): Should also support the case where `.git` is a file + // with a gitdir: ... line. + Command::new("git") + .arg("init") + .arg(".") + .current_dir(&vulnerable_root) + .output() + .expect("git init ."); + + fs::create_dir_all(vulnerable_root.join(".codex")).expect("create .codex"); + fs::write( + vulnerable_root.join(".codex").join("config.toml"), + "sandbox_mode = \"read-only\"\n", + ) + .expect("write .codex/config.toml"); + + let empty_root = tmp.join("empty_root"); + fs::create_dir_all(&empty_root).expect("create empty_root"); + + // Ensure we have canonical paths for -D parameter matching. + let vulnerable_root_canonical = vulnerable_root + .canonicalize() + .expect("canonicalize vulnerable_root"); + let dot_git_canonical = vulnerable_root_canonical.join(".git"); + let dot_codex_canonical = vulnerable_root_canonical.join(".codex"); + let empty_root_canonical = empty_root.canonicalize().expect("canonicalize empty_root"); + PopulatedTmp { + vulnerable_root, + vulnerable_root_canonical, + dot_git_canonical, + dot_codex_canonical, + empty_root, + empty_root_canonical, + } +} diff --git a/codex-rs/sandbox/src/spawn.rs b/codex-rs/sandbox/src/spawn.rs new file mode 100644 index 0000000000..575a2f777c --- /dev/null +++ b/codex-rs/sandbox/src/spawn.rs @@ -0,0 +1,125 @@ +use codex_network_proxy::NetworkProxy; +use std::collections::HashMap; +use std::path::PathBuf; +use std::process::Stdio; +use tokio::process::Child; +use tokio::process::Command; +use tracing::trace; + +use codex_protocol::permissions::NetworkSandboxPolicy; + +/// Experimental environment variable that will be set to some non-empty value +/// if both of the following are true: +/// +/// 1. The process was spawned by Codex as part of a shell tool call. +/// 2. NetworkSandboxPolicy is restricted for the tool call. +/// +/// We may try to have just one environment variable for all sandboxing +/// attributes, so this may change in the future. +pub const CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR: &str = "CODEX_SANDBOX_NETWORK_DISABLED"; + +/// Should be set when the process is spawned under a sandbox. Currently, the +/// value is "seatbelt" for macOS, but it may change in the future to +/// accommodate sandboxing configuration and other sandboxing mechanisms. +pub const CODEX_SANDBOX_ENV_VAR: &str = "CODEX_SANDBOX"; + +#[derive(Debug, Clone, Copy)] +pub enum StdioPolicy { + RedirectForShellTool, + Inherit, +} + +/// Spawns the appropriate child process for the ExecParams and SandboxPolicy, +/// ensuring the args and environment variables used to create the `Command` +/// (and `Child`) honor the configuration. +/// +/// For now, we take `NetworkSandboxPolicy` as a parameter to spawn_child() +/// because we need to determine whether to set the +/// `CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR` environment variable. +pub(crate) struct SpawnChildRequest<'a> { + pub program: PathBuf, + pub args: Vec, + pub arg0: Option<&'a str>, + pub cwd: PathBuf, + pub network_sandbox_policy: NetworkSandboxPolicy, + pub network: Option<&'a NetworkProxy>, + pub stdio_policy: StdioPolicy, + pub env: HashMap, +} + +pub(crate) async fn spawn_child_async(request: SpawnChildRequest<'_>) -> std::io::Result { + let SpawnChildRequest { + program, + args, + arg0, + cwd, + network_sandbox_policy, + network, + stdio_policy, + mut env, + } = request; + + trace!( + "spawn_child_async: {program:?} {args:?} {arg0:?} {cwd:?} {network_sandbox_policy:?} {stdio_policy:?} {env:?}" + ); + + let mut cmd = Command::new(&program); + #[cfg(unix)] + cmd.arg0(arg0.map_or_else(|| program.to_string_lossy().to_string(), String::from)); + cmd.args(args); + cmd.current_dir(cwd); + if let Some(network) = network { + network.apply_to_env(&mut env); + } + cmd.env_clear(); + cmd.envs(env); + + if !network_sandbox_policy.is_enabled() { + cmd.env(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR, "1"); + } + + // If this Codex process dies (including being killed via SIGKILL), we want + // any child processes that were spawned as part of a `"shell"` tool call + // to also be terminated. + + #[cfg(unix)] + unsafe { + let detach_from_tty = matches!(stdio_policy, StdioPolicy::RedirectForShellTool); + #[cfg(target_os = "linux")] + let parent_pid = libc::getpid(); + cmd.pre_exec(move || { + if detach_from_tty { + codex_utils_pty::process_group::detach_from_tty()?; + } + + // This relies on prctl(2), so it only works on Linux. + #[cfg(target_os = "linux")] + { + // This prctl call effectively requests, "deliver SIGTERM when my + // current parent dies." + codex_utils_pty::process_group::set_parent_death_signal(parent_pid)?; + } + Ok(()) + }); + } + + match stdio_policy { + StdioPolicy::RedirectForShellTool => { + // Do not create a file descriptor for stdin because otherwise some + // commands may hang forever waiting for input. For example, ripgrep has + // a heuristic where it may try to read from stdin as explained here: + // https://github.com/BurntSushi/ripgrep/blob/e2362d4d5185d02fa857bf381e7bd52e66fafc73/crates/core/flags/hiargs.rs#L1101-L1103 + cmd.stdin(Stdio::null()); + + cmd.stdout(Stdio::piped()).stderr(Stdio::piped()); + } + StdioPolicy::Inherit => { + // Inherit stdin, stdout, and stderr from the parent process. + cmd.stdin(Stdio::inherit()) + .stdout(Stdio::inherit()) + .stderr(Stdio::inherit()); + } + } + + cmd.kill_on_drop(true).spawn() +} diff --git a/codex-rs/sandbox/src/text_encoding.rs b/codex-rs/sandbox/src/text_encoding.rs new file mode 100644 index 0000000000..b70d8af54c --- /dev/null +++ b/codex-rs/sandbox/src/text_encoding.rs @@ -0,0 +1,121 @@ +//! Text encoding detection and conversion utilities for shell output. +//! +//! Windows users frequently run into code pages such as CP1251 or CP866 when invoking commands +//! through VS Code. Those bytes show up as invalid UTF-8 and used to be replaced with the standard +//! Unicode replacement character. We now lean on `chardetng` and `encoding_rs` so we can +//! automatically detect and decode the vast majority of legacy encodings before falling back to +//! lossy UTF-8 decoding. + +use chardetng::EncodingDetector; +use encoding_rs::Encoding; +use encoding_rs::IBM866; +use encoding_rs::WINDOWS_1252; + +/// Attempts to convert arbitrary bytes to UTF-8 with best-effort encoding detection. +pub fn bytes_to_string_smart(bytes: &[u8]) -> String { + if bytes.is_empty() { + return String::new(); + } + + if let Ok(utf8_str) = std::str::from_utf8(bytes) { + return utf8_str.to_owned(); + } + + let encoding = detect_encoding(bytes); + decode_bytes(bytes, encoding) +} + +// Windows-1252 reassigns a handful of 0x80-0x9F slots to smart punctuation (curly quotes, dashes, +// ™). CP866 uses those *same byte values* for uppercase Cyrillic letters. When chardetng sees shell +// snippets that mix these bytes with ASCII it sometimes guesses IBM866, so “smart quotes” render as +// Cyrillic garbage (“УФЦ”) in VS Code. However, CP866 uppercase tokens are perfectly valid output +// (e.g., `ПРИ test`) so we cannot flip every 0x80-0x9F byte to Windows-1252 either. The compromise +// is to only coerce IBM866 to Windows-1252 when (a) the high bytes are exclusively the punctuation +// values listed below and (b) we spot adjacent ASCII. This targets the real failure case without +// clobbering legitimate Cyrillic text. If another code page has a similar collision, introduce a +// dedicated allowlist (like this one) plus unit tests that capture the actual shell output we want +// to preserve. Windows-1252 byte values for smart punctuation. +const WINDOWS_1252_PUNCT_BYTES: [u8; 8] = [ + 0x91, // ‘ (left single quotation mark) + 0x92, // ’ (right single quotation mark) + 0x93, // “ (left double quotation mark) + 0x94, // ” (right double quotation mark) + 0x95, // • (bullet) + 0x96, // – (en dash) + 0x97, // — (em dash) + 0x99, // ™ (trade mark sign) +]; + +fn detect_encoding(bytes: &[u8]) -> &'static Encoding { + let mut detector = EncodingDetector::new(); + detector.feed(bytes, true); + let (encoding, _is_confident) = detector.guess_assess(None, true); + + // chardetng occasionally reports IBM866 for short strings that only contain Windows-1252 “smart + // punctuation” bytes (0x80-0x9F) because that range maps to Cyrillic letters in IBM866. When + // those bytes show up alongside an ASCII word (typical shell output: `"“`test), we know the + // intent was likely CP1252 quotes/dashes. Prefer WINDOWS_1252 in that specific situation so we + // render the characters users expect instead of Cyrillic junk. References: + // - Windows-1252 reserving 0x80-0x9F for curly quotes/dashes: + // https://en.wikipedia.org/wiki/Windows-1252 + // - CP866 mapping 0x93/0x94/0x96 to Cyrillic letters, so the same bytes show up as “УФЦ” when + // mis-decoded: https://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/PC/CP866.TXT + if encoding == IBM866 && looks_like_windows_1252_punctuation(bytes) { + return WINDOWS_1252; + } + + encoding +} + +fn decode_bytes(bytes: &[u8], encoding: &'static Encoding) -> String { + let (decoded, _, had_errors) = encoding.decode(bytes); + + if had_errors { + return String::from_utf8_lossy(bytes).into_owned(); + } + + decoded.into_owned() +} + +/// Detect whether the byte stream looks like Windows-1252 “smart punctuation” wrapped around +/// otherwise-ASCII text. +/// +/// Context: IBM866 and Windows-1252 share the 0x80-0x9F slot range. In IBM866 these bytes decode to +/// Cyrillic letters, whereas Windows-1252 maps them to curly quotes and dashes. chardetng can guess +/// IBM866 for short snippets that only contain those bytes, which turns shell output such as +/// `“test”` into unreadable Cyrillic. To avoid that, we treat inputs comprising a handful of bytes +/// from the problematic range plus ASCII letters as CP1252 punctuation. We deliberately do *not* +/// cap how many of those punctuation bytes we accept: VS Code frequently prints several quoted +/// phrases (e.g., `"foo" – "bar"`), and truncating the count would once again mis-decode those as +/// Cyrillic. If we discover additional encodings with overlapping byte ranges, prefer adding +/// encoding-specific byte allowlists like `WINDOWS_1252_PUNCT` and tests that exercise real-world +/// shell snippets. +fn looks_like_windows_1252_punctuation(bytes: &[u8]) -> bool { + let mut saw_extended_punctuation = false; + let mut saw_ascii_word = false; + + for &byte in bytes { + if byte >= 0xA0 { + return false; + } + if (0x80..=0x9F).contains(&byte) { + if !is_windows_1252_punct(byte) { + return false; + } + saw_extended_punctuation = true; + } + if byte.is_ascii_alphabetic() { + saw_ascii_word = true; + } + } + + saw_extended_punctuation && saw_ascii_word +} + +fn is_windows_1252_punct(byte: u8) -> bool { + WINDOWS_1252_PUNCT_BYTES.contains(&byte) +} + +#[cfg(test)] +#[path = "text_encoding_tests.rs"] +mod tests; diff --git a/codex-rs/sandbox/src/text_encoding_tests.rs b/codex-rs/sandbox/src/text_encoding_tests.rs new file mode 100644 index 0000000000..6368f38be4 --- /dev/null +++ b/codex-rs/sandbox/src/text_encoding_tests.rs @@ -0,0 +1,340 @@ +use super::*; +use encoding_rs::BIG5; +use encoding_rs::EUC_KR; +use encoding_rs::GBK; +use encoding_rs::ISO_8859_2; +use encoding_rs::ISO_8859_3; +use encoding_rs::ISO_8859_4; +use encoding_rs::ISO_8859_5; +use encoding_rs::ISO_8859_6; +use encoding_rs::ISO_8859_7; +use encoding_rs::ISO_8859_8; +use encoding_rs::ISO_8859_10; +use encoding_rs::ISO_8859_13; +use encoding_rs::SHIFT_JIS; +use encoding_rs::WINDOWS_874; +use encoding_rs::WINDOWS_1250; +use encoding_rs::WINDOWS_1251; +use encoding_rs::WINDOWS_1253; +use encoding_rs::WINDOWS_1254; +use encoding_rs::WINDOWS_1255; +use encoding_rs::WINDOWS_1256; +use encoding_rs::WINDOWS_1257; +use encoding_rs::WINDOWS_1258; +use pretty_assertions::assert_eq; + +#[test] +fn test_utf8_passthrough() { + // Fast path: when UTF-8 is valid we should avoid copies and return as-is. + let utf8_text = "Hello, мир! 世界"; + let bytes = utf8_text.as_bytes(); + assert_eq!(bytes_to_string_smart(bytes), utf8_text); +} + +#[test] +fn test_cp1251_russian_text() { + // Cyrillic text emitted by PowerShell/WSL in CP1251 should decode cleanly. + let bytes = b"\xEF\xF0\xE8\xEC\xE5\xF0"; // "пример" encoded with Windows-1251 + assert_eq!(bytes_to_string_smart(bytes), "пример"); +} + +#[test] +fn test_cp1251_privet_word() { + // Regression: CP1251 words like "Привет" must not be mis-identified as Windows-1252. + let bytes = b"\xCF\xF0\xE8\xE2\xE5\xF2"; // "Привет" encoded with Windows-1251 + assert_eq!(bytes_to_string_smart(bytes), "Привет"); +} + +#[test] +fn test_koi8_r_privet_word() { + // KOI8-R output should decode to the original Cyrillic as well. + let bytes = b"\xF0\xD2\xC9\xD7\xC5\xD4"; // "Привет" encoded with KOI8-R + assert_eq!(bytes_to_string_smart(bytes), "Привет"); +} + +#[test] +fn test_cp866_russian_text() { + // Legacy consoles (cmd.exe) commonly emit CP866 bytes for Cyrillic content. + let bytes = b"\xAF\xE0\xA8\xAC\xA5\xE0"; // "пример" encoded with CP866 + assert_eq!(bytes_to_string_smart(bytes), "пример"); +} + +#[test] +fn test_cp866_uppercase_text() { + // Ensure the IBM866 heuristic still returns IBM866 for uppercase-only words. + let bytes = b"\x8F\x90\x88"; // "ПРИ" encoded with CP866 uppercase letters + assert_eq!(bytes_to_string_smart(bytes), "ПРИ"); +} + +#[test] +fn test_cp866_uppercase_followed_by_ascii() { + // Regression test: uppercase CP866 tokens next to ASCII text should not be treated as + // CP1252. + let bytes = b"\x8F\x90\x88 test"; // "ПРИ test" encoded with CP866 uppercase letters followed by ASCII + assert_eq!(bytes_to_string_smart(bytes), "ПРИ test"); +} + +#[test] +fn test_windows_1252_quotes() { + // Smart detection should map Windows-1252 punctuation into proper Unicode. + let bytes = b"\x93\x94test"; + assert_eq!(bytes_to_string_smart(bytes), "\u{201C}\u{201D}test"); +} + +#[test] +fn test_windows_1252_multiple_quotes() { + // Longer snippets of punctuation (e.g., “foo” – “bar”) should still flip to CP1252. + let bytes = b"\x93foo\x94 \x96 \x93bar\x94"; + assert_eq!( + bytes_to_string_smart(bytes), + "\u{201C}foo\u{201D} \u{2013} \u{201C}bar\u{201D}" + ); +} + +#[test] +fn test_windows_1252_privet_gibberish_is_preserved() { + // Windows-1252 cannot encode Cyrillic; if the input literally contains "ПÑ..." we should not "fix" it. + let bytes = "Привет".as_bytes(); + assert_eq!(bytes_to_string_smart(bytes), "Привет"); +} + +#[test] +fn test_iso8859_1_latin_text() { + // ISO-8859-1 (code page 28591) is the Latin segment used by LatArCyrHeb. + // encoding_rs unifies ISO-8859-1 with Windows-1252, so reuse that constant here. + let (encoded, _, had_errors) = WINDOWS_1252.encode("Hello"); + assert!(!had_errors, "failed to encode Latin sample"); + assert_eq!(bytes_to_string_smart(encoded.as_ref()), "Hello"); +} + +#[test] +fn test_iso8859_2_central_european_text() { + // ISO-8859-2 (code page 28592) covers additional Central European glyphs. + let (encoded, _, had_errors) = ISO_8859_2.encode("Příliš žluťoučký kůň"); + assert!(!had_errors, "failed to encode ISO-8859-2 sample"); + assert_eq!( + bytes_to_string_smart(encoded.as_ref()), + "Příliš žluťoučký kůň" + ); +} + +#[test] +fn test_iso8859_3_south_europe_text() { + // ISO-8859-3 (code page 28593) adds support for Maltese/Esperanto letters. + // chardetng rarely distinguishes ISO-8859-3 from neighboring Latin code pages, so we rely on + // an ASCII-only sample to ensure round-tripping still succeeds. + let (encoded, _, had_errors) = ISO_8859_3.encode("Esperanto and Maltese"); + assert!(!had_errors, "failed to encode ISO-8859-3 sample"); + assert_eq!( + bytes_to_string_smart(encoded.as_ref()), + "Esperanto and Maltese" + ); +} + +#[test] +fn test_iso8859_4_baltic_text() { + // ISO-8859-4 (code page 28594) targets the Baltic/Nordic repertoire. + let sample = "Šis ir rakstzīmju kodēšanas tests. Dažās valodās, kurās tiek \ + izmantotas latīņu valodas burti, lēmuma pieņemšanai mums ir nepieciešams \ + vairāk ieguldījuma."; + let (encoded, _, had_errors) = ISO_8859_4.encode(sample); + assert!(!had_errors, "failed to encode ISO-8859-4 sample"); + assert_eq!(bytes_to_string_smart(encoded.as_ref()), sample); +} + +#[test] +fn test_iso8859_5_cyrillic_text() { + // ISO-8859-5 (code page 28595) covers the Cyrillic portion. + let (encoded, _, had_errors) = ISO_8859_5.encode("Привет"); + assert!(!had_errors, "failed to encode Cyrillic sample"); + assert_eq!(bytes_to_string_smart(encoded.as_ref()), "Привет"); +} + +#[test] +fn test_iso8859_6_arabic_text() { + // ISO-8859-6 (code page 28596) covers the Arabic glyphs. + let (encoded, _, had_errors) = ISO_8859_6.encode("مرحبا"); + assert!(!had_errors, "failed to encode Arabic sample"); + assert_eq!(bytes_to_string_smart(encoded.as_ref()), "مرحبا"); +} + +#[test] +fn test_iso8859_7_greek_text() { + // ISO-8859-7 (code page 28597) is used for Greek locales. + let (encoded, _, had_errors) = ISO_8859_7.encode("Καλημέρα"); + assert!(!had_errors, "failed to encode ISO-8859-7 sample"); + assert_eq!(bytes_to_string_smart(encoded.as_ref()), "Καλημέρα"); +} + +#[test] +fn test_iso8859_8_hebrew_text() { + // ISO-8859-8 (code page 28598) covers the Hebrew glyphs. + let (encoded, _, had_errors) = ISO_8859_8.encode("שלום"); + assert!(!had_errors, "failed to encode Hebrew sample"); + assert_eq!(bytes_to_string_smart(encoded.as_ref()), "שלום"); +} + +#[test] +fn test_iso8859_9_turkish_text() { + // ISO-8859-9 (code page 28599) mirrors Latin-1 but inserts Turkish letters. + // encoding_rs exposes the equivalent Windows-1254 mapping. + let (encoded, _, had_errors) = WINDOWS_1254.encode("İstanbul"); + assert!(!had_errors, "failed to encode ISO-8859-9 sample"); + assert_eq!(bytes_to_string_smart(encoded.as_ref()), "İstanbul"); +} + +#[test] +fn test_iso8859_10_nordic_text() { + // ISO-8859-10 (code page 28600) adds additional Nordic letters. + let sample = "Þetta er prófun fyrir Ægir og Øystein."; + let (encoded, _, had_errors) = ISO_8859_10.encode(sample); + assert!(!had_errors, "failed to encode ISO-8859-10 sample"); + assert_eq!(bytes_to_string_smart(encoded.as_ref()), sample); +} + +#[test] +fn test_iso8859_11_thai_text() { + // ISO-8859-11 (code page 28601) mirrors TIS-620 / Windows-874 for Thai. + let sample = "ภาษาไทยสำหรับการทดสอบ ISO-8859-11"; + // encoding_rs exposes the equivalent Windows-874 encoding, so use that constant. + let (encoded, _, had_errors) = WINDOWS_874.encode(sample); + assert!(!had_errors, "failed to encode ISO-8859-11 sample"); + assert_eq!(bytes_to_string_smart(encoded.as_ref()), sample); +} + +// ISO-8859-12 was never standardized, and encodings 14–16 cannot be distinguished reliably +// without the heuristics we removed (chardetng generally reports neighboring Latin pages), so +// we intentionally omit coverage for those slots until the detector can identify them. + +#[test] +fn test_iso8859_13_baltic_text() { + // ISO-8859-13 (code page 28603) is common across Baltic languages. + let (encoded, _, had_errors) = ISO_8859_13.encode("Sveiki"); + assert!(!had_errors, "failed to encode ISO-8859-13 sample"); + assert_eq!(bytes_to_string_smart(encoded.as_ref()), "Sveiki"); +} + +#[test] +fn test_windows_1250_central_european_text() { + let (encoded, _, had_errors) = WINDOWS_1250.encode("Příliš žluťoučký kůň"); + assert!(!had_errors, "failed to encode Central European sample"); + assert_eq!( + bytes_to_string_smart(encoded.as_ref()), + "Příliš žluťoučký kůň" + ); +} + +#[test] +fn test_windows_1251_encoded_text() { + let (encoded, _, had_errors) = WINDOWS_1251.encode("Привет из Windows-1251"); + assert!(!had_errors, "failed to encode Windows-1251 sample"); + assert_eq!( + bytes_to_string_smart(encoded.as_ref()), + "Привет из Windows-1251" + ); +} + +#[test] +fn test_windows_1253_greek_text() { + let (encoded, _, had_errors) = WINDOWS_1253.encode("Γειά σου"); + assert!(!had_errors, "failed to encode Greek sample"); + assert_eq!(bytes_to_string_smart(encoded.as_ref()), "Γειά σου"); +} + +#[test] +fn test_windows_1254_turkish_text() { + let (encoded, _, had_errors) = WINDOWS_1254.encode("İstanbul"); + assert!(!had_errors, "failed to encode Turkish sample"); + assert_eq!(bytes_to_string_smart(encoded.as_ref()), "İstanbul"); +} + +#[test] +fn test_windows_1255_hebrew_text() { + let (encoded, _, had_errors) = WINDOWS_1255.encode("שלום"); + assert!(!had_errors, "failed to encode Windows-1255 Hebrew sample"); + assert_eq!(bytes_to_string_smart(encoded.as_ref()), "שלום"); +} + +#[test] +fn test_windows_1256_arabic_text() { + let (encoded, _, had_errors) = WINDOWS_1256.encode("مرحبا"); + assert!(!had_errors, "failed to encode Windows-1256 Arabic sample"); + assert_eq!(bytes_to_string_smart(encoded.as_ref()), "مرحبا"); +} + +#[test] +fn test_windows_1257_baltic_text() { + let (encoded, _, had_errors) = WINDOWS_1257.encode("Pērkons"); + assert!(!had_errors, "failed to encode Baltic sample"); + assert_eq!(bytes_to_string_smart(encoded.as_ref()), "Pērkons"); +} + +#[test] +fn test_windows_1258_vietnamese_text() { + let (encoded, _, had_errors) = WINDOWS_1258.encode("Xin chào"); + assert!(!had_errors, "failed to encode Vietnamese sample"); + assert_eq!(bytes_to_string_smart(encoded.as_ref()), "Xin chào"); +} + +#[test] +fn test_windows_874_thai_text() { + let (encoded, _, had_errors) = WINDOWS_874.encode("สวัสดีครับ นี่คือการทดสอบภาษาไทย"); + assert!(!had_errors, "failed to encode Thai sample"); + assert_eq!( + bytes_to_string_smart(encoded.as_ref()), + "สวัสดีครับ นี่คือการทดสอบภาษาไทย" + ); +} + +#[test] +fn test_windows_932_shift_jis_text() { + let (encoded, _, had_errors) = SHIFT_JIS.encode("こんにちは"); + assert!(!had_errors, "failed to encode Shift-JIS sample"); + assert_eq!(bytes_to_string_smart(encoded.as_ref()), "こんにちは"); +} + +#[test] +fn test_windows_936_gbk_text() { + let (encoded, _, had_errors) = GBK.encode("你好,世界,这是一个测试"); + assert!(!had_errors, "failed to encode GBK sample"); + assert_eq!( + bytes_to_string_smart(encoded.as_ref()), + "你好,世界,这是一个测试" + ); +} + +#[test] +fn test_windows_949_korean_text() { + let (encoded, _, had_errors) = EUC_KR.encode("안녕하세요"); + assert!(!had_errors, "failed to encode Korean sample"); + assert_eq!(bytes_to_string_smart(encoded.as_ref()), "안녕하세요"); +} + +#[test] +fn test_windows_950_big5_text() { + let (encoded, _, had_errors) = BIG5.encode("繁體"); + assert!(!had_errors, "failed to encode Big5 sample"); + assert_eq!(bytes_to_string_smart(encoded.as_ref()), "繁體"); +} + +#[test] +fn test_latin1_cafe() { + // Latin-1 bytes remain common in Western-European locales; decode them directly. + let bytes = b"caf\xE9"; // codespell:ignore caf + assert_eq!(bytes_to_string_smart(bytes), "café"); +} + +#[test] +fn test_preserves_ansi_sequences() { + // ANSI escape sequences should survive regardless of the detected encoding. + let bytes = b"\x1b[31mred\x1b[0m"; + assert_eq!(bytes_to_string_smart(bytes), "\x1b[31mred\x1b[0m"); +} + +#[test] +fn test_fallback_to_lossy() { + // Completely invalid sequences fall back to the old lossy behavior. + let invalid_bytes = [0xFF, 0xFE, 0xFD]; + let result = bytes_to_string_smart(&invalid_bytes); + assert_eq!(result, String::from_utf8_lossy(&invalid_bytes)); +} diff --git a/codex-rs/sandbox/src/windows_sandbox.rs b/codex-rs/sandbox/src/windows_sandbox.rs new file mode 100644 index 0000000000..0143589186 --- /dev/null +++ b/codex-rs/sandbox/src/windows_sandbox.rs @@ -0,0 +1,432 @@ +use crate::protocol::SandboxPolicy; +use codex_features::Feature; +use codex_features::Features; +use codex_features::FeaturesToml; +use codex_otel::sanitize_metric_tag_value; +use codex_protocol::config_types::WindowsSandboxLevel; +use std::collections::BTreeMap; +use std::collections::HashMap; +use std::path::Path; +use std::path::PathBuf; +use std::time::Instant; + +/// Kill switch for the elevated sandbox NUX on Windows. +/// +/// When false, revert to the previous sandbox NUX, which only +/// prompts users to enable the legacy sandbox feature. +pub const ELEVATED_SANDBOX_NUX_ENABLED: bool = true; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WindowsSandboxMode { + Elevated, + Unelevated, +} + +pub trait WindowsSandboxLevelExt { + fn from_mode_and_features( + windows_sandbox_mode: Option, + features: &Features, + ) -> WindowsSandboxLevel; + fn from_features(features: &Features) -> WindowsSandboxLevel; +} + +impl WindowsSandboxLevelExt for WindowsSandboxLevel { + fn from_mode_and_features( + windows_sandbox_mode: Option, + features: &Features, + ) -> WindowsSandboxLevel { + match windows_sandbox_mode { + Some(WindowsSandboxMode::Elevated) => WindowsSandboxLevel::Elevated, + Some(WindowsSandboxMode::Unelevated) => WindowsSandboxLevel::RestrictedToken, + None => Self::from_features(features), + } + } + + fn from_features(features: &Features) -> WindowsSandboxLevel { + if features.enabled(Feature::WindowsSandboxElevated) { + return WindowsSandboxLevel::Elevated; + } + if features.enabled(Feature::WindowsSandbox) { + WindowsSandboxLevel::RestrictedToken + } else { + WindowsSandboxLevel::Disabled + } + } +} + +pub fn resolve_windows_sandbox_mode( + profile_mode: Option, + profile_features: Option<&FeaturesToml>, + cfg_mode: Option, + cfg_features: Option<&FeaturesToml>, +) -> Option { + if let Some(mode) = legacy_windows_sandbox_mode(profile_features) { + return Some(mode); + } + if legacy_windows_sandbox_keys_present(profile_features) { + return None; + } + + profile_mode + .or(cfg_mode) + .or_else(|| legacy_windows_sandbox_mode(cfg_features)) +} + +pub fn resolve_windows_sandbox_private_desktop( + profile_private_desktop: Option, + cfg_private_desktop: Option, +) -> bool { + profile_private_desktop + .or(cfg_private_desktop) + .unwrap_or(true) +} + +fn legacy_windows_sandbox_keys_present(features: Option<&FeaturesToml>) -> bool { + let Some(entries) = features.map(|features| &features.entries) else { + return false; + }; + entries.contains_key(Feature::WindowsSandboxElevated.key()) + || entries.contains_key(Feature::WindowsSandbox.key()) + || entries.contains_key("enable_experimental_windows_sandbox") +} + +pub fn legacy_windows_sandbox_mode(features: Option<&FeaturesToml>) -> Option { + let entries = features.map(|features| &features.entries)?; + legacy_windows_sandbox_mode_from_entries(entries) +} + +pub fn legacy_windows_sandbox_mode_from_entries( + entries: &BTreeMap, +) -> Option { + if entries + .get(Feature::WindowsSandboxElevated.key()) + .copied() + .unwrap_or(false) + { + return Some(WindowsSandboxMode::Elevated); + } + if entries + .get(Feature::WindowsSandbox.key()) + .copied() + .unwrap_or(false) + || entries + .get("enable_experimental_windows_sandbox") + .copied() + .unwrap_or(false) + { + Some(WindowsSandboxMode::Unelevated) + } else { + None + } +} + +#[cfg(target_os = "windows")] +pub fn sandbox_setup_is_complete(codex_home: &Path) -> bool { + codex_windows_sandbox::sandbox_setup_is_complete(codex_home) +} + +#[cfg(not(target_os = "windows"))] +pub fn sandbox_setup_is_complete(_codex_home: &Path) -> bool { + false +} + +#[cfg(target_os = "windows")] +pub fn elevated_setup_failure_details(err: &anyhow::Error) -> Option<(String, String)> { + let failure = codex_windows_sandbox::extract_setup_failure(err)?; + let code = failure.code.as_str().to_string(); + let message = codex_windows_sandbox::sanitize_setup_metric_tag_value(&failure.message); + Some((code, message)) +} + +#[cfg(not(target_os = "windows"))] +pub fn elevated_setup_failure_details(_err: &anyhow::Error) -> Option<(String, String)> { + None +} + +#[cfg(target_os = "windows")] +pub fn elevated_setup_failure_metric_name(err: &anyhow::Error) -> &'static str { + if codex_windows_sandbox::extract_setup_failure(err).is_some_and(|failure| { + matches!( + failure.code, + codex_windows_sandbox::SetupErrorCode::OrchestratorHelperLaunchCanceled + ) + }) { + "codex.windows_sandbox.elevated_setup_canceled" + } else { + "codex.windows_sandbox.elevated_setup_failure" + } +} + +#[cfg(not(target_os = "windows"))] +pub fn elevated_setup_failure_metric_name(_err: &anyhow::Error) -> &'static str { + panic!("elevated_setup_failure_metric_name is only supported on Windows") +} + +#[cfg(target_os = "windows")] +pub fn run_elevated_setup( + policy: &SandboxPolicy, + policy_cwd: &Path, + command_cwd: &Path, + env_map: &HashMap, + codex_home: &Path, +) -> anyhow::Result<()> { + codex_windows_sandbox::run_elevated_setup( + policy, + policy_cwd, + command_cwd, + env_map, + codex_home, + /*read_roots_override*/ None, + /*write_roots_override*/ None, + ) +} + +#[cfg(not(target_os = "windows"))] +pub fn run_elevated_setup( + _policy: &SandboxPolicy, + _policy_cwd: &Path, + _command_cwd: &Path, + _env_map: &HashMap, + _codex_home: &Path, +) -> anyhow::Result<()> { + anyhow::bail!("elevated Windows sandbox setup is only supported on Windows") +} + +#[cfg(target_os = "windows")] +pub fn run_legacy_setup_preflight( + policy: &SandboxPolicy, + policy_cwd: &Path, + command_cwd: &Path, + env_map: &HashMap, + codex_home: &Path, +) -> anyhow::Result<()> { + codex_windows_sandbox::run_windows_sandbox_legacy_preflight( + policy, + policy_cwd, + codex_home, + command_cwd, + env_map, + ) +} + +#[cfg(target_os = "windows")] +pub fn run_setup_refresh_with_extra_read_roots( + policy: &SandboxPolicy, + policy_cwd: &Path, + command_cwd: &Path, + env_map: &HashMap, + codex_home: &Path, + extra_read_roots: Vec, +) -> anyhow::Result<()> { + codex_windows_sandbox::run_setup_refresh_with_extra_read_roots( + policy, + policy_cwd, + command_cwd, + env_map, + codex_home, + extra_read_roots, + ) +} + +#[cfg(not(target_os = "windows"))] +pub fn run_legacy_setup_preflight( + _policy: &SandboxPolicy, + _policy_cwd: &Path, + _command_cwd: &Path, + _env_map: &HashMap, + _codex_home: &Path, +) -> anyhow::Result<()> { + anyhow::bail!("legacy Windows sandbox setup is only supported on Windows") +} + +#[cfg(not(target_os = "windows"))] +pub fn run_setup_refresh_with_extra_read_roots( + _policy: &SandboxPolicy, + _policy_cwd: &Path, + _command_cwd: &Path, + _env_map: &HashMap, + _codex_home: &Path, + _extra_read_roots: Vec, +) -> anyhow::Result<()> { + anyhow::bail!("Windows sandbox read-root refresh is only supported on Windows") +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WindowsSandboxSetupMode { + Elevated, + Unelevated, +} + +#[derive(Debug, Clone)] +pub struct WindowsSandboxSetupRequest { + pub mode: WindowsSandboxSetupMode, + pub policy: SandboxPolicy, + pub policy_cwd: PathBuf, + pub command_cwd: PathBuf, + pub env_map: HashMap, + pub codex_home: PathBuf, + pub originator_tag: Option, +} + +pub async fn run_windows_sandbox_setup(request: WindowsSandboxSetupRequest) -> anyhow::Result<()> { + let start = Instant::now(); + let mode = request.mode; + let originator_tag = request + .originator_tag + .as_deref() + .map(sanitize_metric_tag_value) + .unwrap_or_else(|| "unknown".to_string()); + let result = run_windows_sandbox_setup_impl(request).await; + + match result { + Ok(()) => { + emit_windows_sandbox_setup_success_metrics( + mode, + originator_tag.as_str(), + start.elapsed(), + ); + Ok(()) + } + Err(err) => { + emit_windows_sandbox_setup_failure_metrics( + mode, + originator_tag.as_str(), + start.elapsed(), + &err, + ); + Err(err) + } + } +} + +async fn run_windows_sandbox_setup_impl(request: WindowsSandboxSetupRequest) -> anyhow::Result<()> { + let mode = request.mode; + let policy = request.policy; + let policy_cwd = request.policy_cwd; + let command_cwd = request.command_cwd; + let env_map = request.env_map; + let codex_home = request.codex_home; + let setup_codex_home = codex_home.clone(); + + let setup_result = tokio::task::spawn_blocking(move || -> anyhow::Result<()> { + match mode { + WindowsSandboxSetupMode::Elevated => { + if !sandbox_setup_is_complete(setup_codex_home.as_path()) { + run_elevated_setup( + &policy, + policy_cwd.as_path(), + command_cwd.as_path(), + &env_map, + setup_codex_home.as_path(), + )?; + } + } + WindowsSandboxSetupMode::Unelevated => { + run_legacy_setup_preflight( + &policy, + policy_cwd.as_path(), + command_cwd.as_path(), + &env_map, + setup_codex_home.as_path(), + )?; + } + } + Ok(()) + }) + .await + .map_err(|join_err| anyhow::anyhow!("windows sandbox setup task failed: {join_err}"))?; + + setup_result +} + +fn emit_windows_sandbox_setup_success_metrics( + mode: WindowsSandboxSetupMode, + originator_tag: &str, + duration: std::time::Duration, +) { + let Some(metrics) = codex_otel::metrics::global() else { + return; + }; + let mode_tag = windows_sandbox_mode_tag(mode); + let _ = metrics.record_duration( + "codex.windows_sandbox.setup_duration_ms", + duration, + &[ + ("result", "success"), + ("originator", originator_tag), + ("mode", mode_tag), + ], + ); + let _ = metrics.counter( + "codex.windows_sandbox.setup_success", + /*inc*/ 1, + &[("originator", originator_tag), ("mode", mode_tag)], + ); +} + +fn emit_windows_sandbox_setup_failure_metrics( + mode: WindowsSandboxSetupMode, + originator_tag: &str, + duration: std::time::Duration, + _err: &anyhow::Error, +) { + let Some(metrics) = codex_otel::metrics::global() else { + return; + }; + let mode_tag = windows_sandbox_mode_tag(mode); + let _ = metrics.record_duration( + "codex.windows_sandbox.setup_duration_ms", + duration, + &[ + ("result", "failure"), + ("originator", originator_tag), + ("mode", mode_tag), + ], + ); + let _ = metrics.counter( + "codex.windows_sandbox.setup_failure", + /*inc*/ 1, + &[("originator", originator_tag), ("mode", mode_tag)], + ); + + if matches!(mode, WindowsSandboxSetupMode::Elevated) { + #[cfg(target_os = "windows")] + { + let mut failure_tags: Vec<(&str, &str)> = vec![("originator", originator_tag)]; + let mut code_tag: Option = None; + let mut message_tag: Option = None; + if let Some((code, message)) = elevated_setup_failure_details(_err) { + code_tag = Some(code); + message_tag = Some(message); + } + if let Some(code) = code_tag.as_deref() { + failure_tags.push(("code", code)); + } + if let Some(message) = message_tag.as_deref() { + failure_tags.push(("message", message)); + } + let _ = metrics.counter( + elevated_setup_failure_metric_name(_err), + /*inc*/ 1, + &failure_tags, + ); + } + } else { + let _ = metrics.counter( + "codex.windows_sandbox.legacy_setup_preflight_failed", + /*inc*/ 1, + &[("originator", originator_tag)], + ); + } +} + +pub fn windows_sandbox_mode_tag(mode: WindowsSandboxSetupMode) -> &'static str { + match mode { + WindowsSandboxSetupMode::Elevated => "elevated", + WindowsSandboxSetupMode::Unelevated => "unelevated", + } +} + +#[cfg(test)] +#[path = "windows_sandbox_tests.rs"] +mod tests; diff --git a/codex-rs/sandbox/src/windows_sandbox_read_grants.rs b/codex-rs/sandbox/src/windows_sandbox_read_grants.rs new file mode 100644 index 0000000000..ec08e55cfd --- /dev/null +++ b/codex-rs/sandbox/src/windows_sandbox_read_grants.rs @@ -0,0 +1,40 @@ +use crate::protocol::SandboxPolicy; +use crate::windows_sandbox::run_setup_refresh_with_extra_read_roots; +use anyhow::Result; +use std::collections::HashMap; +use std::path::Path; +use std::path::PathBuf; + +pub fn grant_read_root_non_elevated( + policy: &SandboxPolicy, + policy_cwd: &Path, + command_cwd: &Path, + env_map: &HashMap, + codex_home: &Path, + read_root: &Path, +) -> Result { + if !read_root.is_absolute() { + anyhow::bail!("path must be absolute: {}", read_root.display()); + } + if !read_root.exists() { + anyhow::bail!("path does not exist: {}", read_root.display()); + } + if !read_root.is_dir() { + anyhow::bail!("path must be a directory: {}", read_root.display()); + } + + let canonical_root = dunce::canonicalize(read_root)?; + run_setup_refresh_with_extra_read_roots( + policy, + policy_cwd, + command_cwd, + env_map, + codex_home, + vec![canonical_root.clone()], + )?; + Ok(canonical_root) +} + +#[cfg(test)] +#[path = "windows_sandbox_read_grants_tests.rs"] +mod tests; diff --git a/codex-rs/sandbox/src/windows_sandbox_read_grants_tests.rs b/codex-rs/sandbox/src/windows_sandbox_read_grants_tests.rs new file mode 100644 index 0000000000..c23920264b --- /dev/null +++ b/codex-rs/sandbox/src/windows_sandbox_read_grants_tests.rs @@ -0,0 +1,57 @@ +use super::grant_read_root_non_elevated; +use crate::protocol::SandboxPolicy; +use std::collections::HashMap; +use std::path::Path; +use tempfile::TempDir; + +fn policy() -> SandboxPolicy { + SandboxPolicy::new_workspace_write_policy() +} + +#[test] +fn rejects_relative_path() { + let tmp = TempDir::new().expect("tempdir"); + let err = grant_read_root_non_elevated( + &policy(), + tmp.path(), + tmp.path(), + &HashMap::new(), + tmp.path(), + Path::new("relative"), + ) + .expect_err("relative path should fail"); + assert!(err.to_string().contains("path must be absolute")); +} + +#[test] +fn rejects_missing_path() { + let tmp = TempDir::new().expect("tempdir"); + let missing = tmp.path().join("does-not-exist"); + let err = grant_read_root_non_elevated( + &policy(), + tmp.path(), + tmp.path(), + &HashMap::new(), + tmp.path(), + missing.as_path(), + ) + .expect_err("missing path should fail"); + assert!(err.to_string().contains("path does not exist")); +} + +#[test] +fn rejects_file_path() { + let tmp = TempDir::new().expect("tempdir"); + let file_path = tmp.path().join("file.txt"); + std::fs::write(&file_path, "hello").expect("write file"); + let err = grant_read_root_non_elevated( + &policy(), + tmp.path(), + tmp.path(), + &HashMap::new(), + tmp.path(), + file_path.as_path(), + ) + .expect_err("file path should fail"); + assert!(err.to_string().contains("path must be a directory")); +} diff --git a/codex-rs/sandbox/src/windows_sandbox_tests.rs b/codex-rs/sandbox/src/windows_sandbox_tests.rs new file mode 100644 index 0000000000..84f6f7366f --- /dev/null +++ b/codex-rs/sandbox/src/windows_sandbox_tests.rs @@ -0,0 +1,136 @@ +use super::*; +use codex_features::Feature; +use codex_features::Features; +use codex_features::FeaturesToml; +use pretty_assertions::assert_eq; +use std::collections::BTreeMap; + +#[test] +fn elevated_flag_works_by_itself() { + let mut features = Features::with_defaults(); + features.enable(Feature::WindowsSandboxElevated); + + assert_eq!( + WindowsSandboxLevel::from_features(&features), + WindowsSandboxLevel::Elevated + ); +} + +#[test] +fn restricted_token_flag_works_by_itself() { + let mut features = Features::with_defaults(); + features.enable(Feature::WindowsSandbox); + + assert_eq!( + WindowsSandboxLevel::from_features(&features), + WindowsSandboxLevel::RestrictedToken + ); +} + +#[test] +fn no_flags_means_no_sandbox() { + let features = Features::with_defaults(); + + assert_eq!( + WindowsSandboxLevel::from_features(&features), + WindowsSandboxLevel::Disabled + ); +} + +#[test] +fn elevated_wins_when_both_flags_are_enabled() { + let mut features = Features::with_defaults(); + features.enable(Feature::WindowsSandbox); + features.enable(Feature::WindowsSandboxElevated); + + assert_eq!( + WindowsSandboxLevel::from_features(&features), + WindowsSandboxLevel::Elevated + ); +} + +#[test] +fn legacy_mode_prefers_elevated() { + let mut entries = BTreeMap::new(); + entries.insert("experimental_windows_sandbox".to_string(), true); + entries.insert("elevated_windows_sandbox".to_string(), true); + + assert_eq!( + legacy_windows_sandbox_mode_from_entries(&entries), + Some(WindowsSandboxMode::Elevated) + ); +} + +#[test] +fn legacy_mode_supports_alias_key() { + let mut entries = BTreeMap::new(); + entries.insert("enable_experimental_windows_sandbox".to_string(), true); + + assert_eq!( + legacy_windows_sandbox_mode_from_entries(&entries), + Some(WindowsSandboxMode::Unelevated) + ); +} + +#[test] +fn resolve_windows_sandbox_mode_prefers_profile_windows() { + assert_eq!( + resolve_windows_sandbox_mode( + Some(WindowsSandboxMode::Elevated), + None, + Some(WindowsSandboxMode::Unelevated), + None, + ), + Some(WindowsSandboxMode::Elevated) + ); +} + +#[test] +fn resolve_windows_sandbox_mode_falls_back_to_legacy_keys() { + let mut entries = BTreeMap::new(); + entries.insert("experimental_windows_sandbox".to_string(), true); + let cfg_features = FeaturesToml { entries }; + + assert_eq!( + resolve_windows_sandbox_mode(None, None, None, Some(&cfg_features)), + Some(WindowsSandboxMode::Unelevated) + ); +} + +#[test] +fn resolve_windows_sandbox_mode_profile_legacy_false_blocks_top_level_legacy_true() { + let mut profile_entries = BTreeMap::new(); + profile_entries.insert("experimental_windows_sandbox".to_string(), false); + let profile_features = FeaturesToml { + entries: profile_entries, + }; + + let mut cfg_entries = BTreeMap::new(); + cfg_entries.insert("experimental_windows_sandbox".to_string(), true); + let cfg_features = FeaturesToml { + entries: cfg_entries, + }; + + assert_eq!( + resolve_windows_sandbox_mode(None, Some(&profile_features), None, Some(&cfg_features)), + None + ); +} + +#[test] +fn resolve_windows_sandbox_private_desktop_prefers_profile_windows() { + assert!(resolve_windows_sandbox_private_desktop( + Some(true), + Some(false) + )); +} + +#[test] +fn resolve_windows_sandbox_private_desktop_defaults_to_true() { + assert!(resolve_windows_sandbox_private_desktop(None, None)); +} + +#[test] +fn resolve_windows_sandbox_private_desktop_respects_explicit_cfg_value() { + assert!(!resolve_windows_sandbox_private_desktop(None, Some(false))); +} diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index 8013b1325e..98d9a3d57f 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -43,6 +43,7 @@ codex-file-search = { workspace = true } codex-login = { workspace = true } codex-otel = { workspace = true } codex-protocol = { workspace = true } +codex-sandbox = { workspace = true } codex-shell-command = { workspace = true } codex-state = { workspace = true } codex-terminal-detection = { workspace = true } diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 4aa51df21c..d8c516dc0d 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -68,8 +68,6 @@ use codex_core::models_manager::collaboration_mode_presets::CollaborationModesCo use codex_core::models_manager::manager::RefreshStrategy; use codex_core::models_manager::model_presets::HIDE_GPT_5_1_CODEX_MAX_MIGRATION_PROMPT_CONFIG; use codex_core::models_manager::model_presets::HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG; -#[cfg(target_os = "windows")] -use codex_core::windows_sandbox::WindowsSandboxLevelExt; use codex_features::Feature; use codex_otel::SessionTelemetry; use codex_otel::TelemetryAuthMode; @@ -93,6 +91,20 @@ use codex_protocol::protocol::SessionConfiguredEvent; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SkillErrorInfo; use codex_protocol::protocol::TokenUsage; +#[cfg(target_os = "windows")] +use codex_sandbox::WindowsSandboxLevelExt; +#[cfg(target_os = "windows")] +use codex_sandbox::elevated_setup_failure_details; +#[cfg(target_os = "windows")] +use codex_sandbox::elevated_setup_failure_metric_name; +#[cfg(target_os = "windows")] +use codex_sandbox::grant_read_root_non_elevated; +#[cfg(target_os = "windows")] +use codex_sandbox::run_elevated_setup; +#[cfg(target_os = "windows")] +use codex_sandbox::run_legacy_setup_preflight; +#[cfg(target_os = "windows")] +use codex_sandbox::sandbox_setup_is_complete; use codex_terminal_detection::user_agent; use codex_utils_absolute_path::AbsolutePathBuf; use color_eyre::eyre::Result; @@ -118,6 +130,14 @@ use std::time::Duration; use std::time::Instant; use tokio::select; use tokio::sync::Mutex; + +#[cfg(target_os = "windows")] +fn windows_sandbox_level(config: &Config) -> WindowsSandboxLevel { + WindowsSandboxLevel::from_mode_and_features( + config.permissions.windows_sandbox_mode.map(Into::into), + &config.features, + ) +} use tokio::sync::broadcast; use tokio::sync::mpsc; use tokio::sync::mpsc::error::TryRecvError; @@ -1272,7 +1292,7 @@ impl App { if windows_sandbox_changed { #[cfg(target_os = "windows")] { - let windows_sandbox_level = WindowsSandboxLevel::from_config(&self.config); + let windows_sandbox_level = windows_sandbox_level(&self.config); self.app_event_tx .send(AppEvent::CodexOp(Op::OverrideTurnContext { cwd: None, @@ -2443,8 +2463,7 @@ impl App { // On startup, if Agent mode (workspace-write) or ReadOnly is active, warn about world-writable dirs on Windows. #[cfg(target_os = "windows")] { - let should_check = WindowsSandboxLevel::from_config(&app.config) - != WindowsSandboxLevel::Disabled + let should_check = windows_sandbox_level(&app.config) != WindowsSandboxLevel::Disabled && matches!( app.config.permissions.sandbox_policy.get(), codex_protocol::protocol::SandboxPolicy::WorkspaceWrite { .. } @@ -3078,8 +3097,7 @@ impl App { // If the elevated setup already ran on this machine, don't prompt for // elevation again - just flip the config to use the elevated path. - if codex_core::windows_sandbox::sandbox_setup_is_complete(codex_home.as_path()) - { + if sandbox_setup_is_complete(codex_home.as_path()) { tx.send(AppEvent::EnableWindowsSandboxForAgentMode { preset, mode: WindowsSandboxEnableMode::Elevated, @@ -3091,7 +3109,7 @@ impl App { self.windows_sandbox.setup_started_at = Some(Instant::now()); let session_telemetry = self.session_telemetry.clone(); tokio::task::spawn_blocking(move || { - let result = codex_core::windows_sandbox::run_elevated_setup( + let result = run_elevated_setup( &policy, policy_cwd.as_path(), command_cwd.as_path(), @@ -3113,10 +3131,7 @@ impl App { Err(err) => { let mut code_tag: Option = None; let mut message_tag: Option = None; - if let Some((code, message)) = - codex_core::windows_sandbox::elevated_setup_failure_details( - &err, - ) + if let Some((code, message)) = elevated_setup_failure_details(&err) { code_tag = Some(code); message_tag = Some(message); @@ -3129,9 +3144,7 @@ impl App { tags.push(("message", message)); } session_telemetry.counter( - codex_core::windows_sandbox::elevated_setup_failure_metric_name( - &err, - ), + elevated_setup_failure_metric_name(&err), /*inc*/ 1, &tags, ); @@ -3164,7 +3177,7 @@ impl App { self.chat_widget.show_windows_sandbox_setup_status(); tokio::task::spawn_blocking(move || { - if let Err(err) = codex_core::windows_sandbox::run_legacy_setup_preflight( + if let Err(err) = run_legacy_setup_preflight( &policy, policy_cwd.as_path(), command_cwd.as_path(), @@ -3211,7 +3224,7 @@ impl App { tokio::task::spawn_blocking(move || { let requested_path = PathBuf::from(path); - let event = match codex_core::windows_sandbox_read_grants::grant_read_root_non_elevated( + let event = match grant_read_root_non_elevated( &policy, policy_cwd.as_path(), command_cwd.as_path(), @@ -3284,8 +3297,7 @@ impl App { self.chat_widget.set_windows_sandbox_mode( self.config.permissions.windows_sandbox_mode, ); - let windows_sandbox_level = - WindowsSandboxLevel::from_config(&self.config); + let windows_sandbox_level = windows_sandbox_level(&self.config); if let Some((sample_paths, extra_count, failed_scan)) = self.chat_widget.world_writable_warning_details() { @@ -3571,7 +3583,7 @@ impl App { return Ok(AppRunControl::Continue); } - let should_check = WindowsSandboxLevel::from_config(&self.config) + let should_check = windows_sandbox_level(&self.config) != WindowsSandboxLevel::Disabled && policy_is_workspace_write_or_ro && !self.chat_widget.world_writable_warning_hidden(); diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index e2480c4ec0..fe5c09be14 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -76,8 +76,6 @@ use codex_core::models_manager::manager::ModelsManager; use codex_core::plugins::PluginsManager; use codex_core::project_doc::DEFAULT_PROJECT_DOC_FILENAME; use codex_core::skills::model::SkillMetadata; -#[cfg(target_os = "windows")] -use codex_core::windows_sandbox::WindowsSandboxLevelExt; use codex_features::FEATURES; use codex_features::Feature; use codex_otel::RuntimeMetricsSummary; @@ -155,6 +153,12 @@ use codex_protocol::request_permissions::RequestPermissionsEvent; use codex_protocol::request_user_input::RequestUserInputEvent; use codex_protocol::user_input::TextElement; use codex_protocol::user_input::UserInput; +#[cfg(target_os = "windows")] +use codex_sandbox::ELEVATED_SANDBOX_NUX_ENABLED; +#[cfg(target_os = "windows")] +use codex_sandbox::WindowsSandboxLevelExt; +#[cfg(target_os = "windows")] +use codex_sandbox::sandbox_setup_is_complete; use codex_terminal_detection::TerminalName; use codex_terminal_detection::terminal_info; use codex_utils_sleep_inhibitor::SleepInhibitor; @@ -178,6 +182,14 @@ use tracing::debug; use tracing::warn; use unicode_segmentation::UnicodeSegmentation; +#[cfg(target_os = "windows")] +fn windows_sandbox_level(config: &Config) -> WindowsSandboxLevel { + WindowsSandboxLevel::from_mode_and_features( + config.permissions.windows_sandbox_mode.map(Into::into), + &config.features, + ) +} + const DEFAULT_MODEL_DISPLAY_NAME: &str = "loading"; const PLAN_IMPLEMENTATION_TITLE: &str = "Implement this plan?"; const PLAN_IMPLEMENTATION_YES: &str = "Yes, implement this plan"; @@ -3743,9 +3755,9 @@ impl ChatWidget { .set_queued_message_edit_binding(widget.queued_message_edit_binding); #[cfg(target_os = "windows")] widget.bottom_pane.set_windows_degraded_sandbox_active( - codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED + ELEVATED_SANDBOX_NUX_ENABLED && matches!( - WindowsSandboxLevel::from_config(&widget.config), + windows_sandbox_level(&widget.config), WindowsSandboxLevel::RestrictedToken ), ); @@ -4135,9 +4147,9 @@ impl ChatWidget { .set_queued_message_edit_binding(widget.queued_message_edit_binding); #[cfg(target_os = "windows")] widget.bottom_pane.set_windows_degraded_sandbox_active( - codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED + ELEVATED_SANDBOX_NUX_ENABLED && matches!( - WindowsSandboxLevel::from_config(&widget.config), + windows_sandbox_level(&widget.config), WindowsSandboxLevel::RestrictedToken ), ); @@ -4517,12 +4529,10 @@ impl ChatWidget { SlashCommand::ElevateSandbox => { #[cfg(target_os = "windows")] { - let windows_sandbox_level = WindowsSandboxLevel::from_config(&self.config); + let windows_sandbox_level = windows_sandbox_level(&self.config); let windows_degraded_sandbox_enabled = matches!(windows_sandbox_level, WindowsSandboxLevel::RestrictedToken); - if !windows_degraded_sandbox_enabled - || !codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED - { + if !windows_degraded_sandbox_enabled || !ELEVATED_SANDBOX_NUX_ENABLED { // This command should not be visible/recognized outside degraded mode, // but guard anyway in case something dispatches it directly. return; @@ -6978,14 +6988,14 @@ impl ChatWidget { let presets: Vec = builtin_approval_presets(); #[cfg(target_os = "windows")] - let windows_sandbox_level = WindowsSandboxLevel::from_config(&self.config); + let windows_sandbox_level = windows_sandbox_level(&self.config); #[cfg(target_os = "windows")] let windows_degraded_sandbox_enabled = matches!(windows_sandbox_level, WindowsSandboxLevel::RestrictedToken); #[cfg(not(target_os = "windows"))] let windows_degraded_sandbox_enabled = false; - let show_elevate_sandbox_hint = codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED + let show_elevate_sandbox_hint = ELEVATED_SANDBOX_NUX_ENABLED && windows_degraded_sandbox_enabled && presets.iter().any(|preset| preset.id == "auto"); @@ -7039,14 +7049,10 @@ impl ChatWidget { } else if preset.id == "auto" { #[cfg(target_os = "windows")] { - if WindowsSandboxLevel::from_config(&self.config) - == WindowsSandboxLevel::Disabled - { + if windows_sandbox_level(&self.config) == WindowsSandboxLevel::Disabled { let preset_clone = preset.clone(); - if codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED - && codex_core::windows_sandbox::sandbox_setup_is_complete( - self.config.codex_home.as_path(), - ) + if ELEVATED_SANDBOX_NUX_ENABLED + && sandbox_setup_is_complete(self.config.codex_home.as_path()) { vec![Box::new(move |tx| { tx.send(AppEvent::EnableWindowsSandboxForAgentMode { @@ -7497,7 +7503,7 @@ impl ChatWidget { pub(crate) fn open_windows_sandbox_enable_prompt(&mut self, preset: ApprovalPreset) { use ratatui_macros::line; - if !codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED { + if !ELEVATED_SANDBOX_NUX_ENABLED { // Legacy flow (pre-NUX): explain the experimental sandbox and let the user enable it // directly (no elevation prompts). let mut header = ColumnRenderable::new(); @@ -7717,7 +7723,7 @@ impl ChatWidget { #[cfg(target_os = "windows")] pub(crate) fn maybe_prompt_windows_sandbox_enable(&mut self, show_now: bool) { if show_now - && WindowsSandboxLevel::from_config(&self.config) == WindowsSandboxLevel::Disabled + && windows_sandbox_level(&self.config) == WindowsSandboxLevel::Disabled && let Some(preset) = builtin_approval_presets() .into_iter() .find(|preset| preset.id == "auto") @@ -7783,9 +7789,9 @@ impl ChatWidget { self.config.permissions.windows_sandbox_mode = mode; #[cfg(target_os = "windows")] self.bottom_pane.set_windows_degraded_sandbox_active( - codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED + ELEVATED_SANDBOX_NUX_ENABLED && matches!( - WindowsSandboxLevel::from_config(&self.config), + windows_sandbox_level(&self.config), WindowsSandboxLevel::RestrictedToken ), ); @@ -7836,9 +7842,9 @@ impl ChatWidget { Feature::WindowsSandbox | Feature::WindowsSandboxElevated ) { self.bottom_pane.set_windows_degraded_sandbox_active( - codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED + ELEVATED_SANDBOX_NUX_ENABLED && matches!( - WindowsSandboxLevel::from_config(&self.config), + windows_sandbox_level(&self.config), WindowsSandboxLevel::RestrictedToken ), ); diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 5416200691..3793770d2a 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -34,7 +34,6 @@ use codex_core::format_exec_policy_error_with_source; use codex_core::path_utils; use codex_core::read_session_meta_line; use codex_core::state_db::get_state_db; -use codex_core::windows_sandbox::WindowsSandboxLevelExt; use codex_protocol::ThreadId; use codex_protocol::config_types::AltScreenMode; use codex_protocol::config_types::SandboxMode; @@ -42,6 +41,7 @@ use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::RolloutLine; +use codex_sandbox::WindowsSandboxLevelExt; use codex_state::log_db; use codex_terminal_detection::Multiplexer; use codex_terminal_detection::terminal_info; @@ -60,6 +60,13 @@ use tracing_subscriber::EnvFilter; use tracing_subscriber::prelude::*; use uuid::Uuid; +fn windows_sandbox_level(config: &Config) -> WindowsSandboxLevel { + WindowsSandboxLevel::from_mode_and_features( + config.permissions.windows_sandbox_mode.map(Into::into), + &config.features, + ) +} + mod additional_dirs; mod app; mod app_backtrack; @@ -972,7 +979,7 @@ async fn run_ratatui_app( let should_show_trust_screen = should_show_trust_screen(&config); let should_prompt_windows_sandbox_nux_at_startup = cfg!(target_os = "windows") && trust_decision_was_made - && WindowsSandboxLevel::from_config(&config) == WindowsSandboxLevel::Disabled; + && windows_sandbox_level(&config) == WindowsSandboxLevel::Disabled; let Cli { prompt, diff --git a/codex-rs/tui/src/onboarding/onboarding_screen.rs b/codex-rs/tui/src/onboarding/onboarding_screen.rs index 127ac9f667..6660a09340 100644 --- a/codex-rs/tui/src/onboarding/onboarding_screen.rs +++ b/codex-rs/tui/src/onboarding/onboarding_screen.rs @@ -1,9 +1,9 @@ use codex_core::AuthManager; use codex_core::config::Config; #[cfg(target_os = "windows")] -use codex_core::windows_sandbox::WindowsSandboxLevelExt; -#[cfg(target_os = "windows")] use codex_protocol::config_types::WindowsSandboxLevel; +#[cfg(target_os = "windows")] +use codex_sandbox::WindowsSandboxLevelExt; use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use crossterm::event::KeyEventKind; @@ -73,6 +73,14 @@ pub(crate) struct OnboardingResult { pub should_exit: bool, } +#[cfg(target_os = "windows")] +fn windows_sandbox_level(config: &Config) -> WindowsSandboxLevel { + WindowsSandboxLevel::from_mode_and_features( + config.permissions.windows_sandbox_mode.map(Into::into), + &config.features, + ) +} + impl OnboardingScreen { pub(crate) fn new(tui: &mut Tui, args: OnboardingScreenArgs) -> Self { let OnboardingScreenArgs { @@ -114,7 +122,7 @@ impl OnboardingScreen { } #[cfg(target_os = "windows")] let show_windows_create_sandbox_hint = - WindowsSandboxLevel::from_config(&config) == WindowsSandboxLevel::Disabled; + windows_sandbox_level(&config) == WindowsSandboxLevel::Disabled; #[cfg(not(target_os = "windows"))] let show_windows_create_sandbox_hint = false; let highlighted = TrustDirectorySelection::Trust; diff --git a/codex-rs/tui_app_server/Cargo.toml b/codex-rs/tui_app_server/Cargo.toml index 8866042051..e30446ec09 100644 --- a/codex-rs/tui_app_server/Cargo.toml +++ b/codex-rs/tui_app_server/Cargo.toml @@ -47,6 +47,7 @@ codex-file-search = { workspace = true } codex-login = { workspace = true } codex-otel = { workspace = true } codex-protocol = { workspace = true } +codex-sandbox = { workspace = true } codex-shell-command = { workspace = true } codex-state = { workspace = true } codex-terminal-detection = { workspace = true } diff --git a/codex-rs/tui_app_server/src/app.rs b/codex-rs/tui_app_server/src/app.rs index 171df69270..6126bc409a 100644 --- a/codex-rs/tui_app_server/src/app.rs +++ b/codex-rs/tui_app_server/src/app.rs @@ -76,8 +76,6 @@ use codex_core::message_history; use codex_core::models_manager::collaboration_mode_presets::CollaborationModesConfig; use codex_core::models_manager::model_presets::HIDE_GPT_5_1_CODEX_MAX_MIGRATION_PROMPT_CONFIG; use codex_core::models_manager::model_presets::HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG; -#[cfg(target_os = "windows")] -use codex_core::windows_sandbox::WindowsSandboxLevelExt; use codex_features::Feature; use codex_otel::SessionTelemetry; use codex_protocol::ThreadId; @@ -100,6 +98,20 @@ use codex_protocol::protocol::SandboxPolicy; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SkillErrorInfo; use codex_protocol::protocol::TokenUsage; +#[cfg(target_os = "windows")] +use codex_sandbox::WindowsSandboxLevelExt; +#[cfg(target_os = "windows")] +use codex_sandbox::elevated_setup_failure_details; +#[cfg(target_os = "windows")] +use codex_sandbox::elevated_setup_failure_metric_name; +#[cfg(target_os = "windows")] +use codex_sandbox::grant_read_root_non_elevated; +#[cfg(target_os = "windows")] +use codex_sandbox::run_elevated_setup; +#[cfg(target_os = "windows")] +use codex_sandbox::run_legacy_setup_preflight; +#[cfg(target_os = "windows")] +use codex_sandbox::sandbox_setup_is_complete; use codex_terminal_detection::user_agent; use codex_utils_absolute_path::AbsolutePathBuf; use color_eyre::eyre::Result; @@ -124,6 +136,14 @@ use std::time::Duration; use std::time::Instant; use tokio::select; use tokio::sync::Mutex; + +#[cfg(target_os = "windows")] +fn windows_sandbox_level(config: &Config) -> WindowsSandboxLevel { + WindowsSandboxLevel::from_mode_and_features( + config.permissions.windows_sandbox_mode.map(Into::into), + &config.features, + ) +} use tokio::sync::mpsc; use tokio::sync::mpsc::error::TryRecvError; use tokio::sync::mpsc::error::TrySendError; @@ -1364,7 +1384,7 @@ impl App { if windows_sandbox_changed { #[cfg(target_os = "windows")] { - let windows_sandbox_level = WindowsSandboxLevel::from_config(&self.config); + let windows_sandbox_level = windows_sandbox_level(&self.config); self.app_event_tx.send(AppEvent::CodexOp( AppCommand::override_turn_context( /*cwd*/ None, @@ -3172,8 +3192,7 @@ impl App { // On startup, if Agent mode (workspace-write) or ReadOnly is active, warn about world-writable dirs on Windows. #[cfg(target_os = "windows")] { - let should_check = WindowsSandboxLevel::from_config(&app.config) - != WindowsSandboxLevel::Disabled + let should_check = windows_sandbox_level(&app.config) != WindowsSandboxLevel::Disabled && matches!( app.config.permissions.sandbox_policy.get(), codex_protocol::protocol::SandboxPolicy::WorkspaceWrite { .. } @@ -3810,8 +3829,7 @@ impl App { // If the elevated setup already ran on this machine, don't prompt for // elevation again - just flip the config to use the elevated path. - if codex_core::windows_sandbox::sandbox_setup_is_complete(codex_home.as_path()) - { + if sandbox_setup_is_complete(codex_home.as_path()) { tx.send(AppEvent::EnableWindowsSandboxForAgentMode { preset, mode: WindowsSandboxEnableMode::Elevated, @@ -3823,7 +3841,7 @@ impl App { self.windows_sandbox.setup_started_at = Some(Instant::now()); let session_telemetry = self.session_telemetry.clone(); tokio::task::spawn_blocking(move || { - let result = codex_core::windows_sandbox::run_elevated_setup( + let result = run_elevated_setup( &policy, policy_cwd.as_path(), command_cwd.as_path(), @@ -3845,10 +3863,7 @@ impl App { Err(err) => { let mut code_tag: Option = None; let mut message_tag: Option = None; - if let Some((code, message)) = - codex_core::windows_sandbox::elevated_setup_failure_details( - &err, - ) + if let Some((code, message)) = elevated_setup_failure_details(&err) { code_tag = Some(code); message_tag = Some(message); @@ -3861,9 +3876,7 @@ impl App { tags.push(("message", message)); } session_telemetry.counter( - codex_core::windows_sandbox::elevated_setup_failure_metric_name( - &err, - ), + elevated_setup_failure_metric_name(&err), /*inc*/ 1, &tags, ); @@ -3896,7 +3909,7 @@ impl App { self.chat_widget.show_windows_sandbox_setup_status(); tokio::task::spawn_blocking(move || { - if let Err(err) = codex_core::windows_sandbox::run_legacy_setup_preflight( + if let Err(err) = run_legacy_setup_preflight( &policy, policy_cwd.as_path(), command_cwd.as_path(), @@ -3943,7 +3956,7 @@ impl App { tokio::task::spawn_blocking(move || { let requested_path = PathBuf::from(path); - let event = match codex_core::windows_sandbox_read_grants::grant_read_root_non_elevated( + let event = match grant_read_root_non_elevated( &policy, policy_cwd.as_path(), command_cwd.as_path(), @@ -4016,8 +4029,7 @@ impl App { self.chat_widget.set_windows_sandbox_mode( self.config.permissions.windows_sandbox_mode, ); - let windows_sandbox_level = - WindowsSandboxLevel::from_config(&self.config); + let windows_sandbox_level = windows_sandbox_level(&self.config); if let Some((sample_paths, extra_count, failed_scan)) = self.chat_widget.world_writable_warning_details() { @@ -4307,7 +4319,7 @@ impl App { return Ok(AppRunControl::Continue); } - let should_check = WindowsSandboxLevel::from_config(&self.config) + let should_check = windows_sandbox_level(&self.config) != WindowsSandboxLevel::Disabled && policy_is_workspace_write_or_ro && !self.chat_widget.world_writable_warning_hidden(); diff --git a/codex-rs/tui_app_server/src/chatwidget.rs b/codex-rs/tui_app_server/src/chatwidget.rs index 5e0cff03c7..266186dce0 100644 --- a/codex-rs/tui_app_server/src/chatwidget.rs +++ b/codex-rs/tui_app_server/src/chatwidget.rs @@ -94,8 +94,6 @@ use codex_core::git_info::local_git_branches; use codex_core::plugins::PluginsManager; use codex_core::project_doc::DEFAULT_PROJECT_DOC_FILENAME; use codex_core::skills::model::SkillMetadata; -#[cfg(target_os = "windows")] -use codex_core::windows_sandbox::WindowsSandboxLevelExt; use codex_features::FEATURES; use codex_features::Feature; use codex_otel::RuntimeMetricsSummary; @@ -199,6 +197,12 @@ use codex_protocol::request_user_input::RequestUserInputEvent; use codex_protocol::request_user_input::RequestUserInputQuestionOption; use codex_protocol::user_input::TextElement; use codex_protocol::user_input::UserInput; +#[cfg(target_os = "windows")] +use codex_sandbox::ELEVATED_SANDBOX_NUX_ENABLED; +#[cfg(target_os = "windows")] +use codex_sandbox::WindowsSandboxLevelExt; +#[cfg(target_os = "windows")] +use codex_sandbox::sandbox_setup_is_complete; use codex_terminal_detection::TerminalName; use codex_terminal_detection::terminal_info; use codex_utils_sleep_inhibitor::SleepInhibitor; @@ -220,6 +224,14 @@ use tokio::sync::mpsc::UnboundedSender; use tracing::debug; use tracing::warn; +#[cfg(target_os = "windows")] +fn windows_sandbox_level(config: &Config) -> WindowsSandboxLevel { + WindowsSandboxLevel::from_mode_and_features( + config.permissions.windows_sandbox_mode.map(Into::into), + &config.features, + ) +} + const DEFAULT_MODEL_DISPLAY_NAME: &str = "loading"; const PLAN_IMPLEMENTATION_TITLE: &str = "Implement this plan?"; const PLAN_IMPLEMENTATION_YES: &str = "Yes, implement this plan"; @@ -4295,9 +4307,9 @@ impl ChatWidget { .set_queued_message_edit_binding(widget.queued_message_edit_binding); #[cfg(target_os = "windows")] widget.bottom_pane.set_windows_degraded_sandbox_active( - codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED + ELEVATED_SANDBOX_NUX_ENABLED && matches!( - WindowsSandboxLevel::from_config(&widget.config), + windows_sandbox_level(&widget.config), WindowsSandboxLevel::RestrictedToken ), ); @@ -4676,12 +4688,10 @@ impl ChatWidget { SlashCommand::ElevateSandbox => { #[cfg(target_os = "windows")] { - let windows_sandbox_level = WindowsSandboxLevel::from_config(&self.config); + let windows_sandbox_level = windows_sandbox_level(&self.config); let windows_degraded_sandbox_enabled = matches!(windows_sandbox_level, WindowsSandboxLevel::RestrictedToken); - if !windows_degraded_sandbox_enabled - || !codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED - { + if !windows_degraded_sandbox_enabled || !ELEVATED_SANDBOX_NUX_ENABLED { // This command should not be visible/recognized outside degraded mode, // but guard anyway in case something dispatches it directly. return; @@ -8154,14 +8164,14 @@ impl ChatWidget { let presets: Vec = builtin_approval_presets(); #[cfg(target_os = "windows")] - let windows_sandbox_level = WindowsSandboxLevel::from_config(&self.config); + let windows_sandbox_level = windows_sandbox_level(&self.config); #[cfg(target_os = "windows")] let windows_degraded_sandbox_enabled = matches!(windows_sandbox_level, WindowsSandboxLevel::RestrictedToken); #[cfg(not(target_os = "windows"))] let windows_degraded_sandbox_enabled = false; - let show_elevate_sandbox_hint = codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED + let show_elevate_sandbox_hint = ELEVATED_SANDBOX_NUX_ENABLED && windows_degraded_sandbox_enabled && presets.iter().any(|preset| preset.id == "auto"); @@ -8215,14 +8225,10 @@ impl ChatWidget { } else if preset.id == "auto" { #[cfg(target_os = "windows")] { - if WindowsSandboxLevel::from_config(&self.config) - == WindowsSandboxLevel::Disabled - { + if windows_sandbox_level(&self.config) == WindowsSandboxLevel::Disabled { let preset_clone = preset.clone(); - if codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED - && codex_core::windows_sandbox::sandbox_setup_is_complete( - self.config.codex_home.as_path(), - ) + if ELEVATED_SANDBOX_NUX_ENABLED + && sandbox_setup_is_complete(self.config.codex_home.as_path()) { vec![Box::new(move |tx| { tx.send(AppEvent::EnableWindowsSandboxForAgentMode { @@ -8676,7 +8682,7 @@ impl ChatWidget { pub(crate) fn open_windows_sandbox_enable_prompt(&mut self, preset: ApprovalPreset) { use ratatui_macros::line; - if !codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED { + if !ELEVATED_SANDBOX_NUX_ENABLED { // Legacy flow (pre-NUX): explain the experimental sandbox and let the user enable it // directly (no elevation prompts). let mut header = ColumnRenderable::new(); @@ -8896,7 +8902,7 @@ impl ChatWidget { #[cfg(target_os = "windows")] pub(crate) fn maybe_prompt_windows_sandbox_enable(&mut self, show_now: bool) { if show_now - && WindowsSandboxLevel::from_config(&self.config) == WindowsSandboxLevel::Disabled + && windows_sandbox_level(&self.config) == WindowsSandboxLevel::Disabled && let Some(preset) = builtin_approval_presets() .into_iter() .find(|preset| preset.id == "auto") @@ -8962,9 +8968,9 @@ impl ChatWidget { self.config.permissions.windows_sandbox_mode = mode; #[cfg(target_os = "windows")] self.bottom_pane.set_windows_degraded_sandbox_active( - codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED + ELEVATED_SANDBOX_NUX_ENABLED && matches!( - WindowsSandboxLevel::from_config(&self.config), + windows_sandbox_level(&self.config), WindowsSandboxLevel::RestrictedToken ), ); @@ -9015,9 +9021,9 @@ impl ChatWidget { Feature::WindowsSandbox | Feature::WindowsSandboxElevated ) { self.bottom_pane.set_windows_degraded_sandbox_active( - codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED + ELEVATED_SANDBOX_NUX_ENABLED && matches!( - WindowsSandboxLevel::from_config(&self.config), + windows_sandbox_level(&self.config), WindowsSandboxLevel::RestrictedToken ), ); diff --git a/codex-rs/tui_app_server/src/lib.rs b/codex-rs/tui_app_server/src/lib.rs index 17e309d5fb..84c1039705 100644 --- a/codex-rs/tui_app_server/src/lib.rs +++ b/codex-rs/tui_app_server/src/lib.rs @@ -39,7 +39,6 @@ use codex_core::format_exec_policy_error_with_source; use codex_core::path_utils; use codex_core::read_session_meta_line; use codex_core::state_db::get_state_db; -use codex_core::windows_sandbox::WindowsSandboxLevelExt; use codex_protocol::ThreadId; use codex_protocol::config_types::AltScreenMode; use codex_protocol::config_types::SandboxMode; @@ -48,6 +47,7 @@ use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::RolloutLine; use codex_protocol::protocol::TurnContextItem; +use codex_sandbox::WindowsSandboxLevelExt; use codex_state::log_db; use codex_terminal_detection::Multiplexer; use codex_terminal_detection::terminal_info; @@ -71,6 +71,13 @@ use tracing_subscriber::prelude::*; use url::Url; use uuid::Uuid; +fn windows_sandbox_level(config: &Config) -> WindowsSandboxLevel { + WindowsSandboxLevel::from_mode_and_features( + config.permissions.windows_sandbox_mode.map(Into::into), + &config.features, + ) +} + mod additional_dirs; mod app; mod app_backtrack; @@ -1279,7 +1286,7 @@ async fn run_ratatui_app( let should_show_trust_screen = should_show_trust_screen(&config); let should_prompt_windows_sandbox_nux_at_startup = cfg!(target_os = "windows") && trust_decision_was_made - && WindowsSandboxLevel::from_config(&config) == WindowsSandboxLevel::Disabled; + && windows_sandbox_level(&config) == WindowsSandboxLevel::Disabled; let Cli { prompt, diff --git a/codex-rs/tui_app_server/src/onboarding/onboarding_screen.rs b/codex-rs/tui_app_server/src/onboarding/onboarding_screen.rs index 61b00d6bec..17f008dbda 100644 --- a/codex-rs/tui_app_server/src/onboarding/onboarding_screen.rs +++ b/codex-rs/tui_app_server/src/onboarding/onboarding_screen.rs @@ -3,9 +3,9 @@ use codex_app_server_client::AppServerRequestHandle; use codex_app_server_protocol::ServerNotification; use codex_core::config::Config; #[cfg(target_os = "windows")] -use codex_core::windows_sandbox::WindowsSandboxLevelExt; -#[cfg(target_os = "windows")] use codex_protocol::config_types::WindowsSandboxLevel; +#[cfg(target_os = "windows")] +use codex_sandbox::WindowsSandboxLevelExt; use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use crossterm::event::KeyEventKind; @@ -76,6 +76,14 @@ pub(crate) struct OnboardingResult { pub should_exit: bool, } +#[cfg(target_os = "windows")] +fn windows_sandbox_level(config: &Config) -> WindowsSandboxLevel { + WindowsSandboxLevel::from_mode_and_features( + config.permissions.windows_sandbox_mode.map(Into::into), + &config.features, + ) +} + impl OnboardingScreen { pub(crate) fn new(tui: &mut Tui, args: OnboardingScreenArgs) -> Self { let OnboardingScreenArgs { @@ -121,7 +129,7 @@ impl OnboardingScreen { } #[cfg(target_os = "windows")] let show_windows_create_sandbox_hint = - WindowsSandboxLevel::from_config(&config) == WindowsSandboxLevel::Disabled; + windows_sandbox_level(&config) == WindowsSandboxLevel::Disabled; #[cfg(not(target_os = "windows"))] let show_windows_create_sandbox_hint = false; let highlighted = TrustDirectorySelection::Trust;