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
+4
View File
@@ -49,6 +49,10 @@ tokio-tungstenite = { workspace = true }
tracing = { workspace = true }
uuid = { workspace = true, features = ["v4"] }
[target.'cfg(windows)'.dependencies]
codex-utils-home-dir = { workspace = true }
codex-windows-sandbox = { workspace = true }
[dev-dependencies]
anyhow = { workspace = true }
codex-test-binary-support = { workspace = true }
+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)
}
@@ -0,0 +1,182 @@
#![cfg(target_os = "windows")]
mod common;
use anyhow::Result;
use codex_exec_server::ExecServerRuntimePaths;
use codex_exec_server::ExecutorFileSystem;
use codex_exec_server::FileSystemSandboxContext;
use codex_exec_server::LocalFileSystem;
use codex_protocol::config_types::WindowsSandboxLevel;
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 pretty_assertions::assert_eq;
use serial_test::serial;
use tempfile::TempDir;
struct EnvVarGuard {
key: &'static str,
original: Option<std::ffi::OsString>,
}
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),
}
}
}
}
struct SandboxedFileSystem {
codex_home: TempDir,
_guard: EnvVarGuard,
file_system: LocalFileSystem,
}
fn sandboxed_file_system() -> Result<SandboxedFileSystem> {
let codex_home = TempDir::new()?;
let guard = EnvVarGuard::set("CODEX_HOME", codex_home.path().as_os_str());
let (codex_exe, codex_linux_sandbox_exe) = common::current_test_binary_helper_paths()?;
let file_system = LocalFileSystem::with_runtime_paths(ExecServerRuntimePaths::new(
codex_exe,
codex_linux_sandbox_exe,
)?);
Ok(SandboxedFileSystem {
codex_home,
_guard: guard,
file_system,
})
}
fn root_read_sandbox_with_writes(
workspace: AbsolutePathBuf,
writable_roots: Vec<AbsolutePathBuf>,
windows_sandbox_level: WindowsSandboxLevel,
) -> FileSystemSandboxContext {
let mut entries = vec![FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
access: FileSystemAccessMode::Read,
}];
entries.extend(
writable_roots
.into_iter()
.map(|path| FileSystemSandboxEntry {
path: FileSystemPath::Path { path },
access: FileSystemAccessMode::Write,
}),
);
let file_system_policy = FileSystemSandboxPolicy::restricted(entries);
let permissions = PermissionProfile::from_runtime_permissions(
&file_system_policy,
NetworkSandboxPolicy::Restricted,
);
let mut sandbox =
FileSystemSandboxContext::from_permission_profile_with_cwd(permissions, workspace);
sandbox.windows_sandbox_level = windows_sandbox_level;
sandbox
}
fn workspace_write_sandbox(
workspace: AbsolutePathBuf,
windows_sandbox_level: WindowsSandboxLevel,
) -> FileSystemSandboxContext {
root_read_sandbox_with_writes(workspace.clone(), vec![workspace], windows_sandbox_level)
}
fn read_only_sandbox_with_write_elsewhere(
workspace: AbsolutePathBuf,
writable_root: AbsolutePathBuf,
windows_sandbox_level: WindowsSandboxLevel,
) -> FileSystemSandboxContext {
root_read_sandbox_with_writes(workspace, vec![writable_root], windows_sandbox_level)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial(codex_home)]
async fn restricted_token_fs_helper_rejects_read_only_write() -> Result<()> {
let sandboxed = sandboxed_file_system()?;
let workspace_dir = TempDir::new()?;
let workspace = AbsolutePathBuf::try_from(std::fs::canonicalize(workspace_dir.path())?)?;
let writable_dir = workspace.join("writable");
std::fs::create_dir_all(&writable_dir)?;
let blocked_path = workspace.join("blocked.txt");
let sandbox = read_only_sandbox_with_write_elsewhere(
workspace,
writable_dir,
WindowsSandboxLevel::RestrictedToken,
);
let error = sandboxed
.file_system
.write_file(&blocked_path, b"blocked".to_vec(), Some(&sandbox))
.await
.expect_err("read-only sandboxed helper should reject writes");
assert!(
error.to_string().contains("Access is denied")
|| error.to_string().contains("Permission denied")
|| error.to_string().contains("Operation not permitted")
|| error.to_string().contains("is not permitted"),
"unexpected sandbox denial message: {error}",
);
assert_eq!(blocked_path.exists(), false);
assert!(
!sandboxed
.codex_home
.path()
.join(".sandbox-bin")
.read_dir()
.ok()
.into_iter()
.flatten()
.filter_map(std::result::Result::ok)
.any(|entry| {
entry
.file_name()
.to_string_lossy()
.starts_with(".codex-fs-helper-request-")
}),
"request file should be removed after helper exits",
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial(codex_home)]
async fn restricted_token_fs_helper_allows_writable_path() -> Result<()> {
let sandboxed = sandboxed_file_system()?;
let workspace_dir = TempDir::new()?;
let workspace = AbsolutePathBuf::try_from(std::fs::canonicalize(workspace_dir.path())?)?;
let file_path = workspace.join("allowed.txt");
let sandbox = workspace_write_sandbox(workspace, WindowsSandboxLevel::RestrictedToken);
sandboxed
.file_system
.write_file(&file_path, b"allowed".to_vec(), Some(&sandbox))
.await?;
assert_eq!(std::fs::read(&file_path)?, b"allowed");
Ok(())
}