Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Align Windows sandbox temp permissions with the child environment (#51512)

zm-oai7efc49b25858
diff --git a/codex-rs/core/src/exec_tests.rs b/codex-rs/core/src/exec_tests.rs
index 710c23935c..db07135e3b 100644
--- a/codex-rs/core/src/exec_tests.rs
+++ b/codex-rs/core/src/exec_tests.rs
@@ -886,6 +886,7 @@ fn windows_elevated_supports_split_restricted_read_roots() {
&permission_profile,
&temp_dir.path().abs(),
/*use_windows_elevated_backend*/ true,
+ &std::collections::HashMap::new(),
),
Ok(Some(WindowsSandboxFilesystemOverrides {
read_roots_override: Some(vec![expected_docs]),
@@ -939,6 +940,7 @@ fn windows_elevated_supports_split_write_read_carveouts() {
&permission_profile,
&temp_dir.path().abs(),
/*use_windows_elevated_backend*/ true,
+ &std::collections::HashMap::new(),
),
Ok(Some(WindowsSandboxFilesystemOverrides {
read_roots_override: None,
@@ -965,6 +967,7 @@ fn windows_workspace_defaults_do_not_hide_explicit_metadata_carveouts() {
&default_profile,
&cwd,
/*use_windows_elevated_backend*/ true,
+ &std::collections::HashMap::new(),
)
.expect("resolve workspace defaults");
assert!(
@@ -992,6 +995,7 @@ fn windows_workspace_defaults_do_not_hide_explicit_metadata_carveouts() {
&explicit_profile,
&cwd,
/*use_windows_elevated_backend*/ true,
+ &std::collections::HashMap::new(),
)
.expect("resolve explicit metadata carveout")
.expect("explicit metadata carveout needs an override");
@@ -1041,6 +1045,7 @@ fn windows_elevated_supports_unreadable_split_carveouts() {
&permission_profile,
&temp_dir.path().abs(),
/*use_windows_elevated_backend*/ true,
+ &std::collections::HashMap::new(),
),
Ok(Some(WindowsSandboxFilesystemOverrides {
read_roots_override: None,
@@ -1102,6 +1107,7 @@ fn windows_elevated_supports_unreadable_globs() {
&permission_profile,
&temp_dir.path().abs(),
/*use_windows_elevated_backend*/ true,
+ &std::collections::HashMap::new(),
),
Ok(Some(WindowsSandboxFilesystemOverrides {
read_roots_override: None,
diff --git a/codex-rs/core/src/sandboxing/mod.rs b/codex-rs/core/src/sandboxing/mod.rs
index 43003e8ad0..69f6ff9044 100644
--- a/codex-rs/core/src/sandboxing/mod.rs
+++ b/codex-rs/core/src/sandboxing/mod.rs
@@ -149,6 +149,7 @@ impl ExecRequest {
&permission_profile,
&sandbox_policy_cwd,
use_windows_elevated_backend,
+ &env,
)
} else {
resolve_windows_restricted_token_filesystem_overrides(
diff --git a/codex-rs/core/tests/suite/windows_sandbox.rs b/codex-rs/core/tests/suite/windows_sandbox.rs
index 8afde91cda..006913e4d4 100644
--- a/codex-rs/core/tests/suite/windows_sandbox.rs
+++ b/codex-rs/core/tests/suite/windows_sandbox.rs
@@ -25,6 +25,13 @@ use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::ReviewDecision;
use codex_protocol::user_input::UserInput;
+use codex_sandboxing::SandboxCommand;
+use codex_sandboxing::SandboxDirectSpawnTransformRequest;
+use codex_sandboxing::SandboxManager;
+use codex_sandboxing::SandboxTransformRequest;
+use codex_sandboxing::SandboxType;
+use codex_sandboxing::WindowsSandboxProxySettingsMode;
+use codex_utils_path_uri::PathUri;
use codex_windows_sandbox_test_support::WindowsSandboxAccountTestGuard;
use core_test_support::PathExt;
use core_test_support::responses::ev_assistant_message;
@@ -402,6 +409,190 @@ async fn windows_restricted_token_rejects_exact_and_glob_deny_read_policy() -> a
Ok(())
}
+#[tokio::test]
+#[serial(codex_home)]
+async fn windows_elevated_temp_only_core_and_direct_spawn_enforce_carveouts() -> anyhow::Result<()>
+{
+ let _account_guard = WindowsSandboxAccountTestGuard::acquire()?;
+ let codex_home = codex_home_for_windows_sandbox_test("windows-temp-only-child-codex-home")?;
+ let _codex_home_guard = EnvVarGuard::set("CODEX_HOME", codex_home.path().as_os_str());
+ stage_windows_sandbox_helpers()?;
+ let fixture = TempDir::new()?;
+ let root = dunce::canonicalize(fixture.path())?;
+ let (codex, _) = stage_windows_sandbox_cli(&root.join("bin"))?;
+ let cwd = root.join("work").abs();
+ let temp = root.join("selected-temp");
+ let other = root.join("other-temp");
+ let read_only = temp.join("read-only");
+ let denied = temp.join("denied");
+ for path in [
+ cwd.as_path(),
+ other.as_path(),
+ read_only.as_path(),
+ denied.as_path(),
+ ] {
+ std::fs::create_dir_all(path)?;
+ }
+ std::fs::write(read_only.join("public.txt"), "READ-CONTROL\n")?;
+ std::fs::write(denied.join("secret.txt"), "SECRET-CONTROL\n")?;
+ let permission_profile = PermissionProfile::from_runtime_permissions(
+ &FileSystemSandboxPolicy::restricted(vec![
+ FileSystemSandboxEntry::new(
+ FileSystemPath::Special {
+ value: FileSystemSpecialPath::Root,
+ },
+ FileSystemAccessMode::Read,
+ ),
+ FileSystemSandboxEntry::new(
+ FileSystemPath::Special {
+ value: FileSystemSpecialPath::Tmpdir,
+ },
+ FileSystemAccessMode::Write,
+ ),
+ FileSystemSandboxEntry::new(read_only.clone().abs().into(), FileSystemAccessMode::Read),
+ FileSystemSandboxEntry::new(denied.clone().abs().into(), FileSystemAccessMode::Deny),
+ ]),
+ NetworkSandboxPolicy::Restricted,
+ );
+ let command = concat!(
+ "echo allowed>%ALLOWED_FILE% 2>NUL & ",
+ "echo wrong>%OTHER_FILE% 2>NUL & ",
+ "echo wrong>cwd.txt 2>NUL & ",
+ "type %PUBLIC_FILE% 2>NUL & ",
+ "echo wrong>%READONLY_FILE% 2>NUL & ",
+ "type %SECRET_FILE% 2>NUL & ",
+ "echo wrong>%DENIED_FILE% 2>NUL & exit /b 0"
+ );
+ // Cover duplicate TEMP through Core and a lone mixed-case TMP through the
+ // actual direct-spawn wrapper. In both cases the child's value must match its grant.
+ for direct_spawn in [false, true] {
+ // As in the deny-read test below, put quoted paths in the environment
+ // rather than in cmd /C's argument: the Win32 argv encoder escapes
+ // literal argument quotes for CRT parsing, which cmd does not use.
+ let mut env: HashMap<String, String> = [
+ ("ALLOWED_FILE", temp.join("allowed.txt")),
+ ("OTHER_FILE", other.join("wrong.txt")),
+ ("PUBLIC_FILE", read_only.join("public.txt")),
+ ("READONLY_FILE", read_only.join("wrong.txt")),
+ ("SECRET_FILE", denied.join("secret.txt")),
+ ("DENIED_FILE", denied.join("wrong.txt")),
+ ]
+ .into_iter()
+ .map(|(name, path)| (name.to_string(), format!("\"{}\"", path.display())))
+ .collect();
+ let child_var = if direct_spawn {
+ env.insert("tMp".to_string(), temp.to_string_lossy().into_owned());
+ "%TMP%"
+ } else {
+ env.insert("Temp".to_string(), other.to_string_lossy().into_owned());
+ env.insert("TEMP".to_string(), temp.to_string_lossy().into_owned());
+ "%TEMP%"
+ };
+ let command = format!("echo CHILD-TEMP:{child_var} & {command}");
+ let (exit_code, stdout, stderr) = if direct_spawn {
+ let cwd_uri = PathUri::from_abs_path(&cwd);
+ let request = SandboxManager::new().transform_for_direct_spawn(
+ SandboxDirectSpawnTransformRequest {
+ workspace_roots: std::slice::from_ref(&cwd),
+ windows_sandbox_proxy_settings_mode: WindowsSandboxProxySettingsMode::Preserve,
+ transform: SandboxTransformRequest {
+ command: SandboxCommand {
+ program: "cmd.exe".into(),
+ args: vec!["/D".into(), "/C".into(), command],
+ cwd: cwd_uri.clone(),
+ env,
+ managed_network: None,
+ additional_permissions: None,
+ },
+ permissions: &permission_profile,
+ sandbox: SandboxType::WindowsRestrictedToken,
+ enforce_managed_network: false,
+ environment_id: None,
+ network: None,
+ sandbox_policy_cwd: &cwd_uri,
+ sandbox_exe: Some(codex.as_path()),
+ use_legacy_landlock: false,
+ windows_sandbox_level: WindowsSandboxLevel::Elevated,
+ },
+ },
+ )?;
+ let output = Command::new(&request.command[0])
+ .args(&request.command[1..])
+ .current_dir(request.cwd.to_abs_path()?)
+ .env_clear()
+ .envs(&request.env)
+ .output()?;
+ (
+ output.status.code().unwrap_or(-1),
+ String::from_utf8_lossy(&output.stdout).into_owned(),
+ String::from_utf8_lossy(&output.stderr).into_owned(),
+ )
+ } else {
+ let output = process_exec_tool_call(
+ ExecParams {
+ command: vec!["cmd.exe".into(), "/D".into(), "/C".into(), command],
+ cwd: cwd.clone(),
+ expiration: 30_000.into(),
+ capture_policy: ExecCapturePolicy::ShellTool,
+ env,
+ network: None,
+ network_environment_id: None,
+ sandbox_permissions: SandboxPermissions::UseDefault,
+ windows_sandbox_level: WindowsSandboxLevel::Elevated,
+ justification: None,
+ arg0: None,
+ },
+ &permission_profile,
+ &cwd,
+ std::slice::from_ref(&cwd),
+ &None,
+ /*codex_self_exe*/ &None,
+ /*use_legacy_landlock*/ false,
+ /*stdout_stream*/ None,
+ )
+ .await?;
+ (output.exit_code, output.stdout.text, output.stderr.text)
+ };
+ assert_eq!(
+ exit_code, 0,
+ "direct_spawn={direct_spawn}: {stdout} {stderr}"
+ );
+ let expected_temp = format!("CHILD-TEMP:{}", temp.display());
+ assert!(
+ stdout
+ .lines()
+ .any(|line| line.trim().eq_ignore_ascii_case(&expected_temp)),
+ "child TEMP did not match granted directory, direct_spawn={direct_spawn}: {stdout} {stderr}"
+ );
+ assert!(
+ stdout.contains("READ-CONTROL"),
+ "direct_spawn={direct_spawn}: {stdout} {stderr}"
+ );
+ assert!(
+ !stdout.contains("SECRET-CONTROL"),
+ "direct_spawn={direct_spawn}: {stdout} {stderr}"
+ );
+ assert_eq!(
+ std::fs::read_to_string(temp.join("allowed.txt"))?.trim(),
+ "allowed"
+ );
+ for path in [
+ other.join("wrong.txt"),
+ cwd.join("cwd.txt").into_path_buf(),
+ read_only.join("wrong.txt"),
+ denied.join("wrong.txt"),
+ ] {
+ assert!(
+ !path.exists(),
+ "direct_spawn={direct_spawn}: unexpectedly wrote {}",
+ path.display()
+ );
+ }
+ std::fs::remove_file(temp.join("allowed.txt"))?;
+ }
+ Ok(())
+}
+
#[tokio::test]
#[serial(codex_home)]
async fn windows_elevated_does_not_create_missing_workspace_metadata() -> anyhow::Result<()> {
diff --git a/codex-rs/exec-server/src/process_sandbox.rs b/codex-rs/exec-server/src/process_sandbox.rs
index fd2c89ee16..8c81ce5ec5 100644
--- a/codex-rs/exec-server/src/process_sandbox.rs
+++ b/codex-rs/exec-server/src/process_sandbox.rs
@@ -310,6 +310,7 @@ pub(crate) async fn prepare_exec_request_with_telemetry(
&permissions,
&native_sandbox_policy_cwd,
use_elevated,
+ &request.env,
)
} else {
resolve_windows_restricted_token_filesystem_overrides(
diff --git a/codex-rs/exec-server/tests/exec_process/windows_sandbox.rs b/codex-rs/exec-server/tests/exec_process/windows_sandbox.rs
index 01f7f90abd..3a5ceb9e3d 100644
--- a/codex-rs/exec-server/tests/exec_process/windows_sandbox.rs
+++ b/codex-rs/exec-server/tests/exec_process/windows_sandbox.rs
@@ -1,6 +1,8 @@
//! Shared Windows sandbox behavior over the real exec-server RPC connection.
use super::*;
+use codex_exec_server::ExecEnvPolicy;
+use codex_protocol::config_types::ShellEnvironmentPolicyInherit;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
@@ -77,11 +79,45 @@ async fn powershell_alias_falls_back_without_primary_runtime_over_rpc(
Ok(())
}
+#[test_case::test_case(WindowsSandboxSelection::Mxc, codex_sandboxing::SandboxType::WindowsMxc; "mxc")]
+#[test_case::test_case(WindowsSandboxSelection::Elevated, codex_sandboxing::SandboxType::WindowsRestrictedToken; "elevated")]
#[cfg_attr(not(windows), ignore = "requires a native Windows sandbox")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial_test::serial(remote_exec_server)]
-async fn mxc_tmpdir_uses_command_environment_over_rpc() -> Result<()> {
- crate::skip_if_mxc_unavailable!(Ok(()));
+async fn tmpdir_uses_command_environment_over_rpc(
+ selection: WindowsSandboxSelection,
+ expected_type: codex_sandboxing::SandboxType,
+) -> Result<()> {
+ if selection == WindowsSandboxSelection::Mxc {
+ crate::skip_if_mxc_unavailable!(Ok(()));
+ }
+ #[cfg(windows)]
+ let _account_guard = if selection == WindowsSandboxSelection::Elevated {
+ let guard = codex_windows_sandbox_test_support::WindowsSandboxAccountTestGuard::acquire()?;
+ // The RPC server re-enters this test executable, as in file_system_windows.
+ let executable = std::env::current_exe()?;
+ let resources = executable
+ .parent()
+ .context("Windows test executable should have a parent directory")?
+ .join("codex-resources");
+ if let Err(error) = std::fs::create_dir_all(&resources)
+ && !(error.kind() == std::io::ErrorKind::PermissionDenied && resources.is_dir())
+ {
+ return Err(error).context("create Windows sandbox test resources");
+ }
+ for name in ["codex-windows-sandbox-setup", "codex-command-runner"] {
+ let source = codex_utils_cargo_bin::cargo_bin(name)?;
+ let destination = resources.join(std::path::Path::new(name).with_extension("exe"));
+ if let Err(error) = codex_utils_cargo_bin::copy_executable(&source, &destination)
+ && !(error.kind() == std::io::ErrorKind::PermissionDenied && destination.is_file())
+ {
+ return Err(error).with_context(|| format!("stage Windows sandbox helper {name}"));
+ }
+ }
+ Some(guard)
+ } else {
+ None
+ };
let root = TempDir::new()?;
let command_temp = root.path().join("command temp");
let server_temp = root.path().join("server temp");
@@ -117,8 +153,30 @@ async fn mxc_tmpdir_uses_command_environment_over_rpc() -> Result<()> {
PermissionProfile::from_runtime_permissions(&fs, NetworkSandboxPolicy::Restricted),
cwd.clone(),
);
- sandbox.windows_sandbox_selection = codex_exec_server::WindowsSandboxSelection::Mxc;
- let command_temp = command_temp.to_string_lossy().into_owned();
+ sandbox.windows_sandbox_selection = selection;
+ let env = HashMap::from([
+ ("SystemRoot".to_owned(), std::env::var("SystemRoot")?),
+ (
+ "ALLOWED_FILE".to_owned(),
+ format!("\"{}\"", command_temp.join("allowed.txt").display()),
+ ),
+ (
+ "OUTSIDE_FILE".to_owned(),
+ format!("\"{}\"", outside.display()),
+ ),
+ ]);
+ // Raw params have no TEMP. The executor must finish the env policy before
+ // resolving permissions. No inheritance: omitted TMP must not grant server_temp.
+ let mut configured_temp = HashMap::from([(
+ "TEMP".to_owned(),
+ command_temp.to_string_lossy().into_owned(),
+ )]);
+ if selection == WindowsSandboxSelection::Mxc {
+ configured_temp.insert(
+ "TMP".to_owned(),
+ command_temp.to_string_lossy().into_owned(),
+ );
+ }
let started = environment
.get_exec_backend()
.start(ExecParams {
@@ -129,19 +187,18 @@ async fn mxc_tmpdir_uses_command_environment_over_rpc() -> Result<()> {
"/D".to_owned(),
"/S".to_owned(),
"/C".to_owned(),
- format!(
- "echo allowed>\"%TEMP%\\allowed.txt\" & 2>\"%TEMP%\\denied.txt\" echo modified>\"{}\" & exit /b 0",
- outside.display()
- ),
+ "echo CHILD-TEMP:%TEMP% & echo allowed>%ALLOWED_FILE% & echo modified>%OUTSIDE_FILE% & exit /b 0".to_owned(),
],
cwd,
- env_policy: None,
+ env_policy: Some(ExecEnvPolicy {
+ inherit: ShellEnvironmentPolicyInherit::None,
+ ignore_default_excludes: false,
+ exclude: Vec::new(),
+ r#set: configured_temp,
+ include_only: Vec::new(),
+ }),
shell_snapshot: None,
- env: HashMap::from([
- ("SystemRoot".to_owned(), std::env::var("SystemRoot")?),
- ("TEMP".to_owned(), command_temp.clone()),
- ("TMP".to_owned(), command_temp),
- ]),
+ env,
tty: false,
pipe_stdin: false,
arg0: None,
@@ -151,21 +208,24 @@ async fn mxc_tmpdir_uses_command_environment_over_rpc() -> Result<()> {
network_proxy: None,
})
.await?;
+ assert_eq!(started.sandbox_type, Some(expected_type));
+ let (stdout, stderr, code, exited) = collect_process_output_from_events_with_timeout(
+ started.process,
+ Duration::from_secs(/*secs*/ 30),
+ )
+ .await?;
assert_eq!(
- started.sandbox_type,
- Some(codex_sandboxing::SandboxType::WindowsMxc)
- );
- assert_eq!(
- collect_process_output_from_events_with_timeout(
- started.process,
- Duration::from_secs(/*secs*/ 30),
- )
- .await?,
- (String::new(), String::new(), Some(0), true)
+ (stdout.trim(), code, exited),
+ (
+ format!("CHILD-TEMP:{}", command_temp.display()).as_str(),
+ Some(0),
+ true
+ ),
+ "unexpected launch result, stderr: {stderr}"
);
assert_eq!(
(
- std::fs::read_to_string(root.path().join("command temp").join("allowed.txt"))?
+ std::fs::read_to_string(command_temp.join("allowed.txt"))?
.trim_end()
.to_owned(),
std::fs::read_to_string(outside)?
diff --git a/codex-rs/sandboxing/src/manager.rs b/codex-rs/sandboxing/src/manager.rs
index 2bdcecfc52..540754116c 100644
--- a/codex-rs/sandboxing/src/manager.rs
+++ b/codex-rs/sandboxing/src/manager.rs
@@ -582,15 +582,19 @@ impl SandboxManager {
) -> Result<SandboxExecRequest, SandboxTransformError> {
let workspace_roots = request.workspace_roots;
let proxy_settings_mode = request.windows_sandbox_proxy_settings_mode;
+ let sandbox_exe = request.transform.sandbox_exe.ok_or_else(|| {
+ SandboxTransformError::WindowsSandboxPreparation(
+ "missing Codex executable path".to_string(),
+ )
+ })?;
let mut request = self.transform(request.transform)?;
- if request.sandbox == SandboxType::WindowsRestrictedToken {
- wrap_windows_sandbox_exec_request_for_direct_spawn(
- &mut request,
- workspace_roots,
- codex_home,
- proxy_settings_mode,
- )?;
- }
+ wrap_windows_sandbox_exec_request_for_direct_spawn(
+ &mut request,
+ workspace_roots,
+ codex_home,
+ sandbox_exe,
+ proxy_settings_mode,
+ )?;
Ok(request)
}
}
@@ -600,6 +604,7 @@ fn wrap_windows_sandbox_exec_request_for_direct_spawn(
request: &mut SandboxExecRequest,
workspace_roots: &[AbsolutePathBuf],
codex_home: &Path,
+ sandbox_exe: &Path,
proxy_settings_mode: codex_windows_sandbox::WindowsSandboxProxySettingsMode,
) -> Result<(), SandboxTransformError> {
// TODO(anp): Keep PathUri through the Windows sandbox wrapper boundary.
@@ -622,9 +627,12 @@ fn wrap_windows_sandbox_exec_request_for_direct_spawn(
"sandbox command was empty".to_string(),
));
};
- let source = std::path::PathBuf::from(&program);
- let helper = codex_windows_sandbox::resolve_exe_for_launch(source.as_path(), codex_home);
- *program = helper.to_string_lossy().into_owned();
+ // transform() may have made the inner command a Codex helper. Only that
+ // helper needs materializing; an arbitrary workload such as cmd.exe does not.
+ if Path::new(program.as_str()) == sandbox_exe {
+ let helper = codex_windows_sandbox::resolve_exe_for_launch(sandbox_exe, codex_home);
+ *program = helper.to_string_lossy().into_owned();
+ }
let inner_command = std::mem::take(&mut request.command);
let proxy_enforced = request.network.is_some();
@@ -648,6 +656,7 @@ fn wrap_windows_sandbox_exec_request_for_direct_spawn(
&request.permission_profile,
&native_sandbox_policy_cwd,
use_elevated,
+ &request.env,
)
} else {
resolve_windows_restricted_token_filesystem_overrides(
@@ -695,7 +704,11 @@ fn wrap_windows_sandbox_exec_request_for_direct_spawn(
.map_err(|err| SandboxTransformError::WindowsSandboxPreparation(err.to_string()))?;
request.command = Vec::with_capacity(1 + wrapper_args.len());
- request.command.push(source.to_string_lossy().into_owned());
+ // This outer process interprets Codex wrapper arguments, so it must be the
+ // supplied Codex executable even when the inner command is another program.
+ request
+ .command
+ .push(sandbox_exe.to_string_lossy().into_owned());
request.command.append(&mut wrapper_args);
request.sandbox = SandboxType::None;
request.arg0 = None;
diff --git a/codex-rs/sandboxing/src/manager_tests.rs b/codex-rs/sandboxing/src/manager_tests.rs
index 3daac3d45e..22dcf91632 100644
--- a/codex-rs/sandboxing/src/manager_tests.rs
+++ b/codex-rs/sandboxing/src/manager_tests.rs
@@ -764,7 +764,7 @@ fn transform_for_direct_spawn_windows_materializes_inner_helper() {
environment_id: None,
network: None,
sandbox_policy_cwd: &cwd_uri,
- sandbox_exe: None,
+ sandbox_exe: Some(configured_helper.as_path()),
use_legacy_landlock: false,
windows_sandbox_level: WindowsSandboxLevel::RestrictedToken,
},
diff --git a/codex-rs/sandboxing/src/windows.rs b/codex-rs/sandboxing/src/windows.rs
index b69168ca98..0f9df8191a 100644
--- a/codex-rs/sandboxing/src/windows.rs
+++ b/codex-rs/sandboxing/src/windows.rs
@@ -1,4 +1,5 @@
use std::collections::BTreeSet;
+use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
@@ -56,6 +57,7 @@ pub fn unsupported_windows_restricted_token_sandbox_reason(
permission_profile,
sandbox_policy_cwd,
windows_sandbox_level == WindowsSandboxLevel::Elevated,
+ &HashMap::new(),
)
.err()
} else {
@@ -215,6 +217,7 @@ pub fn resolve_windows_elevated_filesystem_overrides(
permission_profile: &PermissionProfile,
sandbox_policy_cwd: &AbsolutePathBuf,
use_windows_elevated_backend: bool,
+ workload_env: &HashMap<String, String>,
) -> std::result::Result<Option<WindowsSandboxFilesystemOverrides>, String> {
if sandbox != SandboxType::WindowsRestrictedToken || !use_windows_elevated_backend {
return Ok(None);
@@ -236,6 +239,14 @@ pub fn resolve_windows_elevated_filesystem_overrides(
// deny-write sentinels.
file_system_sandbox_policy.remove_skip_missing_path_entries();
+ #[cfg(target_os = "windows")]
+ codex_windows_sandbox::resolve_workload_temp_paths(
+ &mut file_system_sandbox_policy,
+ workload_env,
+ );
+ #[cfg(not(target_os = "windows"))]
+ let _ = workload_env;
+
let additional_deny_read_paths = codex_windows_sandbox::resolve_windows_deny_read_paths(
&file_system_sandbox_policy,
sandbox_policy_cwd,
@@ -399,3 +410,7 @@ fn has_reopened_writable_descendant(writable_roots: &[WritableRoot]) -> bool {
})
})
}
+
+#[cfg(all(test, target_os = "windows"))]
+#[path = "windows_tests.rs"]
+mod tests;
diff --git a/codex-rs/sandboxing/src/windows_tests.rs b/codex-rs/sandboxing/src/windows_tests.rs
new file mode 100644
index 0000000000..9525011e9f
--- /dev/null
+++ b/codex-rs/sandboxing/src/windows_tests.rs
@@ -0,0 +1,58 @@
+//! Windows temp override behavior not covered by a successful child launch.
+use super::*;
+use codex_protocol::permissions::FileSystemAccessMode;
+use codex_protocol::permissions::FileSystemPath;
+use codex_protocol::permissions::FileSystemSandboxEntry;
+use codex_protocol::permissions::FileSystemSpecialPath;
+use codex_protocol::permissions::NetworkSandboxPolicy;
+use pretty_assertions::assert_eq;
+
+#[test]
+fn elevated_non_write_temp_never_grants_write_access() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let cwd = AbsolutePathBuf::from_absolute_path(dir.path().join("work")).unwrap();
+ let temp = dir.path().join("temp");
+ std::fs::create_dir_all(cwd.as_path()).unwrap();
+ std::fs::create_dir_all(&temp).unwrap();
+ let env = HashMap::from([("Temp".into(), temp.to_string_lossy().into_owned())]);
+ for access in [FileSystemAccessMode::Read, FileSystemAccessMode::Deny] {
+ let profile = PermissionProfile::from_runtime_permissions(
+ &FileSystemSandboxPolicy::restricted(vec![
+ FileSystemSandboxEntry::new(
+ FileSystemPath::Special {
+ value: FileSystemSpecialPath::Root,
+ },
+ FileSystemAccessMode::Read,
+ ),
+ FileSystemSandboxEntry::new(
+ FileSystemPath::Special {
+ value: FileSystemSpecialPath::Tmpdir,
+ },
+ access,
+ ),
+ ]),
+ NetworkSandboxPolicy::Restricted,
+ );
+ let overrides = resolve_windows_elevated_filesystem_overrides(
+ SandboxType::WindowsRestrictedToken,
+ &profile,
+ &cwd,
+ true,
+ &env,
+ )
+ .unwrap();
+ let write_roots = overrides
+ .as_ref()
+ .and_then(|o| o.write_roots_override.as_ref());
+ assert!(write_roots.is_none_or(Vec::is_empty));
+ if access == FileSystemAccessMode::Deny {
+ assert_eq!(
+ overrides.unwrap().additional_deny_read_paths,
+ vec![
+ AbsolutePathBuf::from_absolute_path(dunce::canonicalize(&temp).unwrap())
+ .unwrap(),
+ ]
+ );
+ }
+ }
+}
diff --git a/codex-rs/windows-sandbox-rs/src/lib.rs b/codex-rs/windows-sandbox-rs/src/lib.rs
index 229836756a..0537e9cf9a 100644
--- a/codex-rs/windows-sandbox-rs/src/lib.rs
+++ b/codex-rs/windows-sandbox-rs/src/lib.rs
@@ -398,6 +398,8 @@ pub use resolved_permissions::ResolvedWindowsSandboxPermissions;
#[cfg(target_os = "windows")]
pub use resolved_permissions::WindowsSandboxTokenMode;
#[cfg(target_os = "windows")]
+pub use resolved_permissions::resolve_workload_temp_paths;
+#[cfg(target_os = "windows")]
pub use resolved_permissions::token_mode_for_permission_profile;
#[cfg(target_os = "windows")]
pub use runtime_ownership::APP_CORE_RUNNER_ALIAS;
diff --git a/codex-rs/windows-sandbox-rs/src/process.rs b/codex-rs/windows-sandbox-rs/src/process.rs
index e8049d6beb..36be9377d9 100644
--- a/codex-rs/windows-sandbox-rs/src/process.rs
+++ b/codex-rs/windows-sandbox-rs/src/process.rs
@@ -51,15 +51,8 @@ pub enum ConsoleMode {
}
pub fn make_env_block(env: &HashMap<String, String>) -> Vec<u16> {
- let mut items: Vec<(String, String)> =
- env.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
- items.sort_by(|a, b| {
- a.0.to_uppercase()
- .cmp(&b.0.to_uppercase())
- .then(a.0.cmp(&b.0))
- });
let mut w: Vec<u16> = Vec::new();
- for (k, v) in items {
+ for (k, v) in ordered_env_entries(env) {
let mut s = to_wide(format!("{k}={v}"));
s.pop();
w.extend_from_slice(&s);
@@ -69,6 +62,23 @@ pub fn make_env_block(env: &HashMap<String, String>) -> Vec<u16> {
w
}
+// Match the environment we actually serialize, including for callers which
+// supply multiple spellings of a Windows key. Keep the first spelling in the
+// existing block order instead of letting HashMap iteration pick the value.
+pub(crate) fn ordered_env_entries(env: &HashMap<String, String>) -> Vec<(&str, &str)> {
+ let mut items: Vec<(&str, &str)> = env
+ .iter()
+ .map(|(key, value)| (key.as_str(), value.as_str()))
+ .collect();
+ items.sort_by(|a, b| {
+ a.0.to_uppercase()
+ .cmp(&b.0.to_uppercase())
+ .then(a.0.cmp(b.0))
+ });
+ items.dedup_by(|a, b| a.0.eq_ignore_ascii_case(b.0));
+ items
+}
+
unsafe fn ensure_inheritable_stdio(si: &mut STARTUPINFOW) -> Result<()> {
for kind in [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] {
let h = GetStdHandle(kind);
diff --git a/codex-rs/windows-sandbox-rs/src/resolved_permissions.rs b/codex-rs/windows-sandbox-rs/src/resolved_permissions.rs
index 392dd5fc0d..12e24d94a3 100644
--- a/codex-rs/windows-sandbox-rs/src/resolved_permissions.rs
+++ b/codex-rs/windows-sandbox-rs/src/resolved_permissions.rs
@@ -156,19 +156,8 @@ impl ResolvedWindowsSandboxPermissions {
env_map: &HashMap<String, String>,
) -> Vec<WindowsWritableRoot> {
let mut file_system = self.file_system.clone();
+ resolve_workload_temp_paths(&mut file_system, env_map);
file_system
- .entries
- .retain(|FileSystemSandboxEntry { path, .. }| {
- !matches!(
- path,
- FileSystemPath::Special {
- value: codex_protocol::permissions::FileSystemSpecialPath::Tmpdir
- | codex_protocol::permissions::FileSystemSpecialPath::SlashTmp,
- }
- )
- });
-
- let mut roots = file_system
.get_writable_roots_with_cwd(cwd)
.into_iter()
.map(|root| WindowsWritableRoot {
@@ -179,46 +168,43 @@ impl ResolvedWindowsSandboxPermissions {
.map(AbsolutePathBuf::into_path_buf)
.collect(),
})
- .collect::<Vec<_>>();
-
- if self.has_writable_tmpdir_entry() {
- roots.extend(windows_temp_env_roots(env_map).into_iter().map(|root| {
- WindowsWritableRoot {
- root,
- read_only_subpaths: Vec::new(),
- }
- }));
- }
-
- roots
- }
-
- fn has_writable_tmpdir_entry(&self) -> bool {
- self.file_system
- .entries
- .iter()
- .any(|FileSystemSandboxEntry { path, access, .. }| {
- matches!(
- path,
- FileSystemPath::Special {
- value: codex_protocol::permissions::FileSystemSpecialPath::Tmpdir,
- }
- ) && access.can_write()
- })
+ .collect()
}
}
-fn windows_temp_env_roots(env_map: &HashMap<String, String>) -> Vec<PathBuf> {
- ["TEMP", "TMP"]
+/// Replace `:tmpdir` with absolute TEMP/TMP paths from the completed Windows
+/// workload environment. Use the same key order as the child's environment
+/// block; never use host TEMP/TMP. Preserve access and missing-path rules so
+/// the ordinary policy evaluator still handles read/deny carveouts.
+pub fn resolve_workload_temp_paths(
+ file_system: &mut FileSystemSandboxPolicy,
+ workload_env: &HashMap<String, String>,
+) {
+ use codex_protocol::permissions::FileSystemSpecialPath;
+
+ file_system.entries = std::mem::take(&mut file_system.entries)
.into_iter()
- .filter_map(|key| {
- env_map
- .get(key)
- .map(|value| PathBuf::from(value.as_str()))
- .or_else(|| std::env::var_os(key).map(PathBuf::from))
+ .flat_map(|entry| match &entry.path {
+ FileSystemPath::Special {
+ value: FileSystemSpecialPath::Tmpdir,
+ } => crate::process::ordered_env_entries(workload_env)
+ .into_iter()
+ .filter(|(key, value)| {
+ (key.eq_ignore_ascii_case("TEMP") || key.eq_ignore_ascii_case("TMP"))
+ && Path::new(value).is_absolute()
+ })
+ .filter_map(|(_, value)| AbsolutePathBuf::from_absolute_path(value).ok())
+ .map(|path| FileSystemSandboxEntry {
+ path: path.into(),
+ ..entry.clone()
+ })
+ .collect(),
+ FileSystemPath::Special {
+ value: FileSystemSpecialPath::SlashTmp,
+ } => Vec::new(),
+ _ => vec![entry],
})
- .filter(|path| path.is_absolute())
- .collect()
+ .collect();
}
#[cfg(test)]
@@ -269,7 +255,7 @@ mod tests {
.collect::<std::collections::HashSet<_>>();
let expected_roots = [
- temp_dir,
+ dunce::canonicalize(&temp_dir).expect("canonicalize temp dir"),
dunce::canonicalize(&cwd).expect("canonicalize cwd"),
]
.into_iter()
@@ -278,6 +264,90 @@ mod tests {
assert_eq!(expected_roots, roots);
}
+ #[test]
+ fn explicit_empty_or_missing_override_does_not_fall_back_to_temp() {
+ let dir = TempDir::new().unwrap();
+ let cwd = dir.path().join("work");
+ let codex_home = dir.path().join("codex-home");
+ let temp = dir.path().join("temp");
+ for path in [&cwd, &codex_home, &temp] {
+ std::fs::create_dir_all(path).unwrap();
+ }
+ let env = HashMap::from([("Temp".into(), temp.to_string_lossy().into_owned())]);
+ let profile = permission_profile_with_entries(vec![
+ FileSystemSandboxEntry::new(
+ FileSystemPath::Special {
+ value: FileSystemSpecialPath::Root,
+ },
+ FileSystemAccessMode::Read,
+ ),
+ FileSystemSandboxEntry::new(
+ FileSystemPath::Special {
+ value: FileSystemSpecialPath::Tmpdir,
+ },
+ FileSystemAccessMode::Write,
+ ),
+ ]);
+ let permissions =
+ ResolvedWindowsSandboxPermissions::try_from_permission_profile(&profile).unwrap();
+ assert_eq!(
+ token_mode_for_permission_profile(&profile, &[], &cwd, &env).unwrap(),
+ WindowsSandboxTokenMode::WritableRootsCapability
+ );
+ for overrides in [vec![], vec![dir.path().join("missing")]] {
+ assert!(
+ crate::setup::effective_write_roots_for_permissions(
+ &permissions,
+ &cwd,
+ &env,
+ &codex_home,
+ Some(&overrides)
+ )
+ .is_empty(),
+ "invalid override {overrides:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn unavailable_windows_temp_never_creates_write_capabilities() {
+ let dir = TempDir::new().unwrap();
+ let cwd = dir.path().join("work");
+ std::fs::create_dir_all(&cwd).unwrap();
+ let profile = permission_profile_with_entries(vec![
+ FileSystemSandboxEntry::new(
+ FileSystemPath::Special {
+ value: FileSystemSpecialPath::Root,
+ },
+ FileSystemAccessMode::Read,
+ ),
+ FileSystemSandboxEntry::new(
+ FileSystemPath::Special {
+ value: FileSystemSpecialPath::Tmpdir,
+ },
+ FileSystemAccessMode::Write,
+ ),
+ FileSystemSandboxEntry::new(
+ FileSystemPath::Special {
+ value: FileSystemSpecialPath::SlashTmp,
+ },
+ FileSystemAccessMode::Write,
+ ),
+ ]);
+ let explicit_empty = HashMap::from([
+ ("TEMP".into(), String::new()),
+ ("TMP".into(), "relative".into()),
+ ]);
+ assert_eq!(
+ token_mode_for_permission_profile(&profile, &[], &cwd, &explicit_empty).unwrap(),
+ WindowsSandboxTokenMode::ReadOnlyCapability
+ );
+ assert_eq!(
+ token_mode_for_permission_profile(&profile, &[], &cwd, &HashMap::new()).unwrap(),
+ WindowsSandboxTokenMode::ReadOnlyCapability
+ );
+ }
+
#[test]
fn permission_profile_workspace_root_uses_runtime_workspace_roots() {
let tmp = TempDir::new().expect("tempdir");