Move sandbox preparation into platform backends (#62317)

## What changed

Have `SandboxManager` handle backend selection and shared preparation, then
delegate command wrapping and session setup to the Linux, macOS Seatbelt,
Windows token, and Windows MXC backends.

Centralize Windows managed proxy routing in `codex-sandboxing` so the exec
server and other callers use the same rule for selecting dedicated MXC
listeners.

GitOrigin-RevId: a75886809aefebf6c267bb39dbc104f76bda3409
This commit is contained in:
viyatb-oai
2026-11-18 17:09:03 +00:00
committed by copyberry
parent daa59ebd29
commit 6257fbc4bd
13 changed files with 405 additions and 299 deletions
@@ -1,8 +1,8 @@
use super::*;
use codex_core::exec_env::inject_apply_patch_env;
use codex_core::windows_sandbox::local_binding_policy_for_sandbox;
use codex_core::windows_sandbox::managed_proxy_routing_for_windows_sandbox;
use codex_protocol::shell_environment::is_non_inheritable_env_var;
use codex_sandboxing::managed_proxy_routing_for_windows_sandbox;
#[derive(Clone)]
pub(crate) struct CommandExecRequestProcessor {
+1 -1
View File
@@ -20,7 +20,6 @@ use codex_core::exec_env::create_env;
use codex_core::spawn::CODEX_SANDBOX_ENV_VAR;
use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR;
use codex_core::windows_sandbox::local_binding_policy_for_sandbox;
use codex_core::windows_sandbox::managed_proxy_routing_for_windows_sandbox;
use codex_protocol::config_types::SandboxMode;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::models::PermissionProfile;
@@ -34,6 +33,7 @@ use codex_sandboxing::SandboxSelection;
use codex_sandboxing::SandboxTransformRequest;
use codex_sandboxing::SandboxType as SandboxBackend;
use codex_sandboxing::SandboxType::WindowsMxc;
use codex_sandboxing::managed_proxy_routing_for_windows_sandbox;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_cli::CliConfigOverrides;
use codex_utils_path_uri::PathUri;
+1 -1
View File
@@ -186,6 +186,7 @@ use codex_rollout_trace::CompactionTraceContext;
use codex_rollout_trace::ThreadStartedTraceMetadata;
use codex_rollout_trace::ThreadTraceContext;
use codex_sandboxing::SandboxType;
use codex_sandboxing::managed_proxy_routing_for_windows_sandbox;
use codex_sandboxing::policy_transforms::intersect_permission_profiles_with_context;
use codex_shell_command::parse_command::parse_command;
use codex_terminal_detection::user_agent;
@@ -366,7 +367,6 @@ use crate::turn_timing::record_turn_ttfm_metric;
use crate::unified_exec::UnifiedExecProcessManager;
use crate::windows_sandbox::WindowsSandboxLevelExt;
use crate::windows_sandbox::local_binding_policy_for_sandbox;
use crate::windows_sandbox::managed_proxy_routing_for_windows_sandbox;
use codex_core_plugins::PluginCommandAttribution;
use codex_core_plugins::PluginsManager;
use codex_git_utils::get_git_repo_root;
-10
View File
@@ -93,16 +93,6 @@ pub fn local_binding_policy_for_sandbox(
}
}
pub fn managed_proxy_routing_for_windows_sandbox(
sandbox_type: SandboxType,
) -> codex_network_proxy::ManagedProxyRouting {
if cfg!(windows) && sandbox_type == SandboxType::WindowsMxc {
codex_network_proxy::ManagedProxyRouting::DedicatedListeners
} else {
codex_network_proxy::ManagedProxyRouting::SharedIngress
}
}
/// Adapts the selected implementation for legacy checks that only understand setup levels.
/// Backend selection must continue to use [`SandboxType`] directly.
pub(crate) fn windows_sandbox_level_for_legacy_checks(
+12 -21
View File
@@ -8,7 +8,6 @@ use codex_exec_server_protocol::JSONRPCErrorError;
use codex_exec_server_protocol::ProcessStartErrorData;
use codex_file_system::WindowsSandboxSelection;
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_network_proxy::ManagedProxyRouting;
use codex_network_proxy::NetworkPolicyAuditObserver;
use codex_network_proxy::NetworkPolicyDecider;
use codex_network_proxy::NetworkProxy;
@@ -22,6 +21,7 @@ use codex_sandboxing::SandboxManager;
use codex_sandboxing::SandboxNetwork;
use codex_sandboxing::SandboxTransformRequest;
use codex_sandboxing::WrappedSandboxCommand;
use codex_sandboxing::executor_managed_proxy_routing;
#[cfg(windows)]
use codex_shell_command::shell_detect::fallback_powershell_shell_for_windows_sandbox;
use codex_utils_path_uri::PathUri;
@@ -34,6 +34,7 @@ use crate::protocol::ExecParams;
use crate::rpc::internal_error;
use crate::rpc::invalid_params;
use crate::sandbox_selection::sandbox_selection;
use crate::sandbox_selection::windows_sandbox_backend;
#[tracing::instrument(
name = "codex.exec_server.process_prepare_sandbox",
@@ -215,27 +216,17 @@ async fn prepare_managed_network(
let Some(launch) = &params.network_proxy else {
return without_executor_proxy(env);
};
#[cfg(windows)]
let routing = match params
.sandbox
.as_ref()
.map(|sandbox| sandbox.windows_sandbox_selection)
{
None => {
// Native Windows commands have no sandbox token SID for shared ingress.
let mut native_env = env;
codex_network_proxy::strip_managed_proxy_env(&mut native_env);
return without_executor_proxy(native_env);
}
Some(WindowsSandboxSelection::Mxc) => ManagedProxyRouting::DedicatedListeners,
Some(
WindowsSandboxSelection::Disabled
| WindowsSandboxSelection::RestrictedToken
| WindowsSandboxSelection::Elevated,
) => ManagedProxyRouting::SharedIngress,
let routing = executor_managed_proxy_routing(
params
.sandbox
.as_ref()
.map(|sandbox| windows_sandbox_backend(sandbox.windows_sandbox_selection)),
);
let Some(routing) = routing else {
let mut native_env = env;
codex_network_proxy::strip_managed_proxy_env(&mut native_env);
return without_executor_proxy(native_env);
};
#[cfg(not(windows))]
let routing = ManagedProxyRouting::SharedIngress;
let mut state = NetworkProxyState::from_remote_launch_config(
launch.clone(),
codex_utils_path_uri::Platform::native(),
+13 -6
View File
@@ -17,16 +17,27 @@ pub(crate) fn validate_remote_mxc(info: &crate::EnvironmentInfo) -> std::io::Res
Ok(())
}
pub(crate) fn windows_sandbox_backend(selection: WindowsSandboxSelection) -> SandboxType {
match selection {
WindowsSandboxSelection::Disabled => SandboxType::None,
WindowsSandboxSelection::RestrictedToken | WindowsSandboxSelection::Elevated => {
SandboxType::WindowsRestrictedToken
}
WindowsSandboxSelection::Mxc => SandboxType::WindowsMxc,
}
}
pub(crate) fn sandbox_selection(
context: &FileSystemSandboxContext,
) -> (SandboxSelection, WindowsSandboxLevel) {
let windows_sandbox = windows_sandbox_backend(context.windows_sandbox_selection);
let level = match context.windows_sandbox_selection {
WindowsSandboxSelection::Disabled => WindowsSandboxLevel::Disabled,
WindowsSandboxSelection::RestrictedToken => WindowsSandboxLevel::RestrictedToken,
WindowsSandboxSelection::Elevated => WindowsSandboxLevel::Elevated,
WindowsSandboxSelection::Mxc => {
return (
SandboxSelection::Explicit(SandboxType::WindowsMxc),
SandboxSelection::Explicit(windows_sandbox),
WindowsSandboxLevel::Disabled,
);
}
@@ -34,11 +45,7 @@ pub(crate) fn sandbox_selection(
(
SandboxSelection::Platform {
preference: SandboxablePreference::Require,
windows_sandbox: if level == WindowsSandboxLevel::Disabled {
SandboxType::None
} else {
SandboxType::WindowsRestrictedToken
},
windows_sandbox,
},
level,
)
+2 -12
View File
@@ -5,10 +5,9 @@ use crate::SandboxIntegrityRequest;
use crate::SandboxType;
use crate::SpawnOptions;
use crate::SpawnRequest;
use crate::WindowsSandboxFilesystemOverrides;
use crate::WindowsSandboxProxySettingsMode;
use crate::WindowsSandboxSpawnRequest;
use crate::spawn::spawn_process;
use crate::windows::WindowsSessionPolicy;
use anyhow::Context;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::sandbox::SandboxOverride;
@@ -34,15 +33,6 @@ use codex_utils_path_uri::LegacyAppPathString;
use codex_utils_path_uri::PathConvention;
use codex_utils_path_uri::PathUri;
pub(super) struct WindowsSessionPolicy {
pub(super) workspace_roots: Vec<AbsolutePathBuf>,
pub(super) filesystem_overrides: Option<WindowsSandboxFilesystemOverrides>,
pub(super) proxy_enforced: bool,
#[cfg(windows)]
pub(super) restricting_sid: Option<String>,
pub(super) proxy_settings_mode: WindowsSandboxProxySettingsMode,
}
/// A command prepared for its selected sandbox. Native Windows token sessions
/// must use the Windows session launcher.
#[must_use]
@@ -233,7 +223,7 @@ impl WrappedSandboxCommand {
}
#[derive(Clone, Default)]
pub(super) enum SandboxOperation {
pub(crate) enum SandboxOperation {
#[default]
Command,
#[cfg(target_os = "macos")]
+2 -1
View File
@@ -12,7 +12,6 @@ mod spawn;
mod terminal_queries;
mod violation;
mod windows;
#[cfg(windows)]
mod windows_mxc;
#[cfg(target_os = "linux")]
@@ -61,6 +60,8 @@ pub use violation::record_filesystem_sandbox_violation;
pub use violation::record_network_sandbox_violation;
pub use violation::record_sandbox_violation;
pub use windows::WindowsSandboxFilesystemOverrides;
pub use windows::executor_managed_proxy_routing;
pub use windows::managed_proxy_routing_for_windows_sandbox;
pub use windows::permission_profile_supports_windows_restricted_token_sandbox;
pub use windows::resolve_windows_elevated_filesystem_overrides;
pub use windows::resolve_windows_restricted_token_filesystem_overrides;
+86 -5
View File
@@ -1,13 +1,17 @@
//! Prepare the Linux sandbox helper command for bubblewrap or legacy Landlock.
#[cfg(target_os = "linux")]
use crate::LinuxSandboxPidNamespace;
use crate::SandboxExecRequest;
use crate::SandboxTransformError;
use crate::manager::SandboxBackend;
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_protocol::models::PermissionProfile;
use codex_utils_absolute_path::AbsolutePathBuf;
use std::ffi::OsStr;
use std::path::Path;
/// Managed proxy and socket grants belong to bubblewrap. Legacy Landlock is a compatibility mode.
pub(super) enum LinuxSandboxMode<'a> {
enum LinuxSandboxMode<'a> {
Bubblewrap {
managed_network: Option<&'a ManagedNetworkSandboxContext>,
},
@@ -15,7 +19,7 @@ pub(super) enum LinuxSandboxMode<'a> {
}
impl<'a> LinuxSandboxMode<'a> {
pub(super) fn resolve(
fn resolve(
use_legacy_landlock: bool,
managed_network: Option<&'a ManagedNetworkSandboxContext>,
) -> Self {
@@ -27,7 +31,7 @@ impl<'a> LinuxSandboxMode<'a> {
}
#[cfg(target_os = "linux")]
pub(super) fn ensure_supported_on_wsl1(
fn ensure_supported_on_wsl1(
&self,
permission_profile: &PermissionProfile,
) -> Result<(), SandboxTransformError> {
@@ -47,6 +51,83 @@ impl<'a> LinuxSandboxMode<'a> {
}
}
pub(super) struct Linux<'a> {
pub(super) pid_namespace: LinuxSandboxPidNamespace,
pub(super) transparent_tcp: bool,
pub(super) sandbox_exe: Option<&'a Path>,
pub(super) use_legacy_landlock: bool,
pub(super) enforce_managed_network: bool,
pub(super) route: Option<ManagedNetworkSandboxContext>,
}
impl SandboxBackend for Linux<'_> {
fn prepare(
&mut self,
exec: &mut SandboxExecRequest,
cwd: &AbsolutePathBuf,
policy_cwd: &AbsolutePathBuf,
) -> Result<(), SandboxTransformError> {
let exe = self
.sandbox_exe
.ok_or(SandboxTransformError::MissingLinuxSandboxExecutable)?;
self.route = match (
self.enforce_managed_network,
self.route.take(),
&exec.network,
) {
(false, _, _) => None,
(true, None, Some(proxy)) => {
let prepared = proxy
.prepare_for_optional_environment(
std::mem::take(&mut exec.env),
exec.network_environment_id.as_deref(),
)
.map_err(|err| {
SandboxTransformError::EnvironmentNetworkProxy(err.to_string())
})?;
exec.env = prepared.env;
Some(prepared.sandbox_context)
}
(true, context, _) => Some(context.unwrap_or_default()),
};
let mode = LinuxSandboxMode::resolve(self.use_legacy_landlock, self.route.as_ref());
#[cfg(target_os = "linux")]
if crate::bwrap::is_wsl1() {
mode.ensure_supported_on_wsl1(&exec.permission_profile)?;
}
let program = exe.to_string_lossy().into_owned();
let mut args = create_linux_sandbox_command_args_for_permission_profile(
std::mem::take(&mut exec.command),
cwd,
&exec.permission_profile,
policy_cwd,
mode,
);
// Only the startup opt-in requires a helper that understands PID inheritance.
if self.pid_namespace == LinuxSandboxPidNamespace::Inherit {
args.insert(0, "--inherit-pid-namespace".to_owned());
}
if self
.route
.as_ref()
.is_some_and(|ctx| ctx.transparent_tcp || self.transparent_tcp)
{
args.insert(0, "--transparent-tcp".to_owned());
}
exec.command = std::iter::once(program).chain(args).collect();
// Without bwrap --argv0, the Linux helper uses its own argv[0] as the inner executable.
let arg0 = if let Some(path) = exe.to_str()
&& exe.file_name() == Some(OsStr::new(CODEX_LINUX_SANDBOX_ARG0))
{
path
} else {
CODEX_LINUX_SANDBOX_ARG0
};
exec.arg0 = Some(arg0.to_owned());
Ok(())
}
}
/// Basename used when the Codex executable self-invokes as the Linux sandbox
/// helper.
pub const CODEX_LINUX_SANDBOX_ARG0: &str = "codex-linux-sandbox";
@@ -61,7 +142,7 @@ pub const CODEX_LINUX_SANDBOX_ARG0: &str = "codex-linux-sandbox";
/// after parsing these arguments. The profile JSON flag is emitted before
/// helper feature flags so the argv order matches the helper's CLI shape. See
/// `docs/linux_sandbox.md` for the Linux semantics.
pub(super) fn create_linux_sandbox_command_args_for_permission_profile(
fn create_linux_sandbox_command_args_for_permission_profile(
command: Vec<String>,
command_cwd: &Path,
permission_profile: &PermissionProfile,
+75 -237
View File
@@ -1,7 +1,5 @@
use self::launch::PreparedLaunchPolicy;
use self::launch::SandboxOperation;
#[cfg(windows)]
use self::launch::WindowsSessionPolicy;
use self::launch::WrappedSandboxCommand;
use crate::LinuxSandboxPidNamespace;
#[cfg(windows)]
@@ -10,12 +8,8 @@ use crate::WindowsSandboxFilesystemOverrides;
use crate::WindowsSandboxProxySettingsMode;
#[cfg(target_os = "linux")]
use crate::bwrap::WSL1_BWRAP_WARNING;
use crate::linux::CODEX_LINUX_SANDBOX_ARG0;
use crate::linux::LinuxSandboxMode;
use crate::policy_transforms::effective_permission_profile;
use crate::policy_transforms::should_require_platform_sandbox;
#[cfg(target_os = "macos")]
use crate::seatbelt::MacosSeatbeltProfile;
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_network_proxy::NetworkProxy;
use codex_protocol::config_types::WindowsSandboxLevel;
@@ -199,44 +193,31 @@ pub struct SandboxTransformRequest<'a> {
pub windows_sandbox_level: WindowsSandboxLevel,
}
// TODO(anp): Revisit this preparation type once this module's PathUri migration is complete.
struct PendingSandboxedExecRequest {
native_command_cwd: AbsolutePathBuf,
native_sandbox_policy_cwd: AbsolutePathBuf,
effective_permission_profile: PermissionProfile,
}
impl PendingSandboxedExecRequest {
fn new(
command_cwd: &PathUri,
sandbox_policy_cwd: &PathUri,
effective_permission_profile: PermissionProfile,
managed_mitm_ca_trust_bundle_path: Option<&AbsolutePathBuf>,
) -> Result<Self, SandboxTransformError> {
// TODO(anp): Move PathUri conversion into the platform sandbox implementations.
let native_command_cwd = command_cwd.to_abs_path().map_err(|source| {
SandboxTransformError::InvalidCommandCwd {
cwd: command_cwd.clone(),
fn prepare_native_sandbox(
exec: &mut SandboxExecRequest,
trust_bundle: Option<&AbsolutePathBuf>,
) -> Result<(AbsolutePathBuf, AbsolutePathBuf), SandboxTransformError> {
let cwd =
exec.cwd
.to_abs_path()
.map_err(|source| SandboxTransformError::InvalidCommandCwd {
cwd: exec.cwd.clone(),
source,
}
})?;
let native_sandbox_policy_cwd = sandbox_policy_cwd.to_abs_path().map_err(|source| {
SandboxTransformError::InvalidSandboxPolicyCwd {
cwd: sandbox_policy_cwd.clone(),
source,
}
})?;
let effective_permission_profile = with_managed_mitm_ca_readable_root(
effective_permission_profile,
managed_mitm_ca_trust_bundle_path,
native_sandbox_policy_cwd.as_path(),
})?;
let policy_cwd = exec.sandbox_policy_cwd.to_abs_path().map_err(|source| {
SandboxTransformError::InvalidSandboxPolicyCwd {
cwd: exec.sandbox_policy_cwd.clone(),
source,
}
})?;
if let Some(trust_bundle) = trust_bundle {
exec.permission_profile = with_managed_mitm_ca_readable_root(
std::mem::take(&mut exec.permission_profile),
Some(trust_bundle),
&policy_cwd,
);
Ok(Self {
native_command_cwd,
native_sandbox_policy_cwd,
effective_permission_profile,
})
}
Ok((cwd, policy_cwd))
}
#[derive(Debug)]
@@ -327,6 +308,16 @@ impl std::error::Error for SandboxTransformError {
}
}
/// Translate the bound policy into platform arguments or a native Windows session.
pub(super) trait SandboxBackend {
fn prepare(
&mut self,
exec: &mut SandboxExecRequest,
cwd: &AbsolutePathBuf,
policy_cwd: &AbsolutePathBuf,
) -> Result<(), SandboxTransformError>;
}
#[derive(Clone, Default)]
pub struct SandboxManager {
#[cfg(windows)]
@@ -583,14 +574,29 @@ impl SandboxManager {
network.and_then(NetworkProxy::managed_mitm_ca_trust_bundle_path)
}
};
let pending = PendingSandboxedExecRequest::new(
&exec.cwd,
&exec.sandbox_policy_cwd,
exec.permission_profile,
managed_mitm_ca_trust_bundle_path.as_ref(),
);
match backend {
#[cfg(windows)]
let mut session = None;
#[cfg(not(windows))]
let session = None;
let platform: &mut dyn SandboxBackend = match backend {
SandboxType::None => unreachable!("native launch returned above"),
SandboxType::LinuxSeccomp => &mut crate::linux::Linux {
pid_namespace: self.linux_sandbox_pid_namespace,
transparent_tcp: self.linux_sandbox_transparent_tcp,
sandbox_exe,
use_legacy_landlock: request.use_legacy_landlock,
enforce_managed_network,
route: managed_network,
},
#[cfg(target_os = "macos")]
SandboxType::MacosSeatbelt => &mut crate::seatbelt::Seatbelt {
operation: &self.operation,
allowed_symlinked_codex_home: self.allowed_symlinked_codex_home.as_ref(),
enforce_managed_network,
route: managed_network,
},
#[cfg(not(target_os = "macos"))]
SandboxType::MacosSeatbelt => return Err(SandboxTransformError::SeatbeltUnavailable),
SandboxType::WindowsMxc => {
if !codex_mxc_sandbox::is_available() {
return Err(SandboxTransformError::WindowsMxcPreparation(
@@ -614,205 +620,37 @@ impl SandboxManager {
}
route => route,
};
let pending = pending?;
exec.permission_profile = pending.effective_permission_profile;
let exe = sandbox_exe.ok_or_else(|| {
SandboxTransformError::WindowsMxcPreparation(
"missing Codex executable path".into(),
)
})?;
let args = codex_mxc_sandbox::create_command_args(
codex_mxc_sandbox::CreateMxcCommandArgsParams {
command: std::mem::take(&mut exec.command),
permission_profile: &exec.permission_profile,
sandbox_policy_cwd: &pending.native_sandbox_policy_cwd,
managed_network: route.as_ref(),
env: &mut exec.env,
},
)
.map_err(|err| SandboxTransformError::WindowsMxcPreparation(err.to_string()))?;
exec.command = std::iter::once(exe.to_string_lossy().into_owned())
.chain(args)
.collect();
}
#[cfg(target_os = "macos")]
SandboxType::MacosSeatbelt => {
use crate::seatbelt::CreateSeatbeltCommandArgsParams;
use crate::seatbelt::MACOS_PATH_TO_SEATBELT_EXECUTABLE;
use crate::seatbelt::SeatbeltPreparationError;
use crate::seatbelt::create_seatbelt_command_args_with_profile;
let pending = pending?;
exec.permission_profile = pending.effective_permission_profile;
let (file_system_sandbox_policy, network_sandbox_policy) =
exec.permission_profile.to_runtime_permissions();
let managed_network = match (managed_network, network) {
(None, Some(proxy)) => {
let prepared = proxy
.prepare_for_optional_environment(exec.env, environment_id)
.map_err(|err| {
SandboxTransformError::EnvironmentNetworkProxy(err.to_string())
})?;
exec.env = prepared.env;
Some(prepared.sandbox_context)
}
(context, _) => context,
};
let (profile, sockets) = match &self.operation {
SandboxOperation::Command => (MacosSeatbeltProfile::Process, [].as_slice()),
SandboxOperation::InheritedTerminal { allow_unix_sockets } => (
MacosSeatbeltProfile::ProcessWithInheritedTerminal,
allow_unix_sockets.as_slice(),
),
SandboxOperation::FileSystemHelper => {
(MacosSeatbeltProfile::FileSystemHelper, [].as_slice())
}
};
let args = create_seatbelt_command_args_with_profile(
CreateSeatbeltCommandArgsParams {
command: std::mem::take(&mut exec.command),
file_system_sandbox_policy: &file_system_sandbox_policy,
network_sandbox_policy,
sandbox_policy_cwd: &pending.native_sandbox_policy_cwd,
enforce_managed_network,
managed_network: managed_network.as_ref(),
environment_id,
network,
extra_allow_unix_sockets: sockets,
},
profile,
self.allowed_symlinked_codex_home.as_ref(),
)
.map_err(|err| match err {
SeatbeltPreparationError::FileSystem(message) => {
SandboxTransformError::SeatbeltPreparation(message)
}
SeatbeltPreparationError::EnvironmentNetworkProxy(message) => {
SandboxTransformError::EnvironmentNetworkProxy(message)
}
})?;
exec.command = std::iter::once(MACOS_PATH_TO_SEATBELT_EXECUTABLE.to_owned())
.chain(args)
.collect();
}
#[cfg(not(target_os = "macos"))]
SandboxType::MacosSeatbelt => return Err(SandboxTransformError::SeatbeltUnavailable),
SandboxType::LinuxSeccomp => {
let pending = pending?;
exec.permission_profile = pending.effective_permission_profile;
let exe =
sandbox_exe.ok_or(SandboxTransformError::MissingLinuxSandboxExecutable)?;
let route = match (enforce_managed_network, managed_network, network) {
(false, _, _) => None,
(true, None, Some(proxy)) => {
let prepared = proxy
.prepare_for_optional_environment(exec.env, environment_id)
.map_err(|err| {
SandboxTransformError::EnvironmentNetworkProxy(err.to_string())
})?;
exec.env = prepared.env;
Some(prepared.sandbox_context)
}
(true, context, _) => Some(context.unwrap_or_default()),
};
self.wrap_linux(
&mut exec,
(
&pending.native_command_cwd,
&pending.native_sandbox_policy_cwd,
),
exe,
request.use_legacy_landlock,
route.as_ref(),
)?;
&mut crate::windows_mxc::Mxc { sandbox_exe, route }
}
#[cfg(not(windows))]
SandboxType::WindowsRestrictedToken => {
let pending = pending?;
exec.permission_profile = pending.effective_permission_profile;
#[cfg(not(windows))]
prepare_native_sandbox(&mut exec, managed_mitm_ca_trust_bundle_path.as_ref())?;
if is_file_system_helper {
return Err(SandboxTransformError::SandboxUnavailable);
}
#[cfg(windows)]
if is_file_system_helper {
let codex_home = codex_utils_home_dir::find_codex_home().map_err(|err| {
SandboxTransformError::WindowsSandboxPreparation(err.to_string())
})?;
wrap_windows_file_system_helper(
&mut exec,
&policy.workspace_roots,
&codex_home,
sandbox_exe,
)?;
} else if let Some(proxy_settings_mode) = self.windows_token_session {
let filesystem_overrides = WindowsSandboxFilesystemOverrides::resolve(
backend,
&exec.permission_profile,
&pending.native_sandbox_policy_cwd,
exec.windows_sandbox_level,
&exec.env,
)
.map_err(|err| SandboxTransformError::InvalidPolicy(io::Error::other(err)))?;
let session = WindowsSessionPolicy {
workspace_roots: policy.workspace_roots,
filesystem_overrides,
proxy_enforced: enforce_managed_network,
restricting_sid: windows_proxy_restricting_sid(network, environment_id)?,
proxy_settings_mode,
};
return Ok(wrapped(exec, Some(Box::new(session))));
}
return Ok(wrapped(exec, None));
}
}
Ok(wrapped(exec, None))
}
fn wrap_linux(
&self,
exec: &mut SandboxExecRequest,
(cwd, policy_cwd): (&AbsolutePathBuf, &AbsolutePathBuf),
exe: &Path,
use_legacy_landlock: bool,
managed_network: Option<&ManagedNetworkSandboxContext>,
) -> Result<(), SandboxTransformError> {
let mode = LinuxSandboxMode::resolve(use_legacy_landlock, managed_network);
#[cfg(target_os = "linux")]
if crate::bwrap::is_wsl1() {
mode.ensure_supported_on_wsl1(&exec.permission_profile)?;
}
let program = exe.to_string_lossy().into_owned();
let mut args = crate::linux::create_linux_sandbox_command_args_for_permission_profile(
std::mem::take(&mut exec.command),
cwd,
&exec.permission_profile,
policy_cwd,
mode,
);
// Only the startup opt-in requires a helper that understands PID inheritance.
if self.linux_sandbox_pid_namespace == LinuxSandboxPidNamespace::Inherit {
args.insert(0, "--inherit-pid-namespace".to_owned());
}
if managed_network
.is_some_and(|ctx| ctx.transparent_tcp || self.linux_sandbox_transparent_tcp)
{
args.insert(0, "--transparent-tcp".to_owned());
}
exec.command = std::iter::once(program).chain(args).collect();
// Without bwrap --argv0, the Linux helper uses its own argv[0] as the inner executable.
let arg0 = if let Some(path) = exe.to_str()
&& exe.file_name() == Some(OsStr::new(CODEX_LINUX_SANDBOX_ARG0))
{
path
} else {
CODEX_LINUX_SANDBOX_ARG0
#[cfg(windows)]
SandboxType::WindowsRestrictedToken => &mut crate::windows::WindowsToken {
proxy_settings: self.windows_token_session,
file_system_helper: is_file_system_helper,
sandbox_exe,
workspace_roots: policy.workspace_roots,
enforce_managed_network,
network,
environment_id,
session: &mut session,
},
};
exec.arg0 = Some(arg0.to_owned());
Ok(())
let (cwd, policy_cwd) =
prepare_native_sandbox(&mut exec, managed_mitm_ca_trust_bundle_path.as_ref())?;
platform.prepare(&mut exec, &cwd, &policy_cwd)?;
Ok(wrapped(exec, session))
}
}
#[cfg(windows)]
fn windows_proxy_restricting_sid(
pub(super) fn windows_proxy_restricting_sid(
proxy: Option<&NetworkProxy>,
environment_id: Option<&str>,
) -> Result<Option<String>, SandboxTransformError> {
@@ -830,7 +668,7 @@ fn windows_proxy_restricting_sid(
}
#[cfg(target_os = "windows")]
fn wrap_windows_file_system_helper(
pub(super) fn wrap_windows_file_system_helper(
request: &mut SandboxExecRequest,
workspace_roots: &[AbsolutePathBuf],
codex_home: &Path,
+75
View File
@@ -1,3 +1,7 @@
use crate::SandboxExecRequest;
use crate::SandboxTransformError;
use crate::manager::SandboxBackend;
use crate::manager::launch::SandboxOperation;
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_network_proxy::NetworkProxy;
use codex_network_proxy::PROXY_URL_ENV_KEYS;
@@ -16,6 +20,77 @@ use std::path::PathBuf;
use tracing::warn;
use url::Url;
pub(super) struct Seatbelt<'a> {
pub(super) operation: &'a SandboxOperation,
pub(super) allowed_symlinked_codex_home: Option<&'a AbsolutePathBuf>,
pub(super) enforce_managed_network: bool,
pub(super) route: Option<ManagedNetworkSandboxContext>,
}
impl SandboxBackend for Seatbelt<'_> {
fn prepare(
&mut self,
exec: &mut SandboxExecRequest,
_cwd: &AbsolutePathBuf,
policy_cwd: &AbsolutePathBuf,
) -> Result<(), SandboxTransformError> {
let (file_system_sandbox_policy, network_sandbox_policy) =
exec.permission_profile.to_runtime_permissions();
let managed_network = match (self.route.take(), &exec.network) {
(None, Some(proxy)) => {
let prepared = proxy
.prepare_for_optional_environment(
std::mem::take(&mut exec.env),
exec.network_environment_id.as_deref(),
)
.map_err(|err| {
SandboxTransformError::EnvironmentNetworkProxy(err.to_string())
})?;
exec.env = prepared.env;
Some(prepared.sandbox_context)
}
(context, _) => context,
};
let (profile, sockets) = match self.operation {
SandboxOperation::Command => (MacosSeatbeltProfile::Process, [].as_slice()),
SandboxOperation::InheritedTerminal { allow_unix_sockets } => (
MacosSeatbeltProfile::ProcessWithInheritedTerminal,
allow_unix_sockets.as_slice(),
),
SandboxOperation::FileSystemHelper => {
(MacosSeatbeltProfile::FileSystemHelper, [].as_slice())
}
};
let args = create_seatbelt_command_args_with_profile(
CreateSeatbeltCommandArgsParams {
command: std::mem::take(&mut exec.command),
file_system_sandbox_policy: &file_system_sandbox_policy,
network_sandbox_policy,
sandbox_policy_cwd: policy_cwd,
enforce_managed_network: self.enforce_managed_network,
managed_network: managed_network.as_ref(),
environment_id: exec.network_environment_id.as_deref(),
network: exec.network.as_ref(),
extra_allow_unix_sockets: sockets,
},
profile,
self.allowed_symlinked_codex_home,
)
.map_err(|err| match err {
SeatbeltPreparationError::FileSystem(message) => {
SandboxTransformError::SeatbeltPreparation(message)
}
SeatbeltPreparationError::EnvironmentNetworkProxy(message) => {
SandboxTransformError::EnvironmentNetworkProxy(message)
}
})?;
exec.command = std::iter::once(MACOS_PATH_TO_SEATBELT_EXECUTABLE.to_owned())
.chain(args)
.collect();
Ok(())
}
}
const MACOS_SEATBELT_BASE_POLICY: &str = include_str!("seatbelt_base_policy.sbpl");
const MACOS_SEATBELT_NETWORK_POLICY: &str = include_str!("seatbelt_network_policy.sbpl");
// System libcurl needs this service for TLS; keep it out of Unix-only profiles.
+95
View File
@@ -1,8 +1,20 @@
#[cfg(windows)]
use crate::SandboxExecRequest;
#[cfg(windows)]
use crate::SandboxTransformError;
use crate::WindowsSandboxProxySettingsMode;
#[cfg(windows)]
use crate::manager::SandboxBackend;
#[cfg(windows)]
use codex_network_proxy::NetworkProxy;
use std::collections::BTreeSet;
use std::collections::HashMap;
#[cfg(windows)]
use std::io;
use std::path::Path;
use std::path::PathBuf;
use codex_network_proxy::ManagedProxyRouting;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemPolicyProjection;
@@ -13,6 +25,68 @@ use codex_utils_absolute_path::AbsolutePathBuf;
use crate::SandboxType;
pub(super) struct WindowsSessionPolicy {
pub(super) workspace_roots: Vec<AbsolutePathBuf>,
pub(super) filesystem_overrides: Option<WindowsSandboxFilesystemOverrides>,
pub(super) proxy_enforced: bool,
#[cfg(windows)]
pub(super) restricting_sid: Option<String>,
pub(super) proxy_settings_mode: WindowsSandboxProxySettingsMode,
}
#[cfg(windows)]
pub(super) struct WindowsToken<'a> {
pub(super) proxy_settings: Option<WindowsSandboxProxySettingsMode>,
pub(super) file_system_helper: bool,
pub(super) sandbox_exe: Option<&'a Path>,
pub(super) workspace_roots: Vec<AbsolutePathBuf>,
pub(super) enforce_managed_network: bool,
pub(super) network: Option<&'a NetworkProxy>,
pub(super) environment_id: Option<&'a str>,
pub(super) session: &'a mut Option<Box<WindowsSessionPolicy>>,
}
#[cfg(windows)]
impl SandboxBackend for WindowsToken<'_> {
fn prepare(
&mut self,
exec: &mut SandboxExecRequest,
_cwd: &AbsolutePathBuf,
policy_cwd: &AbsolutePathBuf,
) -> Result<(), SandboxTransformError> {
if self.file_system_helper {
let codex_home = codex_utils_home_dir::find_codex_home()
.map_err(|err| SandboxTransformError::WindowsSandboxPreparation(err.to_string()))?;
crate::manager::wrap_windows_file_system_helper(
exec,
&self.workspace_roots,
&codex_home,
self.sandbox_exe,
)?;
} else if let Some(proxy_settings_mode) = self.proxy_settings {
let filesystem_overrides = WindowsSandboxFilesystemOverrides::resolve(
SandboxType::WindowsRestrictedToken,
&exec.permission_profile,
policy_cwd,
exec.windows_sandbox_level,
&exec.env,
)
.map_err(|err| SandboxTransformError::InvalidPolicy(io::Error::other(err)))?;
*self.session = Some(Box::new(WindowsSessionPolicy {
workspace_roots: std::mem::take(&mut self.workspace_roots),
filesystem_overrides,
proxy_enforced: self.enforce_managed_network,
restricting_sid: crate::manager::windows_proxy_restricting_sid(
self.network,
self.environment_id,
)?,
proxy_settings_mode,
}));
}
Ok(())
}
}
/// Resolved filesystem overrides for the Windows sandbox backends.
///
/// The elevated Windows backend consumes extra deny-read paths plus explicit
@@ -64,6 +138,27 @@ pub fn windows_sandbox_uses_elevated_backend(sandbox_level: WindowsSandboxLevel)
matches!(sandbox_level, WindowsSandboxLevel::Elevated)
}
/// MXC uses dedicated proxy listeners when the proxy runs on Windows.
pub fn managed_proxy_routing_for_windows_sandbox(sandbox_type: SandboxType) -> ManagedProxyRouting {
if cfg!(windows) && sandbox_type == SandboxType::WindowsMxc {
ManagedProxyRouting::DedicatedListeners
} else {
ManagedProxyRouting::SharedIngress
}
}
/// A native Windows process has no sandbox token SID for shared proxy ingress.
/// An explicit sandbox context can request shared ingress even with Windows sandboxing disabled.
pub fn executor_managed_proxy_routing(
windows_sandbox: Option<SandboxType>,
) -> Option<ManagedProxyRouting> {
match windows_sandbox {
Some(sandbox) => Some(managed_proxy_routing_for_windows_sandbox(sandbox)),
None if cfg!(windows) => None,
None => Some(ManagedProxyRouting::SharedIngress),
}
}
pub fn permission_profile_supports_windows_restricted_token_sandbox(
permission_profile: &PermissionProfile,
) -> bool {
+42 -4
View File
@@ -1,12 +1,50 @@
//! Native Windows MXC capability discovery and availability metrics.
//! Prepare the MXC launch command and report native Windows capability.
//! Probing is cached upstream; reporting happens at most once per process.
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use crate::SandboxExecRequest;
use crate::SandboxTransformError;
use crate::manager::SandboxBackend;
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_utils_absolute_path::AbsolutePathBuf;
use std::path::Path;
static AVAILABILITY_RECORDED: AtomicBool = AtomicBool::new(false);
pub(super) struct Mxc<'a> {
pub(super) sandbox_exe: Option<&'a Path>,
pub(super) route: Option<ManagedNetworkSandboxContext>,
}
impl SandboxBackend for Mxc<'_> {
fn prepare(
&mut self,
exec: &mut SandboxExecRequest,
_cwd: &AbsolutePathBuf,
policy_cwd: &AbsolutePathBuf,
) -> Result<(), SandboxTransformError> {
let exe = self.sandbox_exe.ok_or_else(|| {
SandboxTransformError::WindowsMxcPreparation("missing Codex executable path".into())
})?;
let args =
codex_mxc_sandbox::create_command_args(codex_mxc_sandbox::CreateMxcCommandArgsParams {
command: std::mem::take(&mut exec.command),
permission_profile: &exec.permission_profile,
sandbox_policy_cwd: policy_cwd,
managed_network: self.route.as_ref(),
env: &mut exec.env,
})
.map_err(|err| SandboxTransformError::WindowsMxcPreparation(err.to_string()))?;
exec.command = std::iter::once(exe.to_string_lossy().into_owned())
.chain(args)
.collect();
Ok(())
}
}
#[cfg(windows)]
pub(super) fn record_availability_once() {
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
static AVAILABILITY_RECORDED: AtomicBool = AtomicBool::new(false);
// Probe actual PSEC create/close support; symbol presence alone also
// succeeds on transitional Windows builds where MXC is not enabled.
let available = codex_mxc_sandbox::is_available();