Tool Execution and Sandboxing
Overview
This area owns the executor boundary: how a model/tool request becomes an argv, how that argv is checked or classified, how an exec-server launches it locally or remotely, how platform sandboxes are selected and enforced, and how filesystem/search/patch/tunnel helpers use the same executor abstractions.
The CLI-facing codex-rs/…/lib.rs is the headless execution entry point. It loads config, sets session metadata, starts or resumes app-server threads, and turns app-server events into human or JSONL output via codex-rs/…/event_processor*.rs and codex-rs/…/exec_events.rs. The actual command boundary lives in codex-rs/…/protocol.rs: ExecParams carries process_id, argv, executor-local cwd as a PathUri, optional ExecEnvPolicy, tty/stdin flags, arg0, FileSystemSandboxContext, managed-network requirements, and optional executor-local network proxy launch instructions. The same protocol defines process/start, process/read, process/write, process/signal, process/terminate, output/exit/closed notifications, filesystem RPCs, environment discovery, capability discovery, and HTTP request streaming.
codex-rs/…/lib.rs re-exports the executor API and wires the server modules. codex-rs/…/server.rs starts the transport, and codex-rs/…/handler.rs requires the initialize/initialized handshake before serving process, filesystem, environment, capability, and HTTP requests. Process requests route through codex-rs/…/process_handler.rs into codex-rs/…/local_process.rs. LocalProcess::start_process builds the child environment from ExecEnvPolicy, strips non-inheritable executor vars, applies metadata env vars, prepares sandbox/network state with codex-rs/…/process_sandbox.rs, spawns through codex_sandboxing::spawn_process, and retains bounded output history. Output is exposed both as retained process/read pages and as notifications/events (ExecProcessEvent in codex-rs/…/process.rs); stdin writes are idempotent by write_id.
Remote execution uses the same traits. codex-rs/…/client.rs is the JSON-RPC client; it initializes an executor, caches EnvironmentInfo, registers process sessions, orders connection-global output/exit/closed notifications by sequence number, retries/reconnects where supported, and forwards network-policy callbacks. codex-rs/…/remote_process.rs implements ExecBackend by sending ExecParams to a lazy remote exec-server, then exposes the returned session as an ExecProcess. codex-rs/…/remote_file_system.rs similarly implements ExecutorFileSystem over filesystem RPCs and only sends a sandbox on reads after executor capability checks (read_sandbox in that file).
Authorization has two layers. Command approval policy is modeled in codex-rs/execpolicy/src/*: Policy stores prefix rules by program, case-folded/canonical rules, host-executable fallbacks, and network host rules; Policy::check* returns an Evaluation whose Decision is derived from matching RuleMatch values or a caller heuristic. Policy::preserves_managed_requirements prevents transported policy snapshots from weakening managed rules. Separate runtime sandbox authority is carried by FileSystemSandboxContext in codex-rs/…/lib.rs; it serializes permission profiles with executor path URIs, holds policy cwd/workspace roots/home/temp dirs, Windows sandbox selection, and legacy Landlock mode, and decides whether reads or writes require a platform sandbox. codex-rs/…/policy_transforms.rs normalizes, materializes, merges, and intersects additional permission grants before sandboxing.
Sandbox preparation is centralized in codex-rs/…/manager.rs. SandboxManager::transform resolves runtime-readable roots, materializes workspace-root permissions, selects the backend, and returns a SandboxExecRequest. The default backend is MacosSeatbelt on macOS, LinuxSeccomp on Linux, WindowsRestrictedToken on Windows when enabled, or None; WindowsMxc can be explicitly selected through WindowsSandboxSelection::Mxc (codex-rs/…/sandbox_selection.rs). codex-rs/…/launch.rs turns prepared requests into a std::process::Command unless the native Windows restricted-token launcher is required.
Platform enforcement splits as follows:
- Linux: codex-rs/…/landlock.rs creates argv for
codex-linux-sandbox; codex-rs/…/linux_run_main.rs parses the helper CLI, resolves the permission profile, then either applies seccomp/no-new-privs directly for full-write cases or runs bubblewrap first and re-enters an inner seccomp stage. codex-rs/…/bwrap.rs builds read-only-by-default filesystem mounts, writable roots, read-deny masks, WSL/WSLg masks, and network namespace flags. codex-rs/…/seccomp.rs denies network syscalls, ptrace/process-vm, request-key, io_uring, and VM-socket escape paths depending on network policy and managed-proxy routing. codex-rs/…/launcher.rs chooses system bubblewrap if it supports required flags or bundled bubblewrap; codex-rs/…/main.rs is the vendored bubblewrap trampoline. - macOS: codex-rs/…/seatbelt.rs builds
/usr/bin/sandbox-execargv from filesystem and network policy, including optional managed proxy loopback ports and Unix-domain-socket allowlists.SandboxManager::for_inherited_terminalselects a profile that permits required terminal sockets while still denying terminal input injection. - Windows: codex-rs/…/windows.rs decides whether a permission profile can be enforced by the restricted-token backend, when elevated setup is required for split read/write restrictions, and what read/write/deny ACL overrides must be passed to
codex-rs/windows-sandbox-rs. The Windows sandbox crate exposes the wrapper, token, ACL, elevated, setup, stdio bridge, provisioning, WFP, and unified exec machinery via codex-rs/…/lib.rs. codex-rs/…/lib.rs is the native MXC helper path: it validates managed-network loopback constraints, encodes the command and permission profile into launcher-only env, and dispatches--__codex-windows-mxc. codex-rs/…/lib.rs and src/main.rs run the Windows service used for provisioning/registered runtime lifecycle.
Filesystem operations share codex-rs/…/lib.rs's ExecutorFileSystem trait. codex-rs/…/file_system_handler.rs maps RPCs to LocalFileSystem, validates file handle ids, base64-encodes whole-file operations, caps directory entries, and uses FileHandleManager (codex-rs/…/file_handle.rs) for bounded connection-scoped streamed reads/writes. codex-rs/…/local_file_system.rs chooses direct host I/O or SandboxedFileSystem per operation: reads are sandboxed when the policy lacks full-disk read, writes when it lacks full-disk write. codex-rs/…/fs_sandbox.rs launches a sandboxed Codex self-helper (--codex-run-as-fs-helper) with a stripped env allowlist; codex-rs/…/fs_helper.rs performs the requested filesystem operation inside that sandbox and returns structured responses. codex-rs/…/sandboxed_file_open.rs handles streamed fs/open: Unix transfers the opened fd with SCM_RIGHTS, while Windows duplicates the helper process handle.
Patch application is filesystem-abstracted. codex-rs/…/invocation.rs recognizes direct apply_patch <patch> and conservative shell heredoc forms, rejects implicit raw patch bodies, resolves optional cd workdirs against executor PathUris, and verifies resulting changes against an ExecutorFileSystem. codex-rs/…/lib.rs parses hunks, reads/writes/removes through that filesystem with the caller's sandbox, tracks committed deltas (including partially exact failures), and exposes the internal self-invocation flag --codex-run-as-apply-patch.
Search, shell parsing, and tool metadata are adjacent helpers. codex-rs/…/lib.rs implements async-ish fuzzy search with an ignore-aware walker thread and a Nucleo matcher thread, plus a CLI fallback that lists the directory when no query is supplied. codex-rs/…/lib.rs multiplexes OS watch registrations, supports missing-path fallback watches, and offers throttled/debounced receivers. codex-rs/…/parse_command.rs extracts human-readable command metadata from bash/PowerShell wrappers, while codex-rs/…/is_dangerous_command.rs flags forced rm, dangerous Windows/PowerShell commands, and nested shell/env/sudo/trap wrappers with a fail-closed wrapper-depth limit. codex-rs/tools/src/* defines model-visible tool specs, payloads, tool-call context, environment borrowing, and ToolExecutor exposure/routing contracts; command execution itself is still routed through the executor/sandbox layers above.
Networking support in this scope is helper-level. codex-rs/…/lib.rs creates a loopback TCP listener that forwards streams through a verified HTTPS HTTP/3 CONNECT proxy, requiring an exact trusted proxy origin file and stdin bearer/control metadata; SSH mode is exposed from codex-rs/…/ssh.rs. codex-rs/…/lib.rs provides cross-platform async Unix-domain-socket-like streams plus private socket directory preparation (0700 on Unix, user-only DACL on Windows). codex-rs/…/lib.rs bridges stdin/stdout to such a socket. codex-rs/…/lib.rs runs pre-main hardening on Unix platforms by disabling dumps/ptrace and removing loader-injection env vars.
Path-routing notes: process and filesystem RPC schemas live in exec-server-protocol; local/remote transport and execution live in exec-server; sandbox policy transformation lives in sandboxing; concrete Linux helper enforcement lives in linux-sandbox plus bwrap; Windows enforcement/provisioning lives in windows-sandbox-rs, windows-sandbox-service, and mxc-sandbox; command approval policy lives in execpolicy; file/search/watch abstractions live in file-system, file-search, and file-watcher; patch parsing/apply lives in apply-patch; model tool descriptors live in tools; socket/tunnel bridges live in uds, stdio-to-uds, and tcp-tunnel.
Coupling
- If codex-rs/…/protocol.rs adds or changes
ExecParams,ReadResponse, process notifications, or filesystem RPC params, update both codex-rs/…/client.rs and codex-rs/…/handler.rs; local, remote, and replay paths all deserialize the same JSON-RPC shapes, and old clients rely on the wire fallback structs for omitted sandbox policy cwd. - If
FileSystemSandboxContextin codex-rs/…/lib.rs changes, verify codex-rs/…/process_sandbox.rs, codex-rs/…/fs_sandbox.rs, codex-rs/…/remote_file_system.rs, and codex-rs/…/manager.rs; process, filesystem, local, and remote sandbox selection all interpret the same cwd/workspace/home/temp fields. - If sandbox permission semantics change in codex-rs/…/policy_transforms.rs or codex-rs/…/launch.rs, verify the Linux, macOS, Windows, filesystem-helper, and MXC wrappers.
SandboxManager::transformfeeds all of them, and a widened runtime-readable root or incorrect workspace materialization silently widens every backend. - If Linux helper flags change in codex-rs/…/landlock.rs, update codex-rs/…/linux_run_main.rs together. The former serializes
--permission-profile, cwd, legacy Landlock, managed network, transparent TCP, and argv separators; the latter is the only parser/enforcer. - If filesystem streaming limits change in codex-rs/…/lib.rs, also update codex-rs/…/file_handle.rs, codex-rs/…/file_system_handler.rs, and codex-rs/…/remote_file_system.rs; block-size validation and remote fallback buffering must stay within the shared JSON-RPC decoder budget.
- If codex-rs/…/invocation.rs accepts a new shell form, add negative cases as well as positive cases. The verifier intentionally recognizes only whole-script apply_patch forms so a command with extra side effects is not reclassified as a safe patch operation.
- If Windows sandbox selection adds a backend, update codex-rs/…/lib.rs (
WindowsSandboxSelection), codex-rs/…/sandbox_selection.rs, codex-rs/…/manager.rs, codex-rs/…/windows.rs, and theProcessSandboxTypeenum in codex-rs/…/protocol.rs; telemetry and clients rely on the reported sandbox type.
Risks
- codex-rs/…/linux_run_main.rs, codex-rs/…/bwrap.rs, and codex-rs/…/seccomp.rs: Linux enforcement is a two-stage pipeline where bubblewrap establishes filesystem/network namespaces before the inner seccomp stage execs the workload. If argv ordering, preserved fds, or
--apply-seccomp-then-exechandling regresses, commands may run with missing mounts or without intended syscall restrictions. - codex-rs/…/fs_sandbox.rs and codex-rs/…/sandboxed_file_open.rs: sandboxed filesystem streaming depends on a helper subprocess plus fd/handle transfer. If helper env allowlists or close-on-exec behavior are widened, the helper can inherit credentials or leak descriptors into sandboxed workloads.
- codex-rs/…/windows.rs and codex-rs/…/lib.rs: the restricted-token backend cannot directly enforce all split read/write policies. If
resolve_windows_*_filesystem_overridesfalls back incorrectly, Windows commands may run unsandboxed or with read-deny/write-deny carveouts missing. - codex-rs/…/policy.rs: managed execution policy preservation depends on exact prefix, canonical matching, host-executable fallback, and network-denial comparisons. If
preserves_managed_requirementsmisses a shadowing case, a transported policy snapshot can weaken managed command or network requirements without an obvious parse error.