mirror of
https://github.com/openai/codex.git
synced 2026-11-19 22:30:42 +00:00
Select process sandboxes during launch preparation (#62183)
## Why Workspace-relative permission rules need to resolve against the execution host's workspace roots so a grant applies to the intended directory. Restricted launches also need to check that the host can provide the required sandbox. ## What changed - Select the platform sandbox while preparing a launch, using the permission profile, network requirements, and Windows sandbox settings. - Pass workspace roots into policy resolution for local commands and shell snapshots. Already-bound command profiles validate their concrete paths without resolving Windows launcher hints on hosts that do not use them. - Share local launch preparation between tool commands and shell snapshots, and require a platform sandbox for exec-server launches that request one. ## Testing Cover network-only restrictions and verify that a `:workspace_roots` write grant allows writes to the configured subdirectory under the command's working directory while denying writes to a sibling file and the corresponding subdirectory under the parent. Exercise the path grant through both app-server command execution and WebSocket exec-server execution. GitOrigin-RevId: 492fe7ab8deddf30cfd2e2bdabf28d02d67e00c5
This commit is contained in:
+22
-45
@@ -125,19 +125,6 @@ pub enum ExecCapturePolicy {
|
||||
SensitiveFullBuffer,
|
||||
}
|
||||
|
||||
fn select_process_exec_tool_sandbox_type(
|
||||
permission_profile: &PermissionProfile,
|
||||
windows_sandbox_type: SandboxType,
|
||||
enforce_managed_network: bool,
|
||||
) -> SandboxType {
|
||||
SandboxManager::new().select_initial(
|
||||
permission_profile,
|
||||
SandboxablePreference::Auto,
|
||||
windows_sandbox_type,
|
||||
enforce_managed_network,
|
||||
)
|
||||
}
|
||||
|
||||
fn network_proxy_environment_error(
|
||||
network_environment_id: Option<&str>,
|
||||
err: impl std::fmt::Display,
|
||||
@@ -367,14 +354,8 @@ pub async fn build_exec_request(
|
||||
sandbox_permissions: _,
|
||||
} = params;
|
||||
|
||||
let manager = SandboxManager::new();
|
||||
let enforce_managed_network = network.is_some();
|
||||
let sandbox_type = select_process_exec_tool_sandbox_type(
|
||||
permission_profile,
|
||||
windows_sandbox_type,
|
||||
enforce_managed_network,
|
||||
);
|
||||
tracing::debug!("Sandbox type: {sandbox_type:?}");
|
||||
|
||||
let (env, managed_network) = if let Some(network) = network.as_ref() {
|
||||
let prepared = network
|
||||
.prepare_for_optional_environment(env, network_environment_id.as_deref())
|
||||
@@ -385,6 +366,12 @@ pub async fn build_exec_request(
|
||||
} else {
|
||||
(env, None)
|
||||
};
|
||||
let sandbox_policy_cwd_uri = PathUri::from_abs_path(sandbox_cwd);
|
||||
let workspace_roots = if windows_sandbox_workspace_roots.is_empty() {
|
||||
std::slice::from_ref(&sandbox_policy_cwd_uri)
|
||||
} else {
|
||||
windows_sandbox_workspace_roots
|
||||
};
|
||||
let (program, args) = command.split_first().ok_or_else(|| {
|
||||
CodexErr::Io(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
@@ -392,9 +379,6 @@ pub async fn build_exec_request(
|
||||
))
|
||||
})?;
|
||||
let cwd = PathUri::from_abs_path(&cwd);
|
||||
let sandbox_policy_cwd_uri = PathUri::from_abs_path(sandbox_cwd);
|
||||
|
||||
let manager = SandboxManager::new();
|
||||
let command = SandboxCommand {
|
||||
program: program.clone().into(),
|
||||
args: args.to_vec(),
|
||||
@@ -407,13 +391,23 @@ pub async fn build_exec_request(
|
||||
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() {
|
||||
workspace_roots
|
||||
} else {
|
||||
&[]
|
||||
};
|
||||
let request = manager
|
||||
.transform(SandboxTransformRequest {
|
||||
command,
|
||||
permissions: permission_profile,
|
||||
workspace_roots: None,
|
||||
workspace_roots: Some(policy_roots),
|
||||
runtime_readable_paths: None,
|
||||
selection: SandboxSelection::Explicit(sandbox_type),
|
||||
selection: SandboxSelection::Platform {
|
||||
preference: SandboxablePreference::Auto,
|
||||
windows_sandbox: windows_sandbox_type,
|
||||
},
|
||||
network: SandboxNetwork::new(
|
||||
enforce_managed_network,
|
||||
network.as_ref(),
|
||||
@@ -429,26 +423,9 @@ pub async fn build_exec_request(
|
||||
windows_sandbox_level,
|
||||
})?
|
||||
.into_command_request()?;
|
||||
// These hints belong to the native Windows backend. Other backends use
|
||||
// the materialized profile and must not project executor paths onto this host.
|
||||
let windows_sandbox_workspace_roots = if sandbox_type == SandboxType::WindowsRestrictedToken {
|
||||
if windows_sandbox_workspace_roots.is_empty() {
|
||||
vec![sandbox_cwd.clone()]
|
||||
} else {
|
||||
windows_sandbox_workspace_roots
|
||||
.iter()
|
||||
.map(PathUri::to_abs_path)
|
||||
.collect::<io::Result<Vec<_>>>()
|
||||
.map_err(|err| {
|
||||
CodexErr::InvalidRequest(format!(
|
||||
"invalid Windows sandbox workspace roots: {err}"
|
||||
))
|
||||
})?
|
||||
}
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
ExecRequest::from_sandbox_exec_request(request, options, windows_sandbox_workspace_roots).await
|
||||
let request = ExecRequest::from_sandbox_exec_request(request, options, workspace_roots).await?;
|
||||
tracing::debug!("Sandbox type: {:?}", request.sandbox);
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
pub(crate) async fn execute_exec_request(
|
||||
|
||||
@@ -1203,22 +1203,49 @@ fn windows_elevated_rejects_reopened_writable_descendants() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_exec_tool_call_uses_platform_sandbox_for_network_only_restrictions() {
|
||||
let expected = codex_sandboxing::get_platform_sandbox(/*windows_sandbox_enabled*/ false)
|
||||
.unwrap_or(SandboxType::None);
|
||||
fn local_exec_params(
|
||||
cwd: &AbsolutePathBuf,
|
||||
windows_sandbox_level: WindowsSandboxLevel,
|
||||
) -> ExecParams {
|
||||
ExecParams {
|
||||
command: vec!["echo".to_string(), "ok".to_string()],
|
||||
cwd: cwd.clone(),
|
||||
expiration: ExecExpiration::DefaultTimeout,
|
||||
capture_policy: ExecCapturePolicy::ShellTool,
|
||||
env: HashMap::new(),
|
||||
network: None,
|
||||
network_environment_id: None,
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
windows_sandbox_level,
|
||||
justification: None,
|
||||
arg0: None,
|
||||
}
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
select_process_exec_tool_sandbox_type(
|
||||
&PermissionProfile::from_runtime_permissions(
|
||||
&FileSystemSandboxPolicy::unrestricted(),
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
),
|
||||
SandboxType::None,
|
||||
/*enforce_managed_network*/ false,
|
||||
),
|
||||
expected
|
||||
#[tokio::test]
|
||||
async fn process_exec_tool_call_uses_platform_sandbox_for_network_only_restrictions() -> Result<()>
|
||||
{
|
||||
let dir = tempfile::tempdir()?;
|
||||
let cwd = dir.path().abs();
|
||||
let profile = PermissionProfile::from_runtime_permissions(
|
||||
&FileSystemSandboxPolicy::unrestricted(),
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
);
|
||||
let params = local_exec_params(&cwd, WindowsSandboxLevel::Disabled);
|
||||
let expected = codex_sandboxing::get_platform_sandbox(/*windows_sandbox_enabled*/ false);
|
||||
let request = build_exec_request(
|
||||
params,
|
||||
&profile,
|
||||
&cwd,
|
||||
&[],
|
||||
&Some(dir.path().join("codex-linux-sandbox")),
|
||||
/*codex_self_exe*/ &None,
|
||||
SandboxType::None,
|
||||
/*use_legacy_landlock*/ false,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(request.sandbox, expected.unwrap_or(SandboxType::None));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1267,6 +1294,16 @@ async fn build_exec_request_projects_workspace_roots_only_for_windows_sandbox()
|
||||
Vec::new()
|
||||
},
|
||||
);
|
||||
assert_eq!(
|
||||
build_request(&PermissionProfile::read_only(), &[])
|
||||
.await?
|
||||
.windows_sandbox_workspace_roots,
|
||||
if cfg!(windows) {
|
||||
vec![cwd.clone()]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
);
|
||||
|
||||
let foreign_root = PathUri::parse(if cfg!(windows) {
|
||||
"file:///workspace"
|
||||
@@ -1329,10 +1366,11 @@ fn command_runs_after_integrity_check_failure(time_out: bool) -> anyhow::Result<
|
||||
env: std::env::vars().collect(),
|
||||
network: None,
|
||||
network_environment_id: None,
|
||||
sandbox: select_process_exec_tool_sandbox_type(
|
||||
sandbox: SandboxManager::new().select_initial(
|
||||
&permission_profile,
|
||||
SandboxablePreference::Auto,
|
||||
SandboxType::WindowsMxc,
|
||||
/*enforce_managed_network*/ false,
|
||||
/*has_managed_network_requirements*/ false,
|
||||
),
|
||||
sandbox_override: SandboxOverride::NoOverride,
|
||||
windows_sandbox_level: WindowsSandboxLevel::Disabled,
|
||||
@@ -1350,7 +1388,7 @@ fn command_runs_after_integrity_check_failure(time_out: bool) -> anyhow::Result<
|
||||
expiration: ExecExpiration::DefaultTimeout,
|
||||
capture_policy: ExecCapturePolicy::ShellTool,
|
||||
},
|
||||
Vec::new(),
|
||||
&[],
|
||||
));
|
||||
let request = if time_out {
|
||||
tokio::time::pause();
|
||||
|
||||
@@ -23,7 +23,10 @@ use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::exec_output::ExecToolCallOutput;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
pub use codex_protocol::models::SandboxPermissions;
|
||||
use codex_protocol::sandbox::SandboxOverride;
|
||||
use codex_sandboxing::SandboxExecRequest;
|
||||
use codex_sandboxing::SandboxManager;
|
||||
use codex_sandboxing::SandboxTransformRequest;
|
||||
use codex_sandboxing::SandboxType;
|
||||
use codex_sandboxing::WindowsSandboxFilesystemOverrides;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
@@ -126,11 +129,38 @@ impl ExecRequest {
|
||||
}
|
||||
}
|
||||
|
||||
/// Prepare an authorized local attempt for a launcher that owns its pipes or terminal.
|
||||
pub(crate) async fn prepare_local_sandbox(
|
||||
manager: &SandboxManager,
|
||||
request: SandboxTransformRequest<'_>,
|
||||
options: ExecOptions,
|
||||
sandbox_override: SandboxOverride,
|
||||
) -> Result<Self, CodexErr> {
|
||||
let workspace_roots = request.workspace_roots.unwrap_or_default();
|
||||
let mut request = manager.transform(request)?.into_command_request()?;
|
||||
request.sandbox_override = sandbox_override;
|
||||
Self::from_sandbox_exec_request(request, options, workspace_roots).await
|
||||
}
|
||||
|
||||
pub(crate) async fn from_sandbox_exec_request(
|
||||
request: SandboxExecRequest,
|
||||
options: ExecOptions,
|
||||
windows_sandbox_workspace_roots: Vec<AbsolutePathBuf>,
|
||||
workspace_roots: &[PathUri],
|
||||
) -> Result<Self, CodexErr> {
|
||||
let windows_sandbox_workspace_roots =
|
||||
if request.sandbox == SandboxType::WindowsRestrictedToken {
|
||||
workspace_roots
|
||||
.iter()
|
||||
.map(PathUri::to_abs_path)
|
||||
.collect::<std::io::Result<Vec<_>>>()
|
||||
.map_err(|err| {
|
||||
CodexErr::InvalidRequest(format!(
|
||||
"invalid Windows sandbox workspace roots: {err}"
|
||||
))
|
||||
})?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
codex_exec_server::run_integrity_checks((&request).into()).await;
|
||||
let SandboxExecRequest {
|
||||
command,
|
||||
|
||||
@@ -15,12 +15,14 @@ use codex_protocol::error::SandboxErr;
|
||||
use codex_protocol::models::AdditionalPermissionProfile;
|
||||
use codex_protocol::models::FileSystemPermissions;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::sandbox::SandboxOverride;
|
||||
use codex_sandboxing::SandboxCommand;
|
||||
use codex_sandboxing::SandboxManager;
|
||||
use codex_sandboxing::SandboxNetwork;
|
||||
use codex_sandboxing::SandboxSelection;
|
||||
use codex_sandboxing::SandboxTransformRequest;
|
||||
use codex_sandboxing::SandboxType;
|
||||
use codex_sandboxing::SandboxablePreference;
|
||||
use codex_sandboxing::policy_transforms::merge_permission_profiles;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
@@ -35,8 +37,11 @@ mod tests;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ShellSnapshotSandbox {
|
||||
sandbox: SandboxType,
|
||||
selection: SandboxSelection,
|
||||
sandbox_requested: bool,
|
||||
manager: SandboxManager,
|
||||
// Launch observation only. Snapshot reuse depends on the effective policy below.
|
||||
sandbox_override: SandboxOverride,
|
||||
permissions: PermissionProfile,
|
||||
enforce_managed_network: bool,
|
||||
sandbox_policy_cwd: PathUri,
|
||||
@@ -79,8 +84,18 @@ impl ShellSnapshotSandbox {
|
||||
additional_permissions: Option<&AdditionalPermissionProfile>,
|
||||
) -> Self {
|
||||
Self {
|
||||
sandbox: attempt.sandbox,
|
||||
selection: match attempt.local_selection {
|
||||
SandboxSelection::Platform {
|
||||
windows_sandbox, ..
|
||||
} if attempt.sandbox_requested => SandboxSelection::Platform {
|
||||
preference: SandboxablePreference::Require,
|
||||
windows_sandbox,
|
||||
},
|
||||
selection => selection,
|
||||
},
|
||||
sandbox_requested: attempt.sandbox_requested,
|
||||
manager: attempt.manager.clone(),
|
||||
sandbox_override: attempt.sandbox_override,
|
||||
permissions: attempt.permissions.clone(),
|
||||
enforce_managed_network: attempt.enforce_managed_network,
|
||||
sandbox_policy_cwd: attempt.sandbox_cwd.clone(),
|
||||
@@ -97,7 +112,7 @@ impl ShellSnapshotSandbox {
|
||||
|
||||
pub(crate) fn cache_key(&self) -> Result<String> {
|
||||
serde_json::to_string(&(
|
||||
self.sandbox.as_metric_tag(),
|
||||
format!("{:?}", self.selection),
|
||||
self.sandbox_requested,
|
||||
&self.permissions,
|
||||
self.enforce_managed_network,
|
||||
@@ -124,7 +139,12 @@ impl ShellSnapshotSandbox {
|
||||
shell_name: &str,
|
||||
snapshot_read_path: Option<&AbsolutePathBuf>,
|
||||
) -> Result<String> {
|
||||
if self.sandbox_requested && self.sandbox == SandboxType::None {
|
||||
if self.sandbox_requested
|
||||
&& matches!(
|
||||
self.selection,
|
||||
SandboxSelection::Explicit(SandboxType::None)
|
||||
)
|
||||
{
|
||||
bail!("shell snapshot sandbox cannot be enforced on this host");
|
||||
}
|
||||
|
||||
@@ -140,6 +160,15 @@ impl ShellSnapshotSandbox {
|
||||
let (program, args) = args
|
||||
.split_first()
|
||||
.ok_or_else(|| anyhow!("shell snapshot command is empty"))?;
|
||||
let cancellation = self
|
||||
.network_denial_cancellation_token
|
||||
.as_ref()
|
||||
.map_or_else(CancellationToken::new, CancellationToken::child_token);
|
||||
let _cancel_on_drop = cancellation.clone().drop_guard();
|
||||
let expiration = ExecExpiration::TimeoutOrCancellation {
|
||||
timeout: snapshot_timeout,
|
||||
cancellation,
|
||||
};
|
||||
let snapshot_permissions = snapshot_read_path.and_then(|path| {
|
||||
snapshot_read_permissions(
|
||||
path,
|
||||
@@ -154,9 +183,9 @@ impl ShellSnapshotSandbox {
|
||||
self.additional_permissions.as_ref(),
|
||||
snapshot_permissions.as_ref(),
|
||||
);
|
||||
let manager = SandboxManager::new();
|
||||
let request = manager
|
||||
.transform(SandboxTransformRequest {
|
||||
let request = ExecRequest::prepare_local_sandbox(
|
||||
&self.manager,
|
||||
SandboxTransformRequest {
|
||||
command: SandboxCommand {
|
||||
program: program.clone().into(),
|
||||
args: args.to_vec(),
|
||||
@@ -166,9 +195,9 @@ impl ShellSnapshotSandbox {
|
||||
additional_permissions,
|
||||
},
|
||||
permissions: &self.permissions,
|
||||
workspace_roots: None,
|
||||
workspace_roots: Some(&self.workspace_roots),
|
||||
runtime_readable_paths: None,
|
||||
selection: SandboxSelection::Explicit(self.sandbox),
|
||||
selection: self.selection,
|
||||
network: SandboxNetwork::new(
|
||||
self.enforce_managed_network,
|
||||
self.network.as_ref(),
|
||||
@@ -178,34 +207,15 @@ impl ShellSnapshotSandbox {
|
||||
sandbox_exe: self.sandbox_exe.as_deref(),
|
||||
use_legacy_landlock: self.use_legacy_landlock,
|
||||
windows_sandbox_level: self.windows_sandbox_level,
|
||||
})
|
||||
.context("failed to prepare shell snapshot sandbox")?
|
||||
.into_command_request()?;
|
||||
let workspace_roots = self
|
||||
.workspace_roots
|
||||
.iter()
|
||||
.map(PathUri::to_abs_path)
|
||||
.collect::<std::io::Result<Vec<_>>>()
|
||||
.context("failed to resolve shell snapshot workspace roots")?;
|
||||
let cancellation = self
|
||||
.network_denial_cancellation_token
|
||||
.as_ref()
|
||||
.map_or_else(CancellationToken::new, CancellationToken::child_token);
|
||||
let _cancel_on_drop = cancellation.clone().drop_guard();
|
||||
let expiration = ExecExpiration::TimeoutOrCancellation {
|
||||
timeout: snapshot_timeout,
|
||||
cancellation,
|
||||
};
|
||||
let request = ExecRequest::from_sandbox_exec_request(
|
||||
request,
|
||||
},
|
||||
ExecOptions {
|
||||
expiration,
|
||||
capture_policy: ExecCapturePolicy::SensitiveFullBuffer,
|
||||
},
|
||||
workspace_roots,
|
||||
self.sandbox_override,
|
||||
)
|
||||
.await
|
||||
.context("failed to prepare shell snapshot execution")?;
|
||||
.context("failed to prepare shell snapshot sandbox")?;
|
||||
// Caller cancellation must leave execution alive long enough to clean up its process group.
|
||||
let output = tokio::spawn(execute_env(request, /*stdout_stream*/ None))
|
||||
.await
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
use super::*;
|
||||
use codex_protocol::permissions::FileSystemAccessMode;
|
||||
use codex_protocol::permissions::FileSystemPath;
|
||||
use codex_protocol::permissions::FileSystemSandboxEntry;
|
||||
use codex_protocol::permissions::FileSystemSandboxPolicy;
|
||||
use codex_protocol::permissions::FileSystemSpecialPath;
|
||||
use codex_protocol::permissions::NetworkSandboxPolicy;
|
||||
use codex_protocol::sandbox::SandboxOverride;
|
||||
use codex_sandboxing::SandboxType;
|
||||
use core_test_support::PathExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::tempdir;
|
||||
@@ -8,6 +15,7 @@ use test_case::test_case;
|
||||
#[derive(Clone, Copy)]
|
||||
enum SnapshotFailure {
|
||||
Exit,
|
||||
WorkspaceRootDenial,
|
||||
Timeout,
|
||||
NetworkDenial,
|
||||
CallerDrop,
|
||||
@@ -15,6 +23,7 @@ enum SnapshotFailure {
|
||||
}
|
||||
|
||||
#[test_case(SnapshotFailure::Exit; "startup_exit")]
|
||||
#[test_case(SnapshotFailure::WorkspaceRootDenial; "denied_read_in_second_workspace_root")]
|
||||
#[test_case(SnapshotFailure::Timeout; "timeout")]
|
||||
#[test_case(SnapshotFailure::NetworkDenial; "network_denial")]
|
||||
#[test_case(SnapshotFailure::CallerDrop; "caller_drop")]
|
||||
@@ -27,24 +36,60 @@ async fn snapshot_failure_omits_credentials_and_stops_descendants(
|
||||
SnapshotFailure::NetworkDenial | SnapshotFailure::CallerDropWithNetworkToken => {
|
||||
Some(CancellationToken::new())
|
||||
}
|
||||
SnapshotFailure::Exit | SnapshotFailure::Timeout | SnapshotFailure::CallerDrop => None,
|
||||
SnapshotFailure::Exit
|
||||
| SnapshotFailure::WorkspaceRootDenial
|
||||
| SnapshotFailure::Timeout
|
||||
| SnapshotFailure::CallerDrop => None,
|
||||
};
|
||||
let dir = tempdir()?;
|
||||
let cwd = dir.path().abs();
|
||||
let cwd = dir.path().join("first").abs();
|
||||
std::fs::create_dir(&cwd)?;
|
||||
let cwd_uri = PathUri::from_abs_path(&cwd);
|
||||
let permissions = PermissionProfile::Disabled;
|
||||
let mut workspace_roots = vec![cwd_uri.clone()];
|
||||
let workspace_denial = matches!(failure, SnapshotFailure::WorkspaceRootDenial);
|
||||
let (permissions, local_selection, sandbox_exe) = if workspace_denial {
|
||||
core_test_support::skip_if_sandbox!(Ok(()));
|
||||
let second = dir.path().join("second").abs();
|
||||
std::fs::create_dir(&second)?;
|
||||
for root in [&cwd, &second] {
|
||||
std::fs::write(root.join("allowed"), "visible")?;
|
||||
std::fs::write(root.join("private"), "private contents")?;
|
||||
}
|
||||
workspace_roots.push(PathUri::from_abs_path(&second));
|
||||
let mut policy = FileSystemSandboxPolicy::read_only();
|
||||
policy.entries.push(FileSystemSandboxEntry::new(
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::project_roots(Some("private".into())),
|
||||
},
|
||||
FileSystemAccessMode::Deny,
|
||||
));
|
||||
(
|
||||
PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted),
|
||||
SandboxSelection::Platform {
|
||||
preference: SandboxablePreference::Auto,
|
||||
windows_sandbox: SandboxType::None,
|
||||
},
|
||||
core_test_support::codex_linux_sandbox_exe_or_skip!(Ok(())),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
PermissionProfile::Disabled,
|
||||
SandboxSelection::Explicit(SandboxType::None),
|
||||
None,
|
||||
)
|
||||
};
|
||||
let manager = SandboxManager::new();
|
||||
let attempt = SandboxAttempt {
|
||||
sandbox_override: SandboxOverride::NoOverride,
|
||||
sandbox: SandboxType::None,
|
||||
sandbox_requested: false,
|
||||
local_selection,
|
||||
sandbox_requested: workspace_denial,
|
||||
permissions: &permissions,
|
||||
exec_server_permissions: &permissions,
|
||||
enforce_managed_network: false,
|
||||
manager: &manager,
|
||||
sandbox_cwd: &cwd_uri,
|
||||
workspace_roots: std::slice::from_ref(&cwd_uri),
|
||||
sandbox_exe: None,
|
||||
workspace_roots: &workspace_roots,
|
||||
sandbox_exe: sandbox_exe.as_ref(),
|
||||
use_legacy_landlock: false,
|
||||
windows_sandbox_type: SandboxType::None,
|
||||
windows_sandbox_level: WindowsSandboxLevel::Disabled,
|
||||
@@ -56,6 +101,7 @@ async fn snapshot_failure_omits_credentials_and_stops_descendants(
|
||||
);
|
||||
let snapshot_timeout = match failure {
|
||||
SnapshotFailure::Exit
|
||||
| SnapshotFailure::WorkspaceRootDenial
|
||||
| SnapshotFailure::NetworkDenial
|
||||
| SnapshotFailure::CallerDrop
|
||||
| SnapshotFailure::CallerDropWithNetworkToken => Duration::from_secs(30),
|
||||
@@ -63,6 +109,14 @@ async fn snapshot_failure_omits_credentials_and_stops_descendants(
|
||||
};
|
||||
let script = match failure {
|
||||
SnapshotFailure::Exit => "exit 23",
|
||||
SnapshotFailure::WorkspaceRootDenial => {
|
||||
r#"for root in . ../second; do
|
||||
[ "$(/bin/cat "$root/allowed")" = visible ] || exit 41
|
||||
done
|
||||
if /bin/cat private >/dev/null 2>&1; then exit 42; fi
|
||||
if /bin/cat ../second/private >/dev/null 2>&1; then exit 43; fi
|
||||
exit 23"#
|
||||
}
|
||||
SnapshotFailure::Timeout
|
||||
| SnapshotFailure::NetworkDenial
|
||||
| SnapshotFailure::CallerDrop
|
||||
@@ -83,9 +137,12 @@ async fn snapshot_failure_omits_credentials_and_stops_descendants(
|
||||
/*snapshot_read_path*/ None,
|
||||
);
|
||||
let cancel_after_startup = async {
|
||||
if !matches!(failure, SnapshotFailure::Exit) {
|
||||
if !matches!(
|
||||
failure,
|
||||
SnapshotFailure::Exit | SnapshotFailure::WorkspaceRootDenial
|
||||
) {
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while !dir.path().join("started").exists() {
|
||||
while !cwd.join("started").exists() {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
@@ -128,7 +185,9 @@ async fn snapshot_failure_omits_credentials_and_stops_descendants(
|
||||
if let Some(result) = result {
|
||||
let error = result.err().context("failed snapshot must not be used")?;
|
||||
let expected = match failure {
|
||||
SnapshotFailure::Exit => "Snapshot command exited with status 23",
|
||||
SnapshotFailure::Exit | SnapshotFailure::WorkspaceRootDenial => {
|
||||
"Snapshot command exited with status 23"
|
||||
}
|
||||
SnapshotFailure::Timeout => "Snapshot command timed out",
|
||||
SnapshotFailure::NetworkDenial => "Snapshot command exited with status 1",
|
||||
SnapshotFailure::CallerDrop | SnapshotFailure::CallerDropWithNetworkToken => {
|
||||
@@ -139,7 +198,7 @@ async fn snapshot_failure_omits_credentials_and_stops_descendants(
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(1_100)).await;
|
||||
assert!(
|
||||
!dir.path().join("late_write").exists(),
|
||||
!cwd.join("late_write").exists(),
|
||||
"startup descendant survived snapshot expiration"
|
||||
);
|
||||
Ok(())
|
||||
|
||||
@@ -275,7 +275,9 @@ async fn inactive_profiles_keep_snapshots_but_active_brokers_require_sandbox() -
|
||||
use codex_protocol::protocol::EnvironmentConfigState;
|
||||
use codex_protocol::protocol::TurnEnvironmentSelection;
|
||||
use codex_sandboxing::SandboxManager;
|
||||
use codex_sandboxing::SandboxSelection;
|
||||
use codex_sandboxing::SandboxType;
|
||||
use codex_sandboxing::SandboxablePreference;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
let dir = tempdir()?;
|
||||
@@ -490,7 +492,10 @@ async fn inactive_profiles_keep_snapshots_but_active_brokers_require_sandbox() -
|
||||
let cancellation = CancellationToken::new();
|
||||
let mut attempt = SandboxAttempt {
|
||||
sandbox_override: SandboxOverride::NoOverride,
|
||||
sandbox: SandboxType::None,
|
||||
local_selection: SandboxSelection::Platform {
|
||||
preference: SandboxablePreference::Auto,
|
||||
windows_sandbox: SandboxType::None,
|
||||
},
|
||||
sandbox_requested: false,
|
||||
permissions: &permissions,
|
||||
exec_server_permissions: &permissions,
|
||||
|
||||
@@ -34,6 +34,7 @@ use codex_protocol::permissions::file_system_root;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::ReviewDecision;
|
||||
use codex_sandboxing::SandboxManager;
|
||||
use codex_sandboxing::SandboxSelection;
|
||||
use codex_sandboxing::SandboxType;
|
||||
use codex_sandboxing::policy_transforms::effective_network_sandbox_policy;
|
||||
use std::sync::Arc;
|
||||
@@ -83,7 +84,7 @@ impl ToolOrchestrator {
|
||||
};
|
||||
let attempt_with_network_approval = SandboxAttempt {
|
||||
sandbox_override: attempt.sandbox_override,
|
||||
sandbox: attempt.sandbox,
|
||||
local_selection: attempt.local_selection,
|
||||
sandbox_requested: attempt.sandbox_requested,
|
||||
permissions: attempt.permissions,
|
||||
exec_server_permissions: attempt.exec_server_permissions,
|
||||
@@ -331,32 +332,36 @@ impl ToolOrchestrator {
|
||||
turn_ctx.network.is_some()
|
||||
};
|
||||
let sandbox_preference = tool.sandbox_preference();
|
||||
let sandbox_requested = match sandbox_override {
|
||||
SandboxOverride::BypassSandboxFirstAttempt => false,
|
||||
SandboxOverride::NoOverride | SandboxOverride::EscalatedSandboxWithRestrictions => {
|
||||
sandbox_manager.should_sandbox(
|
||||
initial_permissions,
|
||||
sandbox_preference,
|
||||
managed_network_active,
|
||||
)
|
||||
}
|
||||
};
|
||||
let policy_requires_sandbox = sandbox_manager.should_sandbox(
|
||||
initial_permissions,
|
||||
sandbox_preference,
|
||||
managed_network_active,
|
||||
);
|
||||
let windows_sandbox_type = codex_protocol::sandbox::effective_windows_sandbox_type(
|
||||
sandbox_config.windows_sandbox_type,
|
||||
sandbox_config.windows_sandbox_level,
|
||||
);
|
||||
let initial_sandbox = if sandbox_requested && !executor_managed_process_sandbox {
|
||||
sandbox_manager.select_initial(
|
||||
let sandbox_requested = sandbox_override != SandboxOverride::BypassSandboxFirstAttempt
|
||||
&& policy_requires_sandbox;
|
||||
let platform_selection = SandboxSelection::Platform {
|
||||
preference: sandbox_preference,
|
||||
windows_sandbox: windows_sandbox_type,
|
||||
};
|
||||
let local_selection = if sandbox_requested {
|
||||
platform_selection
|
||||
} else {
|
||||
SandboxSelection::Explicit(SandboxType::None)
|
||||
};
|
||||
if !executor_managed_process_sandbox
|
||||
&& sandbox_override == SandboxOverride::EscalatedSandboxWithRestrictions
|
||||
{
|
||||
let available = sandbox_manager.select_initial(
|
||||
initial_permissions,
|
||||
sandbox_preference,
|
||||
windows_sandbox_type,
|
||||
managed_network_active,
|
||||
)
|
||||
} else {
|
||||
SandboxType::None
|
||||
};
|
||||
if !executor_managed_process_sandbox {
|
||||
ensure_native_sandbox(sandbox_override, initial_sandbox)?;
|
||||
);
|
||||
ensure_native_sandbox(sandbox_override, available)?;
|
||||
}
|
||||
|
||||
let sandbox_policy_cwd = tool
|
||||
@@ -370,7 +375,7 @@ impl ToolOrchestrator {
|
||||
};
|
||||
let initial_attempt = SandboxAttempt {
|
||||
sandbox_override,
|
||||
sandbox: initial_sandbox,
|
||||
local_selection,
|
||||
sandbox_requested,
|
||||
permissions: initial_permissions,
|
||||
exec_server_permissions: escalated_profile.as_ref().unwrap_or(permission_profile),
|
||||
@@ -553,22 +558,11 @@ impl ToolOrchestrator {
|
||||
.result?;
|
||||
}
|
||||
|
||||
let retry_sandbox_requested = !unsandboxed_allowed
|
||||
&& sandbox_manager.should_sandbox(
|
||||
initial_permissions,
|
||||
sandbox_preference,
|
||||
managed_network_active,
|
||||
);
|
||||
let retry_sandbox = if retry_sandbox_requested && !executor_managed_process_sandbox
|
||||
{
|
||||
sandbox_manager.select_initial(
|
||||
initial_permissions,
|
||||
sandbox_preference,
|
||||
windows_sandbox_type,
|
||||
managed_network_active,
|
||||
)
|
||||
let retry_sandbox_requested = !unsandboxed_allowed && policy_requires_sandbox;
|
||||
let local_selection = if retry_sandbox_requested {
|
||||
platform_selection
|
||||
} else {
|
||||
SandboxType::None
|
||||
SandboxSelection::Explicit(SandboxType::None)
|
||||
};
|
||||
let retry_sandbox_exe = if unsandboxed_allowed {
|
||||
None
|
||||
@@ -577,7 +571,7 @@ impl ToolOrchestrator {
|
||||
};
|
||||
let retry_attempt = SandboxAttempt {
|
||||
sandbox_override,
|
||||
sandbox: retry_sandbox,
|
||||
local_selection,
|
||||
sandbox_requested: retry_sandbox_requested,
|
||||
permissions: initial_permissions,
|
||||
exec_server_permissions: escalated_profile
|
||||
|
||||
@@ -13,6 +13,7 @@ use crate::tools::sandboxing::Sandboxable;
|
||||
use crate::tools::sandboxing::ToolCtx;
|
||||
use crate::tools::sandboxing::ToolError;
|
||||
use crate::tools::sandboxing::ToolRuntime;
|
||||
use crate::tools::sandboxing::ensure_native_sandbox;
|
||||
use crate::tools::sandboxing::executor_windows_sandbox_selection;
|
||||
use codex_apply_patch::AppliedPatchDelta;
|
||||
use codex_apply_patch::AppliedPatchFileChange;
|
||||
@@ -176,6 +177,20 @@ impl ToolRuntime<ApplyPatchRequest, ApplyPatchRuntimeOutput> for ApplyPatchRunti
|
||||
ctx: &ToolCtx,
|
||||
) -> Result<ApplyPatchRuntimeOutput, ToolError> {
|
||||
let started_at = Instant::now();
|
||||
let remote = self.uses_executor_managed_process_sandbox(req);
|
||||
let local_backend = if attempt.sandbox_requested && !remote {
|
||||
attempt.manager.select_initial(
|
||||
attempt.permissions,
|
||||
self.sandbox_preference(),
|
||||
attempt.windows_sandbox_type,
|
||||
attempt.enforce_managed_network,
|
||||
)
|
||||
} else {
|
||||
SandboxType::None
|
||||
};
|
||||
if !remote {
|
||||
ensure_native_sandbox(attempt.sandbox_override, local_backend)?;
|
||||
}
|
||||
let fs = req.turn_environment.environment().get_filesystem();
|
||||
let sandbox = Self::file_system_sandbox_context_for_attempt(req, attempt);
|
||||
let mut stdout = Vec::new();
|
||||
@@ -239,16 +254,16 @@ impl ToolRuntime<ApplyPatchRequest, ApplyPatchRuntimeOutput> for ApplyPatchRunti
|
||||
timed_out: false,
|
||||
};
|
||||
let sandbox_denied = failed
|
||||
&& if attempt.sandbox == SandboxType::None {
|
||||
&& if local_backend == SandboxType::None {
|
||||
attempt.sandbox_requested && is_likely_executor_managed_sandbox_denied(&output)
|
||||
} else {
|
||||
is_likely_sandbox_denied(attempt.sandbox, &output)
|
||||
is_likely_sandbox_denied(local_backend, &output)
|
||||
};
|
||||
if sandbox_denied {
|
||||
// TODO(iceweasel): Report executor filesystem sandbox backends like process/start so
|
||||
// executor-managed apply_patch denials can emit backend-specific violation telemetry.
|
||||
if attempt.sandbox != SandboxType::None {
|
||||
record_filesystem_sandbox_violation(attempt.sandbox, &output);
|
||||
if local_backend != SandboxType::None {
|
||||
record_filesystem_sandbox_violation(local_backend, &output);
|
||||
}
|
||||
return Err(ToolError::Codex(CodexErr::Sandbox(SandboxErr::Denied {
|
||||
output: Box::new(output),
|
||||
|
||||
@@ -13,6 +13,7 @@ use codex_protocol::protocol::GranularApprovalConfig;
|
||||
use codex_protocol::protocol::TurnEnvironmentSelection;
|
||||
use codex_protocol::sandbox::SandboxOverride;
|
||||
use codex_sandboxing::SandboxManager;
|
||||
use codex_sandboxing::SandboxSelection;
|
||||
use codex_sandboxing::SandboxType;
|
||||
use codex_sandboxing::policy_transforms::effective_file_system_sandbox_policy;
|
||||
use codex_sandboxing::policy_transforms::effective_network_sandbox_policy;
|
||||
@@ -241,7 +242,7 @@ async fn file_system_sandbox_context_preserves_executor_workspace_permissions()
|
||||
let sandbox_policy_cwd = PathUri::from_abs_path(&path);
|
||||
let attempt = SandboxAttempt {
|
||||
sandbox_override: SandboxOverride::NoOverride,
|
||||
sandbox: SandboxType::MacosSeatbelt,
|
||||
local_selection: SandboxSelection::Explicit(SandboxType::MacosSeatbelt),
|
||||
sandbox_requested: true,
|
||||
permissions: &permissions,
|
||||
exec_server_permissions: &exec_server_permissions,
|
||||
@@ -309,7 +310,7 @@ async fn file_system_sandbox_context_respects_sandbox_request() {
|
||||
let sandbox_policy_cwd = PathUri::from_abs_path(&path);
|
||||
let attempt = SandboxAttempt {
|
||||
sandbox_override: SandboxOverride::NoOverride,
|
||||
sandbox: SandboxType::None,
|
||||
local_selection: SandboxSelection::Explicit(SandboxType::None),
|
||||
sandbox_requested: false,
|
||||
permissions: &permissions,
|
||||
exec_server_permissions: &permissions,
|
||||
|
||||
@@ -23,6 +23,7 @@ use codex_protocol::config_types::WindowsSandboxLevel;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::sandbox::SandboxOverride;
|
||||
use codex_sandboxing::SandboxManager;
|
||||
use codex_sandboxing::SandboxSelection;
|
||||
use codex_sandboxing::SandboxType;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
@@ -121,7 +122,7 @@ async fn explicit_escalation_prepares_exec_without_managed_network() -> anyhow::
|
||||
let manager = SandboxManager::new();
|
||||
let attempt = SandboxAttempt {
|
||||
sandbox_override: SandboxOverride::NoOverride,
|
||||
sandbox: SandboxType::None,
|
||||
local_selection: SandboxSelection::Explicit(SandboxType::None),
|
||||
sandbox_requested: false,
|
||||
permissions: &permissions,
|
||||
exec_server_permissions: &permissions,
|
||||
|
||||
@@ -410,8 +410,8 @@ pub(crate) trait ToolRuntime<Req, Out>: Approvable<Req> + Sandboxable {
|
||||
|
||||
pub(crate) struct SandboxAttempt<'a> {
|
||||
pub sandbox_override: SandboxOverride,
|
||||
pub sandbox: SandboxType,
|
||||
/// Whether policy requested sandboxing, independent of this host's concrete wrapper.
|
||||
pub(crate) local_selection: SandboxSelection,
|
||||
/// Whether this attempt requests a sandbox, after applying any approved bypass.
|
||||
pub sandbox_requested: bool,
|
||||
pub permissions: &'a codex_protocol::models::PermissionProfile,
|
||||
/// Canonical permissions before this host materializes workspace roots.
|
||||
@@ -504,29 +504,24 @@ impl<'a> SandboxAttempt<'a> {
|
||||
network: Option<&NetworkProxy>,
|
||||
environment_id: Option<&str>,
|
||||
) -> Result<crate::sandboxing::ExecRequest, CodexErr> {
|
||||
let mut request = self
|
||||
.manager
|
||||
.transform(SandboxTransformRequest {
|
||||
crate::sandboxing::ExecRequest::prepare_local_sandbox(
|
||||
self.manager,
|
||||
SandboxTransformRequest {
|
||||
command,
|
||||
permissions: self.permissions,
|
||||
workspace_roots: None,
|
||||
workspace_roots: Some(self.workspace_roots),
|
||||
runtime_readable_paths: None,
|
||||
selection: SandboxSelection::Explicit(self.sandbox),
|
||||
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),
|
||||
use_legacy_landlock: self.use_legacy_landlock,
|
||||
windows_sandbox_level: self.windows_sandbox_level,
|
||||
})?
|
||||
.into_command_request()?;
|
||||
request.sandbox_override = self.sandbox_override;
|
||||
let workspace_roots = self
|
||||
.workspace_roots
|
||||
.iter()
|
||||
.map(PathUri::to_abs_path)
|
||||
.collect::<std::io::Result<Vec<_>>>()?;
|
||||
crate::sandboxing::ExecRequest::from_sandbox_exec_request(request, options, workspace_roots)
|
||||
.await
|
||||
},
|
||||
options,
|
||||
self.sandbox_override,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -557,7 +552,7 @@ impl<'a> SandboxAttempt<'a> {
|
||||
arg0: None,
|
||||
};
|
||||
let mut exec_request =
|
||||
crate::sandboxing::ExecRequest::from_sandbox_exec_request(request, options, Vec::new())
|
||||
crate::sandboxing::ExecRequest::from_sandbox_exec_request(request, options, &[])
|
||||
.await?;
|
||||
exec_request.exec_server_managed_network = managed_network;
|
||||
// A controller-only proxy may be disabled on the executor. With no launch config,
|
||||
|
||||
@@ -301,7 +301,7 @@ async fn windows_sandbox_env_preserves_denied_reads_or_rejects_unsupported_backe
|
||||
let manager = SandboxManager::new();
|
||||
let mut attempt = SandboxAttempt {
|
||||
sandbox_override: SandboxOverride::NoOverride,
|
||||
sandbox: SandboxType::WindowsRestrictedToken,
|
||||
local_selection: SandboxSelection::Explicit(SandboxType::WindowsRestrictedToken),
|
||||
sandbox_requested: true,
|
||||
permissions: &permissions,
|
||||
exec_server_permissions: &permissions,
|
||||
@@ -376,7 +376,7 @@ async fn exec_server_env_keeps_command_native_and_carries_sandbox_context() {
|
||||
let manager = SandboxManager::new();
|
||||
let mut attempt = SandboxAttempt {
|
||||
sandbox_override: SandboxOverride::NoOverride,
|
||||
sandbox: SandboxType::None,
|
||||
local_selection: SandboxSelection::Explicit(SandboxType::None),
|
||||
sandbox_requested: true,
|
||||
permissions: &permissions,
|
||||
exec_server_permissions: &exec_server_permissions,
|
||||
|
||||
@@ -13,8 +13,8 @@
|
||||
//! Flow at a glance (open process)
|
||||
//! 1) Build a small request `{ command, cwd }`.
|
||||
//! 2) Orchestrator: approval (bypass/cache/prompt) → select sandbox → run.
|
||||
//! 3) Runtime: transform `SandboxTransformRequest` -> `ExecRequest` -> spawn PTY.
|
||||
//! 4) If denial, orchestrator retries with `SandboxType::None`.
|
||||
//! 3) Prepare the approved sandbox on the execution host, then spawn the PTY.
|
||||
//! 4) On sandbox denial, the orchestrator may authorize a retry with different permissions.
|
||||
//! 5) Process handle is returned with streaming output + metadata.
|
||||
//!
|
||||
//! This keeps policy logic and user interaction centralized while the PTY/process
|
||||
|
||||
Reference in New Issue
Block a user