Support Windows sandboxing in the exec server (#34423)

## Why

Sandboxed process launch through the exec server was unsupported on Windows.

## What changed

- Add a shared native process launcher that selects the Windows sandbox session backend when required and otherwise launches PTY or pipe-based processes.
- Pass Windows permission, workspace-root, proxy, filesystem-override, and desktop settings through exec-server process preparation.
- Preserve piped stdin and inherited file descriptors across the shared launch path.

## Testing

- Verify that a remote Windows sandbox process accepts stdin while blocking a write under a read-only policy.
- Enable workspace-root sandbox tests on native Windows while continuing to skip environments that cannot emulate Windows sandbox semantics.

GitOrigin-RevId: 6719ccbe87ad0d5a57af56503e3f23f894c60a71
This commit is contained in:
iceweasel-oai
2026-07-20 22:35:14 +00:00
committed by copyberry
parent 60272096bc
commit 35c2278dd5
16 changed files with 494 additions and 254 deletions
+15 -34
View File
@@ -18,7 +18,6 @@ use codex_sandboxing::SandboxType;
use codex_sandboxing::is_likely_sandbox_denied;
use codex_utils_pty::ExecCommandSession;
use codex_utils_pty::ProcessSignal as PtyProcessSignal;
use codex_utils_pty::TerminalSize;
use tokio::sync::Mutex;
use tokio::sync::Notify;
use tokio::sync::mpsc;
@@ -241,10 +240,9 @@ impl LocalProcess {
let process_id = params.process_id.clone();
let prepared =
prepare_exec_request(&params, child_env(&params), self.runtime_paths.as_ref()).await?;
let (program, args) = prepared
.command
.split_first()
.ok_or_else(|| invalid_params("argv must not be empty".to_string()))?;
if prepared.command.is_empty() {
return Err(invalid_params("argv must not be empty".to_string()));
}
let start = Arc::new(ProcessStart);
{
@@ -260,35 +258,18 @@ impl LocalProcess {
);
}
let spawned_result = if params.tty {
codex_utils_pty::spawn_pty_process(
program,
args,
prepared.cwd.as_path(),
&prepared.env,
&prepared.arg0,
TerminalSize::default(),
)
.await
} else if params.pipe_stdin {
codex_utils_pty::spawn_pipe_process(
program,
args,
prepared.cwd.as_path(),
&prepared.env,
&prepared.arg0,
)
.await
} else {
codex_utils_pty::spawn_pipe_process_no_stdin(
program,
args,
prepared.cwd.as_path(),
&prepared.env,
&prepared.arg0,
)
.await
};
let spawned_result = codex_sandboxing::spawn_process(codex_sandboxing::SpawnRequest {
command: &prepared.command,
cwd: prepared.cwd.as_path(),
env: &prepared.env,
arg0: &prepared.arg0,
sandbox: prepared.sandbox,
windows_sandbox: prepared.windows_sandbox_spawn_request(),
tty: params.tty,
stdin_open: params.tty || params.pipe_stdin,
inherited_fds: &[],
})
.await;
let spawned = match spawned_result {
Ok(spawned) => spawned,
Err(err) => {
+104 -41
View File
@@ -16,6 +16,12 @@ use codex_sandboxing::SandboxManager;
use codex_sandboxing::SandboxTransformRequest;
use codex_sandboxing::SandboxType;
use codex_sandboxing::SandboxablePreference;
use codex_sandboxing::WindowsSandboxFilesystemOverrides;
use codex_sandboxing::WindowsSandboxProxySettingsMode;
use codex_sandboxing::WindowsSandboxSpawnRequest;
use codex_sandboxing::resolve_windows_elevated_filesystem_overrides;
use codex_sandboxing::resolve_windows_restricted_token_filesystem_overrides;
use codex_sandboxing::windows_sandbox_uses_elevated_backend;
use codex_sandboxing::with_managed_mitm_ca_readable_root;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
@@ -32,6 +38,32 @@ pub(crate) struct PreparedExecRequest {
pub(crate) arg0: Option<String>,
pub(crate) sandbox: SandboxType,
pub(crate) network_proxy_handle: Option<NetworkProxyHandle>,
windows_sandbox: Option<PreparedWindowsSandboxRequest>,
}
struct PreparedWindowsSandboxRequest {
permission_profile: PermissionProfile,
workspace_roots: Vec<AbsolutePathBuf>,
windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel,
proxy_enforced: bool,
filesystem_overrides: Option<WindowsSandboxFilesystemOverrides>,
use_private_desktop: bool,
}
impl PreparedExecRequest {
pub(crate) fn windows_sandbox_spawn_request(&self) -> Option<WindowsSandboxSpawnRequest<'_>> {
self.windows_sandbox
.as_ref()
.map(|request| WindowsSandboxSpawnRequest {
permission_profile: &request.permission_profile,
workspace_roots: &request.workspace_roots,
windows_sandbox_level: request.windows_sandbox_level,
proxy_enforced: request.proxy_enforced,
proxy_settings_mode: WindowsSandboxProxySettingsMode::Reconcile,
filesystem_overrides: request.filesystem_overrides.as_ref(),
use_private_desktop: request.use_private_desktop,
})
}
}
pub(crate) async fn prepare_exec_request(
@@ -53,6 +85,7 @@ pub(crate) async fn prepare_exec_request(
arg0: params.arg0.clone(),
sandbox: SandboxType::None,
network_proxy_handle,
windows_sandbox: None,
});
};
let runtime_paths = runtime_paths
@@ -112,54 +145,83 @@ pub(crate) async fn prepare_exec_request(
sandbox_context.windows_sandbox_level,
params.enforce_managed_network,
);
match sandbox {
SandboxType::None => {
return Err(invalid_params(
"sandbox intent cannot be enforced on this executor".to_string(),
));
}
SandboxType::WindowsRestrictedToken => {
// TODO(jif): Launch generic remote commands through the Windows sandbox session API
// while preserving argv and TTY behavior and passing the child environment out of band.
return Err(invalid_params(
"sandboxed remote process launch is not supported on Windows".to_string(),
));
}
SandboxType::MacosSeatbelt | SandboxType::LinuxSeccomp => {}
if sandbox == SandboxType::None {
return Err(invalid_params(
"sandbox intent cannot be enforced on this executor".to_string(),
));
}
let (program, args) = params
.argv
.split_first()
.ok_or_else(|| invalid_params("argv must not be empty".to_string()))?;
let request = sandbox_manager
.transform_for_direct_spawn(SandboxDirectSpawnTransformRequest {
workspace_roots,
windows_sandbox_proxy_settings_mode:
codex_sandboxing::WindowsSandboxProxySettingsMode::Reconcile,
transform: SandboxTransformRequest {
// TODO(jif): Preserve params.arg0 for the inner command across the sandbox
// wrapper, or reject sandboxed requests with a custom arg0.
command: SandboxCommand {
program: program.into(),
args: args.to_vec(),
cwd: params.cwd.clone(),
env,
managed_network,
additional_permissions: None,
},
permissions: &permissions,
sandbox,
enforce_managed_network: params.enforce_managed_network,
environment_id: None,
network: None,
sandbox_policy_cwd,
codex_linux_sandbox_exe: runtime_paths.codex_linux_sandbox_exe.as_deref(),
use_legacy_landlock: sandbox_context.use_legacy_landlock,
windows_sandbox_level: sandbox_context.windows_sandbox_level,
windows_sandbox_private_desktop: sandbox_context.windows_sandbox_private_desktop,
let transform_request = SandboxDirectSpawnTransformRequest {
workspace_roots,
windows_sandbox_proxy_settings_mode:
codex_sandboxing::WindowsSandboxProxySettingsMode::Reconcile,
transform: SandboxTransformRequest {
// TODO(jif): Preserve params.arg0 for the inner command across the sandbox
// wrapper, or reject sandboxed requests with a custom arg0.
command: SandboxCommand {
program: program.into(),
args: args.to_vec(),
cwd: params.cwd.clone(),
env,
managed_network,
additional_permissions: None,
},
})
permissions: &permissions,
sandbox,
enforce_managed_network: params.enforce_managed_network,
environment_id: None,
network: None,
sandbox_policy_cwd,
codex_linux_sandbox_exe: runtime_paths.codex_linux_sandbox_exe.as_deref(),
use_legacy_landlock: sandbox_context.use_legacy_landlock,
windows_sandbox_level: sandbox_context.windows_sandbox_level,
windows_sandbox_private_desktop: sandbox_context.windows_sandbox_private_desktop,
},
};
let mut request = if sandbox == SandboxType::WindowsRestrictedToken {
// The shared launcher invokes the native Windows session spawner directly.
sandbox_manager.transform(transform_request.transform)
} else {
sandbox_manager.transform_for_direct_spawn(transform_request)
}
.map_err(|err| invalid_params(format!("failed to prepare process sandbox: {err}")))?;
let windows_sandbox = if sandbox == SandboxType::WindowsRestrictedToken {
request.arg0 = params.arg0.clone();
let proxy_enforced = params.enforce_managed_network;
let use_elevated = windows_sandbox_uses_elevated_backend(
sandbox_context.windows_sandbox_level,
proxy_enforced,
);
let filesystem_overrides = if use_elevated {
resolve_windows_elevated_filesystem_overrides(
sandbox,
&permissions,
&native_sandbox_policy_cwd,
use_elevated,
)
} else {
resolve_windows_restricted_token_filesystem_overrides(
sandbox,
&permissions,
&native_sandbox_policy_cwd,
sandbox_context.windows_sandbox_level,
)
}
.map_err(|err| invalid_params(format!("failed to prepare process sandbox: {err}")))?;
Some(PreparedWindowsSandboxRequest {
permission_profile: permissions,
workspace_roots: native_workspace_roots,
windows_sandbox_level: sandbox_context.windows_sandbox_level,
proxy_enforced,
filesystem_overrides,
use_private_desktop: sandbox_context.windows_sandbox_private_desktop,
})
} else {
None
};
Ok(PreparedExecRequest {
command: request.command,
cwd: native_path(&request.cwd, "cwd")?,
@@ -167,6 +229,7 @@ pub(crate) async fn prepare_exec_request(
arg0: request.arg0,
sandbox: request.sandbox,
network_proxy_handle,
windows_sandbox,
})
}
@@ -7,7 +7,9 @@ use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_network_proxy::NetworkProxyConfig;
use codex_network_proxy::RemoteNetworkProxyConfig;
use codex_network_proxy::RemoteNetworkProxyLaunchConfig;
#[cfg(unix)]
#[cfg(windows)]
use codex_protocol::config_types::WindowsSandboxLevel;
#[cfg(any(unix, windows))]
use codex_protocol::models::PermissionProfile;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
@@ -18,9 +20,9 @@ use tokio::time::timeout;
use super::prepare_exec_request;
use crate::ExecParams;
#[cfg(unix)]
#[cfg(any(unix, windows))]
use crate::ExecServerRuntimePaths;
#[cfg(unix)]
#[cfg(any(unix, windows))]
use crate::FileSystemSandboxContext;
use crate::ProcessId;
@@ -272,3 +274,50 @@ async fn disabled_remote_proxy_config_is_rejected_before_exporting_ports() {
.contains("executor-local network proxy launch requires an enabled proxy")
);
}
#[cfg(windows)]
#[tokio::test]
async fn managed_network_selects_elevated_windows_spawn() {
let cwd: AbsolutePathBuf = std::env::current_dir()
.expect("current directory")
.try_into()
.expect("absolute cwd");
let cwd_uri = PathUri::from_abs_path(&cwd);
let self_exe = std::env::current_exe().expect("current executable");
let runtime_paths = ExecServerRuntimePaths::new(self_exe, None).expect("runtime paths");
let permissions = PermissionProfile::read_only();
let mut sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd(
permissions.clone(),
cwd_uri.clone(),
);
sandbox.windows_sandbox_level = WindowsSandboxLevel::RestrictedToken;
let params = ExecParams {
process_id: ProcessId::from("process-managed-network"),
argv: vec!["cmd.exe".to_string(), "/c".to_string(), "exit".to_string()],
cwd: cwd_uri,
env_policy: None,
env: HashMap::new(),
tty: false,
pipe_stdin: false,
arg0: None,
sandbox: Some(sandbox),
enforce_managed_network: true,
managed_network: None,
network_proxy: None,
};
let prepared = prepare_exec_request(&params, HashMap::new(), Some(&runtime_paths))
.await
.expect("prepare sandboxed request");
let spawn = prepared
.windows_sandbox_spawn_request()
.expect("Windows sandbox spawn request");
assert_eq!(
spawn.windows_sandbox_level,
WindowsSandboxLevel::RestrictedToken
);
assert!(spawn.proxy_enforced);
assert_eq!(spawn.permission_profile, &permissions);
assert_eq!(spawn.workspace_roots, std::slice::from_ref(&cwd));
}
+69 -1
View File
@@ -13,13 +13,14 @@ use codex_exec_server::ExecOutputStream;
use codex_exec_server::ExecParams;
use codex_exec_server::ExecProcess;
use codex_exec_server::ExecProcessEvent;
#[cfg(unix)]
#[cfg(any(unix, windows))]
use codex_exec_server::FileSystemSandboxContext;
use codex_exec_server::ProcessId;
use codex_exec_server::ProcessSignal;
use codex_exec_server::ReadResponse;
use codex_exec_server::StartedExecProcess;
use codex_exec_server::WriteStatus;
use codex_protocol::config_types::WindowsSandboxLevel;
#[cfg(unix)]
use codex_protocol::models::PermissionProfile;
#[cfg(unix)]
@@ -34,6 +35,7 @@ use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::FileSystemSpecialPath;
#[cfg(unix)]
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_protocol::protocol::SandboxPolicy;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
@@ -699,6 +701,65 @@ async fn assert_exec_process_write_then_read_without_tty(use_remote: bool) -> Re
Ok(())
}
async fn assert_remote_windows_sandbox_process_write() -> Result<()> {
let context = create_process_context(/*use_remote*/ true).await?;
let workspace = TempDir::new()?;
let blocked_file = workspace.path().join("blocked.txt");
let cwd = PathUri::from_host_native_path(workspace.path())?;
let mut sandbox = FileSystemSandboxContext::from_legacy_sandbox_policy(
SandboxPolicy::new_read_only_policy(),
cwd.clone(),
)?;
sandbox.windows_sandbox_level = WindowsSandboxLevel::RestrictedToken;
let session = match context
.backend
.start(ExecParams {
process_id: ProcessId::from("proc-windows-sandbox-stdin"),
argv: vec![
r"C:\Windows\System32\cmd.exe".to_string(),
"/D".to_string(),
"/V:ON".to_string(),
"/S".to_string(),
"/C".to_string(),
format!(
"set /P line= & echo blocked > \"{}\" & echo from-stdin:!line!",
blocked_file.display()
),
],
cwd,
env_policy: /*env_policy*/ None,
env: Default::default(),
tty: false,
pipe_stdin: true,
arg0: None,
sandbox: Some(sandbox),
enforce_managed_network: false,
managed_network: None,
network_proxy: None,
})
.await
{
Ok(session) => session,
Err(err) => return Err(err.into()),
};
let write_response = session.process.write(b"hello\n".to_vec()).await?;
assert_eq!(write_response.status, WriteStatus::Accepted);
let StartedExecProcess { process, .. } = session;
let wake_rx = process.subscribe_wake();
let (output, exit_code, closed) = collect_process_output_from_reads(process, wake_rx).await?;
assert!(
output.contains("from-stdin:hello"),
"unexpected output: {output:?}"
);
assert_eq!(exit_code, Some(0));
assert!(closed);
assert!(!blocked_file.exists());
Ok(())
}
async fn assert_exec_process_rejects_write_without_pipe_stdin(use_remote: bool) -> Result<()> {
let context = create_process_context(use_remote).await?;
let process_id = "proc-stdin-closed".to_string();
@@ -1098,6 +1159,13 @@ async fn exec_process_write_then_read_without_tty(use_remote: bool) -> Result<()
assert_exec_process_write_then_read_without_tty(use_remote).await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(not(windows), ignore = "Windows-only exec-server sandbox process test")]
#[serial_test::serial(remote_exec_server)]
async fn remote_windows_sandbox_process_accepts_process_write() -> Result<()> {
assert_remote_windows_sandbox_process_write().await
}
#[test_case(false ; "local")]
#[test_case(true ; "remote")]
#[cfg_attr(not(unix), ignore = "Unix-only exec-server process test")]