Keep sandbox preparation with the command through launch (#62205)

## What changed

- Keep the prepared `SandboxExecRequest` intact in core and let
  `command/exec` borrow the prepared command for streaming. Windows
  restricted-token commands continue through the dedicated sandbox launcher.
- Move runtime read-path selection for exec-server commands and filesystem
  helpers into `SandboxManager`. It derives the paths from the executor's
  binaries and, for managed process launches, finds the generated proxy CA
  bundle in the command environment.

GitOrigin-RevId: 8c9d278496d84589bc4a7b7d0ed08cb1b8e6ba21
This commit is contained in:
viyatb-oai
2026-11-18 06:22:36 +00:00
committed by copyberry
parent a734a13ad7
commit a4495dd5c9
22 changed files with 495 additions and 372 deletions
+86 -57
View File
@@ -22,7 +22,7 @@ use codex_core::config::StartedNetworkProxy;
use codex_core::exec::ExecExpiration;
use codex_core::exec::ExecExpirationOutcome;
use codex_core::exec::IO_DRAIN_TIMEOUT_MS;
use codex_core::sandboxing::ExecRequest;
use codex_core::sandboxing::PreparedLocalExecRequest;
use codex_protocol::exec_output::bytes_to_string_smart;
use codex_sandboxing::SandboxType;
use codex_utils_pty::DEFAULT_OUTPUT_BYTES_CAP;
@@ -88,7 +88,7 @@ pub(crate) struct StartCommandExecParams {
pub(crate) outgoing: Arc<OutgoingMessageSender>,
pub(crate) request_id: ConnectionRequestId,
pub(crate) process_id: Option<String>,
pub(crate) exec_request: ExecRequest,
pub(crate) exec_request: PreparedLocalExecRequest,
pub(crate) started_network_proxy: Option<StartedNetworkProxy>,
pub(crate) tty: bool,
pub(crate) stream_stdin: bool,
@@ -175,7 +175,7 @@ impl CommandExecManager {
process_id: process_id.clone(),
};
if matches!(exec_request.sandbox, SandboxType::WindowsRestrictedToken) {
if exec_request.as_ref().sandbox() == SandboxType::WindowsRestrictedToken {
if tty || stream_stdin || stream_stdout_stderr {
return Err(invalid_request(
"streaming command/exec is not supported with windows sandbox",
@@ -202,8 +202,11 @@ impl CommandExecManager {
let sessions = Arc::clone(&self.sessions);
tokio::spawn(async move {
let _started_network_proxy = started_network_proxy;
match codex_core::sandboxing::execute_env(exec_request, /*stdout_stream*/ None)
.await
match codex_core::sandboxing::execute_env(
exec_request.into_exec_request(),
/*stdout_stream*/ None,
)
.await
{
Ok(output) => {
outgoing
@@ -228,13 +231,18 @@ impl CommandExecManager {
return Ok(());
}
let env = &exec_request.env;
let arg0 = &exec_request.arg0;
let command = exec_request
.direct_command()
.ok_or_else(|| invalid_request("command must not be empty"))?;
let program = command.program;
// TODO(anp): Keep PathUri through the local command launch boundary.
let cwd = exec_request
let cwd = command
.cwd
.to_abs_path()
.map_err(|err| invalid_request(format!("invalid command cwd: {err}")))?;
let args = command.args;
let env = command.env;
let arg0 = command.arg0;
let stream_stdin = tty || stream_stdin;
let stream_stdout_stderr = tty || stream_stdout_stderr;
@@ -245,9 +253,6 @@ impl CommandExecManager {
};
let sessions = Arc::clone(&self.sessions);
let (program, args) = exec_request
.program_and_args()
.ok_or_else(|| invalid_request("command must not be empty"))?;
{
let mut sessions = self.sessions.lock().await;
if sessions.contains_key(&process_key) {
@@ -302,7 +307,7 @@ impl CommandExecManager {
control_rx,
stream_stdin,
stream_stdout_stderr,
expiration: exec_request.expiration,
expiration: exec_request.into_exec_request().expiration,
output_bytes_cap,
})
.await;
@@ -682,9 +687,17 @@ mod tests {
use std::collections::HashMap;
use crate::error_code::INVALID_REQUEST_ERROR_CODE;
use codex_core::exec::ExecCapturePolicy;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::models::PermissionProfile;
use codex_sandboxing::SandboxCommand;
use codex_sandboxing::SandboxExecutables;
use codex_sandboxing::SandboxManager;
use codex_sandboxing::SandboxNetwork;
use codex_sandboxing::SandboxSelection;
use codex_sandboxing::SandboxTransformRequest;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
#[cfg(not(target_os = "windows"))]
use tokio::time::Duration;
@@ -699,22 +712,42 @@ mod tests {
#[cfg(not(target_os = "windows"))]
use crate::outgoing_message::OutgoingMessage;
fn windows_sandbox_exec_request() -> ExecRequest {
let cwd = AbsolutePathBuf::current_dir().expect("current dir");
ExecRequest::new(
vec!["cmd".to_string()],
cwd.clone(),
HashMap::new(),
/*network*/ None,
/*network_environment_id*/ None,
ExecExpiration::DefaultTimeout,
codex_core::exec::ExecCapturePolicy::ShellTool,
SandboxType::WindowsRestrictedToken,
vec![cwd],
WindowsSandboxLevel::Disabled,
PermissionProfile::read_only(),
/*arg0*/ None,
async fn prepared_exec_request(
sandbox: SandboxType,
program: &str,
args: &[&str],
expiration: ExecExpiration,
) -> PreparedLocalExecRequest {
let cwd = PathUri::from(AbsolutePathBuf::current_dir().expect("current dir"));
let roots = std::slice::from_ref(&cwd);
let wrapped = SandboxManager::new()
.transform(SandboxTransformRequest {
command: SandboxCommand {
program: program.into(),
args: args.iter().copied().map(str::to_owned).collect(),
cwd: cwd.clone(),
env: HashMap::new(),
managed_network: None,
additional_permissions: None,
},
permissions: &PermissionProfile::read_only(),
workspace_roots: Some(roots),
selection: SandboxSelection::Explicit(sandbox),
network: SandboxNetwork::default(),
sandbox_policy_cwd: &cwd,
executables: SandboxExecutables::Launcher(None),
use_legacy_landlock: false,
windows_sandbox_level: WindowsSandboxLevel::RestrictedToken,
})
.expect("wrap command");
PreparedLocalExecRequest::from_wrapped(
wrapped,
expiration,
ExecCapturePolicy::ShellTool,
roots,
)
.await
.expect("prepare local command")
}
#[tokio::test]
@@ -732,7 +765,13 @@ mod tests {
request_id: codex_app_server_protocol::RequestId::Integer(42),
},
process_id: Some("proc-42".to_string()),
exec_request: windows_sandbox_exec_request(),
exec_request: prepared_exec_request(
SandboxType::WindowsRestrictedToken,
"cmd",
&[],
ExecExpiration::DefaultTimeout,
)
.await,
started_network_proxy: None,
tty: false,
stream_stdin: false,
@@ -768,7 +807,13 @@ mod tests {
)),
request_id: request_id.clone(),
process_id: Some("proc-99".to_string()),
exec_request: windows_sandbox_exec_request(),
exec_request: prepared_exec_request(
SandboxType::WindowsRestrictedToken,
"cmd",
&[],
ExecExpiration::DefaultTimeout,
)
.await,
started_network_proxy: None,
tty: false,
stream_stdin: false,
@@ -808,7 +853,6 @@ mod tests {
connection_id: ConnectionId(8),
request_id: codex_app_server_protocol::RequestId::Integer(100),
};
let cwd = AbsolutePathBuf::current_dir().expect("current dir");
manager
.start(StartCommandExecParams {
@@ -818,20 +862,13 @@ mod tests {
)),
request_id: request_id.clone(),
process_id: Some("proc-100".to_string()),
exec_request: ExecRequest::new(
vec!["sh".to_string(), "-lc".to_string(), "sleep 30".to_string()],
cwd.clone(),
HashMap::new(),
/*network*/ None,
/*network_environment_id*/ None,
ExecExpiration::Cancellation(CancellationToken::new()),
codex_core::exec::ExecCapturePolicy::ShellTool,
exec_request: prepared_exec_request(
SandboxType::None,
vec![cwd.clone()],
WindowsSandboxLevel::Disabled,
PermissionProfile::read_only(),
/*arg0*/ None,
),
"sh",
&["-lc", "sleep 30"],
ExecExpiration::Cancellation(CancellationToken::new()),
)
.await,
started_network_proxy: None,
tty: false,
stream_stdin: false,
@@ -898,7 +935,6 @@ mod tests {
};
let cancellation = CancellationToken::new();
let cancel = cancellation.clone();
let cwd = AbsolutePathBuf::current_dir().expect("current dir");
manager
.start(StartCommandExecParams {
@@ -908,23 +944,16 @@ mod tests {
)),
request_id: request_id.clone(),
process_id: Some("proc-101".to_string()),
exec_request: ExecRequest::new(
vec!["sh".to_string(), "-lc".to_string(), "sleep 30".to_string()],
cwd.clone(),
HashMap::new(),
/*network*/ None,
/*network_environment_id*/ None,
exec_request: prepared_exec_request(
SandboxType::None,
"sh",
&["-lc", "sleep 30"],
ExecExpiration::TimeoutOrCancellation {
timeout: Duration::from_secs(30),
cancellation,
},
codex_core::exec::ExecCapturePolicy::ShellTool,
SandboxType::None,
vec![cwd],
WindowsSandboxLevel::Disabled,
PermissionProfile::read_only(),
/*arg0*/ None,
),
)
.await,
started_network_proxy: None,
tty: false,
stream_stdin: false,
+2 -2
View File
@@ -27,6 +27,7 @@ use codex_protocol::models::PermissionProfile;
use codex_protocol::models::SandboxEnforcement;
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_sandboxing::SandboxCommand;
use codex_sandboxing::SandboxExecutables;
use codex_sandboxing::SandboxManager;
use codex_sandboxing::SandboxNetwork;
use codex_sandboxing::SandboxSelection;
@@ -437,7 +438,6 @@ async fn run_command_under_sandbox(
},
permissions: &permission_profile,
workspace_roots: workspace_roots.as_deref(),
runtime_readable_paths: None,
selection: SandboxSelection::Explicit(sandbox),
network: SandboxNetwork::new(
network.is_some(),
@@ -445,7 +445,7 @@ async fn run_command_under_sandbox(
/*environment_id*/ None,
),
sandbox_policy_cwd: &cwd,
sandbox_exe: sandbox_exe.as_deref(),
executables: SandboxExecutables::Launcher(sandbox_exe.as_deref()),
use_legacy_landlock,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
})?;
+30 -32
View File
@@ -19,7 +19,7 @@ use tokio::process::Child;
use tokio_util::sync::CancellationToken;
use crate::sandboxing::ExecOptions;
use crate::sandboxing::ExecRequest;
use crate::sandboxing::PreparedLocalExecRequest;
use crate::sandboxing::SandboxPermissions;
use crate::spawn::SpawnChildRequest;
use crate::spawn::StdioPolicy;
@@ -37,6 +37,8 @@ use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::ExecCommandOutputDeltaEvent;
use codex_protocol::protocol::ExecOutputStream;
use codex_sandboxing::SandboxCommand;
use codex_sandboxing::SandboxExecRequest;
use codex_sandboxing::SandboxExecutables;
use codex_sandboxing::SandboxManager;
use codex_sandboxing::SandboxNetwork;
use codex_sandboxing::SandboxSelection;
@@ -321,7 +323,7 @@ pub async fn process_exec_tool_call(
.await?;
// Route through the sandboxing module for a single, unified execution path.
crate::sandboxing::execute_env(exec_req, stdout_stream).await
crate::sandboxing::execute_env(exec_req.into_exec_request(), stdout_stream).await
}
/// Transform a portable exec request into the concrete argv/env that should be
@@ -336,7 +338,7 @@ pub async fn build_exec_request(
codex_self_exe: &Option<PathBuf>,
windows_sandbox_type: SandboxType,
use_legacy_landlock: bool,
) -> Result<ExecRequest> {
) -> Result<PreparedLocalExecRequest> {
let ExecParams {
command,
cwd,
@@ -387,10 +389,6 @@ pub async fn build_exec_request(
managed_network,
additional_permissions: None,
};
let options = ExecOptions {
expiration,
capture_policy,
};
// An already-bound profile only needs its concrete paths validated. Its Windows
// launcher hints can include foreign roots that this host won't use.
let policy_roots = if permission_profile.has_workspace_root_rules() {
@@ -398,12 +396,11 @@ pub async fn build_exec_request(
} else {
&[]
};
let request = manager
.transform(SandboxTransformRequest {
let request = PreparedLocalExecRequest::from_wrapped(
manager.transform(SandboxTransformRequest {
command,
permissions: permission_profile,
workspace_roots: Some(policy_roots),
runtime_readable_paths: None,
selection: SandboxSelection::Platform {
preference: SandboxablePreference::Auto,
windows_sandbox: windows_sandbox_type,
@@ -414,48 +411,49 @@ pub async fn build_exec_request(
network_environment_id.as_deref(),
),
sandbox_policy_cwd: &sandbox_policy_cwd_uri,
sandbox_exe: if cfg!(windows) {
executables: SandboxExecutables::Launcher(if cfg!(windows) {
codex_self_exe.as_deref()
} else {
codex_linux_sandbox_exe.as_deref()
},
}),
use_legacy_landlock,
windows_sandbox_level,
})?
.into_command_request()?;
let request = ExecRequest::from_sandbox_exec_request(request, options, workspace_roots).await?;
tracing::debug!("Sandbox type: {:?}", request.sandbox);
})?,
expiration,
capture_policy,
workspace_roots,
)
.await?;
tracing::debug!("Sandbox type: {:?}", request.as_ref().sandbox());
Ok(request)
}
pub(crate) async fn execute_exec_request(
exec_request: ExecRequest,
pub(crate) async fn capture_sandbox_request(
request: SandboxExecRequest,
options: ExecOptions,
windows_sandbox_workspace_roots: Vec<AbsolutePathBuf>,
windows_sandbox_filesystem_overrides: Option<WindowsSandboxFilesystemOverrides>,
stdout_stream: Option<StdoutStream>,
after_spawn: Option<Box<dyn FnOnce() + Send>>,
) -> Result<ExecToolCallOutput> {
let ExecRequest {
let SandboxExecRequest {
command,
native_program,
cwd,
env,
exec_server_env_config: _,
exec_server_shell_snapshot: _,
network,
expiration,
capture_policy,
sandbox,
windows_sandbox_policy_cwd,
windows_sandbox_workspace_roots,
sandbox_policy_cwd: windows_sandbox_policy_cwd,
windows_sandbox_level,
permission_profile,
windows_sandbox_filesystem_overrides,
network_environment_id,
arg0,
exec_server_sandbox: _,
exec_server_enforce_managed_network: _,
exec_server_managed_network: _,
exec_server_network_proxy: _,
} = exec_request;
..
} = request;
let ExecOptions {
expiration,
capture_policy,
} = options;
let network_sandbox_policy = permission_profile.network_sandbox_policy();
// TODO(anp): Keep PathUri through the local process launch boundary.
@@ -473,7 +471,7 @@ pub(crate) async fn execute_exec_request(
expiration,
capture_policy,
env,
network: network.clone(),
network,
network_environment_id,
sandbox_permissions: SandboxPermissions::UseDefault,
windows_sandbox_level,
+6 -1
View File
@@ -1,4 +1,5 @@
use super::*;
use crate::sandboxing::ExecRequest;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemAccessMode;
@@ -1244,7 +1245,10 @@ async fn process_exec_tool_call_uses_platform_sandbox_for_network_only_restricti
/*use_legacy_landlock*/ false,
)
.await?;
assert_eq!(request.sandbox, expected.unwrap_or(SandboxType::None));
assert_eq!(
request.as_ref().sandbox(),
expected.unwrap_or(SandboxType::None)
);
Ok(())
}
@@ -1276,6 +1280,7 @@ async fn build_exec_request_projects_workspace_roots_only_for_windows_sandbox()
/*use_legacy_landlock*/ false,
)
.await
.map(PreparedLocalExecRequest::into_exec_request)
};
let native_roots = vec![cwd.clone(), temp_dir.path().join("additional").abs()];
let request = build_request(
+143 -72
View File
@@ -1,16 +1,15 @@
/*
Module: sandboxing
Core-owned adapter types for exec/runtime plumbing. Policy selection and
command transformation live in the codex-sandboxing crate; this module keeps
the exec-only metadata and translates transformed sandbox commands back into
ExecRequest for execution.
Core keeps the prepared sandbox request with its execution options until the
local launcher takes ownership. Remote launches retain the portable paths and
permissions sent to the executor.
*/
use crate::exec::ExecCapturePolicy;
use crate::exec::ExecExpiration;
use crate::exec::StdoutStream;
use crate::exec::execute_exec_request;
use crate::exec::capture_sandbox_request;
#[cfg(target_os = "macos")]
use crate::spawn::CODEX_SANDBOX_ENV_VAR;
use crate::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR;
@@ -29,12 +28,12 @@ use codex_sandboxing::SandboxManager;
use codex_sandboxing::SandboxTransformRequest;
use codex_sandboxing::SandboxType;
use codex_sandboxing::WindowsSandboxFilesystemOverrides;
use codex_sandboxing::WrappedSandboxCommand;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use codex_utils_string::truncate_middle_with_token_budget;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::ffi::OsString;
#[derive(Debug)]
pub(crate) struct ExecOptions {
@@ -50,41 +49,85 @@ pub(crate) struct ExecServerEnvConfig {
#[derive(Debug)]
pub struct ExecRequest {
pub command: Vec<String>,
pub(crate) native_program: Option<OsString>,
pub cwd: PathUri,
pub env: HashMap<String, String>,
// Only the capture adapter takes ownership. Other launchers borrow the prepared workload.
launch: SandboxExecRequest,
pub(crate) exec_server_env_config: Option<ExecServerEnvConfig>,
pub(crate) exec_server_shell_snapshot: Option<codex_exec_server::ShellSnapshotRequest>,
pub network: Option<NetworkProxy>,
pub network_environment_id: Option<String>,
pub expiration: ExecExpiration,
pub capture_policy: ExecCapturePolicy,
pub sandbox: SandboxType,
pub windows_sandbox_policy_cwd: PathUri,
pub windows_sandbox_workspace_roots: Vec<AbsolutePathBuf>,
// TODO(anp): Reconcile these backend copies with TurnEnvironment::sandbox_context
// and exec_server_sandbox so local and remote launches use the same settings.
pub windows_sandbox_level: WindowsSandboxLevel,
pub permission_profile: PermissionProfile,
pub(crate) windows_sandbox_filesystem_overrides: Option<WindowsSandboxFilesystemOverrides>,
pub arg0: Option<String>,
pub(crate) exec_server_sandbox: Option<FileSystemSandboxContext>,
pub(crate) exec_server_enforce_managed_network: bool,
pub(crate) exec_server_managed_network: Option<ManagedNetworkSandboxContext>,
pub(crate) exec_server_network_proxy: Option<RemoteNetworkProxyLaunchConfig>,
}
/// A prepared workload whose sandbox can be entered by spawning its command.
pub struct DirectSandboxCommand<'a> {
pub program: &'a OsStr,
pub args: &'a [String],
pub cwd: &'a PathUri,
pub env: &'a HashMap<String, String>,
pub arg0: &'a Option<String>,
}
/// A local launch whose command has already been prepared for its selected sandbox.
#[derive(Debug)]
pub struct PreparedLocalExecRequest(ExecRequest);
impl PreparedLocalExecRequest {
/// Attach capture options and native Windows launcher roots to a prepared command.
/// A command that already owns a Windows token session must use its session launcher.
pub async fn from_wrapped(
command: WrappedSandboxCommand,
expiration: ExecExpiration,
capture_policy: ExecCapturePolicy,
workspace_roots: &[PathUri],
) -> Result<Self, CodexErr> {
let request = ExecRequest::from_sandbox_exec_request(
command.into_command_request()?,
ExecOptions {
expiration,
capture_policy,
},
workspace_roots,
)
.await?;
Ok(Self(request))
}
/// Borrow the prepared command for a caller that owns its terminal and output streams.
pub fn direct_command(&self) -> Option<DirectSandboxCommand<'_>> {
let launch = &self.0.launch;
if launch.sandbox == SandboxType::WindowsRestrictedToken {
return None;
}
let (program, args) = launch.program_and_args()?;
Some(DirectSandboxCommand {
program,
args,
arg0: &launch.arg0,
cwd: &launch.cwd,
env: &launch.env,
})
}
pub fn into_exec_request(self) -> ExecRequest {
self.0
}
}
impl AsRef<ExecRequest> for PreparedLocalExecRequest {
fn as_ref(&self) -> &ExecRequest {
&self.0
}
}
impl ExecRequest {
/// Borrow the host executable and arguments for a local launch.
pub fn program_and_args(&self) -> Option<(&OsStr, &[String])> {
let (program, args) = self.command.split_first()?;
Some((
self.native_program
.as_deref()
.unwrap_or_else(|| OsStr::new(program)),
args,
))
pub(crate) fn program_and_args(&self) -> Option<(&OsStr, &[String])> {
self.launch.program_and_args()
}
#[allow(clippy::too_many_arguments)]
@@ -105,23 +148,26 @@ impl ExecRequest {
let cwd = PathUri::from_abs_path(&cwd);
let windows_sandbox_policy_cwd = cwd.clone();
Self {
command,
native_program: None,
cwd,
env,
exec_server_env_config: None,
exec_server_shell_snapshot: None,
network,
network_environment_id,
launch: SandboxExecRequest {
native_program: None,
command,
cwd,
env,
network,
network_environment_id,
sandbox,
sandbox_policy_cwd: windows_sandbox_policy_cwd,
windows_sandbox_level,
permission_profile,
arg0,
sandbox_override: SandboxOverride::NoOverride,
},
expiration,
capture_policy,
sandbox,
windows_sandbox_policy_cwd,
windows_sandbox_workspace_roots,
windows_sandbox_level,
permission_profile,
windows_sandbox_filesystem_overrides: None,
arg0,
exec_server_env_config: None,
exec_server_shell_snapshot: None,
exec_server_sandbox: None,
exec_server_enforce_managed_network: false,
exec_server_managed_network: None,
@@ -129,6 +175,39 @@ impl ExecRequest {
}
}
pub fn sandbox(&self) -> SandboxType {
self.launch.sandbox
}
pub(crate) fn argv(&self) -> &[String] {
&self.launch.command
}
pub(crate) fn cwd(&self) -> &PathUri {
&self.launch.cwd
}
pub(crate) fn env(&self) -> &HashMap<String, String> {
&self.launch.env
}
pub(crate) fn arg0(&self) -> &Option<String> {
&self.launch.arg0
}
pub(crate) fn sandbox_policy_cwd(&self) -> &PathUri {
&self.launch.sandbox_policy_cwd
}
pub(crate) fn has_network_proxy(&self) -> bool {
self.launch.network.is_some()
}
/// Core's legacy native Windows session still needs its token and route-specific policy.
pub(crate) fn native_windows(&self) -> Option<&SandboxExecRequest> {
(self.sandbox() == SandboxType::WindowsRestrictedToken).then_some(&self.launch)
}
/// Prepare an authorized local attempt for a launcher that owns its pipes or terminal.
pub(crate) async fn prepare_local_sandbox(
manager: &SandboxManager,
@@ -143,7 +222,7 @@ impl ExecRequest {
}
pub(crate) async fn from_sandbox_exec_request(
request: SandboxExecRequest,
mut request: SandboxExecRequest,
options: ExecOptions,
workspace_roots: &[PathUri],
) -> Result<Self, CodexErr> {
@@ -162,20 +241,11 @@ impl ExecRequest {
Vec::new()
};
codex_exec_server::run_integrity_checks((&request).into()).await;
let SandboxExecRequest {
command,
native_program,
cwd,
sandbox_policy_cwd: windows_sandbox_policy_cwd,
mut env,
network,
network_environment_id,
sandbox,
windows_sandbox_level,
permission_profile,
arg0,
..
} = request;
let sandbox = request.sandbox;
let windows_sandbox_policy_cwd = &request.sandbox_policy_cwd;
let windows_sandbox_level = request.windows_sandbox_level;
let permission_profile = &request.permission_profile;
let env = &mut request.env;
let ExecOptions {
expiration,
capture_policy,
@@ -187,10 +257,10 @@ impl ExecRequest {
.map_err(|err| CodexErr::InvalidRequest(format!("invalid sandbox cwd: {err}")))?;
WindowsSandboxFilesystemOverrides::resolve(
sandbox,
&permission_profile,
permission_profile,
&sandbox_policy_cwd,
windows_sandbox_level,
&env,
env,
)
.map_err(|error| {
CodexErr::UnsupportedOperation(
@@ -212,23 +282,13 @@ impl ExecRequest {
env.insert(CODEX_SANDBOX_ENV_VAR.to_string(), "seatbelt".to_string());
}
Ok(Self {
command,
native_program,
cwd,
env,
exec_server_env_config: None,
exec_server_shell_snapshot: None,
network,
network_environment_id,
launch: request,
expiration,
capture_policy,
sandbox,
windows_sandbox_policy_cwd,
windows_sandbox_workspace_roots,
windows_sandbox_level,
permission_profile,
windows_sandbox_filesystem_overrides,
arg0,
exec_server_env_config: None,
exec_server_shell_snapshot: None,
exec_server_sandbox: None,
exec_server_enforce_managed_network: false,
exec_server_managed_network: None,
@@ -241,7 +301,7 @@ pub async fn execute_env(
exec_request: ExecRequest,
stdout_stream: Option<StdoutStream>,
) -> codex_protocol::error::Result<ExecToolCallOutput> {
execute_exec_request(exec_request, stdout_stream, /*after_spawn*/ None).await
execute_exec_request_with_after_spawn(exec_request, stdout_stream, /*after_spawn*/ None).await
}
pub async fn execute_exec_request_with_after_spawn(
@@ -249,5 +309,16 @@ pub async fn execute_exec_request_with_after_spawn(
stdout_stream: Option<StdoutStream>,
after_spawn: Option<Box<dyn FnOnce() + Send>>,
) -> codex_protocol::error::Result<ExecToolCallOutput> {
execute_exec_request(exec_request, stdout_stream, after_spawn).await
capture_sandbox_request(
exec_request.launch,
ExecOptions {
expiration: exec_request.expiration,
capture_policy: exec_request.capture_policy,
},
exec_request.windows_sandbox_workspace_roots,
exec_request.windows_sandbox_filesystem_overrides,
stdout_stream,
after_spawn,
)
.await
}
+2 -2
View File
@@ -17,6 +17,7 @@ use codex_protocol::models::FileSystemPermissions;
use codex_protocol::models::PermissionProfile;
use codex_protocol::sandbox::SandboxOverride;
use codex_sandboxing::SandboxCommand;
use codex_sandboxing::SandboxExecutables;
use codex_sandboxing::SandboxManager;
use codex_sandboxing::SandboxNetwork;
use codex_sandboxing::SandboxSelection;
@@ -196,7 +197,6 @@ impl ShellSnapshotSandbox {
},
permissions: &self.permissions,
workspace_roots: Some(&self.workspace_roots),
runtime_readable_paths: None,
selection: self.selection,
network: SandboxNetwork::new(
self.enforce_managed_network,
@@ -204,7 +204,7 @@ impl ShellSnapshotSandbox {
Some(&self.environment_id),
),
sandbox_policy_cwd: &self.sandbox_policy_cwd,
sandbox_exe: self.sandbox_exe.as_deref(),
executables: SandboxExecutables::Launcher(self.sandbox_exe.as_deref()),
use_legacy_landlock: self.use_legacy_landlock,
windows_sandbox_level: self.windows_sandbox_level,
},
+16 -26
View File
@@ -12,11 +12,11 @@ use uuid::Uuid;
use crate::exec::ExecCapturePolicy;
use crate::exec::StdoutStream;
use crate::exec::execute_exec_request;
use crate::exec_env::create_env;
use crate::exec_env::inject_apply_patch_env;
use crate::exec_env::inject_session_env;
use crate::sandboxing::ExecRequest;
use crate::sandboxing::execute_env;
use crate::session::TurnInput;
use crate::session::turn_context::TurnContext;
use crate::shell::Shell;
@@ -209,31 +209,21 @@ pub(crate) async fn execute_user_shell_command(
.await;
let permission_profile = PermissionProfile::Disabled;
let exec_env = ExecRequest {
native_program: None,
command: exec_command.clone(),
cwd: cwd.clone().into(),
env: exec_env_map,
exec_server_env_config: None,
exec_server_shell_snapshot: None,
// `/shell` is the explicit full-access escape hatch, so it must not
// inherit a managed proxy from the surrounding session or turn.
network: None,
network_environment_id: None,
expiration: timeout_ms.unwrap_or(USER_SHELL_TIMEOUT_MS).into(),
capture_policy: ExecCapturePolicy::ShellTool,
sandbox: SandboxType::None,
windows_sandbox_policy_cwd: cwd.clone().into(),
windows_sandbox_workspace_roots: Vec::new(),
windows_sandbox_level: turn_context.windows_sandbox_level,
// `/shell` is the explicit full-access escape hatch, so it must not inherit a managed proxy.
let exec_env = ExecRequest::new(
exec_command,
cwd.clone(),
exec_env_map,
/*network*/ None,
/*network_environment_id*/ None,
timeout_ms.unwrap_or(USER_SHELL_TIMEOUT_MS).into(),
ExecCapturePolicy::ShellTool,
SandboxType::None,
Vec::new(),
turn_context.windows_sandbox_level,
permission_profile,
windows_sandbox_filesystem_overrides: None,
arg0: None,
exec_server_sandbox: None,
exec_server_enforce_managed_network: false,
exec_server_managed_network: None,
exec_server_network_proxy: None,
};
/*arg0*/ None,
);
let stdout_stream = Some(StdoutStream {
sub_id: turn_context.sub_id.clone(),
@@ -241,7 +231,7 @@ pub(crate) async fn execute_user_shell_command(
tx_event: session.get_tx_event(),
});
let exec_result = execute_exec_request(exec_env, stdout_stream, /*after_spawn*/ None)
let exec_result = execute_env(exec_env, stdout_stream)
.or_cancel(&cancellation_token)
.await;
@@ -151,22 +151,22 @@ async fn explicit_escalation_prepares_exec_without_managed_network() -> anyhow::
.await
.expect("prepare exec request");
assert_eq!(exec_request.cwd, PathUri::from_abs_path(&command_cwd));
assert_eq!(*exec_request.cwd(), PathUri::from_abs_path(&command_cwd));
assert_eq!(
exec_request.windows_sandbox_policy_cwd,
*exec_request.sandbox_policy_cwd(),
PathUri::from_abs_path(&native_sandbox_policy_cwd)
);
assert_eq!(exec_request.network, None);
assert!(!exec_request.has_network_proxy());
for key in PROXY_ENV_KEYS {
assert_eq!(exec_request.env.get(*key), None, "{key} should be unset");
assert_eq!(exec_request.env().get(*key), None, "{key} should be unset");
}
for key in CUSTOM_CA_ENV_KEYS {
assert_eq!(exec_request.env.get(key), None, "{key} should be unset");
assert_eq!(exec_request.env().get(key), None, "{key} should be unset");
}
#[cfg(target_os = "macos")]
assert_eq!(exec_request.env.get(PROXY_GIT_SSH_COMMAND_ENV_KEY), None);
assert_eq!(exec_request.env().get(PROXY_GIT_SSH_COMMAND_ENV_KEY), None);
assert_eq!(
exec_request.env.get("CUSTOM_ENV"),
exec_request.env().get("CUSTOM_ENV"),
Some(&"kept".to_string())
);
+5 -3
View File
@@ -28,6 +28,7 @@ use codex_protocol::protocol::ReviewDecision;
pub(crate) use codex_protocol::sandbox::SandboxOverride;
use codex_sandboxing::SandboxCommand;
use codex_sandboxing::SandboxExecRequest;
use codex_sandboxing::SandboxExecutables;
use codex_sandboxing::SandboxManager;
use codex_sandboxing::SandboxNetwork;
use codex_sandboxing::SandboxSelection;
@@ -510,11 +511,12 @@ impl<'a> SandboxAttempt<'a> {
command,
permissions: self.permissions,
workspace_roots: Some(self.workspace_roots),
runtime_readable_paths: None,
selection: self.local_selection,
network: SandboxNetwork::new(self.enforce_managed_network, network, environment_id),
sandbox_policy_cwd: self.sandbox_cwd,
sandbox_exe: self.sandbox_exe.map(std::path::PathBuf::as_path),
executables: SandboxExecutables::Launcher(
self.sandbox_exe.map(std::path::PathBuf::as_path),
),
use_legacy_landlock: self.use_legacy_landlock,
windows_sandbox_level: self.windows_sandbox_level,
},
@@ -569,7 +571,7 @@ impl<'a> SandboxAttempt<'a> {
exec_request.exec_server_sandbox = Some(FileSystemSandboxContext {
permissions: exec_server_permissions,
sandbox_override: self.sandbox_override,
cwd: exec_request.windows_sandbox_policy_cwd.clone(),
cwd: exec_request.sandbox_policy_cwd().clone(),
workspace_roots: self.workspace_roots.to_vec(),
user_home_dir: None,
temporary_directories: None,
+4 -3
View File
@@ -340,6 +340,7 @@ async fn windows_sandbox_env_preserves_denied_reads_or_rejects_unsupported_backe
.expect("prepare elevated Windows sandbox request");
let overrides = request
.windows_sandbox_filesystem_overrides
.as_ref()
.expect("elevated Windows sandbox should preserve deny-read overrides");
assert_eq!(overrides.additional_deny_read_paths, vec![denied_path]);
assert_eq!(request.windows_sandbox_workspace_roots, vec![cwd]);
@@ -427,9 +428,9 @@ async fn exec_server_env_keeps_command_native_and_carries_sandbox_context() {
.expect("prepare remote exec request");
assert!(!attempt.is_escalated());
assert_eq!(request.command, argv);
assert_eq!(request.arg0, None);
assert_eq!(request.sandbox, SandboxType::None);
assert_eq!(request.argv(), argv);
assert_eq!(request.arg0(), &None);
assert_eq!(request.sandbox(), SandboxType::None);
assert_eq!(
request.exec_server_sandbox,
Some(codex_exec_server::FileSystemSandboxContext {
+2 -1
View File
@@ -821,7 +821,7 @@ async fn completed_local_commands_preserve_exit_code(tty: bool) -> anyhow::Resul
cwd: cwd.clone(),
expiration: request.expiration,
capture_policy: request.capture_policy,
env: request.env,
env: shell_env(),
network: None,
network_environment_id: None,
sandbox_permissions: SandboxPermissions::UseDefault,
@@ -838,6 +838,7 @@ async fn completed_local_commands_preserve_exit_code(tty: bool) -> anyhow::Resul
/*use_legacy_landlock*/ false,
)
.await?
.into_exec_request()
} else {
request
};
@@ -196,14 +196,14 @@ fn exec_server_env_for_request(
) {
if let Some(exec_server_env_config) = &request.exec_server_env_config {
let mut env =
env_overlay_for_exec_server(&request.env, &exec_server_env_config.local_policy_env);
env_overlay_for_exec_server(request.env(), &exec_server_env_config.local_policy_env);
if request.exec_server_shell_snapshot.is_some()
&& !exec_server_env_config.policy.r#set.contains_key("PATH")
{
env.remove("PATH");
}
if request.exec_server_managed_network.is_some() {
for (key, value) in &request.env {
for (key, value) in request.env() {
if is_managed_proxy_env_var(key, value) {
env.insert(key.clone(), value.clone());
}
@@ -211,7 +211,7 @@ fn exec_server_env_for_request(
}
(Some(exec_server_env_config.policy.clone()), env)
} else {
(None, request.env.clone())
(None, request.env().clone())
}
}
@@ -236,14 +236,14 @@ fn exec_server_params_for_request(
thread_id: Some(ctx.session.thread_id()),
tool_call_id: Some(ctx.call_id.clone()),
}),
argv: request.command.clone(),
cwd: request.cwd.clone(),
argv: request.argv().to_vec(),
cwd: request.cwd().clone(),
env_policy,
shell_snapshot: request.exec_server_shell_snapshot.clone(),
env,
tty,
pipe_stdin: false,
arg0: request.arg0.clone(),
arg0: request.arg0().clone(),
sandbox,
enforce_managed_network: request.exec_server_enforce_managed_network,
managed_network: request.exec_server_managed_network.clone(),
@@ -1316,7 +1316,7 @@ impl UnifiedExecProcessManager {
&self,
process_id: i32,
tool_ctx: &ToolCtx,
request: ExecRequest,
mut request: ExecRequest,
network: Option<&NetworkProxy>,
exec_server_env_config: Option<ExecServerEnvConfig>,
shell_snapshot: Option<codex_exec_server::ShellSnapshotRequest>,
@@ -1329,11 +1329,8 @@ impl UnifiedExecProcessManager {
.as_ref()
.filter(|launch| launch.policy_decision_timeout_ms.is_some())
.and_then(|launch| network?.remote_policy_decider(launch.proxy.allow_local_binding));
let request = ExecRequest {
exec_server_env_config,
exec_server_shell_snapshot: shell_snapshot,
..request
};
request.exec_server_env_config = exec_server_env_config;
request.exec_server_shell_snapshot = shell_snapshot;
self.open_session_with_prepared_exec_env(
process_id,
&request,
@@ -1403,12 +1400,13 @@ impl UnifiedExecProcessManager {
}
// TODO(anp): Keep PathUri through the local PTY/process launch boundary.
let native_cwd = request
.cwd
.to_abs_path()
.map_err(|_| UnifiedExecError::ForeignPath {
path: request.cwd.clone(),
})?;
let native_cwd =
request
.cwd()
.to_abs_path()
.map_err(|_| UnifiedExecError::ForeignPath {
path: request.cwd().clone(),
})?;
let (program, args) = request
.program_and_args()
@@ -1416,14 +1414,14 @@ impl UnifiedExecProcessManager {
let network_proxy_restricting_sid = {
#[cfg(target_os = "windows")]
{
if request.sandbox == codex_sandboxing::SandboxType::WindowsRestrictedToken {
request
if let Some(launch) = request.native_windows() {
launch
.network
.as_ref()
.map(|network| {
network
.network_proxy_restricting_sid(
request.network_environment_id.as_deref(),
launch.network_environment_id.as_deref(),
)
.ok_or_else(|| {
UnifiedExecError::create_process(
@@ -1443,26 +1441,24 @@ impl UnifiedExecProcessManager {
}
};
let windows_sandbox =
if request.sandbox == codex_sandboxing::SandboxType::WindowsRestrictedToken {
Some(codex_sandboxing::WindowsSandboxSpawnRequest {
permission_profile: &request.permission_profile,
request
.native_windows()
.map(|launch| codex_sandboxing::WindowsSandboxSpawnRequest {
permission_profile: &launch.permission_profile,
workspace_roots: &request.windows_sandbox_workspace_roots,
windows_sandbox_level: request.windows_sandbox_level,
proxy_enforced: request.network.is_some(),
windows_sandbox_level: launch.windows_sandbox_level,
proxy_enforced: request.has_network_proxy(),
network_proxy_restricting_sid: network_proxy_restricting_sid.as_deref(),
proxy_settings_mode: windows_sandbox_proxy_settings_mode,
filesystem_overrides: request.windows_sandbox_filesystem_overrides.as_ref(),
})
} else {
None
};
});
let spawn_result = codex_sandboxing::spawn_process(codex_sandboxing::SpawnRequest {
program,
args,
cwd: native_cwd.as_path(),
env: &request.env,
arg0: &request.arg0,
sandbox: request.sandbox,
env: request.env(),
arg0: request.arg0(),
sandbox: request.sandbox(),
windows_sandbox,
tty,
stdin_open: tty,
@@ -1471,7 +1467,7 @@ impl UnifiedExecProcessManager {
.await;
let spawned =
spawn_result.map_err(|err| UnifiedExecError::create_process(err.to_string()))?;
UnifiedExecProcess::from_spawned(spawned, request.sandbox).await
UnifiedExecProcess::from_spawned(spawned, request.sandbox()).await
}
#[tracing::instrument(
@@ -1,4 +1,5 @@
use super::*;
use crate::sandboxing::ExecOptions;
use crate::tools::handlers::unified_exec::preparation::ExecCommandLifetime;
use crate::tools::handlers::unified_exec::preparation::ParsedExecCommand;
use crate::unified_exec::clamp_yield_time;
@@ -7,6 +8,10 @@ use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_network_proxy::NetworkProxyConfig;
use codex_network_proxy::RemoteNetworkProxyConfig;
use codex_network_proxy::RemoteNetworkProxyLaunchConfig;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::sandbox::SandboxOverride;
use codex_sandboxing::SandboxExecRequest;
use codex_sandboxing::SandboxType;
use core_test_support::assert_regex_match;
use pretty_assertions::assert_eq;
use tokio::sync::Notify;
@@ -175,12 +180,10 @@ fn exec_env_policy_excludes_non_inheritable_and_runtime_variables() {
);
}
#[test]
fn exec_server_params_use_path_uri_and_env_policy_overlay_contract() {
let cwd: codex_utils_absolute_path::AbsolutePathBuf = std::env::current_dir()
.expect("current dir")
.try_into()
.expect("absolute path");
#[tokio::test]
async fn exec_server_params_use_path_uri_and_env_policy_overlay_contract() {
let policy_cwd = PathUri::parse("file:///workspace").expect("policy cwd");
let command_cwd = PathUri::parse("file:///workspace/subdir").expect("command cwd");
let permission_profile = codex_protocol::models::PermissionProfile::Disabled;
let managed_network = ManagedNetworkSandboxContext {
loopback_ports: vec![43123],
@@ -188,10 +191,11 @@ fn exec_server_params_use_path_uri_and_env_policy_overlay_contract() {
transparent_tcp: true,
..Default::default()
};
let mut request = ExecRequest {
native_program: None,
let launch = SandboxExecRequest {
command: vec!["bash".to_string(), "-lc".to_string(), "true".to_string()],
cwd: cwd.clone().into(),
native_program: None,
cwd: command_cwd.clone(),
sandbox_policy_cwd: policy_cwd.clone(),
env: HashMap::from([
("HOME".to_string(), "/client-home".to_string()),
("PATH".to_string(), "/sandbox-path".to_string()),
@@ -206,46 +210,48 @@ fn exec_server_params_use_path_uri_and_env_policy_overlay_contract() {
"/client/custom-ca.pem".to_string(),
),
]),
exec_server_env_config: Some(ExecServerEnvConfig {
policy: codex_exec_server::ExecEnvPolicy {
inherit: codex_protocol::config_types::ShellEnvironmentPolicyInherit::Core,
ignore_default_excludes: false,
exclude: Vec::new(),
r#set: HashMap::new(),
include_only: Vec::new(),
},
local_policy_env: HashMap::from([
("HOME".to_string(), "/client-home".to_string()),
("PATH".to_string(), "/client-path".to_string()),
(
"HTTP_PROXY".to_string(),
"http://127.0.0.1:43123".to_string(),
),
("CODEX_NETWORK_PROXY_ACTIVE".to_string(), "1".to_string()),
(
"SSL_CERT_FILE".to_string(),
"/client/custom-ca.pem".to_string(),
),
]),
}),
exec_server_shell_snapshot: None,
network: None,
network_environment_id: None,
expiration: crate::exec::ExecExpiration::DefaultTimeout,
capture_policy: crate::exec::ExecCapturePolicy::ShellTool,
sandbox: codex_sandboxing::SandboxType::None,
windows_sandbox_policy_cwd: cwd.clone().into(),
windows_sandbox_workspace_roots: vec![cwd],
windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel::Disabled,
sandbox: SandboxType::None,
sandbox_override: SandboxOverride::NoOverride,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
permission_profile: permission_profile.clone(),
windows_sandbox_filesystem_overrides: None,
arg0: None,
exec_server_sandbox: None,
exec_server_enforce_managed_network: true,
exec_server_managed_network: Some(managed_network.clone()),
exec_server_network_proxy: None,
};
let mut request = ExecRequest::from_sandbox_exec_request(
launch,
ExecOptions {
expiration: crate::exec::ExecExpiration::DefaultTimeout,
capture_policy: crate::exec::ExecCapturePolicy::ShellTool,
},
&[],
)
.await
.expect("exec request");
request.exec_server_env_config = Some(ExecServerEnvConfig {
policy: codex_exec_server::ExecEnvPolicy {
inherit: codex_protocol::config_types::ShellEnvironmentPolicyInherit::Core,
ignore_default_excludes: false,
exclude: Vec::new(),
r#set: HashMap::new(),
include_only: Vec::new(),
},
local_policy_env: HashMap::from([
("HOME".to_string(), "/client-home".to_string()),
("PATH".to_string(), "/client-path".to_string()),
(
"HTTP_PROXY".to_string(),
"http://127.0.0.1:43123".to_string(),
),
("CODEX_NETWORK_PROXY_ACTIVE".to_string(), "1".to_string()),
(
"SSL_CERT_FILE".to_string(),
"/client/custom-ca.pem".to_string(),
),
]),
});
request.exec_server_enforce_managed_network = true;
request.exec_server_managed_network = Some(managed_network.clone());
let proxy_settings_mode = codex_sandboxing::WindowsSandboxProxySettingsMode::Preserve;
let params_for_request = |request: &ExecRequest| {
exec_server_params_for_request(
@@ -264,7 +270,6 @@ fn exec_server_params_use_path_uri_and_env_policy_overlay_contract() {
);
assert_ne!(params.process_id, params_for_request(&request).process_id);
assert_eq!(params.metadata, None);
assert_eq!(params.cwd, request.cwd);
assert!(params.enforce_managed_network);
assert_eq!(
params.managed_network,
@@ -299,11 +304,16 @@ fn exec_server_params_use_path_uri_and_env_policy_overlay_contract() {
request.exec_server_sandbox = Some(
codex_exec_server::FileSystemSandboxContext::from_permission_profile(
permission_profile,
request.cwd.clone(),
request.sandbox_policy_cwd().clone(),
),
);
let first = params_for_request(&request);
let second = params_for_request(&request);
assert_eq!(first.cwd, command_cwd);
assert_eq!(
first.sandbox.as_ref().map(|sandbox| &sandbox.cwd),
Some(&policy_cwd)
);
assert_eq!(first.requests_transparent_tcp(), cfg!(target_os = "linux"));
assert_eq!(
first
+2 -2
View File
@@ -38,6 +38,7 @@ use codex_protocol::protocol::Op;
use codex_protocol::protocol::ReviewDecision;
use codex_protocol::user_input::UserInput;
use codex_sandboxing::SandboxCommand;
use codex_sandboxing::SandboxExecutables;
use codex_sandboxing::SandboxManager;
use codex_sandboxing::SandboxSelection;
use codex_sandboxing::SandboxTransformRequest;
@@ -516,11 +517,10 @@ async fn windows_elevated_temp_only_core_and_direct_spawn_enforce_carveouts() ->
},
permissions: &permission_profile,
workspace_roots: Some(std::slice::from_ref(&cwd_uri)),
runtime_readable_paths: None,
selection: SandboxSelection::Explicit(SandboxType::WindowsRestrictedToken),
network: Default::default(),
sandbox_policy_cwd: &cwd_uri,
sandbox_exe: Some(codex.as_path()),
executables: SandboxExecutables::Launcher(Some(codex.as_path())),
use_legacy_landlock: false,
windows_sandbox_level: WindowsSandboxLevel::Elevated,
})?
+5 -15
View File
@@ -5,6 +5,7 @@ use std::time::Duration;
use codex_exec_server_protocol::JSONRPCErrorError;
use codex_sandboxing::SandboxCommand;
use codex_sandboxing::SandboxExecRequest;
use codex_sandboxing::SandboxExecutables;
use codex_sandboxing::SandboxManager;
use codex_sandboxing::SandboxTransformRequest;
use codex_utils_path_uri::PathUri;
@@ -88,16 +89,6 @@ impl FileSystemSandboxRunner {
sandbox: &FileSystemSandboxContext,
) -> Result<SandboxExecRequest, JSONRPCErrorError> {
let helper = &self.runtime_paths.codex_self_exe;
let mut helper_readable_paths = Vec::new();
if !sandbox.use_legacy_landlock {
helper_readable_paths.push(helper.clone());
if let Some(linux_helper) = &self.runtime_paths.codex_linux_sandbox_exe
&& linux_helper != helper
{
helper_readable_paths.push(linux_helper.clone());
}
}
let sandbox_manager = SandboxManager::for_file_system_helpers()
.with_linux_sandbox_pid_namespace(self.runtime_paths.linux_sandbox_pid_namespace);
#[cfg(target_os = "macos")]
@@ -128,14 +119,13 @@ impl FileSystemSandboxRunner {
command,
permissions: &sandbox.permissions,
workspace_roots: Some(&sandbox.workspace_roots),
runtime_readable_paths: Some(&helper_readable_paths),
selection,
network: Default::default(),
sandbox_policy_cwd: &sandbox.cwd,
sandbox_exe: if cfg!(windows) {
Some(helper.as_path())
} else {
self.runtime_paths.codex_linux_sandbox_exe.as_deref()
executables: SandboxExecutables::Executor {
codex: helper,
linux_sandbox: self.runtime_paths.codex_linux_sandbox_exe.as_ref(),
arg0: None,
},
use_legacy_landlock: sandbox.use_legacy_landlock,
windows_sandbox_level,
+5 -31
View File
@@ -7,8 +7,6 @@ use crate::process_telemetry::ProcessTelemetry;
use codex_exec_server_protocol::JSONRPCErrorError;
use codex_exec_server_protocol::ProcessStartErrorData;
use codex_file_system::WindowsSandboxSelection;
use codex_network_proxy::CHILD_ONLY_CA_ENV_KEYS;
use codex_network_proxy::CUSTOM_CA_ENV_KEYS;
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_network_proxy::ManagedProxyRouting;
use codex_network_proxy::NetworkPolicyAuditObserver;
@@ -18,15 +16,14 @@ use codex_network_proxy::NetworkProxyHandle;
use codex_network_proxy::NetworkProxyState;
use codex_network_proxy::RemoteCredentialBrokerCache;
use codex_network_proxy::ShellStartupCredentials;
use codex_network_proxy::is_managed_mitm_ca_trust_bundle_path;
use codex_sandboxing::SandboxCommand;
use codex_sandboxing::SandboxExecutables;
use codex_sandboxing::SandboxManager;
use codex_sandboxing::SandboxNetwork;
use codex_sandboxing::SandboxTransformRequest;
use codex_sandboxing::WrappedSandboxCommand;
#[cfg(windows)]
use codex_shell_command::shell_detect::fallback_powershell_shell_for_windows_sandbox;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
#[cfg(unix)]
@@ -100,28 +97,6 @@ pub(crate) async fn prepare_exec_request_with_telemetry(
"sandbox runtime paths are not configured".to_string(),
))
})?;
let mut runtime_readable_paths = Vec::new();
if cfg!(target_os = "linux") || (cfg!(unix) && params.arg0.is_some()) {
runtime_readable_paths.push(runtime_paths.codex_self_exe.clone());
}
if cfg!(target_os = "linux") {
runtime_readable_paths.extend(runtime_paths.codex_linux_sandbox_exe.iter().cloned());
}
let managed_mitm_ca_trust_bundle_path = if managed_network.is_some() {
CUSTOM_CA_ENV_KEYS
.into_iter()
.chain(CHILD_ONLY_CA_ENV_KEYS)
.find_map(|key| {
let path = env.get(key)?;
if !is_managed_mitm_ca_trust_bundle_path(path) {
return None;
}
AbsolutePathBuf::from_absolute_path(path).ok()
})
} else {
None
};
runtime_readable_paths.extend(managed_mitm_ca_trust_bundle_path);
let sandbox_manager = SandboxManager::new()
.with_linux_sandbox_pid_namespace(runtime_paths.linux_sandbox_pid_namespace)
.with_linux_sandbox_transparent_tcp(runtime_paths.linux_sandbox_transparent_tcp);
@@ -186,7 +161,6 @@ pub(crate) async fn prepare_exec_request_with_telemetry(
},
permissions: &sandbox_context.permissions,
workspace_roots: Some(&sandbox_context.workspace_roots),
runtime_readable_paths: Some(&runtime_readable_paths),
selection,
network: SandboxNetwork::new(
enforce_managed_network,
@@ -194,10 +168,10 @@ pub(crate) async fn prepare_exec_request_with_telemetry(
/*environment_id*/ None,
),
sandbox_policy_cwd: &sandbox_context.cwd,
sandbox_exe: if cfg!(windows) {
Some(runtime_paths.codex_self_exe.as_path())
} else {
runtime_paths.codex_linux_sandbox_exe.as_deref()
executables: SandboxExecutables::Executor {
codex: &runtime_paths.codex_self_exe,
linux_sandbox: runtime_paths.codex_linux_sandbox_exe.as_ref(),
arg0: params.arg0.as_deref(),
},
use_legacy_landlock: sandbox_context.use_legacy_landlock,
windows_sandbox_level,
+7 -8
View File
@@ -59,24 +59,23 @@ pub(super) async fn spawn_command_under_sandbox(
.await
.map_err(|err| io::Error::other(err.to_string()))?;
let (program, args) = exec_request
.command
.split_first()
let command = exec_request
.direct_command()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "command args are empty"))?;
let mut child = tokio::process::Command::new(program);
if let Some(arg0) = exec_request.arg0.as_deref() {
let mut child = tokio::process::Command::new(command.program);
if let Some(arg0) = command.arg0 {
child.arg0(arg0);
}
child.args(args);
child.args(command.args);
// TODO(anp): Keep PathUri through the macOS sandbox process launch boundary.
let native_cwd = exec_request
let native_cwd = command
.cwd
.to_abs_path()
.map_err(|err| io::Error::other(err.to_string()))?;
child.current_dir(native_cwd);
child.env_clear();
child.envs(exec_request.env);
child.envs(command.env);
match stdio_policy {
StdioPolicy::RedirectForShellTool => {
+15
View File
@@ -3,6 +3,7 @@ use anyhow::Context as _;
use anyhow::Result;
use anyhow::anyhow;
use base64::Engine as _;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_home_dir::find_codex_home;
use rama_net::tls::ApplicationProtocol;
use rama_tls_rustls::dep::pki_types::CertificateDer;
@@ -604,6 +605,20 @@ fn is_generated_managed_ca_artifact_path(path: &Path, proxy_dir: &Path, prefix:
format!("{:x}", Sha256::digest(trust_bundle)) == expected_hash
}
/// Find a generated CA in the environment prepared for a managed route on this host.
pub fn managed_mitm_ca_from_env(env: &HashMap<String, String>) -> Option<AbsolutePathBuf> {
CUSTOM_CA_ENV_KEYS
.into_iter()
.chain(CHILD_ONLY_CA_ENV_KEYS)
.filter_map(|key| env.get(key))
.find_map(|path| {
if !is_managed_mitm_ca_trust_bundle_path(path) {
return None;
}
AbsolutePathBuf::from_absolute_path(path).ok()
})
}
/// Returns whether `path` points at a current Codex-generated MITM CA bundle.
pub fn is_managed_mitm_ca_trust_bundle_path(path: &str) -> bool {
let Ok(proxy_dir) = managed_ca_dir() else {
+1
View File
@@ -46,6 +46,7 @@ pub use aws_sigv4::ProxySecretSource;
pub use certs::CHILD_ONLY_CA_ENV_KEYS;
pub use certs::CUSTOM_CA_ENV_KEYS;
pub use certs::is_managed_mitm_ca_trust_bundle_path;
pub use certs::managed_mitm_ca_from_env;
pub use codex_utils_path_uri::Platform;
pub use config::NetworkDomainPermission;
pub use config::NetworkDomainPermissionEntry;
+1
View File
@@ -33,6 +33,7 @@ pub use denial::is_likely_sandbox_denied;
pub use linux_pid_namespace::LinuxSandboxPidNamespace;
pub use manager::SandboxCommand;
pub use manager::SandboxExecRequest;
pub use manager::SandboxExecutables;
pub use manager::SandboxManager;
pub use manager::SandboxNetwork;
pub use manager::SandboxSelection;
+60 -17
View File
@@ -169,6 +169,19 @@ impl<'a> SandboxNetwork<'a> {
}
}
/// Executables supplied by the host. Only executor-provisioned helpers can receive runtime read access.
#[derive(Clone, Copy)]
pub enum SandboxExecutables<'a> {
/// A caller supplies its backend launcher and needs no additional executable grants.
Launcher(Option<&'a Path>),
/// Paths from executor startup and the optional argv[0] used by its command helper.
Executor {
codex: &'a AbsolutePathBuf,
linux_sandbox: Option<&'a AbsolutePathBuf>,
arg0: Option<&'a str>,
},
}
/// Bundled arguments for sandbox transformation.
///
/// This keeps call sites self-documenting when several fields are optional.
@@ -177,13 +190,10 @@ pub struct SandboxTransformRequest<'a> {
pub permissions: &'a PermissionProfile,
/// Bind symbolic workspace rules to these executor roots. `None` means they are already resolved.
pub workspace_roots: Option<&'a [PathUri]>,
/// Complete set of runtime files the executor selected for this launch, including its CA
/// bundle, if any. With `None`, the sandbox manager looks up the live proxy's CA bundle.
pub runtime_readable_paths: Option<&'a [AbsolutePathBuf]>,
pub selection: SandboxSelection,
pub network: SandboxNetwork<'a>,
pub sandbox_policy_cwd: &'a PathUri,
pub sandbox_exe: Option<&'a Path>,
pub executables: SandboxExecutables<'a>,
// TODO(anp): Reconcile these backend inputs with the supplied sandbox context
// (TurnEnvironment::sandbox_context for turns) so selection shares its authority.
pub use_legacy_landlock: bool,
@@ -437,6 +447,33 @@ impl SandboxManager {
&self,
request: SandboxTransformRequest<'_>,
) -> Result<WrappedSandboxCommand, SandboxTransformError> {
let mut runtime_readable_paths = Vec::new();
if let SandboxExecutables::Executor {
codex,
linux_sandbox,
arg0,
} = request.executables
{
if matches!(self.operation, SandboxOperation::FileSystemHelper) {
if !request.use_legacy_landlock {
runtime_readable_paths.push(codex.clone());
runtime_readable_paths
.extend(linux_sandbox.filter(|path| *path != codex).cloned());
}
} else {
if cfg!(target_os = "linux") || (cfg!(unix) && arg0.is_some()) {
runtime_readable_paths.push(codex.clone());
}
if cfg!(target_os = "linux") {
runtime_readable_paths.extend(linux_sandbox.cloned());
}
if request.command.managed_network.is_some() {
runtime_readable_paths.extend(codex_network_proxy::managed_mitm_ca_from_env(
&request.command.env,
));
}
}
}
let command = request.command;
let SandboxNetwork {
enforce_managed_network,
@@ -460,7 +497,7 @@ impl SandboxManager {
permissions,
request.sandbox_policy_cwd,
request.workspace_roots,
request.runtime_readable_paths.unwrap_or_default(),
&runtime_readable_paths,
&self.operation,
)
.map_err(SandboxTransformError::InvalidPolicy)?;
@@ -494,14 +531,19 @@ impl SandboxManager {
"managed networking requires the elevated Windows sandbox backend".into(),
));
}
let sandbox_exe = match request.executables {
SandboxExecutables::Launcher(path) => path,
SandboxExecutables::Executor { codex, .. } if cfg!(windows) => Some(codex.as_path()),
SandboxExecutables::Executor { linux_sandbox, .. } => {
linux_sandbox.map(AbsolutePathBuf::as_path)
}
};
let native_program = match backend {
SandboxType::None => Some(command.program.as_os_str()),
SandboxType::LinuxSeccomp | SandboxType::WindowsMxc => {
request.sandbox_exe.map(Path::as_os_str)
}
SandboxType::LinuxSeccomp | SandboxType::WindowsMxc => sandbox_exe.map(Path::as_os_str),
#[cfg(windows)]
SandboxType::WindowsRestrictedToken if is_file_system_helper => {
request.sandbox_exe.map(Path::as_os_str)
sandbox_exe.map(Path::as_os_str)
}
SandboxType::MacosSeatbelt | SandboxType::WindowsRestrictedToken => None,
}
@@ -536,9 +578,11 @@ impl SandboxManager {
if backend == SandboxType::None {
return Ok(wrapped(exec, None));
}
let managed_mitm_ca_trust_bundle_path = match request.runtime_readable_paths {
Some(_) => None,
None => network.and_then(NetworkProxy::managed_mitm_ca_trust_bundle_path),
let managed_mitm_ca_trust_bundle_path = match request.executables {
SandboxExecutables::Executor { .. } => None,
SandboxExecutables::Launcher(_) => {
network.and_then(NetworkProxy::managed_mitm_ca_trust_bundle_path)
}
};
let pending = PendingSandboxedExecRequest::new(
&exec.cwd,
@@ -573,7 +617,7 @@ impl SandboxManager {
};
let pending = pending?;
exec.permission_profile = pending.effective_permission_profile;
let exe = request.sandbox_exe.ok_or_else(|| {
let exe = sandbox_exe.ok_or_else(|| {
SandboxTransformError::WindowsMxcPreparation(
"missing Codex executable path".into(),
)
@@ -657,9 +701,8 @@ impl SandboxManager {
SandboxType::LinuxSeccomp => {
let pending = pending?;
exec.permission_profile = pending.effective_permission_profile;
let exe = request
.sandbox_exe
.ok_or(SandboxTransformError::MissingLinuxSandboxExecutable)?;
let exe =
sandbox_exe.ok_or(SandboxTransformError::MissingLinuxSandboxExecutable)?;
let route = match (enforce_managed_network, managed_network, network) {
(false, _, _) => None,
(true, None, Some(proxy)) => {
@@ -700,7 +743,7 @@ impl SandboxManager {
&mut exec,
&policy.workspace_roots,
&codex_home,
request.sandbox_exe,
sandbox_exe,
)?;
} else if let Some(proxy_settings_mode) = self.windows_token_session {
let filesystem_overrides = WindowsSandboxFilesystemOverrides::resolve(
+10 -13
View File
@@ -1,4 +1,5 @@
use super::SandboxCommand;
use super::SandboxExecutables;
use super::SandboxManager;
use super::SandboxNetwork;
use super::SandboxSelection;
@@ -116,7 +117,6 @@ fn unsandboxed_transform_preserves_foreign_cwd_and_unrestricted_file_system_poli
},
permissions: &permissions,
workspace_roots: None,
runtime_readable_paths: None,
selection: SandboxSelection::Explicit(SandboxType::None),
network: SandboxNetwork::new(
/*enforce_managed_network*/ false,
@@ -124,7 +124,7 @@ fn unsandboxed_transform_preserves_foreign_cwd_and_unrestricted_file_system_poli
Some("remote"),
),
sandbox_policy_cwd: &cwd_uri,
sandbox_exe: None,
executables: SandboxExecutables::Launcher(None),
use_legacy_landlock: false,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
})
@@ -182,11 +182,10 @@ fn symlinked_workspace_reports_seatbelt_preparation_error() {
},
permissions: &permissions,
workspace_roots: None,
runtime_readable_paths: None,
selection: SandboxSelection::Explicit(SandboxType::MacosSeatbelt),
network: Default::default(),
sandbox_policy_cwd: &workspace_uri,
sandbox_exe: None,
executables: SandboxExecutables::Launcher(None),
use_legacy_landlock: false,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
})
@@ -237,11 +236,10 @@ fn transform_additional_permissions_enable_network_for_external_sandbox() {
},
permissions: &permissions,
workspace_roots: None,
runtime_readable_paths: None,
selection: SandboxSelection::Explicit(SandboxType::None),
network: Default::default(),
sandbox_policy_cwd: &cwd_uri,
sandbox_exe: None,
executables: SandboxExecutables::Launcher(None),
use_legacy_landlock: false,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
})
@@ -326,11 +324,10 @@ fn transform_additional_permissions_preserves_denied_entries() {
},
permissions: &permissions,
workspace_roots: Some(roots),
runtime_readable_paths: Some(&[]),
selection: SandboxSelection::Explicit(SandboxType::None),
network: Default::default(),
sandbox_policy_cwd: &cwd_uri,
sandbox_exe: None,
executables: SandboxExecutables::Launcher(None),
use_legacy_landlock: false,
windows_sandbox_level: WindowsSandboxLevel::RestrictedToken,
};
@@ -405,11 +402,10 @@ fn sandbox_transform_request(cwd: &PathUri, sandbox: SandboxType) -> SandboxTran
},
permissions: &PermissionProfile::Disabled,
workspace_roots: None,
runtime_readable_paths: None,
selection: SandboxSelection::Explicit(sandbox),
network: Default::default(),
sandbox_policy_cwd: cwd,
sandbox_exe: None,
executables: SandboxExecutables::Launcher(None),
use_legacy_landlock: false,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
}
@@ -440,7 +436,7 @@ fn transform_linux_seccomp_request(
let cwd = PathUri::from_abs_path(&AbsolutePathBuf::current_dir().expect("current dir"));
manager
.transform(SandboxTransformRequest {
sandbox_exe: Some(codex_linux_sandbox_exe),
executables: SandboxExecutables::Launcher(Some(codex_linux_sandbox_exe)),
..sandbox_transform_request(&cwd, SandboxType::LinuxSeccomp)
})
.expect("transform")
@@ -727,7 +723,6 @@ async fn check_linux_managed_policy(transparent_tcp: bool) -> anyhow::Result<()>
},
permissions: &PermissionProfile::Disabled,
workspace_roots: None,
runtime_readable_paths: None,
selection: SandboxSelection::Explicit(SandboxType::LinuxSeccomp),
network: SandboxNetwork::new(
enforce_managed_network,
@@ -735,7 +730,9 @@ async fn check_linux_managed_policy(transparent_tcp: bool) -> anyhow::Result<()>
/*environment_id*/ None,
),
sandbox_policy_cwd: &cwd_uri,
sandbox_exe: Some(std::path::Path::new("/tmp/codex-linux-sandbox")),
executables: SandboxExecutables::Launcher(Some(std::path::Path::new(
"/tmp/codex-linux-sandbox",
))),
use_legacy_landlock: false,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
})?;