Fix Windows fs helper sandbox launch

This commit is contained in:
David Wiesen
2026-06-08 15:28:47 -07:00
parent 381f0de531
commit 7818148816
7 changed files with 500 additions and 29 deletions
+12 -2
View File
@@ -1,4 +1,5 @@
use std::error::Error;
use std::path::PathBuf;
use tokio::io;
use tokio::io::AsyncReadExt;
@@ -29,8 +30,7 @@ pub fn main() -> ! {
}
async fn run_main() -> Result<(), Box<dyn Error + Send + Sync>> {
let mut input = Vec::new();
io::stdin().read_to_end(&mut input).await?;
let input = read_request_input().await?;
let request: FsHelperRequest = serde_json::from_slice(&input)?;
let response = match run_direct_request(request).await {
Ok(payload) => FsHelperResponse::Ok(payload),
@@ -43,3 +43,13 @@ async fn run_main() -> Result<(), Box<dyn Error + Send + Sync>> {
stdout.write_all(b"\n").await?;
Ok(())
}
async fn read_request_input() -> Result<Vec<u8>, Box<dyn Error + Send + Sync>> {
if let Some(path) = std::env::args_os().nth(2) {
return Ok(tokio::fs::read(PathBuf::from(path)).await?);
}
let mut input = Vec::new();
io::stdin().read_to_end(&mut input).await?;
Ok(input)
}
+203 -22
View File
@@ -59,11 +59,15 @@ impl FileSystemSandboxRunner {
request: FsHelperRequest,
) -> Result<FsHelperPayload, JSONRPCErrorError> {
let cwd = sandbox_cwd(sandbox)?;
let helper = self.helper_exe_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(&self.runtime_paths)
helper_read_roots(&helper, self.runtime_paths.codex_linux_sandbox_exe.as_ref())
};
add_helper_runtime_permissions(&mut file_system_policy, &helper_read_roots, cwd.as_path());
normalize_file_system_policy_root_aliases(&mut file_system_policy);
@@ -73,18 +77,43 @@ impl FileSystemSandboxRunner {
&file_system_policy,
network_policy,
);
let command = self.sandbox_exec_request(&permission_profile, &cwd, sandbox)?;
let command = self.sandbox_exec_request(&permission_profile, &cwd, sandbox, &helper)?;
let request_json = serde_json::to_vec(&request).map_err(json_error)?;
run_command(command, request_json).await
}
fn helper_exe_for_launch(&self) -> Result<AbsolutePathBuf, JSONRPCErrorError> {
#[cfg(target_os = "windows")]
{
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(
self.runtime_paths.codex_self_exe.as_path(),
codex_home.as_path(),
);
AbsolutePathBuf::from_absolute_path(helper.as_path()).map_err(|err| {
internal_error(format!(
"windows fs sandbox helper path is not absolute: {err}"
))
})
}
#[cfg(not(target_os = "windows"))]
{
Ok(self.runtime_paths.codex_self_exe.clone())
}
}
fn sandbox_exec_request(
&self,
permission_profile: &PermissionProfile,
cwd: &AbsolutePathBuf,
sandbox_context: &FileSystemSandboxContext,
helper: &AbsolutePathBuf,
) -> Result<SandboxExecRequest, JSONRPCErrorError> {
let helper = &self.runtime_paths.codex_self_exe;
let sandbox_manager = SandboxManager::new();
let (file_system_policy, network_policy) = permission_profile.to_runtime_permissions();
let sandbox = sandbox_manager.select_initial(
@@ -134,10 +163,13 @@ fn sandbox_cwd(sandbox: &FileSystemSandboxContext) -> Result<AbsolutePathBuf, JS
.map_err(|err| invalid_request(format!("current directory is not absolute: {err}")))
}
fn helper_read_roots(runtime_paths: &ExecServerRuntimePaths) -> Vec<AbsolutePathBuf> {
fn helper_read_roots(
codex_self_exe: &AbsolutePathBuf,
codex_linux_sandbox_exe: Option<&AbsolutePathBuf>,
) -> Vec<AbsolutePathBuf> {
let mut roots = Vec::new();
for path in std::iter::once(runtime_paths.codex_self_exe.as_path())
.chain(runtime_paths.codex_linux_sandbox_exe.as_deref())
for path in std::iter::once(codex_self_exe.as_path())
.chain(codex_linux_sandbox_exe.map(AbsolutePathBuf::as_path))
{
if let Some(parent) = path.parent()
&& let Ok(root) = AbsolutePathBuf::from_absolute_path(parent)
@@ -250,17 +282,8 @@ async fn run_command(
command: SandboxExecRequest,
request_json: Vec<u8>,
) -> Result<FsHelperPayload, JSONRPCErrorError> {
let mut child = spawn_command(command)?;
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)?;
if !output.status.success() {
let output = run_helper_command(command, request_json).await?;
if !output.success {
return Err(internal_error(format!(
"fs sandbox helper failed with status {status}: {stderr}",
status = output.status,
@@ -274,7 +297,52 @@ async fn run_command(
}
}
fn spawn_command(
struct FsHelperCommandOutput {
success: bool,
status: String,
stdout: Vec<u8>,
stderr: Vec<u8>,
}
async fn run_helper_command(
command: SandboxExecRequest,
request_json: Vec<u8>,
) -> Result<FsHelperCommandOutput, JSONRPCErrorError> {
#[cfg(target_os = "windows")]
if command.sandbox == codex_sandboxing::SandboxType::WindowsRestrictedToken {
return tokio::task::spawn_blocking(move || {
run_windows_sandbox_command(command, request_json)
})
.await
.map_err(|err| internal_error(format!("windows fs sandbox helper task failed: {err}")))?;
}
run_child_command(command, request_json).await
}
async fn run_child_command(
command: SandboxExecRequest,
request_json: Vec<u8>,
) -> Result<FsHelperCommandOutput, JSONRPCErrorError> {
let mut child = spawn_child_command(command)?;
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,
cwd,
@@ -304,6 +372,87 @@ fn spawn_command(
command.spawn().map_err(io_error)
}
#[cfg(target_os = "windows")]
fn write_windows_fs_helper_request_file(
helper_program: &str,
request_json: &[u8],
) -> Result<std::path::PathBuf, JSONRPCErrorError> {
let helper_dir = std::path::Path::new(helper_program)
.parent()
.ok_or_else(|| {
invalid_request("windows fs sandbox helper path has no parent".to_string())
})?;
let path = helper_dir.join(format!(
".codex-fs-helper-request-{}.json",
uuid::Uuid::new_v4()
));
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
.map_err(|err| {
internal_error(format!(
"failed to create windows fs sandbox helper request file {}: {err}",
path.display()
))
})?;
std::io::Write::write_all(&mut file, request_json).map_err(|err| {
internal_error(format!(
"failed to write windows fs sandbox helper request file {}: {err}",
path.display()
))
})?;
Ok(path)
}
#[cfg(target_os = "windows")]
fn run_windows_sandbox_command(
SandboxExecRequest {
mut command,
cwd,
env,
windows_sandbox_level,
windows_sandbox_private_desktop,
permission_profile,
..
}: SandboxExecRequest,
request_json: Vec<u8>,
) -> Result<FsHelperCommandOutput, JSONRPCErrorError> {
if command.is_empty() {
return Err(invalid_request("fs sandbox command was empty".to_string()));
}
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 request_file = write_windows_fs_helper_request_file(&command[0], &request_json)?;
command.push(request_file.to_string_lossy().into_owned());
let workspace_roots = vec![cwd.clone()];
let capture = codex_windows_sandbox::run_windows_sandbox_capture_for_level(
windows_sandbox_level,
&permission_profile,
workspace_roots.as_slice(),
codex_home.as_path(),
command,
cwd.as_path(),
env,
windows_sandbox_private_desktop,
);
let _ = std::fs::remove_file(&request_file);
let capture = capture
.map_err(|err| internal_error(format!("windows fs sandbox helper failed to run: {err}")))?;
let exit_code = capture.exit_code;
Ok(FsHelperCommandOutput {
success: exit_code == 0,
status: format!("exit code {exit_code}"),
stdout: capture.stdout,
stderr: capture.stderr,
})
}
fn io_error(err: std::io::Error) -> JSONRPCErrorError {
internal_error(err.to_string())
}
@@ -338,6 +487,8 @@ mod tests {
use super::helper_env_key_is_allowed;
use super::helper_read_roots;
use super::sandbox_cwd;
#[cfg(target_os = "windows")]
use super::write_windows_fs_helper_request_file;
#[test]
fn helper_permissions_enable_minimal_reads_for_restricted_profile() {
@@ -387,7 +538,7 @@ mod tests {
add_helper_runtime_permissions(
&mut policy,
&helper_read_roots(&runtime_paths),
&helper_read_roots(&runtime_paths.codex_self_exe, None),
cwd.as_path(),
);
@@ -498,7 +649,12 @@ mod tests {
let sandbox_context = sandbox_context_with_cwd(&file_system_policy, cwd.clone());
let request = runner
.sandbox_exec_request(&permission_profile, &cwd, &sandbox_context)
.sandbox_exec_request(
&permission_profile,
&cwd,
&sandbox_context,
&runner.runtime_paths.codex_self_exe,
)
.expect("sandbox exec request");
assert_eq!(request.env.get(&path_key), Some(&path));
@@ -556,7 +712,7 @@ mod tests {
add_helper_runtime_permissions(
&mut policy,
&helper_read_roots(&runtime_paths),
&helper_read_roots(&runtime_paths.codex_self_exe, None),
cwd.as_path(),
);
@@ -581,7 +737,10 @@ mod tests {
add_helper_runtime_permissions(
&mut policy,
&helper_read_roots(&runtime_paths),
&helper_read_roots(
&runtime_paths.codex_self_exe,
runtime_paths.codex_linux_sandbox_exe.as_ref(),
),
cwd.as_path(),
);
@@ -589,6 +748,28 @@ mod tests {
assert!(policy.can_read_path_with_cwd(alias_parent.as_path(), cwd.as_path()));
}
#[cfg(target_os = "windows")]
#[test]
fn windows_request_file_writes_payload() {
let root = tempfile::tempdir().expect("temp dir");
let helper = root.path().join("codex.exe");
std::fs::write(&helper, b"helper").expect("write helper");
let request_json = br#"{"operation":"fs/readFile"}"#;
let path = write_windows_fs_helper_request_file(
helper.to_str().expect("utf-8 helper path"),
request_json,
)
.expect("request file");
assert_eq!(
std::fs::read(&path).expect("read request file"),
request_json
);
let _ = std::fs::remove_file(&path);
assert!(!path.exists());
}
fn restricted_policy(entries: Vec<FileSystemSandboxEntry>) -> FileSystemSandboxPolicy {
FileSystemSandboxPolicy::restricted(entries)
}