Files
codex/codex-rs/core/src/unified_exec/mod.rs
T
viyatb-oai 6ee9bc1ba7 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
2026-11-18 03:59:37 +00:00

236 lines
7.5 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Unified Exec: interactive process execution orchestrated with approvals + sandboxing.
//!
//! Responsibilities
//! - Manages interactive processes (create, reuse, buffer output with caps).
//! - Supports completion-only calls that terminate on timeout or cancellation.
//! - Uses the shared ToolOrchestrator to handle approval, sandbox selection, and
//! retry semantics in a single, descriptive flow.
//! - Spawns the PTY from a sandbox-transformed `ExecRequest`; on sandbox denial,
//! retries without sandbox when policy allows (no re‑prompt thanks to caching).
//! - Uses the shared `is_likely_sandbox_denied` heuristic to keep denial messages
//! consistent with other exec paths.
//!
//! Flow at a glance (open process)
//! 1) Build a small request `{ command, cwd }`.
//! 2) Orchestrator: approval (bypass/cache/prompt) → select sandbox → run.
//! 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
//! concerns remain isolated here. The implementation is split between:
//! - `process.rs`: PTY process lifecycle + output buffering.
//! - `process_state.rs`: shared exit/failure state for local and remote processes.
//! - `process_manager.rs`: orchestration (approvals, sandboxing, reuse) and request handling.
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::Weak;
use codex_network_proxy::NetworkProxy;
use codex_utils_output_truncation::TruncationPolicy;
use codex_utils_path_uri::PathUri;
use rand::Rng;
use rand::rng;
use tokio::sync::Mutex;
use tokio_util::sync::CancellationToken;
use crate::session::session::Session;
use crate::session::step_context::StepContext;
use crate::session::turn_context::TurnContext;
use crate::tools::handlers::unified_exec::preparation::PreparedExecCommand;
use crate::tools::network_approval::DeferredNetworkApproval;
use codex_core_plugins::PluginMetricsSidecar;
mod async_watcher;
mod command_sessions;
mod errors;
mod oneshot;
pub(crate) mod output;
mod process;
mod process_manager;
pub(crate) use process_manager::exec_env_policy_from_shell_policy;
mod process_state;
mod shell_snapshot;
mod stdin_approval;
pub(crate) fn set_deterministic_process_ids_for_tests(enabled: bool) {
process_manager::set_deterministic_process_ids_for_tests(enabled);
}
pub(crate) use command_sessions::command_sessions_state;
pub(crate) use errors::UnifiedExecError;
pub(crate) use process::UnifiedExecProcess;
pub(crate) use stdin_approval::TerminalPermissions;
pub(crate) use stdin_approval::TerminalSandboxSource;
pub(crate) const MIN_YIELD_TIME_MS: u64 = 250;
pub(crate) const WINDOWS_INITIAL_EXEC_YIELD_TIME_FLOOR_MS: u64 = 10_000;
// Minimum yield time for an empty `write_stdin`.
pub(crate) const MIN_EMPTY_YIELD_TIME_MS: u64 = 5_000;
pub(crate) const MAX_YIELD_TIME_MS: u64 = 30_000;
pub(crate) const DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS: u64 = 300_000;
pub(crate) const DEFAULT_MAX_OUTPUT_TOKENS: usize = 10_000;
pub(crate) const UNIFIED_EXEC_OUTPUT_MAX_BYTES: usize = 1024 * 1024; // 1 MiB
pub(crate) const UNIFIED_EXEC_OUTPUT_MAX_TOKENS: usize = UNIFIED_EXEC_OUTPUT_MAX_BYTES / 4;
pub(crate) const MAX_UNIFIED_EXEC_PROCESSES: usize = 64;
const MAX_TRACE_ID_BYTES: usize = 256;
fn trace_id(id: &str) -> Option<&str> {
(!id.is_empty() && id.len() <= MAX_TRACE_ID_BYTES).then_some(id)
}
pub(crate) struct UnifiedExecContext {
pub session: Arc<Session>,
pub step_context: Arc<StepContext>,
pub cancellation_token: CancellationToken,
pub call_id: String,
}
impl UnifiedExecContext {
pub fn new(
session: Arc<Session>,
step_context: Arc<StepContext>,
cancellation_token: CancellationToken,
call_id: String,
) -> Self {
Self {
session,
step_context,
cancellation_token,
call_id,
}
}
}
#[derive(Debug)]
pub(crate) struct ExecCommandRequest {
pub prepared: PreparedExecCommand,
pub process_id: i32,
pub network: Option<NetworkProxy>,
}
/// The process and environment behind a terminal session ID at the time of lookup.
#[derive(Clone, Debug)]
pub(crate) struct TerminalSession {
pub(crate) process_id: i32,
process: Arc<UnifiedExecProcess>,
call_id: String,
pub(crate) environment_id: String,
}
#[derive(Debug)]
pub(crate) struct WriteStdinRequest<'a> {
pub terminal: &'a TerminalSession,
pub input: &'a str,
pub yield_time_ms: u64,
pub max_output_tokens: Option<usize>,
pub truncation_policy: TruncationPolicy,
pub interaction_event: Option<WriteStdinInteractionEvent<'a>>,
}
pub(crate) struct WriteStdinInteractionEvent<'a> {
pub session: &'a Arc<Session>,
pub turn: &'a Arc<TurnContext>,
}
impl std::fmt::Debug for WriteStdinInteractionEvent<'_> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("WriteStdinInteractionEvent")
}
}
#[derive(Default)]
pub(crate) struct ProcessStore {
processes: HashMap<i32, ProcessEntry>,
reserved_process_ids: HashSet<i32>,
}
impl ProcessStore {
fn remove(&mut self, process_id: i32) -> Option<ProcessEntry> {
if !process_manager::should_use_deterministic_process_ids() {
self.reserved_process_ids.remove(&process_id);
}
self.processes.remove(&process_id)
}
}
pub(crate) struct UnifiedExecProcessManager {
process_store: Mutex<ProcessStore>,
max_write_stdin_yield_time_ms: u64,
}
impl UnifiedExecProcessManager {
pub(crate) fn new(max_write_stdin_yield_time_ms: u64) -> Self {
Self {
process_store: Mutex::new(ProcessStore::default()),
max_write_stdin_yield_time_ms: max_write_stdin_yield_time_ms
.max(MIN_EMPTY_YIELD_TIME_MS),
}
}
}
impl Default for UnifiedExecProcessManager {
fn default() -> Self {
Self::new(DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS)
}
}
struct ProcessEntry {
process: Arc<UnifiedExecProcess>,
plugin_metrics_sidecar: Option<SharedPluginMetricsSidecar>,
call_id: String,
process_id: i32,
cwd: PathUri,
initial_exec_command_active: Arc<std::sync::atomic::AtomicBool>,
hook_command: String,
tty: bool,
environment_id: String,
permissions: TerminalPermissions,
network_approval: Option<DeferredNetworkApproval>,
session: Weak<Session>,
last_used: tokio::time::Instant,
}
type SharedPluginMetricsSidecar = Arc<std::sync::Mutex<Option<PluginMetricsSidecar>>>;
fn take_plugin_metrics_sidecar(
sidecar: &SharedPluginMetricsSidecar,
) -> Option<PluginMetricsSidecar> {
sidecar
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take()
}
pub(crate) fn clamp_yield_time(yield_time_ms: u64) -> u64 {
let yield_time_ms = if cfg!(windows) {
yield_time_ms.max(WINDOWS_INITIAL_EXEC_YIELD_TIME_FLOOR_MS)
} else {
yield_time_ms
};
yield_time_ms.clamp(MIN_YIELD_TIME_MS, MAX_YIELD_TIME_MS)
}
pub(crate) fn resolve_max_tokens(max_tokens: Option<usize>) -> usize {
max_tokens.unwrap_or(DEFAULT_MAX_OUTPUT_TOKENS)
}
pub(crate) fn generate_chunk_id() -> String {
let mut rng = rng();
(0..6)
.map(|_| format!("{:x}", rng.random_range(0..16)))
.collect()
}
#[cfg(test)]
#[cfg(unix)]
#[path = "process_tests.rs"]
mod process_tests;
#[cfg(test)]
#[cfg(unix)]
#[path = "mod_tests.rs"]
mod tests;