windows sandbox: hint when PATH binary is blocked

This commit is contained in:
David Wiesen
2026-06-15 11:14:12 -07:00
parent dfd03ea01b
commit 086d21dc63
3 changed files with 232 additions and 0 deletions
+148
View File
@@ -43,6 +43,12 @@ use codex_sandboxing::SandboxTransformRequest;
use codex_sandboxing::SandboxType;
use codex_sandboxing::SandboxablePreference;
use codex_sandboxing::compatibility_sandbox_policy_for_permission_profile;
#[cfg(target_os = "windows")]
use codex_shell_command::powershell::UTF8_OUTPUT_PREFIX;
#[cfg(target_os = "windows")]
use codex_shell_command::powershell::extract_powershell_command;
#[cfg(target_os = "windows")]
use codex_shell_command::powershell::parse_powershell_command_into_plain_commands;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use codex_utils_pty::DEFAULT_OUTPUT_BYTES_CAP;
@@ -589,6 +595,139 @@ fn record_windows_sandbox_spawn_failure(
}
}
#[cfg(target_os = "windows")]
fn env_var_case_insensitive<'a>(env: &'a HashMap<String, String>, key: &str) -> Option<&'a str> {
env.iter()
.find(|(candidate, _)| candidate.eq_ignore_ascii_case(key))
.map(|(_, value)| value.as_str())
}
#[cfg(target_os = "windows")]
fn looks_like_windows_command_not_found(output: &str) -> bool {
let lower = output.to_ascii_lowercase();
lower.contains("is not recognized as the name of a cmdlet")
|| lower.contains("is not recognized as an internal or external command")
|| lower.contains("could not be found")
}
#[cfg(target_os = "windows")]
fn is_simple_windows_lookup_target(program: &str) -> bool {
!program.is_empty()
&& !program.contains(['\\', '/', ':'])
&& !program.contains(|c: char| c.is_whitespace())
}
#[cfg(target_os = "windows")]
fn windows_shell_lookup_target(command: &[String]) -> Option<String> {
let (_, script) = extract_powershell_command(command)?;
let script = script.strip_prefix(UTF8_OUTPUT_PREFIX).unwrap_or(script);
let plain_commands = parse_powershell_command_into_plain_commands(&[
command[0].clone(),
"-Command".to_string(),
script.to_string(),
])?;
plain_commands
.into_iter()
.find_map(|plain_command| plain_command.into_iter().next())
.filter(|program| is_simple_windows_lookup_target(program))
}
#[cfg(target_os = "windows")]
fn windows_path_probe_names(program: &str, env: &HashMap<String, String>) -> Vec<String> {
if Path::new(program).extension().is_some() {
return vec![program.to_string()];
}
let probe_names = env_var_case_insensitive(env, "PATHEXT")
.unwrap_or(".COM;.EXE;.BAT;.CMD")
.split(';')
.filter_map(|ext| {
let ext = ext.trim();
(!ext.is_empty()).then(|| format!("{program}{ext}"))
})
.collect::<Vec<_>>();
if probe_names.is_empty() {
vec![format!("{program}.exe")]
} else {
probe_names
}
}
#[cfg(target_os = "windows")]
fn find_windows_sandbox_blocked_path_binary(
command: &[String],
permission_profile: &PermissionProfile,
windows_sandbox_workspace_roots: &[AbsolutePathBuf],
cwd: &AbsolutePathBuf,
env: &HashMap<String, String>,
) -> Option<PathBuf> {
let program = windows_shell_lookup_target(command)?;
let path_value = env_var_case_insensitive(env, "PATH")?;
let permissions =
codex_windows_sandbox::ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots(
permission_profile,
windows_sandbox_workspace_roots,
)
.ok()?;
let probe_names = windows_path_probe_names(&program, env);
let mut blocked_candidate: Option<PathBuf> = None;
for entry in path_value
.split(';')
.filter(|entry| !entry.trim().is_empty())
{
let dir = PathBuf::from(entry.trim_matches('"'));
for candidate_name in &probe_names {
let candidate = dir.join(candidate_name);
if !candidate.is_file() {
continue;
}
if permissions.can_read_path_with_cwd(candidate.as_path(), cwd.as_path()) {
return None;
}
blocked_candidate.get_or_insert(candidate);
}
}
blocked_candidate
}
#[cfg(target_os = "windows")]
fn maybe_append_windows_sandbox_path_hint(
command: &[String],
permission_profile: &PermissionProfile,
windows_sandbox_workspace_roots: &[AbsolutePathBuf],
cwd: &AbsolutePathBuf,
env: &HashMap<String, String>,
stdout: &str,
stderr: &mut String,
) {
if !looks_like_windows_command_not_found(stdout)
&& !looks_like_windows_command_not_found(stderr)
{
return;
}
let Some(candidate) = find_windows_sandbox_blocked_path_binary(
command,
permission_profile,
windows_sandbox_workspace_roots,
cwd,
env,
) else {
return;
};
let note = format!(
"\nCodex note: a matching executable exists on PATH at `{}`, but the Windows sandbox likely cannot read or launch it from that location. Try approving the command outside the sandbox or moving the toolchain under an allowed root.\n",
candidate.display()
);
if !stderr.contains(&note) {
stderr.push_str(&note);
}
}
#[cfg(target_os = "windows")]
async fn exec_windows_sandbox(
params: ExecParams,
@@ -727,6 +866,15 @@ async fn exec_windows_sandbox(
{
stderr_text.truncate(max_bytes);
}
maybe_append_windows_sandbox_path_hint(
&command,
&permission_profile,
workspace_roots.as_slice(),
&cwd,
&env,
&stdout_text,
&mut stderr_text,
);
let stdout = StreamOutput {
text: stdout_text,
truncated_after_lines: None,
+80
View File
@@ -2,11 +2,15 @@ use super::*;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::models::PermissionProfile;
use codex_sandboxing::SandboxType;
#[cfg(target_os = "windows")]
use codex_utils_absolute_path::AbsolutePathBuf;
use core_test_support::PathBufExt;
use core_test_support::PathExt;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
use std::time::Duration;
#[cfg(target_os = "windows")]
use tempfile::TempDir;
use tokio::io::AsyncWriteExt;
use tokio::time::timeout;
@@ -96,6 +100,82 @@ fn sandbox_detection_ignores_network_policy_text_with_zero_exit_code() {
));
}
#[cfg(target_os = "windows")]
#[test]
fn windows_sandbox_path_hint_detects_blocked_path_binary() {
let tmp = TempDir::new().expect("tempdir");
let workspace = tmp.path().join("workspace");
let blocked_bin = tmp.path().join("blocked-bin");
std::fs::create_dir_all(&workspace).expect("workspace");
std::fs::create_dir_all(&blocked_bin).expect("blocked bin");
std::fs::write(blocked_bin.join("go.exe"), b"fake-binary").expect("write go.exe");
let workspace_abs = AbsolutePathBuf::try_from(workspace.as_path()).expect("workspace abs");
let permission_profile = PermissionProfile::workspace_write_with(
&[],
NetworkSandboxPolicy::Restricted,
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ true,
);
let workspace_roots = vec![workspace_abs.clone()];
let mut env = HashMap::new();
env.insert("PATH".to_string(), blocked_bin.display().to_string());
env.insert("PATHEXT".to_string(), ".EXE;.CMD".to_string());
let blocked = find_windows_sandbox_blocked_path_binary(
&[
"powershell.exe".to_string(),
"-NoProfile".to_string(),
"-Command".to_string(),
format!("{UTF8_OUTPUT_PREFIX}go version"),
],
&permission_profile,
workspace_roots.as_slice(),
&workspace_abs,
&env,
)
.expect("blocked binary should be detected");
assert_eq!(blocked, blocked_bin.join("go.exe"));
}
#[cfg(target_os = "windows")]
#[test]
fn windows_sandbox_path_hint_skips_readable_path_binary() {
let tmp = TempDir::new().expect("tempdir");
let workspace = tmp.path().join("workspace");
let readable_bin = workspace.join("bin");
std::fs::create_dir_all(&readable_bin).expect("readable bin");
std::fs::write(readable_bin.join("go.exe"), b"fake-binary").expect("write go.exe");
let workspace_abs = AbsolutePathBuf::try_from(workspace.as_path()).expect("workspace abs");
let permission_profile = PermissionProfile::workspace_write_with(
&[],
NetworkSandboxPolicy::Restricted,
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ true,
);
let workspace_roots = vec![workspace_abs.clone()];
let mut env = HashMap::new();
env.insert("PATH".to_string(), readable_bin.display().to_string());
env.insert("PATHEXT".to_string(), ".EXE".to_string());
let blocked = find_windows_sandbox_blocked_path_binary(
&[
"powershell.exe".to_string(),
"-NoProfile".to_string(),
"-Command".to_string(),
format!("{UTF8_OUTPUT_PREFIX}go version"),
],
&permission_profile,
workspace_roots.as_slice(),
&workspace_abs,
&env,
);
assert!(blocked.is_none(), "readable binaries should not be hinted");
}
#[tokio::test]
async fn read_output_limits_retained_bytes_for_shell_capture() {
let (mut writer, reader) = tokio::io::duplex(1024);
@@ -118,6 +118,10 @@ impl ResolvedWindowsSandboxPermissions {
.collect()
}
pub fn can_read_path_with_cwd(&self, path: &Path, cwd: &Path) -> bool {
self.file_system.can_read_path_with_cwd(path, cwd)
}
pub(crate) fn uses_write_capabilities_for_cwd(
&self,
cwd: &Path,