[codex] expose sandbox ingress to host

This commit is contained in:
Eugenio Panero
2026-06-25 20:05:12 -07:00
parent 25f50de6ed
commit 6c6d291f77
47 changed files with 1207 additions and 46 deletions
+7
View File
@@ -392,6 +392,7 @@ pub fn build_exec_request(
enforce_managed_network,
environment_id: network_environment_id.as_deref(),
network: network.as_ref(),
ingress: None,
sandbox_policy_cwd: &sandbox_policy_cwd_uri,
codex_linux_sandbox_exe: codex_linux_sandbox_exe.as_deref(),
use_legacy_landlock,
@@ -444,6 +445,7 @@ pub(crate) async fn execute_exec_request(
cwd,
env,
exec_server_env_config: _,
ingress,
network,
expiration,
capture_policy,
@@ -462,6 +464,11 @@ pub(crate) async fn execute_exec_request(
exec_server_enforce_managed_network: _,
exec_server_managed_network: _,
} = exec_request;
if ingress.is_some() {
return Err(CodexErr::UnsupportedOperation(
"ingress requires unified exec".to_string(),
));
}
// TODO(anp): Keep PathUri through the local process launch boundary.
let cwd = cwd
+1
View File
@@ -41,6 +41,7 @@ where
sandbox_policy_cwd,
use_legacy_landlock,
allow_network_for_proxy(/*enforce_managed_network*/ false),
/*ingress*/ None,
);
let codex_linux_sandbox_exe = codex_linux_sandbox_exe.as_ref();
// Preserve the helper alias when we already have it; otherwise force argv0
+4
View File
@@ -48,6 +48,7 @@ pub struct ExecRequest {
pub cwd: PathUri,
pub env: HashMap<String, String>,
pub(crate) exec_server_env_config: Option<ExecServerEnvConfig>,
pub ingress: Option<u16>,
pub network: Option<NetworkProxy>,
pub network_environment_id: Option<String>,
pub expiration: ExecExpiration,
@@ -93,6 +94,7 @@ impl ExecRequest {
cwd,
env,
exec_server_env_config: None,
ingress: None,
network,
network_environment_id,
expiration,
@@ -123,6 +125,7 @@ impl ExecRequest {
cwd,
sandbox_policy_cwd: windows_sandbox_policy_cwd,
mut env,
ingress,
network,
network_environment_id,
sandbox,
@@ -152,6 +155,7 @@ impl ExecRequest {
cwd,
env,
exec_server_env_config: None,
ingress,
network,
network_environment_id,
expiration,
+1
View File
@@ -203,6 +203,7 @@ pub(crate) async fn execute_user_shell_command(
cwd: cwd.clone().into(),
env: exec_env_map,
exec_server_env_config: None,
ingress: 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,
@@ -55,6 +55,13 @@ pub(crate) fn create_exec_command_tool_with_environment_id(
)),
),
]);
#[cfg(unix)]
properties.insert(
"ingress".to_string(),
JsonSchema::integer(Some(
"Expose a TCP port from the Linux sandbox through the parent host.".to_string(),
)),
);
if include_shell_parameter {
properties.insert(
"shell".to_string(),
@@ -74,6 +74,13 @@ fn exec_command_tool_matches_expected_spec() {
)),
),
]);
#[cfg(unix)]
properties.insert(
"ingress".to_string(),
JsonSchema::integer(Some(
"Expose a TCP port from the Linux sandbox through the parent host.".to_string(),
)),
);
properties.extend(create_approval_parameters(
/*exec_permission_approvals_enabled*/ false,
));
@@ -33,6 +33,8 @@ pub(crate) struct ExecCommandArgs {
login: Option<bool>,
#[serde(default = "default_tty")]
tty: bool,
#[serde(default)]
ingress: Option<u16>,
#[serde(default = "default_exec_yield_time_ms")]
yield_time_ms: u64,
#[serde(default)]
@@ -242,6 +242,7 @@ impl ExecCommandHandler {
let ExecCommandArgs {
tty,
ingress,
yield_time_ms,
max_output_tokens,
sandbox_permissions,
@@ -355,6 +356,7 @@ impl ExecCommandHandler {
shell_mode,
network: context.turn.network.clone(),
tty,
ingress,
sandbox_permissions: effective_additional_permissions.sandbox_permissions,
additional_permissions: normalized_additional_permissions,
additional_permissions_preapproved: effective_additional_permissions
@@ -128,6 +128,7 @@ async fn explicit_escalation_prepares_exec_without_managed_network() -> anyhow::
Some(&proxy),
SandboxPermissions::RequireEscalated,
),
/*ingress*/ None,
/*environment_id*/ None,
)
.expect("prepare exec request");
@@ -326,6 +326,7 @@ impl ToolRuntime<ShellRequest, ExecToolCallOutput> for ShellRuntime {
command,
options,
managed_network,
/*ingress*/ None,
Some(&req.turn_environment.environment_id),
)
.map_err(ToolError::Codex)?;
@@ -144,6 +144,7 @@ pub(super) async fn try_run_zsh_fork(
command,
options,
managed_network_for_sandbox_permissions(req.network.as_ref(), req.sandbox_permissions),
/*ingress*/ None,
Some(&req.turn_environment.environment_id),
)
.map_err(ToolError::Codex)?;
@@ -152,6 +153,7 @@ pub(super) async fn try_run_zsh_fork(
cwd: sandbox_cwd,
env: sandbox_env,
exec_server_env_config: _,
ingress: _,
network: sandbox_network,
network_environment_id,
expiration: _sandbox_expiration,
@@ -887,6 +889,7 @@ impl CoreShellCommandExecutor {
cwd: self.cwd.clone().into(),
env: exec_env,
exec_server_env_config: None,
ingress: None,
network: self.network.clone(),
network_environment_id: self.network_environment_id.clone(),
expiration: ExecExpiration::Cancellation(cancel_rx),
@@ -1026,6 +1029,7 @@ impl CoreShellCommandExecutor {
enforce_managed_network: self.network.is_some(),
environment_id: self.network_environment_id.as_deref(),
network: self.network.as_ref(),
ingress: None,
sandbox_policy_cwd: &sandbox_policy_cwd,
codex_linux_sandbox_exe: self.codex_linux_sandbox_exe.as_deref(),
use_legacy_landlock: self.use_legacy_landlock,
@@ -74,6 +74,7 @@ pub struct UnifiedExecRequest {
pub explicit_env_overrides: HashMap<String, String>,
pub network: Option<NetworkProxy>,
pub tty: bool,
pub ingress: Option<u16>,
pub sandbox_permissions: SandboxPermissions,
pub additional_permissions: Option<AdditionalPermissionProfile>,
#[cfg(unix)]
@@ -90,6 +91,7 @@ pub struct UnifiedExecApprovalKey {
pub command: Vec<String>,
pub cwd: PathUri,
pub tty: bool,
pub ingress: Option<u16>,
pub sandbox_permissions: SandboxPermissions,
pub additional_permissions: Option<AdditionalPermissionProfile>,
}
@@ -163,6 +165,7 @@ impl Approvable<UnifiedExecRequest> for UnifiedExecRuntime<'_> {
command: canonicalize_command_for_approval(&req.command),
cwd: req.cwd.clone(),
tty: req.tty,
ingress: req.ingress,
sandbox_permissions: req.sandbox_permissions,
additional_permissions: req.additional_permissions.clone(),
}]
@@ -409,6 +412,7 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
command,
options,
managed_network,
req.ingress,
Some(&req.turn_environment.environment_id),
)
.map_err(ToolError::Codex)?;
@@ -477,6 +481,7 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
options,
attempt,
managed_network,
req.ingress,
/*environment_id*/ Some(&req.turn_environment.environment_id),
req.exec_server_env_config.clone(),
req.tty,
@@ -574,6 +579,7 @@ mod tests {
explicit_env_overrides: HashMap::new(),
network: None,
tty: false,
ingress: None,
sandbox_permissions: SandboxPermissions::UseDefault,
additional_permissions: None,
#[cfg(unix)]
@@ -676,6 +682,7 @@ mod tests {
explicit_env_overrides: HashMap::new(),
network: None,
tty: false,
ingress: None,
sandbox_permissions,
additional_permissions: None,
#[cfg(unix)]
+5
View File
@@ -431,6 +431,7 @@ impl<'a> SandboxAttempt<'a> {
command: SandboxCommand,
options: ExecOptions,
network: Option<&NetworkProxy>,
ingress: Option<u16>,
environment_id: Option<&str>,
) -> Result<crate::sandboxing::ExecRequest, CodexErr> {
let request = self
@@ -442,6 +443,7 @@ impl<'a> SandboxAttempt<'a> {
enforce_managed_network: self.enforce_managed_network,
environment_id,
network,
ingress,
sandbox_policy_cwd: self.sandbox_cwd,
codex_linux_sandbox_exe: self
.codex_linux_sandbox_exe
@@ -463,6 +465,7 @@ impl<'a> SandboxAttempt<'a> {
command: SandboxCommand,
options: ExecOptions,
network: Option<&NetworkProxy>,
ingress: Option<u16>,
environment_id: Option<&str>,
) -> Result<crate::sandboxing::ExecRequest, CodexErr> {
let managed_network = command.managed_network.clone();
@@ -480,6 +483,7 @@ impl<'a> SandboxAttempt<'a> {
enforce_managed_network: self.enforce_managed_network,
environment_id,
network,
ingress: None,
sandbox_policy_cwd: self.sandbox_cwd,
codex_linux_sandbox_exe: None,
use_legacy_landlock: self.use_legacy_landlock,
@@ -492,6 +496,7 @@ impl<'a> SandboxAttempt<'a> {
options,
self.workspace_roots.to_vec(),
);
exec_request.ingress = ingress;
exec_request.exec_server_managed_network = managed_network;
if self.sandbox_requested {
exec_request.exec_server_sandbox = Some(FileSystemSandboxContext {
+28 -2
View File
@@ -245,7 +245,13 @@ fn exec_server_env_keeps_command_native_and_carries_sandbox_context() {
capture_policy: crate::exec::ExecCapturePolicy::ShellTool,
};
let request = attempt
.env_for_exec_server(command(), options(), /*network*/ None, Some("remote"))
.env_for_exec_server(
command(),
options(),
/*network*/ None,
/*ingress*/ None,
Some("remote"),
)
.expect("prepare remote exec request");
assert_eq!(
@@ -275,9 +281,29 @@ fn exec_server_env_keeps_command_native_and_carries_sandbox_context() {
Some(managed_network.clone())
);
let ingress_request = attempt
.env_for_exec_server(
command(),
options(),
/*network*/ None,
/*ingress*/ Some(4173),
Some("remote"),
)
.expect("prepare ingress remote exec request");
assert_eq!(ingress_request.ingress, Some(4173));
assert_eq!(ingress_request.sandbox, SandboxType::None);
assert!(ingress_request.exec_server_sandbox.is_some());
attempt.sandbox_requested = false;
let request = attempt
.env_for_exec_server(command(), options(), /*network*/ None, Some("remote"))
.env_for_exec_server(
command(),
options(),
/*network*/ None,
/*ingress*/ None,
Some("remote"),
)
.expect("prepare unsandboxed remote exec request");
assert_eq!(request.exec_server_sandbox, None);
+1
View File
@@ -102,6 +102,7 @@ pub(crate) struct ExecCommandRequest {
pub shell_mode: UnifiedExecShellMode,
pub network: Option<NetworkProxy>,
pub tty: bool,
pub ingress: Option<u16>,
pub sandbox_permissions: SandboxPermissions,
pub additional_permissions: Option<AdditionalPermissionProfile>,
pub additional_permissions_preapproved: bool,
@@ -20,6 +20,8 @@ use codex_exec_server::StartedExecProcess;
use codex_exec_server::WriteResponse;
use codex_exec_server::WriteStatus;
use codex_sandboxing::SandboxType;
#[cfg(unix)]
use codex_sandboxing::ingress::INGRESS_LISTENER_FD_ENV_VAR;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_output_truncation::TruncationPolicy;
use codex_utils_output_truncation::approx_token_count;
@@ -28,6 +30,10 @@ use core_test_support::skip_if_sandbox;
use core_test_support::test_codex::test_env as remote_test_env;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
#[cfg(unix)]
use std::net::Ipv4Addr;
#[cfg(unix)]
use std::net::TcpListener;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::Notify;
@@ -201,6 +207,78 @@ async fn exec_command_with_tty(
})
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn local_ingress_passes_inherited_listener_to_child() -> anyhow::Result<()> {
skip_if_sandbox!(Ok(()));
let (session, turn) = test_session_and_turn().await;
let manager = &session.services.unified_exec_manager;
let process_id = manager.allocate_process_id().await;
#[allow(deprecated)]
let cwd = turn.cwd.clone();
let command = vec![
"bash".to_string(),
"-lc".to_string(),
r#"test -n "$CODEX_INGRESS_LISTENER_FD" && eval "true <&${CODEX_INGRESS_LISTENER_FD}" && echo ingress-ready"#
.to_string(),
];
let mut env = shell_env();
env.remove(INGRESS_LISTENER_FD_ENV_VAR);
let mut request = test_exec_request(turn.as_ref(), command, cwd, env);
request.ingress = Some(unused_ingress_port());
let process = manager
.open_session_with_prepared_exec_env(
process_id,
&request,
/*tty*/ false,
Box::new(NoopSpawnLifecycle),
turn.environments
.primary()
.expect("turn environment")
.environment
.as_ref(),
)
.await?;
let OutputHandles {
output_buffer,
output_notify,
output_closed,
output_closed_notify,
cancellation_token,
} = process.output_handles();
let output = UnifiedExecProcessManager::collect_output_until_deadline(
&output_buffer,
&output_notify,
&output_closed,
&output_closed_notify,
&cancellation_token,
Some(session.subscribe_out_of_band_elicitation_pause_state()),
Instant::now() + Duration::from_secs(2),
)
.await;
assert_eq!(process.exit_code(), Some(0));
assert!(
String::from_utf8_lossy(&output).contains("ingress-ready"),
"expected ingress child output, got: {}",
String::from_utf8_lossy(&output),
);
manager.release_process_id(process_id).await;
Ok(())
}
#[cfg(unix)]
fn unused_ingress_port() -> u16 {
TcpListener::bind((Ipv4Addr::UNSPECIFIED, 0))
.expect("bind ephemeral ingress listener")
.local_addr()
.expect("read ephemeral ingress listener address")
.port()
}
#[derive(Debug)]
struct TestSpawnLifecycle {
inherited_fds: Vec<i32>,
@@ -62,6 +62,10 @@ use codex_protocol::error::CodexErr;
use codex_protocol::error::SandboxErr;
use codex_protocol::protocol::ExecCommandSource;
use codex_sandboxing::SandboxCommand;
#[cfg(unix)]
use codex_sandboxing::ingress::IngressListener;
#[cfg(unix)]
use codex_sandboxing::ingress::IngressListenerError;
use codex_tools::ToolName;
use codex_utils_output_truncation::approx_token_count;
use codex_utils_path_uri::PathUri;
@@ -188,6 +192,7 @@ fn exec_server_params_for_request(
env,
tty,
pipe_stdin: false,
ingress: request.ingress,
arg0: request.arg0.clone(),
sandbox: request.exec_server_sandbox.clone(),
enforce_managed_network: request.exec_server_enforce_managed_network,
@@ -920,6 +925,7 @@ impl UnifiedExecProcessManager {
options: ExecOptions,
attempt: &SandboxAttempt<'_>,
network: Option<&NetworkProxy>,
ingress: Option<u16>,
environment_id: Option<&str>,
exec_server_env_config: Option<ExecServerEnvConfig>,
tty: bool,
@@ -927,9 +933,9 @@ impl UnifiedExecProcessManager {
environment: &codex_exec_server::Environment,
) -> Result<UnifiedExecProcess, ToolError> {
let mut request = if environment.is_remote() {
attempt.env_for_exec_server(command, options, network, environment_id)
attempt.env_for_exec_server(command, options, network, ingress, environment_id)
} else {
attempt.env_for(command, options, network, environment_id)
attempt.env_for(command, options, network, ingress, environment_id)
}
.map_err(ToolError::Codex)?;
request.exec_server_env_config = exec_server_env_config;
@@ -960,8 +966,6 @@ impl UnifiedExecProcessManager {
mut spawn_lifecycle: SpawnLifecycleHandle,
environment: &codex_exec_server::Environment,
) -> Result<UnifiedExecProcess, UnifiedExecError> {
let inherited_fds = spawn_lifecycle.inherited_fds();
#[cfg(target_os = "windows")]
if request.sandbox == codex_sandboxing::SandboxType::WindowsRestrictedToken {
// TODO(anp): Keep PathUri through the Windows sandbox launch boundary.
@@ -1049,6 +1053,7 @@ impl UnifiedExecProcessManager {
.await;
}
if environment.is_remote() {
let inherited_fds = spawn_lifecycle.inherited_fds();
if !inherited_fds.is_empty() {
return Err(UnifiedExecError::create_process(
"remote exec-server does not support inherited file descriptors".to_string(),
@@ -1064,6 +1069,22 @@ impl UnifiedExecProcessManager {
return UnifiedExecProcess::from_exec_server_started(started).await;
}
let mut env = request.env.clone();
let mut inherited_fds = spawn_lifecycle.inherited_fds();
#[cfg(unix)]
let ingress = IngressListener::prepare(request.ingress).map_err(ingress_error)?;
#[cfg(unix)]
if let Some(ingress) = ingress.as_ref() {
ingress.add_to_child_env(&mut env);
inherited_fds.push(ingress.inherited_fd());
}
#[cfg(not(unix))]
if request.ingress.is_some() {
return Err(UnifiedExecError::create_process(
"ingress is only supported on Unix hosts".to_string(),
));
}
// TODO(anp): Keep PathUri through the local PTY/process launch boundary.
let native_cwd = request
.cwd
@@ -1081,7 +1102,7 @@ impl UnifiedExecProcessManager {
program,
args,
native_cwd.as_path(),
&request.env,
&env,
&request.arg0,
codex_utils_pty::TerminalSize::default(),
&inherited_fds,
@@ -1092,7 +1113,7 @@ impl UnifiedExecProcessManager {
program,
args,
native_cwd.as_path(),
&request.env,
&env,
&request.arg0,
&inherited_fds,
)
@@ -1100,6 +1121,8 @@ impl UnifiedExecProcessManager {
};
let spawned =
spawn_result.map_err(|err| UnifiedExecError::create_process(err.to_string()))?;
#[cfg(unix)]
drop(ingress);
spawn_lifecycle.after_spawn();
UnifiedExecProcess::from_spawned(spawned, request.sandbox, spawn_lifecycle).await
}
@@ -1166,6 +1189,7 @@ impl UnifiedExecProcessManager {
.clone(),
network: request.network.clone(),
tty: request.tty,
ingress: request.ingress,
sandbox_permissions: request.sandbox_permissions,
additional_permissions: request.additional_permissions.clone(),
#[cfg(unix)]
@@ -1448,6 +1472,21 @@ impl UnifiedExecProcessManager {
}
}
#[cfg(unix)]
fn ingress_error(error: IngressListenerError) -> UnifiedExecError {
match error {
IngressListenerError::InvalidPort => {
UnifiedExecError::create_process("ingress port must be between 1 and 65535".to_string())
}
IngressListenerError::PortInUse(port) => UnifiedExecError::create_process(format!(
"ingress port {port} is already in use by another process"
)),
IngressListenerError::Io(error) => {
UnifiedExecError::create_process(format!("failed to prepare ingress listener: {error}"))
}
}
}
enum ProcessStatus {
Alive {
exit_code: Option<i32>,
@@ -157,6 +157,7 @@ fn exec_server_params_use_path_uri_and_env_policy_overlay_contract() {
),
]),
}),
ingress: None,
network: None,
network_environment_id: None,
expiration: crate::exec::ExecExpiration::DefaultTimeout,
@@ -287,6 +288,7 @@ async fn failed_initial_end_for_unstored_process_uses_fallback_output() {
shell_mode: codex_tools::UnifiedExecShellMode::Direct,
network: None,
tty: true,
ingress: None,
sandbox_permissions: crate::sandboxing::SandboxPermissions::UseDefault,
additional_permissions: None,
additional_permissions_preapproved: false,