From a489ddd4902a073370256aead0593243882bec8e Mon Sep 17 00:00:00 2001 From: David Wiesen Date: Thu, 11 Jun 2026 18:03:01 -0700 Subject: [PATCH] Tighten Windows fs helper launch flow --- codex-rs/exec-server/src/fs_sandbox.rs | 127 ++++------------ .../exec-server/src/fs_sandbox_windows.rs | 141 ++++++++++++++++++ 2 files changed, 174 insertions(+), 94 deletions(-) diff --git a/codex-rs/exec-server/src/fs_sandbox.rs b/codex-rs/exec-server/src/fs_sandbox.rs index 58ab110223..e1db5ac37f 100644 --- a/codex-rs/exec-server/src/fs_sandbox.rs +++ b/codex-rs/exec-server/src/fs_sandbox.rs @@ -62,16 +62,12 @@ impl FileSystemSandboxRunner { request: FsHelperRequest, ) -> Result { let cwd = sandbox_cwd(sandbox)?; - let helper_paths = self.helper_paths_for_launch()?; let mut file_system_policy = sandbox.permissions.file_system_sandbox_policy(); - // The sandboxed child re-enters Codex as the filesystem helper. On Windows - // that executable can be a materialized copy under CODEX_HOME/.sandbox-bin, - // so derive helper read roots from the exact helper path we will launch. let helper_read_roots = if sandbox.use_legacy_landlock { Vec::new() } else { helper_read_roots( - &helper_paths.sandboxed_helper, + &self.runtime_paths.codex_self_exe, self.runtime_paths.codex_linux_sandbox_exe.as_ref(), ) }; @@ -83,55 +79,16 @@ impl FileSystemSandboxRunner { &file_system_policy, network_policy, ); - let command = - self.sandbox_exec_request(&permission_profile, &cwd, sandbox, &helper_paths)?; + let command = self.sandbox_exec_request(&permission_profile, &cwd, sandbox)?; let request_json = serde_json::to_vec(&request).map_err(json_error)?; run_command(command, request_json).await } - fn helper_paths_for_launch(&self) -> Result { - #[cfg(target_os = "windows")] - { - // Windows sandbox launch grants are prepared around the executable - // path that the sandbox will spawn. When exec-server is embedded or - // hosted, `current_exe()` can point at the host process instead of - // the configured Codex binary, so materialize the runtime-provided - // helper and use that exact path for the sandboxed fs-helper. - let codex_home = codex_utils_home_dir::find_codex_home().map_err(|err| { - internal_error(format!( - "windows fs sandbox helper failed to resolve CODEX_HOME: {err}" - )) - })?; - let sandboxed_helper = codex_windows_sandbox::resolve_exe_for_launch( - self.runtime_paths.codex_self_exe.as_path(), - codex_home.as_path(), - ); - let sandboxed_helper = AbsolutePathBuf::from_absolute_path(sandboxed_helper.as_path()) - .map_err(|err| { - internal_error(format!( - "windows fs sandbox helper path is not absolute: {err}" - )) - })?; - Ok(FsHelperLaunchPaths { - sandboxed_helper, - windows_wrapper: self.runtime_paths.codex_self_exe.clone(), - }) - } - - #[cfg(not(target_os = "windows"))] - { - Ok(FsHelperLaunchPaths { - sandboxed_helper: self.runtime_paths.codex_self_exe.clone(), - }) - } - } - fn sandbox_exec_request( &self, permission_profile: &PermissionProfile, cwd: &AbsolutePathBuf, sandbox_context: &FileSystemSandboxContext, - helper_paths: &FsHelperLaunchPaths, ) -> Result { let sandbox_manager = SandboxManager::new(); let (file_system_policy, network_policy) = permission_profile.to_runtime_permissions(); @@ -143,8 +100,9 @@ impl FileSystemSandboxRunner { /*has_managed_network_requirements*/ false, ); let command = SandboxCommand { - program: helper_paths - .sandboxed_helper + program: self + .runtime_paths + .codex_self_exe .as_path() .as_os_str() .to_owned(), @@ -169,8 +127,14 @@ impl FileSystemSandboxRunner { .map_err(|err| invalid_request(format!("failed to prepare fs sandbox: {err}")))?; #[cfg(target_os = "windows")] if command.sandbox == codex_sandboxing::SandboxType::WindowsRestrictedToken { - let request_file = - windows::wrap_sandbox_exec_request(&mut command, &helper_paths.windows_wrapper)?; + windows::materialize_sandboxed_helper( + &mut command, + &self.runtime_paths.codex_self_exe, + )?; + let request_file = windows::wrap_sandbox_exec_request( + &mut command, + &self.runtime_paths.codex_self_exe, + )?; return Ok(PreparedFsHelperCommand::with_windows_wrapper_request_file( command, request_file, @@ -180,12 +144,6 @@ impl FileSystemSandboxRunner { } } -struct FsHelperLaunchPaths { - sandboxed_helper: AbsolutePathBuf, - #[cfg(target_os = "windows")] - windows_wrapper: AbsolutePathBuf, -} - struct PreparedFsHelperCommand { request: SandboxExecRequest, #[cfg(target_os = "windows")] @@ -348,8 +306,25 @@ async fn run_command( command: PreparedFsHelperCommand, request_json: Vec, ) -> Result { - let output = run_child_command(command, request_json).await?; - if !output.success { + let PreparedFsHelperCommand { + request, + #[cfg(target_os = "windows")] + _windows_wrapper_request_file, + } = command; + let mut child = spawn_child_command(request)?; + let mut stdin = child + .stdin + .take() + .ok_or_else(|| internal_error("failed to open fs sandbox helper stdin".to_string()))?; + stdin.write_all(&request_json).await.map_err(io_error)?; + stdin.shutdown().await.map_err(io_error)?; + drop(stdin); + + let output = child.wait_with_output().await.map_err(io_error)?; + #[cfg(target_os = "windows")] + drop(_windows_wrapper_request_file); + + if !output.status.success() { return Err(internal_error(format!( "fs sandbox helper failed with status {status}: {stderr}", status = output.status, @@ -363,35 +338,6 @@ async fn run_command( } } -struct FsHelperCommandOutput { - success: bool, - status: String, - stdout: Vec, - stderr: Vec, -} - -async fn run_child_command( - command: PreparedFsHelperCommand, - request_json: Vec, -) -> Result { - let mut child = spawn_child_command(command.request)?; - let mut stdin = child - .stdin - .take() - .ok_or_else(|| internal_error("failed to open fs sandbox helper stdin".to_string()))?; - stdin.write_all(&request_json).await.map_err(io_error)?; - stdin.shutdown().await.map_err(io_error)?; - drop(stdin); - - let output = child.wait_with_output().await.map_err(io_error)?; - Ok(FsHelperCommandOutput { - success: output.status.success(), - status: output.status.to_string(), - stdout: output.stdout, - stderr: output.stderr, - }) -} - fn spawn_child_command( SandboxExecRequest { command: argv, @@ -450,7 +396,6 @@ mod tests { use crate::ExecServerRuntimePaths; use super::FileSystemSandboxRunner; - use super::FsHelperLaunchPaths; use super::add_helper_runtime_permissions; use super::helper_env; use super::helper_env_from_vars; @@ -618,14 +563,8 @@ mod tests { let permission_profile = PermissionProfile::from_runtime_permissions(&file_system_policy, network_policy); let sandbox_context = sandbox_context_with_cwd(&file_system_policy, cwd.clone()); - let helper_paths = FsHelperLaunchPaths { - sandboxed_helper: runner.runtime_paths.codex_self_exe.clone(), - #[cfg(target_os = "windows")] - windows_wrapper: runner.runtime_paths.codex_self_exe.clone(), - }; - let request = runner - .sandbox_exec_request(&permission_profile, &cwd, &sandbox_context, &helper_paths) + .sandbox_exec_request(&permission_profile, &cwd, &sandbox_context) .expect("sandbox exec request"); assert_eq!(request.request.env.get(&path_key), Some(&path)); diff --git a/codex-rs/exec-server/src/fs_sandbox_windows.rs b/codex-rs/exec-server/src/fs_sandbox_windows.rs index 184cf78494..7d64988880 100644 --- a/codex-rs/exec-server/src/fs_sandbox_windows.rs +++ b/codex-rs/exec-server/src/fs_sandbox_windows.rs @@ -6,9 +6,33 @@ use codex_sandboxing::SandboxExecRequest; use codex_utils_absolute_path::AbsolutePathBuf; use crate::rpc::internal_error; +use crate::rpc::invalid_request; const WINDOWS_SANDBOX_WRAPPER_SETUP_ENV_ALLOWLIST: &[&str] = &["USERNAME", "USERPROFILE"]; +pub(super) fn materialize_sandboxed_helper( + request: &mut SandboxExecRequest, + source: &AbsolutePathBuf, +) -> Result<(), JSONRPCErrorError> { + let codex_home = codex_utils_home_dir::find_codex_home().map_err(|err| { + internal_error(format!( + "windows fs sandbox helper failed to resolve CODEX_HOME: {err}" + )) + })?; + let helper = + codex_windows_sandbox::resolve_exe_for_launch(source.as_path(), codex_home.as_path()); + let helper = AbsolutePathBuf::from_absolute_path(helper.as_path()).map_err(|err| { + internal_error(format!( + "windows fs sandbox helper path is not absolute: {err}" + )) + })?; + let Some(program) = request.command.first_mut() else { + return Err(invalid_request("fs sandbox command was empty".to_string())); + }; + *program = helper.as_path().to_string_lossy().into_owned(); + Ok(()) +} + pub(super) fn wrap_sandbox_exec_request( request: &mut SandboxExecRequest, helper: &AbsolutePathBuf, @@ -136,17 +160,48 @@ impl Drop for WindowsSandboxWrapperRequestFile { mod tests { use std::collections::HashMap; use std::ffi::OsString; + use std::path::PathBuf; use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::models::PermissionProfile; + use codex_protocol::permissions::FileSystemSandboxPolicy; use codex_protocol::permissions::NetworkSandboxPolicy; + use codex_sandboxing::SandboxExecRequest; + use codex_sandboxing::SandboxType; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; use super::WindowsSandboxWrapperRequestFile; use super::add_wrapper_setup_env_from_vars; + use super::materialize_sandboxed_helper; use super::wrapper_request_dir; + struct EnvVarGuard { + key: &'static str, + original: Option, + } + + impl EnvVarGuard { + fn set(key: &'static str, value: &std::ffi::OsStr) -> Self { + let original = std::env::var_os(key); + unsafe { + std::env::set_var(key, value); + } + Self { key, original } + } + } + + impl Drop for EnvVarGuard { + fn drop(&mut self) { + unsafe { + match &self.original { + Some(value) => std::env::set_var(self.key, value), + None => std::env::remove_var(self.key), + } + } + } + } + #[test] fn wrapper_setup_env_preserves_only_setup_identity() { let mut env = HashMap::from([("PATH".to_string(), r"C:\Windows\System32".to_string())]); @@ -209,4 +264,90 @@ mod tests { assert!(!path.exists()); } + + #[test] + fn materialized_helper_rewrites_inner_command_path() { + let codex_home = tempfile::TempDir::new().expect("codex home"); + let _guard = EnvVarGuard::set("CODEX_HOME", codex_home.path().as_os_str()); + let helper_dir = tempfile::TempDir::new().expect("helper dir"); + let configured_helper = helper_dir.path().join("configured-codex-helper.exe"); + std::fs::write(&configured_helper, b"helper").expect("write configured helper"); + let configured_helper = + AbsolutePathBuf::from_absolute_path(&configured_helper).expect("absolute helper"); + let cwd = AbsolutePathBuf::from_absolute_path(helper_dir.path()).expect("absolute cwd"); + let file_system_sandbox_policy = FileSystemSandboxPolicy::read_only(); + let mut request = SandboxExecRequest { + command: vec![ + configured_helper.as_path().display().to_string(), + "--codex-run-as-fs-helper".to_string(), + ], + cwd, + env: HashMap::new(), + network: None, + sandbox: SandboxType::WindowsRestrictedToken, + windows_sandbox_level: WindowsSandboxLevel::RestrictedToken, + windows_sandbox_private_desktop: false, + permission_profile: PermissionProfile::read_only(), + file_system_sandbox_policy, + network_sandbox_policy: NetworkSandboxPolicy::Restricted, + arg0: None, + }; + + materialize_sandboxed_helper(&mut request, &configured_helper) + .expect("materialize sandboxed helper"); + + let materialized_helper = PathBuf::from(&request.command[0]); + assert_eq!( + materialized_helper.file_name(), + configured_helper.as_path().file_name() + ); + assert_eq!( + materialized_helper + .parent() + .and_then(std::path::Path::file_name), + Some(std::ffi::OsStr::new(".sandbox-bin")) + ); + assert!(materialized_helper.exists()); + } + + #[test] + fn wrapper_request_preserves_elevated_level() { + let codex_home = tempfile::TempDir::new().expect("codex home"); + let _guard = EnvVarGuard::set("CODEX_HOME", codex_home.path().as_os_str()); + let command_cwd = + AbsolutePathBuf::from_absolute_path(codex_home.path()).expect("absolute command cwd"); + let file_system_sandbox_policy = FileSystemSandboxPolicy::read_only(); + let mut request = SandboxExecRequest { + command: vec![ + "helper.exe".to_string(), + "--codex-run-as-fs-helper".to_string(), + ], + cwd: command_cwd, + env: HashMap::new(), + network: None, + sandbox: SandboxType::WindowsRestrictedToken, + windows_sandbox_level: WindowsSandboxLevel::Elevated, + windows_sandbox_private_desktop: true, + permission_profile: PermissionProfile::read_only(), + file_system_sandbox_policy, + network_sandbox_policy: NetworkSandboxPolicy::Restricted, + arg0: None, + }; + let wrapper = AbsolutePathBuf::from_absolute_path(codex_home.path().join("codex.exe")) + .expect("absolute wrapper"); + + let request_file = super::wrap_sandbox_exec_request(&mut request, &wrapper) + .expect("wrap sandbox exec request"); + let wrapper_request: codex_windows_sandbox::WindowsSandboxWrapperRequest = + serde_json::from_slice( + &std::fs::read(&request_file.path).expect("read wrapper request"), + ) + .expect("decode wrapper request"); + + assert_eq!( + wrapper_request.windows_sandbox_level, + WindowsSandboxLevel::Elevated + ); + assert_eq!(wrapper_request.windows_sandbox_private_desktop, true); + } }