Resolve Linux sandbox mode once before launching the helper (#62215)

## Why

Managed proxy routes require bubblewrap's network namespace even when
`features.use_legacy_landlock` is enabled. WSL1 compatibility checks and
helper arguments need to agree on the effective mode.

## What changed

Resolve bubblewrap or legacy Landlock once and use that mode for both the
WSL1 check and the `codex-linux-sandbox` arguments. Use Linux sandbox
naming for the shared launcher and CLI code, and preserve the published
analytics category for a missing helper executable.

## Testing

Unit tests exercise the production argument builder, including managed
network context serialization when legacy Landlock is requested. They
also cover which sandbox configurations WSL1 accepts and rejects.

GitOrigin-RevId: 619ab9d3eef965de6bc6cb13ff8a33132018abcf
This commit is contained in:
viyatb-oai
2026-11-18 07:23:25 +00:00
committed by copyberry
parent ba8ab2d050
commit bcff988bd1
26 changed files with 301 additions and 360 deletions
+1 -1
View File
@@ -10,7 +10,7 @@ use codex_async_utils::THREAD_STACK_SIZE_BYTES;
use codex_exec_server::CODEX_ARG0_EXEC_HELPER_ARG1;
use codex_exec_server::CODEX_FS_HELPER_ARG1;
use codex_install_context::InstallContext;
use codex_sandboxing::landlock::CODEX_LINUX_SANDBOX_ARG0;
use codex_sandboxing::linux::CODEX_LINUX_SANDBOX_ARG0;
use codex_utils_home_dir::find_codex_home;
#[cfg(target_os = "windows")]
use codex_windows_sandbox::CODEX_WINDOWS_SANDBOX_ARG1;
+8 -8
View File
@@ -41,7 +41,7 @@ use tokio::process::Child;
use tokio::process::Command as TokioCommand;
use toml::Value as TomlValue;
use crate::LandlockCommand;
use crate::LinuxSandboxCommand;
use crate::SeatbeltCommand;
use crate::WindowsCommand;
use crate::exit_status::handle_exit_status;
@@ -97,12 +97,12 @@ pub async fn run_command_under_seatbelt(
anyhow::bail!("Seatbelt sandbox is only available on macOS");
}
pub async fn run_command_under_landlock(
command: LandlockCommand,
pub async fn run_command_under_linux_sandbox(
command: LinuxSandboxCommand,
codex_linux_sandbox_exe: Option<PathBuf>,
loader_overrides: LoaderOverrides,
) -> anyhow::Result<()> {
let LandlockCommand {
let LinuxSandboxCommand {
transparent_tcp,
sandbox_state,
permissions_profile,
@@ -127,7 +127,7 @@ pub async fn run_command_under_landlock(
command,
config_overrides,
codex_linux_sandbox_exe,
SandboxType::Landlock { transparent_tcp },
SandboxType::Linux { transparent_tcp },
/*log_denials*/ false,
&[],
)
@@ -173,7 +173,7 @@ pub async fn run_command_under_windows_sandbox(
enum SandboxType {
#[cfg(target_os = "macos")]
Seatbelt,
Landlock {
Linux {
transparent_tcp: bool,
},
Windows,
@@ -310,7 +310,7 @@ async fn run_command_under_sandbox(
};
let transparent_tcp = match sandbox_type {
SandboxType::Landlock { transparent_tcp } => {
SandboxType::Linux { transparent_tcp } => {
transparent_tcp
|| config
.permissions
@@ -330,7 +330,7 @@ async fn run_command_under_sandbox(
SandboxEnforcement::Managed => match sandbox_type {
#[cfg(target_os = "macos")]
SandboxType::Seatbelt => SandboxBackend::MacosSeatbelt,
SandboxType::Landlock { .. } => SandboxBackend::LinuxSeccomp,
SandboxType::Linux { .. } => SandboxBackend::LinuxSeccomp,
#[cfg(windows)]
SandboxType::Windows if windows_sandbox_type == WindowsMxc => WindowsMxc,
#[cfg(windows)]
+2 -2
View File
@@ -11,7 +11,7 @@ use codex_utils_cli::CliConfigOverrides;
use codex_utils_cli::ProfileV2Name;
use std::path::PathBuf;
pub use debug_sandbox::run_command_under_landlock;
pub use debug_sandbox::run_command_under_linux_sandbox;
pub use debug_sandbox::run_command_under_seatbelt;
pub use debug_sandbox::run_command_under_windows_sandbox;
pub use git_credential::GitCredentialArgs;
@@ -108,7 +108,7 @@ fn parse_absolute_path(raw: &str) -> Result<AbsolutePathBuf, String> {
}
#[derive(Debug, Parser)]
pub struct LandlockCommand {
pub struct LinuxSandboxCommand {
/// Route outbound TCP through the managed SOCKS proxy.
#[arg(long)]
pub transparent_tcp: bool,
+2 -2
View File
@@ -487,7 +487,7 @@ enum SandboxSubcommand {
#[cfg(target_os = "macos")]
type HostSandboxArgs = codex_cli::SeatbeltCommand;
#[cfg(target_os = "linux")]
type HostSandboxArgs = codex_cli::LandlockCommand;
type HostSandboxArgs = codex_cli::LinuxSandboxCommand;
#[cfg(target_os = "windows")]
type HostSandboxArgs = codex_cli::WindowsCommand;
@@ -1851,7 +1851,7 @@ async fn dispatch_cli(
)
.await?;
#[cfg(target_os = "linux")]
codex_cli::run_command_under_landlock(
codex_cli::run_command_under_linux_sandbox(
sandbox_cli,
arg0_paths.codex_linux_sandbox_exe.clone(),
loader_overrides,
+1 -1
View File
@@ -203,7 +203,7 @@ pub struct McpConfig {
pub codex_self_exe: Option<PathBuf>,
/// Optional path to `codex-linux-sandbox` for sandboxed MCP tool execution.
pub codex_linux_sandbox_exe: Option<PathBuf>,
/// Whether to use legacy Landlock behavior in the MCP sandbox state.
/// Whether the MCP sandbox state requests legacy Landlock mode.
// TODO(anp): Reconcile this runtime-wide copy with TurnEnvironment::sandbox_context
// for the environment that owns each MCP server.
pub use_legacy_landlock: bool,
+6 -10
View File
@@ -38,16 +38,12 @@ Seatbelt also keeps the legacy default preferences read access
Expects the binary containing `codex-core` to run the equivalent of `codex sandbox` when `arg0` is `codex-linux-sandbox`. See the `codex-arg0` crate for details.
Legacy `SandboxPolicy` / `sandbox_mode` configs are still supported on Linux.
They can continue to use the legacy Landlock path when the split filesystem
policy is sandbox-equivalent to the legacy model after `cwd` resolution.
Split filesystem policies that need direct `FileSystemSandboxPolicy`
enforcement, such as read-only or denied carveouts under a broader writable
root, automatically route through bubblewrap. The legacy Landlock path is used
only when the split filesystem policy round-trips through the legacy
`SandboxPolicy` model without changing semantics. That includes overlapping
cases like `/repo = write`, `/repo/a = none`, `/repo/a/b = write`, where the
more specific writable child must reopen under a denied parent.
The Linux sandbox accepts both legacy `sandbox_mode` configs and permission
profiles. Bubblewrap enforces filesystem restrictions and provides the network
namespace for managed proxy routes. A managed route selects bubblewrap even
when `features.use_legacy_landlock` is set. Without a managed route, the helper
rejects legacy Landlock if the policy restricts filesystem writes. With full
disk write access it can apply network restrictions in process.
The Linux sandbox helper prefers the first `bwrap` found on `PATH` outside the
current working directory whenever it is available. If `bwrap` is present but
+1 -1
View File
@@ -1056,7 +1056,7 @@ async fn augment_mcp_tool_request_meta_with_sandbox_state(
return Ok(meta);
};
// TODO(anp): Build this metadata from the server's captured
// TurnEnvironment::sandbox_context instead of the runtime-wide Landlock value.
// TurnEnvironment::sandbox_context instead of the runtime-wide legacy Landlock setting.
prepared_call
.augment_sandbox_metadata(
&mut meta,
+1 -1
View File
@@ -46,7 +46,7 @@ use codex_protocol::protocol::ThreadSettingsOverrides;
use codex_protocol::protocol::TurnEnvironmentSelection;
use codex_protocol::user_input::UserInput;
#[cfg(target_os = "linux")]
use codex_sandboxing::landlock::CODEX_LINUX_SANDBOX_ARG0;
use codex_sandboxing::linux::CODEX_LINUX_SANDBOX_ARG0;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use core_test_support::PathBufExt;
+1 -1
View File
@@ -3,7 +3,7 @@ use codex_apply_patch::CODEX_CORE_APPLY_PATCH_ARG1;
#[cfg(unix)]
use codex_exec_server::CODEX_ARG0_EXEC_HELPER_ARG1;
use codex_exec_server::CODEX_FS_HELPER_ARG1;
use codex_sandboxing::landlock::CODEX_LINUX_SANDBOX_ARG0;
use codex_sandboxing::linux::CODEX_LINUX_SANDBOX_ARG0;
use codex_test_binary_support::TestBinaryDispatchGuard;
use codex_test_binary_support::TestBinaryDispatchMode;
use codex_test_binary_support::configure_test_binary_dispatch;
@@ -25,7 +25,7 @@ use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::models::PermissionProfile;
use codex_sandboxing::WrappedSandboxCommand;
#[cfg(target_os = "linux")]
use codex_sandboxing::landlock::CODEX_LINUX_SANDBOX_ARG0;
use codex_sandboxing::linux::CODEX_LINUX_SANDBOX_ARG0;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
+1 -1
View File
@@ -13,7 +13,7 @@ use codex_exec_server::ExecServerTelemetry;
use codex_exec_server::RequestDispatchMode;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_sandboxing::landlock::CODEX_LINUX_SANDBOX_ARG0;
use codex_sandboxing::linux::CODEX_LINUX_SANDBOX_ARG0;
use codex_test_binary_support::TestBinaryDispatchGuard;
use codex_test_binary_support::TestBinaryDispatchMode;
use codex_test_binary_support::configure_test_binary_dispatch;
+2 -2
View File
@@ -8,8 +8,8 @@
//! options and launches the non-interactive Codex agent. However, if it is
//! invoked with arg0 as `codex-linux-sandbox`, we instead treat the invocation
//! as a request to run the logic for the standalone `codex-linux-sandbox`
//! executable (i.e., parse any -s args and then run a *sandboxed* command under
//! Landlock + seccomp.
//! executable. The helper applies the requested Linux sandbox policy before
//! starting the command.
//!
//! This allows us to ship a completely separate set of functionality as part
//! of the `codex-exec` binary.
+3 -9
View File
@@ -96,10 +96,8 @@ pub(super) async fn spawn_command_under_sandbox(
#[cfg(target_os = "linux")]
/// Determines whether Linux sandbox tests can run on this host.
///
/// These tests require an enforceable filesystem sandbox. We run a tiny command
/// under the production Landlock path and skip when enforcement is unavailable
/// (for example on kernels or container profiles where Landlock is not
/// enforced).
/// The probe runs `/usr/bin/true` through the Linux sandbox with a read-only
/// profile. The tests skip hosts where that command cannot start successfully.
pub(super) async fn linux_sandbox_test_env() -> Option<HashMap<String, String>> {
let command_cwd = AbsolutePathBuf::current_dir().ok()?;
let sandbox_cwd = command_cwd.clone();
@@ -116,16 +114,13 @@ pub(super) async fn linux_sandbox_test_env() -> Option<HashMap<String, String>>
return Some(HashMap::new());
}
eprintln!("Skipping test: Landlock is not enforceable on this host.");
eprintln!("Skipping test: the Linux sandbox could not run the read-only probe.");
None
}
#[cfg(target_os = "linux")]
/// Returns whether a minimal command can run successfully with the requested
/// Linux sandbox policy applied.
///
/// This is used as a capability probe so sandbox behavior tests only run when
/// Landlock enforcement is actually active.
async fn can_apply_linux_sandbox_policy(
permission_profile: &PermissionProfile,
command_cwd: &AbsolutePathBuf,
@@ -157,7 +152,6 @@ async fn python_multiprocessing_lock_works_under_sandbox() {
#[cfg(target_os = "linux")]
let sandbox_env = match linux_sandbox_test_env().await {
Some(env) => env,
// Skip on Linux hosts where Landlock cannot actually be enforced.
None => return,
};
#[cfg(not(target_os = "linux"))]
+1 -2
View File
@@ -203,8 +203,7 @@ pub enum Feature {
StandaloneWebSearch,
/// Let the host authorize MCP search independently of native search through per-turn policy.
HostedSearchPolicy,
/// Use the legacy Landlock Linux sandbox fallback instead of the default
/// bubblewrap pipeline.
/// Request the legacy Landlock mode of the Linux sandbox.
UseLegacyLandlock,
/// Experimental shell snapshotting.
ShellSnapshot,
+2
View File
@@ -87,6 +87,8 @@ commands that would enter the bubblewrap path.
Unix sockets. Disable `features.use_legacy_landlock` when upgrading.
- Bubblewrap preserves nested read-only and denied filesystem rules from
`PermissionProfile`.
- Managed proxy routes require bubblewrap's network namespace, including when
`features.use_legacy_landlock` is set.
- When bubblewrap is active, the helper applies `PR_SET_NO_NEW_PRIVS` and a
seccomp filter in-process after establishing the filesystem view. Restricted
network policies block network syscalls; filesystem-restricted policies with
+2 -4
View File
@@ -38,7 +38,7 @@ use codex_protocol::protocol::FileSystemSandboxEntry;
use codex_protocol::protocol::FileSystemSandboxPolicy;
use codex_protocol::protocol::FileSystemSpecialPath;
use codex_protocol::protocol::NetworkSandboxPolicy;
use codex_sandboxing::landlock::CODEX_LINUX_SANDBOX_ARG0;
use codex_sandboxing::linux::CODEX_LINUX_SANDBOX_ARG0;
static BWRAP_CHILD_PID: AtomicI32 = AtomicI32::new(0);
static PENDING_FORWARDED_SIGNAL: AtomicI32 = AtomicI32::new(0);
@@ -82,9 +82,7 @@ pub struct LinuxSandboxCommand {
)]
pub permission_profile: Option<PermissionProfile>,
/// Opt-in: use the legacy Landlock Linux sandbox fallback.
///
/// When not set, the helper uses the default bubblewrap pipeline.
/// Request legacy Landlock mode. Bubblewrap is the default.
#[arg(long = "use-legacy-landlock", hide = true, default_value_t = false)]
pub use_legacy_landlock: bool,
+1 -1
View File
@@ -5,7 +5,7 @@ use crate::bwrap::BwrapArgs;
use crate::exec_util::make_files_inheritable;
use crate::proxy_lifecycle::move_fd_above_stdio;
use codex_protocol::protocol::FileSystemSandboxPolicy;
use codex_sandboxing::landlock::CODEX_LINUX_SANDBOX_ARG0;
use codex_sandboxing::linux::CODEX_LINUX_SANDBOX_ARG0;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::fs::File;
+1 -1
View File
@@ -204,7 +204,7 @@ pub struct EnvironmentConfig {
pub windows_sandbox_level: WindowsSandboxLevel,
/// Concrete Windows sandbox backend selected for this environment attachment.
pub windows_sandbox_type: SandboxType,
/// Whether Linux sandbox processes use the legacy Landlock backend.
/// Whether this environment requests legacy Landlock mode.
pub use_legacy_landlock: bool,
/// Additional managed command restrictions for this environment attachment.
pub exec_policy: Option<RequirementsExecPolicy>,
+6 -3
View File
@@ -237,8 +237,11 @@ pub enum CodexErrorDetails {
/// Sandbox error
#[error("sandbox error: {0}")]
Sandbox(#[from] SandboxErr),
// Keep the published analytics category stable across the Rust variant rename.
#[strum_discriminants(serde(rename = "landlock_sandbox_executable_not_provided"))]
#[strum_discriminants(strum(serialize = "landlock_sandbox_executable_not_provided"))]
#[error("codex-linux-sandbox was required but not provided")]
LandlockSandboxExecutableNotProvided,
LinuxSandboxExecutableNotProvided,
#[error("unsupported operation: {0}")]
UnsupportedOperation(String),
#[error("{0}")]
@@ -407,7 +410,7 @@ impl CodexErr {
UsageNotIncluded,
InternalServerError,
InternalAgentDied,
LandlockSandboxExecutableNotProvided,
LinuxSandboxExecutableNotProvided,
);
codex_err_tuple_constructors!(
@@ -504,7 +507,7 @@ impl CodexErr {
| CodexErrorDetails::GatewayLoginRequired(_)
| CodexErrorDetails::UnsupportedOperation(_)
| CodexErrorDetails::Sandbox(_)
| CodexErrorDetails::LandlockSandboxExecutableNotProvided
| CodexErrorDetails::LinuxSandboxExecutableNotProvided
| CodexErrorDetails::ContextWindowExceeded
| CodexErrorDetails::ThreadNotFound(_)
| CodexErrorDetails::AgentLimitReached { .. }
-115
View File
@@ -1,115 +0,0 @@
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_protocol::models::PermissionProfile;
use std::path::Path;
/// Basename used when the Codex executable self-invokes as the Linux sandbox
/// helper.
pub const CODEX_LINUX_SANDBOX_ARG0: &str = "codex-linux-sandbox";
pub fn allow_network_for_proxy(enforce_managed_network: bool) -> bool {
// When managed network requirements are active, request proxy-only
// networking from the Linux sandbox helper. Without managed requirements,
// preserve existing behavior.
enforce_managed_network
}
/// Converts the permission profile into the CLI invocation for
/// `codex-linux-sandbox`.
///
/// A managed context selects proxy isolation; a default context keeps its
/// restrictive policy when an older caller supplies no additional details.
///
/// The helper performs the actual sandboxing (bubblewrap by default + seccomp)
/// 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(crate) fn create_linux_sandbox_command_args_for_permission_profile(
command: Vec<String>,
command_cwd: &Path,
permission_profile: &PermissionProfile,
sandbox_policy_cwd: &Path,
use_legacy_landlock: bool,
managed_network: Option<&ManagedNetworkSandboxContext>,
) -> Vec<String> {
let permission_profile_json = serde_json::to_string(permission_profile)
.unwrap_or_else(|err| panic!("failed to serialize permission profile: {err}"));
let sandbox_policy_cwd = sandbox_policy_cwd
.to_str()
.unwrap_or_else(|| panic!("cwd must be valid UTF-8"))
.to_string();
let command_cwd = command_cwd
.to_str()
.unwrap_or_else(|| panic!("command cwd must be valid UTF-8"))
.to_string();
let mut linux_cmd: Vec<String> = vec![
"--sandbox-policy-cwd".to_string(),
sandbox_policy_cwd,
"--command-cwd".to_string(),
command_cwd,
"--permission-profile".to_string(),
permission_profile_json,
];
// Proxy-only networking requires bubblewrap's isolated network namespace.
if use_legacy_landlock && managed_network.is_none() {
linux_cmd.push("--use-legacy-landlock".to_string());
}
if let Some(managed_network) = managed_network {
linux_cmd.push("--managed-network".to_string());
linux_cmd.push(
serde_json::to_string(managed_network)
.unwrap_or_else(|err| panic!("failed to serialize managed network context: {err}")),
);
}
linux_cmd.push("--".to_string());
linux_cmd.extend(command);
linux_cmd
}
/// Converts the sandbox cwd and execution options into the CLI invocation for
/// `codex-linux-sandbox`.
#[cfg_attr(not(test), allow(dead_code))]
fn create_linux_sandbox_command_args(
command: Vec<String>,
command_cwd: &Path,
sandbox_policy_cwd: &Path,
use_legacy_landlock: bool,
allow_network_for_proxy: bool,
) -> Vec<String> {
let command_cwd = command_cwd
.to_str()
.unwrap_or_else(|| panic!("command cwd must be valid UTF-8"))
.to_string();
let sandbox_policy_cwd = sandbox_policy_cwd
.to_str()
.unwrap_or_else(|| panic!("cwd must be valid UTF-8"))
.to_string();
let mut linux_cmd: Vec<String> = vec![
"--sandbox-policy-cwd".to_string(),
sandbox_policy_cwd,
"--command-cwd".to_string(),
command_cwd,
];
// Proxy-only networking requires bubblewrap's isolated network namespace.
if use_legacy_landlock && !allow_network_for_proxy {
linux_cmd.push("--use-legacy-landlock".to_string());
}
if allow_network_for_proxy {
linux_cmd.push("--managed-network".to_string());
linux_cmd.push("{}".to_string());
}
// Separator so that command arguments starting with `-` are not parsed as
// options of the helper itself.
linux_cmd.push("--".to_string());
// Append the original tool command.
linux_cmd.extend(command);
linux_cmd
}
#[cfg(test)]
#[path = "landlock_tests.rs"]
mod tests;
-92
View File
@@ -1,92 +0,0 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn legacy_landlock_flag_is_included_when_requested() {
let command = vec!["/bin/true".to_string()];
let command_cwd = Path::new("/tmp/link");
let cwd = Path::new("/tmp");
let default_bwrap = create_linux_sandbox_command_args(
command.clone(),
command_cwd,
cwd,
/*use_legacy_landlock*/ false,
/*allow_network_for_proxy*/ false,
);
assert_eq!(
default_bwrap.contains(&"--use-legacy-landlock".to_string()),
false
);
let legacy_landlock = create_linux_sandbox_command_args(
command,
command_cwd,
cwd,
/*use_legacy_landlock*/ true,
/*allow_network_for_proxy*/ false,
);
assert_eq!(
legacy_landlock.contains(&"--use-legacy-landlock".to_string()),
true
);
}
#[test]
fn managed_context_takes_precedence_over_legacy_landlock() {
let command = vec!["/bin/true".to_string()];
let command_cwd = Path::new("/tmp/link");
let cwd = Path::new("/tmp");
let permission_profile = PermissionProfile::read_only();
let args = create_linux_sandbox_command_args_for_permission_profile(
command,
command_cwd,
&permission_profile,
cwd,
/*use_legacy_landlock*/ true,
Some(&ManagedNetworkSandboxContext::default()),
);
assert_eq!(args.contains(&"--managed-network".to_string()), true);
assert_eq!(args.contains(&"--use-legacy-landlock".to_string()), false);
}
#[test]
fn permission_profile_flag_is_included() {
let command = vec!["/bin/true".to_string()];
let command_cwd = Path::new("/tmp/link");
let cwd = Path::new("/tmp");
let permission_profile = PermissionProfile::read_only();
let args = create_linux_sandbox_command_args_for_permission_profile(
command,
command_cwd,
&permission_profile,
cwd,
/*use_legacy_landlock*/ true,
/*managed_network*/ None,
);
assert_eq!(
args.windows(2)
.any(|window| { window[0] == "--permission-profile" && !window[1].is_empty() }),
true
);
assert_eq!(
args.windows(2)
.any(|window| window[0] == "--command-cwd" && window[1] == "/tmp/link"),
true
);
}
#[test]
fn proxy_network_requires_managed_requirements() {
assert_eq!(
allow_network_for_proxy(/*enforce_managed_network*/ false),
false
);
assert_eq!(
allow_network_for_proxy(/*enforce_managed_network*/ true),
true
);
}
+2 -2
View File
@@ -1,7 +1,7 @@
#[cfg(target_os = "linux")]
mod bwrap;
mod denial;
pub mod landlock;
pub mod linux;
mod linux_pid_namespace;
mod manager;
pub mod policy_transforms;
@@ -88,7 +88,7 @@ impl From<SandboxTransformError> for CodexErr {
CodexErr::UnsupportedOperation(error.to_string())
}
SandboxTransformError::MissingLinuxSandboxExecutable => {
CodexErr::LandlockSandboxExecutableNotProvided
CodexErr::LinuxSandboxExecutableNotProvided
}
SandboxTransformError::EnvironmentNetworkProxy(message) => {
CodexErr::UnsupportedOperation(message)
+111
View File
@@ -0,0 +1,111 @@
//! Prepare the Linux sandbox helper command for bubblewrap or legacy Landlock.
#[cfg(target_os = "linux")]
use crate::SandboxTransformError;
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_protocol::models::PermissionProfile;
use std::path::Path;
/// Managed proxy and socket grants belong to bubblewrap. Legacy Landlock is a compatibility mode.
pub(super) enum LinuxSandboxMode<'a> {
Bubblewrap {
managed_network: Option<&'a ManagedNetworkSandboxContext>,
},
LegacyLandlock,
}
impl<'a> LinuxSandboxMode<'a> {
pub(super) fn resolve(
use_legacy_landlock: bool,
managed_network: Option<&'a ManagedNetworkSandboxContext>,
) -> Self {
if use_legacy_landlock && managed_network.is_none() {
Self::LegacyLandlock
} else {
Self::Bubblewrap { managed_network }
}
}
#[cfg(target_os = "linux")]
pub(super) fn ensure_supported_on_wsl1(
&self,
permission_profile: &PermissionProfile,
) -> Result<(), SandboxTransformError> {
let requires_bubblewrap = match self {
Self::Bubblewrap { managed_network } => {
managed_network.is_some()
|| !permission_profile
.file_system_sandbox_policy()
.has_full_disk_write_access()
}
Self::LegacyLandlock => false,
};
if requires_bubblewrap {
return Err(SandboxTransformError::Wsl1UnsupportedForBubblewrap);
}
Ok(())
}
}
/// Basename used when the Codex executable self-invokes as the Linux sandbox
/// helper.
pub const CODEX_LINUX_SANDBOX_ARG0: &str = "codex-linux-sandbox";
/// Converts the permission profile into the CLI invocation for
/// `codex-linux-sandbox`.
///
/// A managed context selects proxy isolation; a default context keeps its
/// restrictive policy when an older caller supplies no additional details.
///
/// The helper performs the actual sandboxing (bubblewrap by default + seccomp)
/// 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(
command: Vec<String>,
command_cwd: &Path,
permission_profile: &PermissionProfile,
sandbox_policy_cwd: &Path,
mode: LinuxSandboxMode<'_>,
) -> Vec<String> {
let permission_profile_json = serde_json::to_string(permission_profile)
.unwrap_or_else(|err| panic!("failed to serialize permission profile: {err}"));
let sandbox_policy_cwd = sandbox_policy_cwd
.to_str()
.unwrap_or_else(|| panic!("cwd must be valid UTF-8"))
.to_string();
let command_cwd = command_cwd
.to_str()
.unwrap_or_else(|| panic!("command cwd must be valid UTF-8"))
.to_string();
let mut linux_cmd: Vec<String> = vec![
"--sandbox-policy-cwd".to_string(),
sandbox_policy_cwd,
"--command-cwd".to_string(),
command_cwd,
"--permission-profile".to_string(),
permission_profile_json,
];
match mode {
LinuxSandboxMode::Bubblewrap {
managed_network: Some(context),
} => {
linux_cmd.push("--managed-network".to_string());
linux_cmd.push(serde_json::to_string(context).unwrap_or_else(|err| {
panic!("failed to serialize managed network context: {err}")
}));
}
LinuxSandboxMode::Bubblewrap {
managed_network: None,
} => {}
LinuxSandboxMode::LegacyLandlock => linux_cmd.push("--use-legacy-landlock".to_string()),
}
linux_cmd.push("--".to_string());
linux_cmd.extend(command);
linux_cmd
}
#[cfg(test)]
#[path = "linux_tests.rs"]
mod tests;
+136
View File
@@ -0,0 +1,136 @@
#![cfg(test)]
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn legacy_landlock_flag_is_included_when_requested() {
let command = vec!["/bin/true".to_string()];
let command_cwd = Path::new("/tmp/link");
let cwd = Path::new("/tmp");
let permission_profile = PermissionProfile::read_only();
let default_bwrap = create_linux_sandbox_command_args_for_permission_profile(
command.clone(),
command_cwd,
&permission_profile,
cwd,
LinuxSandboxMode::resolve(
/*use_legacy_landlock*/ false, /*managed_network*/ None,
),
);
assert_eq!(
default_bwrap.contains(&"--use-legacy-landlock".to_string()),
false
);
let legacy_landlock = create_linux_sandbox_command_args_for_permission_profile(
command,
command_cwd,
&permission_profile,
cwd,
LinuxSandboxMode::resolve(
/*use_legacy_landlock*/ true, /*managed_network*/ None,
),
);
assert_eq!(
legacy_landlock.contains(&"--use-legacy-landlock".to_string()),
true
);
}
#[test]
fn managed_context_takes_precedence_over_legacy_landlock() {
let command = vec!["/bin/true".to_string()];
let command_cwd = Path::new("/tmp/link");
let cwd = Path::new("/tmp");
let permission_profile = PermissionProfile::read_only();
let route = ManagedNetworkSandboxContext {
loopback_ports: vec![8123],
..Default::default()
};
let args = create_linux_sandbox_command_args_for_permission_profile(
command,
command_cwd,
&permission_profile,
cwd,
LinuxSandboxMode::resolve(/*use_legacy_landlock*/ true, Some(&route)),
);
let payload = args
.windows(2)
.find(|pair| pair[0] == "--managed-network")
.expect("managed network argument");
assert_eq!(
serde_json::from_str::<ManagedNetworkSandboxContext>(&payload[1]).expect("network context"),
route
);
assert_eq!(args.contains(&"--use-legacy-landlock".to_string()), false);
}
#[test]
fn permission_profile_flag_is_included() {
let command = vec!["/bin/true".to_string()];
let command_cwd = Path::new("/tmp/link");
let cwd = Path::new("/tmp");
let permission_profile = PermissionProfile::read_only();
let args = create_linux_sandbox_command_args_for_permission_profile(
command,
command_cwd,
&permission_profile,
cwd,
LinuxSandboxMode::LegacyLandlock,
);
assert_eq!(
args.windows(2)
.any(|window| { window[0] == "--permission-profile" && !window[1].is_empty() }),
true
);
assert_eq!(
args.windows(2)
.any(|window| window[0] == "--command-cwd" && window[1] == "/tmp/link"),
true
);
}
#[cfg(target_os = "linux")]
#[test]
fn wsl1_rejects_linux_bubblewrap_path() {
let read_only = PermissionProfile::read_only();
let no_proxy = LinuxSandboxMode::Bubblewrap {
managed_network: None,
};
assert!(matches!(
no_proxy.ensure_supported_on_wsl1(&read_only),
Err(SandboxTransformError::Wsl1UnsupportedForBubblewrap)
));
let route = ManagedNetworkSandboxContext::default();
for use_legacy_landlock in [false, true] {
let mode = LinuxSandboxMode::resolve(use_legacy_landlock, Some(&route));
assert!(matches!(
mode.ensure_supported_on_wsl1(&PermissionProfile::Disabled),
Err(SandboxTransformError::Wsl1UnsupportedForBubblewrap)
));
}
}
#[cfg(target_os = "linux")]
#[test]
fn wsl1_allows_non_bubblewrap_linux_paths() {
let no_proxy = LinuxSandboxMode::Bubblewrap {
managed_network: None,
};
assert!(
no_proxy
.ensure_supported_on_wsl1(&PermissionProfile::Disabled)
.is_ok()
);
assert!(
LinuxSandboxMode::LegacyLandlock
.ensure_supported_on_wsl1(&PermissionProfile::read_only())
.is_ok()
);
}
+8 -28
View File
@@ -10,7 +10,8 @@ use crate::WindowsSandboxFilesystemOverrides;
use crate::WindowsSandboxProxySettingsMode;
#[cfg(target_os = "linux")]
use crate::bwrap::WSL1_BWRAP_WARNING;
use crate::landlock::CODEX_LINUX_SANDBOX_ARG0;
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")]
@@ -20,8 +21,6 @@ use codex_network_proxy::NetworkProxy;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::models::AdditionalPermissionProfile;
use codex_protocol::models::PermissionProfile;
#[cfg(target_os = "linux")]
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::sandbox::SandboxOverride;
pub use codex_protocol::sandbox::SandboxType;
use codex_utils_absolute_path::AbsolutePathBuf;
@@ -776,21 +775,18 @@ impl SandboxManager {
use_legacy_landlock: bool,
managed_network: Option<&ManagedNetworkSandboxContext>,
) -> Result<(), SandboxTransformError> {
let mode = LinuxSandboxMode::resolve(use_legacy_landlock, managed_network);
#[cfg(target_os = "linux")]
ensure_linux_bubblewrap_is_supported(
&exec.permission_profile.file_system_sandbox_policy(),
use_legacy_landlock,
managed_network.is_some(),
crate::bwrap::is_wsl1(),
)?;
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::landlock::create_linux_sandbox_command_args_for_permission_profile(
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,
use_legacy_landlock,
managed_network,
mode,
);
// Only the startup opt-in requires a helper that understands PID inheritance.
if self.linux_sandbox_pid_namespace == LinuxSandboxPidNamespace::Inherit {
@@ -968,22 +964,6 @@ fn add_windows_sandbox_wrapper_setup_env_from_vars(
}
}
#[cfg(target_os = "linux")]
fn ensure_linux_bubblewrap_is_supported(
file_system_sandbox_policy: &FileSystemSandboxPolicy,
use_legacy_landlock: bool,
allow_network_for_proxy: bool,
is_wsl1: bool,
) -> Result<(), SandboxTransformError> {
let requires_bubblewrap = allow_network_for_proxy
|| (!use_legacy_landlock && !file_system_sandbox_policy.has_full_disk_write_access());
if is_wsl1 && requires_bubblewrap {
return Err(SandboxTransformError::Wsl1UnsupportedForBubblewrap);
}
Ok(())
}
#[cfg(test)]
#[path = "manager_tests.rs"]
mod tests;
+1 -72
View File
@@ -442,77 +442,6 @@ fn transform_linux_seccomp_request(
.expect("transform")
}
#[cfg(target_os = "linux")]
#[test]
fn wsl1_rejects_linux_bubblewrap_path() {
let restricted_policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
access: FileSystemAccessMode::Read,
missing_path_behavior: None,
}]);
assert!(matches!(
super::ensure_linux_bubblewrap_is_supported(
&restricted_policy,
/*use_legacy_landlock*/ false,
/*allow_network_for_proxy*/ false,
/*is_wsl1*/ true,
),
Err(super::SandboxTransformError::Wsl1UnsupportedForBubblewrap)
));
assert!(matches!(
super::ensure_linux_bubblewrap_is_supported(
&FileSystemSandboxPolicy::unrestricted(),
/*use_legacy_landlock*/ false,
/*allow_network_for_proxy*/ true,
/*is_wsl1*/ true,
),
Err(super::SandboxTransformError::Wsl1UnsupportedForBubblewrap)
));
assert!(matches!(
super::ensure_linux_bubblewrap_is_supported(
&FileSystemSandboxPolicy::unrestricted(),
/*use_legacy_landlock*/ true,
/*allow_network_for_proxy*/ true,
/*is_wsl1*/ true,
),
Err(super::SandboxTransformError::Wsl1UnsupportedForBubblewrap)
));
}
#[cfg(target_os = "linux")]
#[test]
fn wsl1_allows_non_bubblewrap_linux_paths() {
assert!(
super::ensure_linux_bubblewrap_is_supported(
&FileSystemSandboxPolicy::unrestricted(),
/*use_legacy_landlock*/ false,
/*allow_network_for_proxy*/ false,
/*is_wsl1*/ true,
)
.is_ok()
);
let restricted_policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
access: FileSystemAccessMode::Read,
missing_path_behavior: None,
}]);
assert!(
super::ensure_linux_bubblewrap_is_supported(
&restricted_policy,
/*use_legacy_landlock*/ true,
/*allow_network_for_proxy*/ false,
/*is_wsl1*/ true,
)
.is_ok()
);
}
#[cfg(target_os = "linux")]
#[test]
fn transform_linux_seccomp_preserves_helper_path_in_arg0_when_available() {
@@ -559,7 +488,7 @@ async fn inherited_terminal_preserves_native_linux_helper_and_uses_its_dispatch_
use std::os::unix::fs::symlink;
let dir = tempfile::tempdir()?;
let alias = OsStr::new(crate::landlock::CODEX_LINUX_SANDBOX_ARG0);
let alias = OsStr::new(crate::linux::CODEX_LINUX_SANDBOX_ARG0);
let alias_path = dir.path().join(alias);
for (helper, expected_arg0) in [
(alias_path.clone(), alias_path.as_os_str()),