mirror of
https://github.com/openai/codex.git
synced 2026-11-18 22:20:48 +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:
@@ -32,6 +32,7 @@ pub use core_test_support::test_path_buf_with_windows;
|
||||
pub use core_test_support::test_tmp_path;
|
||||
pub use core_test_support::test_tmp_path_buf;
|
||||
pub use json_logging::app_server_json_shutdown_event;
|
||||
pub use local_websocket_exec_server::LocalWebsocketExecServer;
|
||||
pub use mock_model_server::create_mock_responses_server_repeating_assistant;
|
||||
pub use mock_model_server::create_mock_responses_server_sequence;
|
||||
pub use mock_model_server::create_mock_responses_server_sequence_unchecked;
|
||||
|
||||
@@ -14,17 +14,14 @@ const START_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
#[cfg(target_os = "linux")]
|
||||
const CODEX_LINUX_SANDBOX_EXE_ENV_VAR: &str = "CODEX_TEST_LINUX_SANDBOX_EXE";
|
||||
|
||||
/// Host-local exec-server fixture that exposes a WebSocket URL.
|
||||
///
|
||||
/// This is distinct from the ordinary local stdio executor: callers use it
|
||||
/// when they need a socket transport they can interpose.
|
||||
pub(crate) struct LocalWebsocketExecServer {
|
||||
/// Runs a host-local exec-server over WebSocket for integration tests.
|
||||
pub struct LocalWebsocketExecServer {
|
||||
child: Child,
|
||||
websocket_url: String,
|
||||
}
|
||||
|
||||
impl LocalWebsocketExecServer {
|
||||
pub(crate) async fn start(codex_home: &Path, exec_server_program: &Path) -> Result<Self> {
|
||||
pub async fn start(codex_home: &Path, exec_server_program: &Path) -> Result<Self> {
|
||||
let mut command = Command::new(exec_server_program);
|
||||
command.stdin(Stdio::null());
|
||||
command.stdout(Stdio::piped());
|
||||
@@ -68,7 +65,7 @@ impl LocalWebsocketExecServer {
|
||||
Ok(exec_server)
|
||||
}
|
||||
|
||||
pub(crate) fn websocket_url(&self) -> &str {
|
||||
pub fn websocket_url(&self) -> &str {
|
||||
&self.websocket_url
|
||||
}
|
||||
}
|
||||
|
||||
@@ -512,63 +512,147 @@ async fn command_exec_permission_profile_does_not_reuse_default_network_proxy()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test_case::test_case(false; "local core")]
|
||||
#[test_case::test_case(true; "exec server")]
|
||||
#[tokio::test]
|
||||
async fn command_exec_permission_profile_project_roots_use_command_cwd() -> Result<()> {
|
||||
async fn command_exec_permission_profile_project_roots_use_command_cwd(
|
||||
exec_server: bool,
|
||||
) -> Result<()> {
|
||||
let server = create_mock_responses_server_sequence_unchecked(Vec::new()).await;
|
||||
let codex_home = TempDir::new()?;
|
||||
let command_dir = codex_home.path().join("command-cwd");
|
||||
std::fs::create_dir(&command_dir)?;
|
||||
let granted = command_dir.join("granted/child.txt");
|
||||
let sibling = command_dir.join("sibling.txt");
|
||||
let parent = codex_home.path().join("granted/parent.txt");
|
||||
std::fs::create_dir_all(command_dir.join("granted"))?;
|
||||
std::fs::create_dir(codex_home.path().join("granted"))?;
|
||||
std::fs::write(&sibling, b"original")?;
|
||||
std::fs::write(&parent, b"original")?;
|
||||
create_config_toml(codex_home.path(), &server.uri(), "never")?;
|
||||
insert_command_exec_config(
|
||||
codex_home.path(),
|
||||
r#"
|
||||
[permissions.command-cwd.filesystem]
|
||||
":root" = "read"
|
||||
":workspace_roots" = "write"
|
||||
[permissions.command-cwd.filesystem.":workspace_roots"]
|
||||
"granted" = "write"
|
||||
"#,
|
||||
)?;
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
.without_auto_env()
|
||||
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
|
||||
.await?;
|
||||
let command = vec![
|
||||
"/bin/sh".to_string(),
|
||||
"-c".to_string(),
|
||||
"printf child > granted/child.txt &&
|
||||
! (printf sibling > sibling.txt) 2>/dev/null &&
|
||||
! (printf parent > ../granted/parent.txt) 2>/dev/null"
|
||||
.to_string(),
|
||||
];
|
||||
let (exit_code, output) = if exec_server {
|
||||
use app_test_support::LocalWebsocketExecServer;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_core::config::ConfigOverrides;
|
||||
use codex_core::config::LoaderOverrides;
|
||||
use codex_core::exec_env::create_env;
|
||||
use codex_exec_server::Environment;
|
||||
use codex_exec_server::ExecParams;
|
||||
use codex_exec_server::ExecProcessEvent;
|
||||
use codex_exec_server::FileSystemSandboxContext;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
|
||||
let command_request_id = mcp
|
||||
.send_command_exec_request(CommandExecParams {
|
||||
command: vec![
|
||||
"sh".to_string(),
|
||||
"-lc".to_string(),
|
||||
"printf child > child.txt && ! printf parent > ../parent.txt".to_string(),
|
||||
],
|
||||
process_id: None,
|
||||
tty: false,
|
||||
stream_stdin: false,
|
||||
stream_stdout_stderr: false,
|
||||
output_bytes_cap: None,
|
||||
disable_output_cap: false,
|
||||
disable_timeout: false,
|
||||
timeout_ms: None,
|
||||
cwd: Some("command-cwd".into()),
|
||||
env: None,
|
||||
size: None,
|
||||
sandbox_policy: None,
|
||||
permission_profile: Some("command-cwd".to_string()),
|
||||
})
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.harness_overrides(ConfigOverrides {
|
||||
cwd: Some(command_dir.clone()),
|
||||
default_permissions: Some("command-cwd".to_string()),
|
||||
..Default::default()
|
||||
})
|
||||
.loader_overrides(LoaderOverrides::without_managed_config_for_tests())
|
||||
.build()
|
||||
.await?;
|
||||
let server = LocalWebsocketExecServer::start(
|
||||
codex_home.path(),
|
||||
&codex_utils_cargo_bin::cargo_bin("exec-server")?,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let response: CommandExecResponse = mcp.read_response(command_request_id).await?;
|
||||
assert_eq!(
|
||||
response.exit_code, 0,
|
||||
"parent cwd write should fail under command project-root profile: {response:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(command_dir.join("child.txt"))?,
|
||||
"child"
|
||||
);
|
||||
assert!(
|
||||
!codex_home.path().join("parent.txt").exists(),
|
||||
"permissionProfile :workspace_roots write should not grant the server cwd when command cwd differs"
|
||||
);
|
||||
let environment = Environment::create_for_tests(Some(server.websocket_url().to_owned()))?;
|
||||
let cwd = PathUri::from_host_native_path(&command_dir)?;
|
||||
let sandbox = FileSystemSandboxContext::from_permission_profile(
|
||||
config.permissions.permission_profile().clone(),
|
||||
cwd.clone(),
|
||||
);
|
||||
let started = environment
|
||||
.get_exec_backend()
|
||||
.start(ExecParams {
|
||||
process_id: "restricted-write".into(),
|
||||
metadata: None,
|
||||
argv: command,
|
||||
cwd,
|
||||
env_policy: None,
|
||||
shell_snapshot: None,
|
||||
env: create_env(
|
||||
&config.permissions.shell_environment_policy,
|
||||
/*thread_id*/ None,
|
||||
),
|
||||
tty: false,
|
||||
pipe_stdin: false,
|
||||
arg0: None,
|
||||
sandbox: Some(sandbox),
|
||||
enforce_managed_network: false,
|
||||
managed_network: None,
|
||||
network_proxy: None,
|
||||
})
|
||||
.await?;
|
||||
let mut events = started.process.subscribe_events();
|
||||
let deadline = Instant::now() + DEFAULT_READ_TIMEOUT;
|
||||
let mut status = None;
|
||||
let mut output = String::new();
|
||||
loop {
|
||||
match tokio::time::timeout_at(deadline, events.recv()).await?? {
|
||||
ExecProcessEvent::Output(chunk) => {
|
||||
output.push_str(&String::from_utf8_lossy(&chunk.chunk.into_inner()));
|
||||
}
|
||||
ExecProcessEvent::Exited { exit_code, .. } => status = Some(exit_code),
|
||||
ExecProcessEvent::Closed { .. } => {
|
||||
break (
|
||||
status.context("exec-server closed without an exit code")?,
|
||||
output,
|
||||
);
|
||||
}
|
||||
ExecProcessEvent::Failed(message) => {
|
||||
anyhow::bail!("exec-server failed: {message}\n{output}");
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
.without_auto_env()
|
||||
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
|
||||
.await?;
|
||||
let command_request_id = mcp
|
||||
.send_command_exec_request(CommandExecParams {
|
||||
command,
|
||||
process_id: None,
|
||||
tty: false,
|
||||
stream_stdin: false,
|
||||
stream_stdout_stderr: false,
|
||||
output_bytes_cap: None,
|
||||
disable_output_cap: false,
|
||||
disable_timeout: false,
|
||||
timeout_ms: None,
|
||||
cwd: Some("command-cwd".into()),
|
||||
env: None,
|
||||
size: None,
|
||||
sandbox_policy: None,
|
||||
permission_profile: Some("command-cwd".to_string()),
|
||||
})
|
||||
.await?;
|
||||
let response: CommandExecResponse = mcp.read_response(command_request_id).await?;
|
||||
(response.exit_code, response.stderr)
|
||||
};
|
||||
assert_eq!(exit_code, 0, "{output}");
|
||||
assert_eq!(std::fs::read(granted)?, b"child");
|
||||
assert_eq!(std::fs::read(sibling)?, b"original");
|
||||
assert_eq!(std::fs::read(parent)?, b"original");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+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
|
||||
|
||||
@@ -5,6 +5,7 @@ use codex_file_system::WindowsSandboxSelection;
|
||||
use codex_protocol::config_types::WindowsSandboxLevel;
|
||||
use codex_sandboxing::SandboxSelection;
|
||||
use codex_sandboxing::SandboxType;
|
||||
use codex_sandboxing::SandboxablePreference;
|
||||
|
||||
pub(crate) fn validate_remote_mxc(info: &crate::EnvironmentInfo) -> std::io::Result<()> {
|
||||
if !info.capabilities.windows_mxc {
|
||||
@@ -30,5 +31,15 @@ pub(crate) fn sandbox_selection(
|
||||
);
|
||||
}
|
||||
};
|
||||
(SandboxSelection::RequirePlatform, level)
|
||||
(
|
||||
SandboxSelection::Platform {
|
||||
preference: SandboxablePreference::Require,
|
||||
windows_sandbox: if level == WindowsSandboxLevel::Disabled {
|
||||
SandboxType::None
|
||||
} else {
|
||||
SandboxType::WindowsRestrictedToken
|
||||
},
|
||||
},
|
||||
level,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ use crate::permissions::FileSystemSpecialPath;
|
||||
use crate::permissions::LegacySandboxPolicyProjection;
|
||||
use crate::permissions::NetworkSandboxPolicy;
|
||||
use crate::permissions::RawFileSystemSandboxEntry;
|
||||
use crate::permissions::has_workspace_root_rules;
|
||||
use crate::protocol::SandboxPolicy;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_image::ImageProcessingError;
|
||||
@@ -700,6 +701,17 @@ impl PermissionProfile {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this profile has filesystem rules relative to the execution host's workspace roots.
|
||||
pub fn has_workspace_root_rules(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Managed {
|
||||
file_system: ManagedFileSystemPermissions::Restricted { entries, .. },
|
||||
..
|
||||
} if has_workspace_root_rules(entries)
|
||||
)
|
||||
}
|
||||
|
||||
pub fn network_sandbox_policy(&self) -> NetworkSandboxPolicy {
|
||||
match self {
|
||||
Self::Managed { network, .. } | Self::External { network } => *network,
|
||||
|
||||
@@ -595,6 +595,18 @@ pub fn project_roots_glob_pattern(subpath: &Path) -> String {
|
||||
format!("{PROJECT_ROOTS_GLOB_PATTERN_PREFIX}{}", subpath.display())
|
||||
}
|
||||
|
||||
pub(crate) fn has_workspace_root_rules(entries: &[FileSystemSandboxEntry]) -> bool {
|
||||
entries.iter().any(|entry| match &entry.path {
|
||||
FileSystemPath::Special { value } => {
|
||||
matches!(value, FileSystemSpecialPath::ProjectRoots { .. })
|
||||
}
|
||||
FileSystemPath::GlobPattern { pattern } => {
|
||||
pattern.starts_with(PROJECT_ROOTS_GLOB_PATTERN_PREFIX)
|
||||
}
|
||||
FileSystemPath::Path { .. } => false,
|
||||
})
|
||||
}
|
||||
|
||||
fn read_only_file_system_entries() -> Vec<FileSystemSandboxEntry> {
|
||||
vec![FileSystemSandboxEntry::new(
|
||||
FileSystemPath::Special {
|
||||
|
||||
@@ -8,12 +8,12 @@ use super::FileSystemSandboxPolicy;
|
||||
use super::FileSystemSandboxPolicyContext;
|
||||
use super::FileSystemSpecialPath;
|
||||
use super::InvalidDenyReadGlobBehavior;
|
||||
use super::PROJECT_ROOTS_GLOB_PATTERN_PREFIX;
|
||||
use super::PROTECTED_METADATA_PATH_NAMES;
|
||||
use super::ReadDenyMatcher;
|
||||
use super::deny_read_validator::DenyReadValidator;
|
||||
use super::deny_read_validator::has_context_read_denials;
|
||||
use super::file_system_root;
|
||||
use super::has_workspace_root_rules;
|
||||
use codex_utils_path_uri::PathConvention;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use std::collections::HashSet;
|
||||
@@ -56,20 +56,7 @@ impl FileSystemSandboxPolicy {
|
||||
FileSystemAccessMode::Write,
|
||||
)]);
|
||||
approved.preserve_deny_read_restrictions_from(self);
|
||||
if context.workspace_roots.is_empty()
|
||||
&& approved.entries.iter().any(|entry| {
|
||||
matches!(
|
||||
&entry.path,
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::ProjectRoots { .. }
|
||||
}
|
||||
) || matches!(
|
||||
&entry.path,
|
||||
FileSystemPath::GlobPattern { pattern }
|
||||
if pattern.starts_with(PROJECT_ROOTS_GLOB_PATTERN_PREFIX)
|
||||
)
|
||||
})
|
||||
{
|
||||
if context.workspace_roots.is_empty() && has_workspace_root_rules(&approved.entries) {
|
||||
return self.clone();
|
||||
}
|
||||
let Some(mut approved) =
|
||||
|
||||
@@ -134,13 +134,15 @@ impl SandboxExecRequest {
|
||||
}
|
||||
}
|
||||
|
||||
/// How the execution host selects a backend for this launch.
|
||||
#[derive(Clone, Copy)]
|
||||
/// A backend chosen by the caller, or a sandbox selected from policy on the execution host.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum SandboxSelection {
|
||||
/// Use the selected backend, including an explicitly native launch.
|
||||
Explicit(SandboxType),
|
||||
/// Refuse the launch if this host cannot provide its platform sandbox.
|
||||
RequirePlatform,
|
||||
Platform {
|
||||
preference: SandboxablePreference,
|
||||
windows_sandbox: SandboxType,
|
||||
},
|
||||
}
|
||||
|
||||
/// Network enforcement for one launch. A proxy may be required without a live proxy
|
||||
@@ -464,11 +466,20 @@ impl SandboxManager {
|
||||
.map_err(SandboxTransformError::InvalidPolicy)?;
|
||||
let backend = match request.selection {
|
||||
SandboxSelection::Explicit(sandbox) => sandbox,
|
||||
SandboxSelection::RequirePlatform => {
|
||||
#[cfg(windows)]
|
||||
crate::windows_mxc::record_availability_once();
|
||||
get_platform_sandbox(request.windows_sandbox_level != WindowsSandboxLevel::Disabled)
|
||||
.ok_or(SandboxTransformError::SandboxUnavailable)?
|
||||
SandboxSelection::Platform {
|
||||
preference,
|
||||
windows_sandbox,
|
||||
} => {
|
||||
let sandbox = self.select_initial(
|
||||
request.permissions,
|
||||
preference,
|
||||
windows_sandbox,
|
||||
enforce_managed_network,
|
||||
);
|
||||
if preference == SandboxablePreference::Require && sandbox == SandboxType::None {
|
||||
return Err(SandboxTransformError::SandboxUnavailable);
|
||||
}
|
||||
sandbox
|
||||
}
|
||||
};
|
||||
if is_file_system_helper && backend == SandboxType::None {
|
||||
|
||||
Reference in New Issue
Block a user