unified-exec: preserve PathUri through exec-server (#28681)

## Why

It should be possible for app-server to handle "foreign" OS paths in
unified_exec working directories, allowing e.g. a Linux app-server to
run processes on e.g. a Windows exec-server.

## What

Convert the core unified_exec cwd values to use `PathUri`.

Adds fallible path conversion in several places to try to minimize the
scope of this change. The only time this change suppresses errors from
converting `PathUri` to an `AbsolutePathBuf` is when the turn is
configured with no sandboxing at all to allow us to make progress
testing without sandboxing.

Future changes to apply_patch and sandboxing will clean up these error
paths.

A tool's cwd is resolved from joining a model-provided workdir to the
environment's cwd. When using `AbsolutePathBuf::join()`, an
absolute-path workdir would overwrite the environment's cwd and we would
resolve permissions/sandboxing against the model-provided path. This
change extends `PathUri::join()` to also treat an absolute rhs as an
override of the base/lhs.

This also removes some coverage from the remove_env_windows tests until
a follow-up converts foreign paths in command exec events correctly.

## Breaking Changes

When using `AbsolutePathBuf::join()` for workdir resolution, we ended up
resolving tilde-prefixed paths against the app-server's `$HOME`, e.g.
`~/foo/bar` becomes `/home/anp/foo/bar`. It's difficult to do this with
`PathUri` joining, so after offline discussion this PR no longer
implements it.

A quick check of some power users' rollouts suggests that models don't
actually generate home-prefixed absolute working directories for their
spawns, so this shouldn't have any real blast radius.
This commit is contained in:
Adam Perry @ OpenAI authored and GitHub committed 2026-06-17 19:36:16 +00:00
1 parent cca39d51ba
commit 5867b529ae
33 files changed
+634 -206

No files matched your search

@@ -78,13 +78,15 @@ impl ApplyPatchRuntime {
fn build_guardian_review_request(
req: &ApplyPatchRequest,
call_id: &str,
) -> GuardianApprovalRequest {
GuardianApprovalRequest::ApplyPatch {
) -> std::io::Result<GuardianApprovalRequest> {
// TODO(anp): Remove this conversion once the guardian API supports PathUri.
let cwd = req.action.cwd.to_abs_path()?;
Ok(GuardianApprovalRequest::ApplyPatch {
id: call_id.to_string(),
cwd: req.action.cwd.clone(),
cwd,
files: req.file_paths.clone(),
patch: req.action.patch.clone(),
}
})
}
fn file_system_sandbox_context_for_attempt(
@@ -149,7 +151,16 @@ impl Approvable<ApplyPatchRequest> for ApplyPatchRuntime {
let guardian_review_id = ctx.guardian_review_id.clone();
Box::pin(async move {
if let Some(review_id) = guardian_review_id {
let action = ApplyPatchRuntime::build_guardian_review_request(req, ctx.call_id);
let action = match ApplyPatchRuntime::build_guardian_review_request(
req,
ctx.call_id,
) {
Ok(action) => action,
Err(err) => {
tracing::error!(cwd = %req.action.cwd, %err, "guardian apply_patch cwd is not host-native");
return ReviewDecision::Abort;
}
};
return review_approval_request(session, turn, review_id, action, retry_reason)
.await;
}
@@ -219,7 +230,7 @@ impl Approvable<ApplyPatchRequest> for ApplyPatchRuntime {
}
impl ToolRuntime<ApplyPatchRequest, ApplyPatchRuntimeOutput> for ApplyPatchRuntime {
fn sandbox_cwd<'a>(&self, req: &'a ApplyPatchRequest) -> Option<&'a AbsolutePathBuf> {
fn sandbox_cwd<'a>(&self, req: &'a ApplyPatchRequest) -> Option<&'a PathUri> {
Some(&req.action.cwd)
}
@@ -234,9 +245,15 @@ impl ToolRuntime<ApplyPatchRequest, ApplyPatchRuntimeOutput> for ApplyPatchRunti
let sandbox = Self::file_system_sandbox_context_for_attempt(req, attempt);
let mut stdout = Vec::new();
let mut stderr = Vec::new();
// TODO(anp): Teach apply_patch to operate on PathUri directly.
let cwd = req
.action
.cwd
.to_abs_path()
.map_err(|err| ToolError::Rejected(err.to_string()))?;
let result = codex_apply_patch::apply_patch(
&req.action.patch,
&req.action.cwd,
&cwd,
&mut stdout,
&mut stderr,
fs.as_ref(),
@@ -54,7 +54,7 @@ async fn guardian_review_request_includes_patch_context() {
.join("guardian-apply-patch-test.txt")
.abs();
let action = ApplyPatchAction::new_add_for_test(&path, "hello".to_string());
let expected_cwd = action.cwd.clone();
let expected_cwd = action.cwd.to_abs_path().expect("native patch cwd");
let expected_patch = action.patch.clone();
let request = ApplyPatchRequest {
turn_environment: test_turn_environment(codex_exec_server::LOCAL_ENVIRONMENT_ID),
@@ -74,7 +74,8 @@ async fn guardian_review_request_includes_patch_context() {
permissions_preapproved: false,
};
let guardian_request = ApplyPatchRuntime::build_guardian_review_request(&request, "call-1");
let guardian_request = ApplyPatchRuntime::build_guardian_review_request(&request, "call-1")
.expect("native guardian request cwd");
assert_eq!(
guardian_request,
@@ -129,10 +129,10 @@ 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.cwd, PathUri::from_abs_path(&command_cwd));
assert_eq!(
exec_request.windows_sandbox_policy_cwd,
native_sandbox_policy_cwd
PathUri::from_abs_path(&native_sandbox_policy_cwd)
);
assert_eq!(exec_request.network, None);
for key in PROXY_ENV_KEYS {
@@ -172,6 +172,14 @@ pub(super) async fn try_run_zsh_fork(
let exec_policy = Arc::new(RwLock::new(
ctx.session.services.exec_policy.current().as_ref().clone(),
));
// TODO(anp): Keep PathUri through the shell escalation boundary.
let sandbox_cwd = sandbox_cwd
.to_abs_path()
.map_err(|err| ToolError::Rejected(err.to_string()))?;
// TODO(anp): Keep PathUri through the shell sandbox policy boundary.
let sandbox_policy_cwd = sandbox_policy_cwd
.to_abs_path()
.map_err(|err| ToolError::Rejected(err.to_string()))?;
let command_executor = CoreShellCommandExecutor {
command,
cwd: sandbox_cwd,
@@ -274,9 +282,19 @@ pub(crate) async fn prepare_unified_exec_zsh_fork(
let exec_policy = Arc::new(RwLock::new(
ctx.session.services.exec_policy.current().as_ref().clone(),
));
// TODO(anp): Keep PathUri through the zsh-fork executor boundary.
let cwd = exec_request
.cwd
.to_abs_path()
.map_err(|err| ToolError::Rejected(err.to_string()))?;
// TODO(anp): Keep PathUri through the zsh-fork sandbox policy boundary.
let sandbox_policy_cwd = exec_request
.windows_sandbox_policy_cwd
.to_abs_path()
.map_err(|err| ToolError::Rejected(err.to_string()))?;
let command_executor = CoreShellCommandExecutor {
command: exec_request.command.clone(),
cwd: exec_request.cwd.clone(),
cwd,
permission_profile: exec_request.permission_profile.clone(),
file_system_sandbox_policy: exec_request.file_system_sandbox_policy.clone(),
network_sandbox_policy: exec_request.network_sandbox_policy,
@@ -285,7 +303,7 @@ pub(crate) async fn prepare_unified_exec_zsh_fork(
network: exec_request.network.clone(),
windows_sandbox_level: exec_request.windows_sandbox_level,
arg0: exec_request.arg0.clone(),
sandbox_policy_cwd: exec_request.windows_sandbox_policy_cwd.clone(),
sandbox_policy_cwd,
windows_sandbox_workspace_roots: exec_request.windows_sandbox_workspace_roots.clone(),
codex_linux_sandbox_exe: ctx.turn.config.codex_linux_sandbox_exe.clone(),
use_legacy_landlock: ctx.turn.config.features.use_legacy_landlock(),
@@ -857,14 +875,14 @@ impl CoreShellCommandExecutor {
let result = crate::sandboxing::execute_exec_request_with_after_spawn(
crate::sandboxing::ExecRequest {
command: self.command.clone(),
cwd: self.cwd.clone(),
cwd: self.cwd.clone().into(),
env: exec_env,
exec_server_env_config: None,
network: self.network.clone(),
expiration: ExecExpiration::Cancellation(cancel_rx),
capture_policy: ExecCapturePolicy::ShellTool,
sandbox: self.sandbox,
windows_sandbox_policy_cwd: self.sandbox_policy_cwd.clone(),
windows_sandbox_policy_cwd: self.sandbox_policy_cwd.clone().into(),
windows_sandbox_workspace_roots: self.windows_sandbox_workspace_roots.clone(),
windows_sandbox_level: self.windows_sandbox_level,
windows_sandbox_private_desktop: false,
@@ -1010,7 +1028,8 @@ impl CoreShellCommandExecutor {
Ok(PreparedExec {
command: exec_request.command,
cwd: exec_request.cwd.to_path_buf(),
// TODO(anp): Keep PathUri through the execve-wrapper boundary.
cwd: exec_request.cwd.to_abs_path()?.to_path_buf(),
env: exec_request.env,
arg0: exec_request.arg0,
})
@@ -21,7 +21,6 @@ use crate::tools::network_approval::NetworkApprovalSpec;
use crate::tools::runtimes::RuntimePathPrepends;
#[cfg(unix)]
use crate::tools::runtimes::apply_zsh_fork_path_prepend;
use crate::tools::runtimes::build_sandbox_command;
use crate::tools::runtimes::disable_powershell_profile_for_elevated_windows_sandbox;
use crate::tools::runtimes::exec_env_for_sandbox_permissions;
use crate::tools::runtimes::maybe_wrap_shell_lc_with_snapshot;
@@ -47,13 +46,15 @@ use codex_protocol::error::CodexErr;
use codex_protocol::error::SandboxErr;
use codex_protocol::models::AdditionalPermissionProfile;
use codex_protocol::protocol::ReviewDecision;
use codex_sandboxing::SandboxCommand;
use codex_sandboxing::SandboxablePreference;
use codex_shell_command::powershell::prefix_powershell_script_with_utf8;
use codex_tools::UnifiedExecShellMode;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use futures::future::BoxFuture;
use std::collections::HashMap;
use tokio_util::sync::CancellationToken;
use tracing::error;
/// Request payload used by the unified-exec runtime after approvals and
/// sandbox preferences have been resolved for the current turn.
@@ -63,8 +64,8 @@ pub struct UnifiedExecRequest {
pub shell_type: ShellType,
pub hook_command: String,
pub process_id: i32,
pub cwd: AbsolutePathBuf,
pub sandbox_cwd: AbsolutePathBuf,
pub cwd: PathUri,
pub sandbox_cwd: PathUri,
pub turn_environment: TurnEnvironment,
pub env: HashMap<String, String>,
pub exec_server_env_config: Option<ExecServerEnvConfig>,
@@ -85,7 +86,7 @@ pub struct UnifiedExecRequest {
pub struct UnifiedExecApprovalKey {
pub environment_id: String,
pub command: Vec<String>,
pub cwd: AbsolutePathBuf,
pub cwd: PathUri,
pub tty: bool,
pub sandbox_permissions: SandboxPermissions,
pub additional_permissions: Option<AdditionalPermissionProfile>,
@@ -111,6 +112,24 @@ fn unified_exec_options(
}
}
fn build_unified_exec_sandbox_command(
command: &[String],
cwd: &PathUri,
env: &HashMap<String, String>,
additional_permissions: Option<AdditionalPermissionProfile>,
) -> Result<SandboxCommand, ToolError> {
let (program, args) = command
.split_first()
.ok_or_else(|| ToolError::Rejected("command args are empty".to_string()))?;
Ok(SandboxCommand {
program: program.clone().into(),
args: args.to_vec(),
cwd: cwd.clone(),
env: env.clone(),
additional_permissions,
})
}
impl<'a> UnifiedExecRuntime<'a> {
/// Creates a runtime bound to the shared unified-exec process manager.
pub fn new(manager: &'a UnifiedExecProcessManager, shell_mode: UnifiedExecShellMode) -> Self {
@@ -155,12 +174,20 @@ impl Approvable<UnifiedExecRequest> for UnifiedExecRuntime<'_> {
let turn = ctx.turn;
let call_id = ctx.call_id.to_string();
let command = req.command.clone();
let cwd = req.cwd.clone();
let environment_id = Some(req.turn_environment.environment_id.clone());
let retry_reason = ctx.retry_reason.clone();
let reason = retry_reason.clone().or_else(|| req.justification.clone());
let guardian_review_id = ctx.guardian_review_id.clone();
Box::pin(async move {
let native_cwd = match req.cwd.to_abs_path() {
Ok(c) => c,
Err(e) => {
// TODO(anp) make sandboxing work for foreign OSes, in the meantime this should
// be impossible for single-OS app-servers
error!(cwd = %req.cwd, ?e, "got non-native path in start_approval_async");
return ReviewDecision::Abort;
}
};
if let Some(review_id) = guardian_review_id {
return review_approval_request(
session,
@@ -169,7 +196,7 @@ impl Approvable<UnifiedExecRequest> for UnifiedExecRuntime<'_> {
GuardianApprovalRequest::ExecCommand {
id: call_id,
command,
cwd: cwd.clone(),
cwd: native_cwd.clone(),
sandbox_permissions: req.sandbox_permissions,
additional_permissions: req.additional_permissions.clone(),
justification: req.justification.clone(),
@@ -188,7 +215,7 @@ impl Approvable<UnifiedExecRequest> for UnifiedExecRuntime<'_> {
/*approval_id*/ None,
environment_id,
command,
cwd.clone(),
native_cwd,
reason,
ctx.network_approval_context.clone(),
req.exec_approval_requirement
@@ -226,7 +253,7 @@ impl Approvable<UnifiedExecRequest> for UnifiedExecRuntime<'_> {
}
impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRuntime<'a> {
fn sandbox_cwd<'b>(&self, req: &'b UnifiedExecRequest) -> Option<&'b AbsolutePathBuf> {
fn sandbox_cwd<'b>(&self, req: &'b UnifiedExecRequest) -> Option<&'b PathUri> {
Some(&req.sandbox_cwd)
}
@@ -249,7 +276,7 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
call_id: ctx.call_id.clone(),
tool_name: flat_tool_name(&ctx.tool_name).into_owned(),
command: req.command.clone(),
cwd: req.cwd.clone(),
cwd: req.cwd.to_abs_path().ok()?,
sandbox_permissions: req.sandbox_permissions,
additional_permissions: req.additional_permissions.clone(),
justification: req.justification.clone(),
@@ -272,7 +299,17 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
.shell
.as_ref()
.unwrap_or(session_shell.as_ref());
let shell_snapshot_location = req.turn_environment.shell_snapshot(&req.cwd);
let environment_is_remote = req.turn_environment.environment.is_remote();
let shell_snapshot_location = if environment_is_remote {
None
} else {
// TODO(anp): Make shell snapshot lookup accept PathUri.
let native_cwd = req
.cwd
.to_abs_path()
.map_err(|err| ToolError::Rejected(err.to_string()))?;
req.turn_environment.shell_snapshot(&native_cwd)
};
let (file_system_sandbox_policy, _) = attempt.permissions.to_runtime_permissions();
let launch_sandbox_permissions = sandbox_permissions_preserving_denied_reads(
req.sandbox_permissions,
@@ -286,7 +323,6 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
if let Some(network) = managed_network {
network.apply_to_env(&mut env);
}
let environment_is_remote = req.turn_environment.environment.is_remote();
let explicit_env_overrides = req.explicit_env_overrides.clone();
#[cfg(unix)]
let runtime_path_prepends = {
@@ -333,14 +369,18 @@ 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(|error| match error {
ToolError::Rejected(_) => {
ToolError::Rejected("missing command line for PTY".to_string())
}
error @ ToolError::Codex(_) => error,
})?;
let command = build_unified_exec_sandbox_command(
&command,
&req.cwd,
&env,
req.additional_permissions.clone(),
)
.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)
@@ -389,14 +429,18 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
}
}
}
let command =
build_sandbox_command(&command, &req.cwd, &env, req.additional_permissions.clone())
.map_err(|error| match error {
ToolError::Rejected(_) => {
ToolError::Rejected("missing command line for PTY".to_string())
}
error @ ToolError::Codex(_) => error,
})?;
let command = build_unified_exec_sandbox_command(
&command,
&req.cwd,
&env,
req.additional_permissions.clone(),
)
.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)
@@ -431,16 +475,17 @@ mod tests {
use codex_exec_server::Environment;
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
use codex_tools::ZshForkConfig;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use std::sync::Arc;
use std::time::Duration;
use tempfile::tempdir;
fn test_turn_environment(cwd: AbsolutePathBuf) -> TurnEnvironment {
fn test_turn_environment(cwd: PathUri) -> TurnEnvironment {
TurnEnvironment::new(
LOCAL_ENVIRONMENT_ID.to_string(),
Arc::new(Environment::default_for_tests()),
PathUri::from_abs_path(&cwd),
cwd,
/*shell*/ None,
)
}
@@ -501,9 +546,9 @@ mod tests {
shell_type: ShellType::Sh,
hook_command: "pwd".to_string(),
process_id: 1000,
cwd,
sandbox_cwd: sandbox_cwd.clone(),
turn_environment: test_turn_environment(sandbox_cwd.clone()),
cwd: cwd.into(),
sandbox_cwd: sandbox_cwd.clone().into(),
turn_environment: test_turn_environment(sandbox_cwd.clone().into()),
env: HashMap::new(),
exec_server_env_config: None,
explicit_env_overrides: HashMap::new(),
@@ -520,7 +565,10 @@ mod tests {
},
};
assert_eq!(runtime.sandbox_cwd(&request), Some(&sandbox_cwd));
assert_eq!(
runtime.sandbox_cwd(&request),
Some(&PathUri::from_abs_path(&sandbox_cwd))
);
}
#[tokio::test]
@@ -600,9 +648,9 @@ mod tests {
shell_type: ShellType::Zsh,
hook_command: "echo hi".to_string(),
process_id: 1000,
cwd: cwd.clone(),
sandbox_cwd: cwd.clone(),
turn_environment: test_turn_environment(cwd),
cwd: cwd.clone().into(),
sandbox_cwd: cwd.clone().into(),
turn_environment: test_turn_environment(cwd.into()),
env: HashMap::new(),
exec_server_env_config: None,
explicit_env_overrides: HashMap::new(),