sandboxing: migrate cwd inputs to PathUri (#27816)

## Why

Sandbox cwd values can cross app-server and exec-server host boundaries.
They should retain URI semantics until the receiving host validates them
instead of being interpreted early as native paths.

## What

- Carry `PathUri` through filesystem sandbox contexts, sandbox commands,
and transform inputs.
- Convert command and policy cwd once in `SandboxManager::transform`,
then keep launch requests native.
- Preserve sandbox cwd over remote filesystem transport and reject
non-native URIs without fallback.
- Cache paired native/URI turn-environment cwd values during migration,
with immutable access to keep them synchronized.
- Extend existing protocol, forwarding, transform, and core runtime
tests.
This commit is contained in:
Adam Perry @ OpenAI authored and GitHub committed 2026-06-12 11:38:01 -07:00
1 parent 84520225b9
commit 52a50aec70
40 files changed
+546 -228

No files matched your search

@@ -11,16 +11,18 @@ use codex_sandboxing::SandboxManager;
use codex_sandboxing::SandboxType;
use codex_sandboxing::policy_transforms::effective_file_system_sandbox_policy;
use codex_sandboxing::policy_transforms::effective_network_sandbox_policy;
use codex_utils_path_uri::PathUri;
use core_test_support::PathBufExt;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
fn test_turn_environment(environment_id: &str) -> crate::session::turn_context::TurnEnvironment {
crate::session::turn_context::TurnEnvironment {
environment_id: environment_id.to_string(),
environment: std::sync::Arc::new(codex_exec_server::Environment::default_for_tests()),
cwd: std::env::temp_dir().abs(),
shell: None,
}
crate::session::turn_context::TurnEnvironment::new(
environment_id.to_string(),
std::sync::Arc::new(codex_exec_server::Environment::default_for_tests()),
std::env::temp_dir().abs(),
/*shell*/ None,
)
.expect("turn environment")
}
#[test]
@@ -206,12 +208,13 @@ async fn file_system_sandbox_context_uses_active_attempt() {
NetworkSandboxPolicy::Restricted,
);
let manager = SandboxManager::new();
let sandbox_policy_cwd = PathUri::from_abs_path(&path).expect("path URI");
let attempt = SandboxAttempt {
sandbox: SandboxType::MacosSeatbelt,
permissions: &permissions,
enforce_managed_network: false,
manager: &manager,
sandbox_cwd: &path,
sandbox_cwd: &sandbox_policy_cwd,
workspace_roots: std::slice::from_ref(&path),
codex_linux_sandbox_exe: None,
use_legacy_landlock: true,
@@ -232,7 +235,10 @@ async fn file_system_sandbox_context_uses_active_attempt() {
let expected_permissions =
PermissionProfile::from_runtime_permissions(&file_system_policy, network_policy);
assert_eq!(sandbox.permissions, expected_permissions);
assert_eq!(sandbox.cwd, Some(path.clone()));
assert_eq!(
sandbox.cwd,
Some(codex_utils_path_uri::PathUri::from_abs_path(&path).expect("path URI"))
);
assert_eq!(
sandbox.windows_sandbox_level,
WindowsSandboxLevel::RestrictedToken
@@ -260,12 +266,13 @@ async fn no_sandbox_attempt_has_no_file_system_context() {
};
let permissions = PermissionProfile::Disabled;
let manager = SandboxManager::new();
let sandbox_policy_cwd = PathUri::from_abs_path(&path).expect("path URI");
let attempt = SandboxAttempt {
sandbox: SandboxType::None,
permissions: &permissions,
enforce_managed_network: false,
manager: &manager,
sandbox_cwd: &path,
sandbox_cwd: &sandbox_policy_cwd,
workspace_roots: std::slice::from_ref(&path),
codex_linux_sandbox_exe: None,
use_legacy_landlock: false,
+11 -3
View File
@@ -21,10 +21,12 @@ use codex_network_proxy::PROXY_ENV_KEYS;
use codex_network_proxy::PROXY_GIT_SSH_COMMAND_ENV_KEY;
use codex_network_proxy::is_managed_mitm_ca_trust_bundle_path;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::error::CodexErr;
use codex_protocol::models::AdditionalPermissionProfile;
use codex_sandboxing::SandboxCommand;
use codex_sandboxing::SandboxType;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use std::collections::HashMap;
#[cfg(unix)]
use std::path::Path;
@@ -33,8 +35,9 @@ pub(crate) mod apply_patch;
pub(crate) mod shell;
pub(crate) mod unified_exec;
/// Shared helper to construct sandbox transform inputs from a tokenized command line.
/// Validates that at least a program is present.
/// Shared helper to construct sandbox transform inputs from a tokenized command line and native
/// working directory. Validates that at least a program is present and that the working directory
/// has a file URI representation.
pub(crate) fn build_sandbox_command(
command: &[String],
cwd: &AbsolutePathBuf,
@@ -44,10 +47,15 @@ pub(crate) fn build_sandbox_command(
let (program, args) = command
.split_first()
.ok_or_else(|| ToolError::Rejected("command args are empty".to_string()))?;
let cwd = PathUri::from_abs_path(cwd).map_err(|_| {
ToolError::Codex(CodexErr::InvalidRequest(
"command cwd cannot be represented as a file URI".to_string(),
))
})?;
Ok(SandboxCommand {
program: program.clone().into(),
args: args.to_vec(),
cwd: cwd.clone(),
cwd,
env: env.clone(),
additional_permissions,
})
+13 -4
View File
@@ -25,6 +25,7 @@ use codex_protocol::models::PermissionProfile;
use codex_sandboxing::SandboxManager;
use codex_sandboxing::SandboxType;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use core_test_support::PathBufExt;
use core_test_support::PathExt;
use pretty_assertions::assert_eq;
@@ -88,18 +89,21 @@ async fn test_network_proxy() -> anyhow::Result<NetworkProxy> {
async fn explicit_escalation_prepares_exec_without_managed_network() -> anyhow::Result<()> {
let proxy = test_network_proxy().await?;
let dir = tempdir().expect("create temp dir");
let cwd = dir.path().abs();
let command_cwd = dir.path().join("command").abs();
let native_sandbox_policy_cwd = dir.path().join("sandbox-policy").abs();
let mut env = HashMap::from([("CUSTOM_ENV".to_string(), "kept".to_string())]);
proxy.apply_to_env(&mut env);
let command = vec!["/bin/echo".to_string(), "ok".to_string()];
let command = build_sandbox_command(
&command,
&cwd,
&command_cwd,
&exec_env_for_sandbox_permissions(&env, SandboxPermissions::RequireEscalated),
/*additional_permissions*/ None,
)
.expect("build sandbox command");
assert_eq!(command.cwd, PathUri::from_abs_path(&command_cwd)?);
let sandbox_policy_cwd = PathUri::from_abs_path(&native_sandbox_policy_cwd)?;
let options = ExecOptions {
expiration: ExecExpiration::DefaultTimeout,
capture_policy: ExecCapturePolicy::ShellTool,
@@ -111,8 +115,8 @@ async fn explicit_escalation_prepares_exec_without_managed_network() -> anyhow::
permissions: &permissions,
enforce_managed_network: false,
manager: &manager,
sandbox_cwd: &cwd,
workspace_roots: std::slice::from_ref(&cwd),
sandbox_cwd: &sandbox_policy_cwd,
workspace_roots: std::slice::from_ref(&native_sandbox_policy_cwd),
codex_linux_sandbox_exe: None,
use_legacy_landlock: false,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
@@ -131,6 +135,11 @@ async fn explicit_escalation_prepares_exec_without_managed_network() -> anyhow::
)
.expect("prepare exec request");
assert_eq!(exec_request.cwd, command_cwd);
assert_eq!(
exec_request.windows_sandbox_policy_cwd,
native_sandbox_policy_cwd
);
assert_eq!(exec_request.network, None);
for key in PROXY_ENV_KEYS {
assert_eq!(exec_request.env.get(*key), None, "{key} should be unset");
+1 -1
View File
@@ -310,7 +310,7 @@ impl ToolRuntime<ShellRequest, ExecToolCallOutput> for ShellRuntime {
};
let env = attempt
.env_for(command, options, managed_network)
.map_err(|err| ToolError::Codex(err.into()))?;
.map_err(ToolError::Codex)?;
let out = execute_env(env, Self::stdout_stream(ctx))
.await
.map_err(ToolError::Codex)?;
@@ -66,6 +66,7 @@ use codex_shell_escalation::ShellCommandExecutor;
use codex_shell_escalation::ShellCommandExecutorFuture;
use codex_shell_escalation::Stopwatch;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
@@ -143,7 +144,7 @@ pub(super) async fn try_run_zsh_fork(
options,
managed_network_for_sandbox_permissions(req.network.as_ref(), req.sandbox_permissions),
)
.map_err(|err| ToolError::Codex(err.into()))?;
.map_err(ToolError::Codex)?;
let crate::sandboxing::ExecRequest {
command,
cwd: sandbox_cwd,
@@ -968,10 +969,19 @@ impl CoreShellCommandExecutor {
self.windows_sandbox_level,
self.network.is_some(),
);
let cwd = PathUri::from_abs_path(workdir).map_err(|_| {
CodexErr::InvalidRequest("command cwd cannot be represented as a file URI".to_string())
})?;
let sandbox_policy_cwd =
PathUri::from_abs_path(&self.sandbox_policy_cwd).map_err(|_| {
CodexErr::InvalidRequest(
"sandbox policy cwd cannot be represented as a file URI".to_string(),
)
})?;
let command = SandboxCommand {
program: program.clone().into(),
args: args.to_vec(),
cwd: workdir.clone(),
cwd,
env,
additional_permissions,
};
@@ -985,7 +995,7 @@ impl CoreShellCommandExecutor {
sandbox,
enforce_managed_network: self.network.is_some(),
network: self.network.as_ref(),
sandbox_policy_cwd: &self.sandbox_policy_cwd,
sandbox_policy_cwd: &sandbox_policy_cwd,
codex_linux_sandbox_exe: self.codex_linux_sandbox_exe.as_deref(),
use_legacy_landlock: self.use_legacy_landlock,
windows_sandbox_level: self.windows_sandbox_level,
@@ -994,7 +1004,6 @@ impl CoreShellCommandExecutor {
let mut exec_request = crate::sandboxing::ExecRequest::from_sandbox_exec_request(
exec_request,
options,
self.sandbox_policy_cwd.clone(),
self.windows_sandbox_workspace_roots.clone(),
);
if let Some(network) = exec_request.network.as_ref() {
@@ -326,11 +326,16 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
if let UnifiedExecShellMode::ZshFork(zsh_fork_config) = &self.shell_mode {
let command =
build_sandbox_command(&command, &req.cwd, &env, req.additional_permissions.clone())
.map_err(|_| ToolError::Rejected("missing command line for PTY".to_string()))?;
.map_err(|error| match error {
ToolError::Rejected(_) => {
ToolError::Rejected("missing command line for PTY".to_string())
}
error @ ToolError::Codex(_) => error,
})?;
let options = unified_exec_options(attempt.network_denial_cancellation_token.clone());
let mut exec_env = attempt
.env_for(command, options, managed_network)
.map_err(|err| ToolError::Codex(err.into()))?;
.map_err(ToolError::Codex)?;
exec_env.exec_server_env_config = req.exec_server_env_config.clone();
match zsh_fork_backend::maybe_prepare_unified_exec(
req,
@@ -377,11 +382,16 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
}
let command =
build_sandbox_command(&command, &req.cwd, &env, req.additional_permissions.clone())
.map_err(|_| ToolError::Rejected("missing command line for PTY".to_string()))?;
.map_err(|error| match error {
ToolError::Rejected(_) => {
ToolError::Rejected("missing command line for PTY".to_string())
}
error @ ToolError::Codex(_) => error,
})?;
let options = unified_exec_options(attempt.network_denial_cancellation_token.clone());
let mut exec_env = attempt
.env_for(command, options, managed_network)
.map_err(|err| ToolError::Codex(err.into()))?;
.map_err(ToolError::Codex)?;
exec_env.exec_server_env_config = req.exec_server_env_config.clone();
self.manager
.open_session_with_exec_env(