Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,52 @@
load("//:defs.bzl", "codex_rust_crate")
load("//bazel/rules/testing/compat:exec_server_compat_test.bzl", "exec_server_compat_test")
exports_files(
["src/proto/codex.exec_server.relay.v1.rs"],
visibility = ["//codex-rs/exec-server/tests/support:__pkg__"],
)
codex_rust_crate(
name = "exec-server",
crate_name = "codex_exec_server",
crate_srcs = glob([
"src/**/*.rs",
"tests/unit/**/*.rs",
]),
deps_extra = [
"@crates//:opentelemetry",
"@crates//:opentelemetry_sdk",
"@crates//:toml",
],
extra_binaries = [
"//codex-rs/bwrap:bwrap",
"//codex-rs/windows-sandbox-rs:codex-command-runner",
"//codex-rs/windows-sandbox-rs:codex-windows-sandbox-setup",
],
integration_compile_data_extra = [
"src/proto/codex.exec_server.relay.v1.rs",
],
# Keep the crate's tests single-threaded under Bazel because they install
# process-global test-binary dispatch state, and the remote exec-server
# cases already rely on serialization around the full CLI path.
integration_test_args = ["--test-threads=1"],
test_tags = ["no-sandbox"],
unit_test_args = ["--test-threads=1"],
)
exec_server_compat_test(
name = "exec-server-current-version-test",
comparison_binary = "//codex-rs/cli:codex",
current_binary = "//codex-rs/cli:codex",
)
# Preparation selects both releases; the normal Bazel test invocation runs them.
exec_server_compat_test(
name = "exec-server-stable-release-test",
release = "@codex_release_latest_stable",
)
exec_server_compat_test(
name = "exec-server-historical-release-test",
release = "@codex_release_historical_stable",
)

View File

@@ -0,0 +1,115 @@
[package]
name = "codex-exec-server"
version.workspace = true
edition.workspace = true
license.workspace = true
[lib]
doctest = false
# cargo-shear 1.11.2 misresolves these #[path] modules containing parent directories.
# Both modules are compiled and exercised by the exec-server unit test target.
[package.metadata.cargo-shear]
ignored-paths = [
"tests/unit/client_provisioning_tests.rs",
"src/discoverV2/tests/capability_watchers_tests.rs",
]
[lints]
workspace = true
[dependencies]
codex-utils-process = { workspace = true }
arc-swap = { workspace = true }
axum = { workspace = true, features = ["http1", "tokio", "ws"] }
base64 = { workspace = true }
bytes = { workspace = true }
clatter = { workspace = true }
codex-api = { workspace = true }
codex-build-info = { workspace = true }
codex-config = { workspace = true }
codex-core-plugin-common = { workspace = true }
codex-http-client = { workspace = true }
codex-exec-server-protocol = { workspace = true }
codex-file-system = { workspace = true }
codex-file-watcher = { workspace = true }
codex-network-proxy = { workspace = true }
codex-otel = { workspace = true }
codex-protocol = { workspace = true }
codex-sandboxing = { workspace = true }
codex-shell-command = { workspace = true }
codex-skills = { workspace = true }
codex-utils-absolute-path = { workspace = true }
codex-utils-home-dir = { workspace = true }
codex-utils-path-uri = { workspace = true }
codex-utils-pty = { workspace = true }
codex-utils-redacted-string = { workspace = true }
codex-utils-rustls-provider = { workspace = true }
codex-websocket-auth = { workspace = true }
codex-websocket-client = { workspace = true }
dirs = { workspace = true }
futures = { workspace = true }
http = { workspace = true }
notify = { workspace = true }
opentelemetry = { workspace = true }
prost = "0.14.3"
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
thiserror = { workspace = true }
toml = { workspace = true }
tokio = { workspace = true, features = [
"fs",
"io-std",
"io-util",
"macros",
"net",
"process",
"rt-multi-thread",
"sync",
"time",
] }
tokio-util = { workspace = true, features = ["io", "rt"] }
tokio-tungstenite = { workspace = true }
tracing = { workspace = true }
url = { workspace = true }
uuid = { workspace = true, features = ["v4"] }
[target.'cfg(target_os = "linux")'.dependencies]
codex-linux-sandbox = { workspace = true }
[target.'cfg(unix)'.dependencies]
codex-uds = { workspace = true }
libc = { workspace = true }
rustix = { workspace = true, features = ["fs", "process"] }
tempfile = { workspace = true }
[target.'cfg(windows)'.dependencies]
codex-mxc-sandbox = { workspace = true }
windows-sys = { workspace = true, features = [
"Win32_Foundation",
"Win32_Security",
"Win32_Storage_FileSystem",
"Win32_System_IO",
"Win32_System_Pipes",
"Win32_System_Threading",
] }
[dev-dependencies]
anyhow = { workspace = true }
codex-exec-server-test-support = { workspace = true }
codex-test-binary-support = { workspace = true }
codex-utils-cargo-bin = { workspace = true }
codex-windows-sandbox-test-support = { workspace = true }
ctor = { workspace = true }
http = { workspace = true }
opentelemetry_sdk = { workspace = true }
pretty_assertions = { workspace = true }
rcgen = { workspace = true }
rustls = { workspace = true }
serial_test = { workspace = true }
tempfile = { workspace = true }
test-case = "3.3.1"
tokio = { workspace = true, features = ["test-util"] }
tracing-opentelemetry = { workspace = true }
tracing-subscriber = { workspace = true }
wiremock = { workspace = true }

View File

@@ -0,0 +1,573 @@
# codex-exec-server
`codex-exec-server` is the library backing `codex exec-server` and the standalone
`codex-exec-server` executable, a small
JSON-RPC server for spawning and controlling subprocesses through
`codex-utils-pty`.
It provides:
- CLI entrypoints: `codex exec-server` and `codex-exec-server`
- a Rust client: `ExecServerClient`
- a small protocol module with shared request/response types
This crate owns the transport, protocol, and filesystem/process handlers. The
`codex-exec-server-cli` crate shares startup between the two executables. Both
use `codex-arg0` for hidden filesystem, process, and platform sandbox dispatch.
The standalone executable accepts the same executor arguments and `-c` config
overrides, including `--listen stdio`. Build it with
`cargo build -p codex-exec-server-cli --bin codex-exec-server`.
Canonical packages place it in `bin/` beside the entrypoint, with platform
sandbox resources in `codex-resources/`.
## Command metadata
Launches expose `metadata.threadId` as `CODEX_THREAD_ID` and `metadata.toolCallId`
as `CODEX_TOOL_CALL_ID` in the initial child environment. `exec_command` supplies
the originating execution call ID, unchanged by later input. Code-mode uses the
nested execution call ID, not the outer cell ID.
These reserved labels override inherited values, policy settings, overlays, and
cached snapshots. Present metadata clears omitted fields; absent metadata preserves
thread-only context and unsets the call ID. Snapshot capture and validation helpers
keep available thread context but omit the call ID; newly captured snapshots exclude
both ID exports.
Call IDs are copied unchanged, including empty values; NUL-containing IDs are
omitted. Platform process-environment size limits apply.
Labels support correlation, not authorization. Shell startup, commands, and
descendants can change or remove them; consumers must handle missing or unusable
labels. These guarantees require an updated executor: older executors may ignore
metadata or restore stale snapshot values.
## Transport
The server speaks the exec-specific `codex-exec-server-protocol` message
envelope on the wire.
The CLI entrypoint supports:
- `ws://IP:PORT` (default)
- `--remote URL --environment-id ID [--name NAME]`
- `forward --connect ws://HOST:PORT --remote URL --environment-id ID`
## Authentication
Direct WebSocket listeners support app-server's opt-in auth flags, including `--ws-auth capability-token --ws-token-sha256 HEX`, token files, and signed bearer tokens; clients send `Authorization: Bearer TOKEN` on each connection.
Use a protected transport or TLS proxy for remote access; authentication is checked at connection time and these flags do not apply to stdio, remote registration, or forwarding.
App-server clients can supply the raw token through `environment/add.authBearerToken` or `auth_bearer_token` in an `environments.toml` URL entry; omission preserves unauthenticated behavior.
Tokens require `wss://` or a loopback destination, are redacted in diagnostics, and are reused on reconnect without automatic refresh.
## Remote connections
Remote mode registers the local exec-server with the environment registry,
then reconnects to the service-provided rendezvous websocket as the environment.
To supply registration credentials independently of Codex login, pass
`--registration-bearer-stdin` and write one newline-terminated bearer to the
executor's stdin. Exec-server reads it once and requires an HTTPS registry URL
or an HTTP loopback address. For rotating credentials, use
`--executor-credential-stdin`. Local configuration
and plugins still come from the usual Codex home.
Remote communication uses the Noise relay contract; the registry and harness
must support it.
Forward mode uses the same registration and Noise relay, but opens an independent
WebSocket connection to the destination exec-server for each authenticated
harness stream. Complete message payloads pass unchanged in both directions;
the forwarder does not parse RPCs, initialize sessions, or execute requests.
The destination owns session IDs, processes, and session resumption.
Disconnecting either side closes its peer and resets the remote stream. The
existing harness reconnect flow can then resume a retained destination session.
The forwarder does not replay requests or persist execution state, so recovery
is limited by the destination's session and process-output retention.
It uses the standard Codex ChatGPT sign-in state; run `codex login` first when
remote registration needs authentication. Containerized callers that receive an
Agent Identity JWT in `CODEX_ACCESS_TOKEN` can opt into that auth path with
`--use-agent-identity-auth`; Codex then registers an Agent task and sends the
derived AgentAssertion headers on the registry request.
Alternatively, API users can instead use `CODEX_API_KEY`;
Codex sends it as a bearer token on the registration request. For example:
```sh
CODEX_API_KEY="$OPENAI_API_KEY" \
codex exec-server \
--remote ... \
--environment-id "$ENVIRONMENT_ID"
```
AWS-hosted registries can use SigV4 for registry requests and the executor
WebSocket handshake. Select the transport and authentication with executor
arguments rather than `config.toml` settings:
```sh
codex exec-server \
--remote https://example.com \
--environment-id "$ENVIRONMENT_ID" \
--remote-transport direct \
--aws-sigv4 \
--aws-profile development \
--aws-region us-west-2 \
--aws-service bedrock-mantle
```
Noise remains the default transport. Direct requires `--aws-sigv4`, which
conflicts with `--use-agent-identity-auth` and is not supported for Noise.
The AWS options require `--aws-sigv4`; Direct forwarding remains unsupported.
The AWS SDK default credential and region chains are used when `--aws-profile`
or `--aws-region` is omitted. The signing service defaults to `execute-api`.
Direct mode registers `direct_jsonrpc_v1` through the AWS-owned
`/cloud/environment/{environment_id}/direct/register` endpoint and carries plain
exec-server JSON-RPC over the authenticated WebSocket. The existing Codex Noise
registration endpoint remains unchanged. Production deployments must use TLS
(`https`/`wss`).
Direct registration URLs must remain reusable across disconnects and temporary
connection failures. The executor only refreshes its registration when the
WebSocket handshake returns `409 Conflict`. Handshake `408`, `429`, and `5xx`
responses retry with backoff using the current registration; other `4xx` responses
stop the executor. A backend that issues single-use connection URLs must adapt to
this contract. If the initial registration or a registration refresh fails, the
executor returns the error without retrying registration, matching Noise.
Wire framing:
- local websocket: one JSON-RPC message per websocket message
- direct remote websocket: one JSON-RPC message per websocket message
- Noise remote websocket: binary protobuf relay frames carrying encrypted payloads
## Remote Relay Message Format
In remote mode, the harness and environment communicate through rendezvous using
`codex.exec_server.relay.v1.RelayMessageFrame`; the checked-in schema is in
`src/proto/codex.exec_server.relay.v1.proto`. The relay frame carries stream
identity plus endpoint-owned reliability metadata:
```text
version
stream_id
traceparent // optional W3C parent on the first frame of a traced request
tracestate // optional W3C vendor state paired with traceparent
body // handshake | data | ack_frame | resume | reset | heartbeat
ack // highest contiguous peer segment seq received
ack_bits // bitset for peer segment seqs after ack
seq // data only: segment sequence number
segment_index // data only: 0-based index within message
segment_count // data only: number of segments in message
payload // handshake bytes or encrypted data record
next_seq // resume only: next sender seq
reason // reset only: reset reason
```
`stream_id` identifies one virtual harness/environment JSON-RPC session on the
environment websocket. The harness generates a UUIDv4 `stream_id`; the environment
demuxes frames by `stream_id` and runs an independent `ConnectionProcessor` per
stream.
Use segment-level sequence numbers for reliability:
```text
seq = 0, 1, 2, 3, ...
```
Use contiguous segment sequence ranges to identify and stitch a segmented
application message:
```text
message_start_seq = seq - segment_index
segment_index = 0
segment_count = 1
```
`message_start_seq` is derived by the receiver, not sent on the wire. For
unsplit messages, `message_start_seq == seq`, `segment_index == 0`, and
`segment_count == 1`.
Use cumulative `ack` plus fixed-size `ack_bits` instead of variable ack ranges:
```text
ack = highest contiguous received segment seq
bit i in ack_bits acknowledges seq = ack + 1 + i
```
Send `ack` and `ack_bits` redundantly on every outbound frame. Acks are not
themselves acked. Acks, retries, duplicate suppression, segmentation, and
reassembly are endpoint responsibilities; rendezvous only routes relay frames
by `stream_id`.
## Lifecycle
Each connection follows this sequence:
1. Send `initialize`.
2. Wait for the `initialize` response.
3. Send `initialized`.
4. Call process or filesystem RPCs.
Requests run sequentially by default. Pass `--concurrent-requests <COUNT>` to
enable concurrent processing.
If the server receives any notification other than `initialized`, it replies
with an error using request id `-1`.
If the websocket connection closes, the server terminates any remaining managed
processes for that client connection.
## API
### `initialize`
Initial handshake request.
Request params:
```json
{
"clientName": "my-client"
}
```
Response:
```json
{
"sessionId": "00000000-0000-4000-8000-000000000001",
"environmentInfo": {
"shell": { "name": "bash", "path": "/bin/bash" },
"executorVersion": "1.2.3-alpha.4",
"providerId": "sha256:fb4f62da3e84f6864dcec8ede7bc66f1c96ecaeaf55f8a786b85df994057c8ac",
"cwd": "file:///workspace"
}
}
```
`environmentInfo` contains the same executor metadata returned by
`environment/info`, so clients can use it without a second request.
`executorVersion` is the executor's package release version, or `0.0.0` when unknown.
The executor caches optional `providerId` at startup using
`codex_build_info::build_id(commit, target)`, which CI can also call for an
explicit build target. This opaque compatibility key excludes package version
and requires no manifest. It identifies a standard build configuration, not exact
executable bytes. Unstamped and legacy executors may omit it.
Rust clients cache this metadata for the client's lifetime, including session
resumption. If initialization omits it, the first metadata request fetches and
caches `environment/info`.
### `initialized`
Handshake acknowledgement notification sent by the client after a successful
`initialize` response.
Params are currently ignored. Sending any other notification method is treated
as an invalid request.
### `process/start`
Starts a new managed process.
Request params:
```json
{
"processId": "proc-1",
"argv": ["bash", "-lc", "printf 'hello\\n'"],
"cwd": "file:///absolute/working/directory",
"env": {
"PATH": "/usr/bin:/bin"
},
"tty": true,
"pipeStdin": false,
"arg0": null
}
```
Field definitions:
- `processId`: caller-chosen stable id for this process within the connection.
- `argv`: command vector. It must be non-empty.
- `cwd`: `file:` URI for the child process working directory.
- `env`: environment variables passed to the child process.
- `tty`: when `true`, spawn a PTY-backed interactive process.
- `pipeStdin`: when `true`, keep non-PTY stdin writable via `process/write`.
- `arg0`: optional argv0 override forwarded to `codex-utils-pty`.
Response:
```json
{
"processId": "proc-1"
}
```
Behavior notes:
- Reusing an existing `processId` is rejected.
- PTY-backed processes accept later writes through `process/write`.
- Non-PTY processes reject writes unless `pipeStdin` is `true`.
- Output is streamed asynchronously via `process/output`.
- Exit is reported asynchronously via `process/exited`.
### `process/read`
Reads buffered output and terminal state for a managed process.
Request params:
```json
{
"processId": "proc-1",
"afterSeq": null,
"maxBytes": 65536,
"waitMs": 1000
}
```
Field definitions:
- `processId`: managed process id returned by `process/start`.
- `afterSeq`: optional sequence number cursor; when present, only newer chunks
are returned.
- `maxBytes`: optional response byte budget.
- `waitMs`: optional long-poll timeout in milliseconds.
Response:
```json
{
"chunks": [],
"nextSeq": 1,
"exited": false,
"exitCode": null,
"closed": false,
"failure": null
}
```
### `process/write`
Writes raw bytes to a running process stdin.
Request params:
```json
{
"processId": "proc-1",
"chunk": "aGVsbG8K"
}
```
`chunk` is base64-encoded raw bytes. In the example above it is `hello\n`.
Response:
```json
{
"status": "accepted"
}
```
Behavior notes:
- Writes to an unknown `processId` are rejected.
- Writes to a non-PTY process are rejected unless it started with `pipeStdin`.
### `process/terminate`
Terminates a running managed process.
Request params:
```json
{
"processId": "proc-1"
}
```
Response:
```json
{
"running": true
}
```
If the process is already unknown or already removed, the server responds with:
```json
{
"running": false
}
```
## Notifications
### `process/output`
Streaming output chunk from a running process.
Params:
```json
{
"processId": "proc-1",
"seq": 1,
"stream": "stdout",
"chunk": "aGVsbG8K"
}
```
Fields:
- `processId`: process identifier
- `seq`: per-process output sequence number
- `stream`: `"stdout"`, `"stderr"`, or `"pty"`
- `chunk`: base64-encoded output bytes
### `process/exited`
Final process exit notification.
Params:
```json
{
"processId": "proc-1",
"seq": 2,
"exitCode": 0,
"sandboxDenied": false
}
```
`sandboxDenied` lets streaming clients preserve executor-side sandbox denial
detection without issuing a final `process/read` request. Clients recover it
with `process/read` when an older server omits the field.
### `process/closed`
Notification emitted after process output is closed and the process handle is
removed.
Params:
```json
{
"processId": "proc-1",
"seq": 3
}
```
## Filesystem RPCs
Filesystem methods require valid `file:` URI strings and return JSON-RPC errors
for invalid or unavailable paths. Native absolute path strings are rejected;
callers must convert them to `file:` URIs before sending requests:
- `fs/readFile`
- `fs/open`, `fs/readBlock`, `fs/writeBlock`, and `fs/close` (file handles;
reads also back `ExecutorFileSystem::read_file_stream`)
- `fs/writeFile`
- `fs/createDirectory`
- `fs/getMetadata`
- `fs/canonicalize`
- `fs/readDirectory`
- `fs/remove`
- `fs/copy`
`fs/open.mode` is `read` (default) or `replace` (create or truncate for writing).
Writable handles require `fileWriteStreaming`; `fs/writeBlock` writes a nonempty
base64 `chunk` of up to 1 MiB at an explicit `offset`.
Path-based filesystem requests accept an optional `sandbox` object. When `sandbox`
contains a `ReadOnly` or `WorkspaceWrite` policy, the operation runs in a
hidden helper process launched from the top-level `codex` executable and
prepared through the shared sandbox transform path. Helper requests and
responses are passed over stdin/stdout.
## Errors
The server returns JSON-RPC errors with these codes:
- `-32600`: invalid request
- `-32602`: invalid params
- `-32603`: internal error
Typical error cases:
- unknown method
- malformed params
- empty `argv`
- duplicate `processId`
- writes to unknown processes
- writes to non-PTY processes
- sandbox-denied filesystem operations
## Rust surface
The crate exports:
- `ExecServerClient`
- `ExecServerError`
- `ExecServerClientConnectOptions`
- `RemoteExecServerConnectArgs`
- protocol request/response structs for process and filesystem RPCs
- `DEFAULT_LISTEN_URL` and `ExecServerListenUrlParseError`
- `ExecServerRuntimeOptions`
- `run_main()` for embedding the websocket server
- `RemoteEnvironmentConfig` and `run_remote_environment()` for embedding remote
registration mode
Callers must pass `ExecServerRuntimeOptions` and an explicitly configured
`HttpClientFactory` to `run_main()`. The top-level `codex exec-server` command
builds the runtime options from the `codex` arg0 dispatch state and startup flags,
and resolves its HTTP client factory from the effective Codex configuration.
`RemoteEnvironmentConfig::new(...)` also takes the auth provider and HTTP client
factory that remote registration mode should use; the CLI builds the auth
provider from Codex auth state before starting remote mode.
`--proxy-private-ips-via-upstream` (or
`CODEX_EXEC_SERVER_PROXY_PRIVATE_IPS_VIA_UPSTREAM=true`) allows permitted private IP
destinations to use an inherited upstream proxy. If no valid proxy configuration
applies to the request protocol, routing falls back to a direct connection. This
includes unset, malformed, or unsupported proxy settings. Setting
`allow_upstream_proxy=false` also keeps routing direct; loopback always stays local.
Destination policy still applies to every route. Enforcing mandatory upstream routing
would require a separate fail-closed mode. A connection failure after selecting an
upstream proxy is returned as an error, without retrying directly.
## Example session
Initialize:
```json
{"id":1,"method":"initialize","params":{"clientName":"example-client"}}
{"id":1,"result":{"sessionId":"00000000-0000-4000-8000-000000000001","environmentInfo":{"shell":{"name":"bash","path":"/bin/bash"},"cwd":"file:///tmp"}}}
{"method":"initialized","params":{}}
```
Start a process:
```json
{"id":2,"method":"process/start","params":{"processId":"proc-1","argv":["bash","-lc","printf 'ready\\n'; while IFS= read -r line; do printf 'echo:%s\\n' \"$line\"; done"],"cwd":"file:///tmp","env":{"PATH":"/usr/bin:/bin"},"tty":true,"pipeStdin":false,"arg0":null}}
{"id":2,"result":{"processId":"proc-1"}}
{"method":"process/output","params":{"processId":"proc-1","seq":1,"stream":"stdout","chunk":"cmVhZHkK"}}
```
Write to the process:
```json
{"id":3,"method":"process/write","params":{"processId":"proc-1","chunk":"aGVsbG8K"}}
{"id":3,"result":{"status":"accepted"}}
{"method":"process/output","params":{"processId":"proc-1","seq":2,"stream":"stdout","chunk":"ZWNobzpoZWxsbwo="}}
```
Terminate it:
```json
{"id":4,"method":"process/terminate","params":{"processId":"proc-1"}}
{"id":4,"result":{"running":true}}
{"method":"process/exited","params":{"processId":"proc-1","seq":3,"exitCode":0,"sandboxDenied":false}}
{"method":"process/closed","params":{"processId":"proc-1","seq":4}}
```

View File

@@ -0,0 +1,31 @@
#[cfg(unix)]
use std::process::Command;
pub const CODEX_ARG0_EXEC_HELPER_ARG1: &str = "--codex-run-as-arg0-exec-helper";
#[cfg(unix)]
pub fn main() -> ! {
use std::os::unix::process::CommandExt;
let mut args = std::env::args_os();
let _program = args.next();
let _helper_mode = args.next();
let Some(arg0) = args.next() else {
eprintln!("missing arg0 for exec helper");
std::process::exit(1);
};
let Some(program) = args.next() else {
eprintln!("missing program for exec helper");
std::process::exit(1);
};
let error = Command::new(&program).arg0(arg0).args(args).exec();
eprintln!("failed to exec {program:?}: {error}");
std::process::exit(1);
}
#[cfg(not(unix))]
pub fn main() -> ! {
eprintln!("arg0 exec helper is only supported on Unix");
std::process::exit(1);
}

View File

@@ -0,0 +1,521 @@
use std::collections::HashSet;
use std::io;
use codex_exec_server_protocol::CapabilityRootDiscoverRequest;
use codex_exec_server_protocol::CapabilityRootDiscovery;
use codex_exec_server_protocol::CapabilityRootsDiscoverParams;
use codex_exec_server_protocol::CapabilityRootsDiscoverResponse;
use codex_exec_server_protocol::CapabilityTextFile;
use codex_exec_server_protocol::DISCOVERABLE_PLUGIN_MANIFEST_PATHS;
use codex_exec_server_protocol::DiscoveredPluginFiles;
use codex_exec_server_protocol::DiscoveredSkillFiles;
use codex_file_system::ExecutorFileSystem;
use codex_file_system::FileSystemSandboxContext;
use codex_file_system::WalkEntryKind;
use codex_file_system::WalkOptions;
use codex_utils_path_uri::PathUri;
use futures::StreamExt;
use serde::Deserialize;
use serde_json::Value;
pub(crate) const MAX_ROOTS_PER_REQUEST: usize = 128;
const MAX_SCAN_DEPTH: usize = 6;
const MAX_DIRECTORIES_PER_ROOT: usize = 2_000;
const MAX_ENTRIES_PER_ROOT: usize = 20_000;
const MAX_FILE_BYTES: usize = 1024 * 1024;
const MAX_BUNDLE_BYTES_PER_ROOT: usize = 16 * 1024 * 1024;
pub(crate) const MAX_CONCURRENT_ROOTS: usize = 8;
const SKILL_FILE_NAME: &str = "SKILL.md";
const SKILL_METADATA_PATH: &str = "agents/openai.yaml";
const DEFAULT_MCP_CONFIG_PATH: &str = ".mcp.json";
const DEFAULT_APP_CONFIG_PATH: &str = ".app.json";
#[derive(Debug, thiserror::Error)]
pub enum CapabilityDiscoveryError {
#[error("capability root discovery accepts at most {MAX_ROOTS_PER_REQUEST} roots")]
TooManyRoots,
}
/// Discovers and materializes capability manifests using one executor-local filesystem.
///
/// Product parsing and policy intentionally remain with the caller. This operation owns the
/// filesystem-expensive portion: bounded traversal, recognized-file selection, and reads.
#[tracing::instrument(
name = "capability_roots.discover_v1",
skip_all,
fields(root_count = params.roots.len())
)]
pub async fn discover_capability_roots(
file_system: &dyn ExecutorFileSystem,
params: CapabilityRootsDiscoverParams,
) -> Result<CapabilityRootsDiscoverResponse, CapabilityDiscoveryError> {
if params.roots.len() > MAX_ROOTS_PER_REQUEST {
return Err(CapabilityDiscoveryError::TooManyRoots);
}
let roots = futures::stream::iter(params.roots)
.map(|root| discover_root(file_system, root))
.buffered(MAX_CONCURRENT_ROOTS)
.collect()
.await;
Ok(CapabilityRootsDiscoverResponse { roots })
}
pub(crate) async fn discover_root(
file_system: &dyn ExecutorFileSystem,
request: CapabilityRootDiscoverRequest,
) -> CapabilityRootDiscovery {
let CapabilityRootDiscoverRequest { id, path, sandbox } = request;
let sandbox = sandbox.as_ref();
let mut discovery = CapabilityRootDiscovery {
id,
path: path.clone(),
plugin: None,
skills: Vec::new(),
namespace_manifests: Vec::new(),
warnings: Vec::new(),
error: None,
};
if let Some(sandbox) = sandbox
&& let Err(error) = sandbox.validate_file_system_paths_for_current_host()
{
discovery.error = Some(format!("failed to inspect capability root {path}: {error}"));
return discovery;
}
#[cfg(target_os = "windows")]
if sandbox.is_some_and(|context| {
context.should_read_from_sandbox() && !context.windows_sandbox_is_requested()
}) {
discovery.error = Some("filesystem sandbox is unavailable on this executor".to_string());
return discovery;
}
match file_system
.get_metadata(&path, Default::default(), sandbox)
.await
{
Ok(metadata) if metadata.is_directory => {}
Ok(_) => {
discovery.error = Some(format!("capability root {path} is not a directory"));
return discovery;
}
Err(error) => {
discovery.error = Some(format!("failed to inspect capability root {path}: {error}"));
return discovery;
}
}
let walk = match file_system
.walk(
&path,
WalkOptions {
max_depth: MAX_SCAN_DEPTH,
max_directories: MAX_DIRECTORIES_PER_ROOT,
max_entries: MAX_ENTRIES_PER_ROOT,
follow_directory_symlinks: true,
prune_hidden_directories: false,
},
sandbox,
)
.await
{
Ok(walk) => walk,
Err(error) => {
discovery.error = Some(format!("failed to scan capability root {path}: {error}"));
return discovery;
}
};
discovery
.warnings
.extend(walk.errors.into_iter().map(|error| {
format!(
"failed to scan capability path {}: {}",
error.path, error.message
)
}));
if walk.truncated {
discovery.warnings.push(format!(
"capability scan reached its traversal limit (root: {path})"
));
}
let mut skill_paths = Vec::new();
let mut namespace_manifest_paths = Vec::new();
for entry in walk.entries {
if entry.kind != WalkEntryKind::File {
continue;
}
if entry.path.basename().as_deref() == Some(SKILL_FILE_NAME) {
skill_paths.push(entry.path.clone());
}
if is_plugin_manifest_path(&entry.path) {
namespace_manifest_paths.push(entry.path);
}
}
skill_paths.sort_unstable_by_key(PathUri::to_string);
namespace_manifest_paths.sort_unstable_by(|left, right| {
let left_root = plugin_root_for_manifest(left).map(|path| path.to_string());
let right_root = plugin_root_for_manifest(right).map(|path| path.to_string());
left_root
.cmp(&right_root)
.then_with(|| plugin_manifest_priority(left).cmp(&plugin_manifest_priority(right)))
});
let mut budget = BundleBudget::default();
let root_manifest = read_first_plugin_manifest(
file_system,
&path,
sandbox,
&mut budget,
&mut discovery.warnings,
)
.await;
let inherited_manifest = match root_manifest.as_ref() {
Some(manifest) => Some(manifest.clone()),
None => {
read_nearest_ancestor_manifest(
file_system,
&path,
sandbox,
&mut budget,
&mut discovery.warnings,
)
.await
}
};
let mut seen_namespace_roots = HashSet::new();
if let Some(manifest) = inherited_manifest {
if let Some(plugin_root) = plugin_root_for_manifest(&manifest.path) {
seen_namespace_roots.insert(plugin_root);
}
discovery.namespace_manifests.push(manifest);
}
for manifest_path in namespace_manifest_paths {
let Some(plugin_root) = plugin_root_for_manifest(&manifest_path) else {
continue;
};
if !seen_namespace_roots.insert(plugin_root) {
continue;
}
if let Some(manifest) = read_optional_text_file(
file_system,
manifest_path,
sandbox,
&mut budget,
&mut discovery.warnings,
)
.await
{
discovery.namespace_manifests.push(manifest);
}
}
if let Some(manifest) = root_manifest {
let declarations = plugin_declaration_paths(&path, &manifest, &mut discovery.warnings);
let mcp_path = if declarations.mcp_inline {
None
} else {
declarations
.mcp_config
.or_else(|| path.join(DEFAULT_MCP_CONFIG_PATH).ok())
};
let mcp_config = match mcp_path {
Some(path) => {
read_optional_text_file(
file_system,
path,
sandbox,
&mut budget,
&mut discovery.warnings,
)
.await
}
None => None,
};
let apps_path = declarations
.apps_config
.or_else(|| path.join(DEFAULT_APP_CONFIG_PATH).ok());
let apps_config = match apps_path {
Some(path) => {
read_optional_text_file(
file_system,
path,
sandbox,
&mut budget,
&mut discovery.warnings,
)
.await
}
None => None,
};
discovery.plugin = Some(DiscoveredPluginFiles {
manifest,
mcp_config,
apps_config,
});
}
for skill_path in skill_paths {
let Some(instructions) = read_optional_text_file(
file_system,
skill_path.clone(),
sandbox,
&mut budget,
&mut discovery.warnings,
)
.await
else {
continue;
};
let metadata = match skill_path
.parent()
.and_then(|skill_dir| skill_dir.join(SKILL_METADATA_PATH).ok())
{
Some(metadata_path) => {
read_optional_text_file(
file_system,
metadata_path,
sandbox,
&mut budget,
&mut discovery.warnings,
)
.await
}
None => None,
};
discovery.skills.push(DiscoveredSkillFiles {
instructions,
metadata,
});
}
discovery
}
async fn read_first_plugin_manifest(
file_system: &dyn ExecutorFileSystem,
root: &PathUri,
sandbox: Option<&FileSystemSandboxContext>,
budget: &mut BundleBudget,
warnings: &mut Vec<String>,
) -> Option<CapabilityTextFile> {
for relative_path in DISCOVERABLE_PLUGIN_MANIFEST_PATHS {
let Ok(path) = root.join(relative_path) else {
continue;
};
if let Some(manifest) =
read_optional_text_file(file_system, path, sandbox, budget, warnings).await
{
return Some(manifest);
}
}
None
}
async fn read_nearest_ancestor_manifest(
file_system: &dyn ExecutorFileSystem,
root: &PathUri,
sandbox: Option<&FileSystemSandboxContext>,
budget: &mut BundleBudget,
warnings: &mut Vec<String>,
) -> Option<CapabilityTextFile> {
let mut ancestor = root.parent();
while let Some(path) = ancestor {
if let Some(manifest) =
read_first_plugin_manifest(file_system, &path, sandbox, budget, warnings).await
{
return Some(manifest);
}
ancestor = path.parent();
}
None
}
async fn read_optional_text_file(
file_system: &dyn ExecutorFileSystem,
path: PathUri,
sandbox: Option<&FileSystemSandboxContext>,
budget: &mut BundleBudget,
warnings: &mut Vec<String>,
) -> Option<CapabilityTextFile> {
let metadata = match file_system
.get_metadata(&path, Default::default(), sandbox)
.await
{
Ok(metadata) if metadata.is_file => metadata,
Ok(_) => return None,
Err(error) if error.kind() == io::ErrorKind::NotFound => return None,
Err(error) => {
warnings.push(format!("failed to inspect capability file {path}: {error}"));
return None;
}
};
let Ok(size) = usize::try_from(metadata.size) else {
warnings.push(format!("capability file {path} is too large"));
return None;
};
if size > MAX_FILE_BYTES {
warnings.push(format!(
"capability file {path} exceeds the {MAX_FILE_BYTES}-byte limit"
));
return None;
}
if !budget.can_add(size) {
warnings.push(format!(
"capability root bundle exceeds the {MAX_BUNDLE_BYTES_PER_ROOT}-byte limit"
));
return None;
}
let mut stream = match file_system.read_file_stream(&path, sandbox).await {
Ok(stream) => stream,
Err(error) => {
warnings.push(format!("failed to read capability file {path}: {error}"));
return None;
}
};
let mut contents = Vec::with_capacity(size);
while let Some(chunk) = stream.next().await {
let chunk = match chunk {
Ok(chunk) => chunk,
Err(error) => {
warnings.push(format!("failed to read capability file {path}: {error}"));
return None;
}
};
let Some(new_len) = contents.len().checked_add(chunk.len()) else {
warnings.push(format!("capability file {path} exceeded its read limit"));
return None;
};
if new_len > MAX_FILE_BYTES || !budget.can_add(new_len) {
warnings.push(format!("capability file {path} exceeded its read limit"));
return None;
}
contents.extend_from_slice(&chunk);
}
let contents = match String::from_utf8(contents) {
Ok(contents) => contents,
Err(error) => {
warnings.push(format!("capability file {path} is not UTF-8: {error}"));
return None;
}
};
budget.add(contents.len());
Some(CapabilityTextFile { path, contents })
}
fn is_plugin_manifest_path(path: &PathUri) -> bool {
plugin_manifest_priority(path).is_some()
}
fn plugin_manifest_priority(path: &PathUri) -> Option<usize> {
if path.basename().as_deref() != Some("plugin.json") {
return None;
}
let manifest_directory = path.parent()?.basename()?;
DISCOVERABLE_PLUGIN_MANIFEST_PATHS
.iter()
.position(|relative_path| {
relative_path.strip_suffix("/plugin.json") == Some(manifest_directory.as_str())
})
}
fn plugin_root_for_manifest(path: &PathUri) -> Option<PathUri> {
path.parent()?.parent()
}
#[derive(Default)]
struct BundleBudget {
bytes: usize,
}
impl BundleBudget {
fn can_add(&self, bytes: usize) -> bool {
self.bytes
.checked_add(bytes)
.is_some_and(|total| total <= MAX_BUNDLE_BYTES_PER_ROOT)
}
fn add(&mut self, bytes: usize) {
self.bytes += bytes;
}
}
#[derive(Default)]
struct PluginDeclarationPaths {
mcp_config: Option<PathUri>,
mcp_inline: bool,
apps_config: Option<PathUri>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawPluginDeclarations {
#[serde(default)]
mcp_servers: Option<Value>,
#[serde(default)]
apps: Option<Value>,
}
fn plugin_declaration_paths(
root: &PathUri,
manifest: &CapabilityTextFile,
warnings: &mut Vec<String>,
) -> PluginDeclarationPaths {
let declarations = match serde_json::from_str::<RawPluginDeclarations>(&manifest.contents) {
Ok(declarations) => declarations,
Err(_) => return PluginDeclarationPaths::default(),
};
PluginDeclarationPaths {
mcp_config: declarations.mcp_servers.as_ref().and_then(|value| {
declared_file_path(root, "mcpServers", value, &manifest.path, warnings)
}),
mcp_inline: declarations
.mcp_servers
.as_ref()
.is_some_and(Value::is_object),
apps_config: declarations
.apps
.as_ref()
.and_then(|value| declared_file_path(root, "apps", value, &manifest.path, warnings)),
}
}
fn declared_file_path(
root: &PathUri,
field: &str,
value: &Value,
manifest_path: &PathUri,
warnings: &mut Vec<String>,
) -> Option<PathUri> {
let Value::String(path) = value else {
return None;
};
let Some(relative_path) = path.strip_prefix("./") else {
warnings.push(format!(
"ignoring {field} in {manifest_path}: path must start with `./`"
));
return None;
};
if relative_path.is_empty()
|| relative_path
.split(['/', '\\'])
.any(|component| component == "..")
{
warnings.push(format!(
"ignoring {field} in {manifest_path}: path must remain below the capability root"
));
return None;
}
match root.join(relative_path) {
Ok(path) if path.starts_with(root) => Some(path),
Ok(_) | Err(_) => {
warnings.push(format!(
"ignoring {field} in {manifest_path}: path must remain below the capability root"
));
None
}
}
}

View File

@@ -0,0 +1,309 @@
//! Caches root discovery by captured executor/session, root, and sandbox.
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Weak;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use codex_protocol::capabilities::CapabilityRootLocation;
use codex_protocol::capabilities::SelectedCapabilityRoot;
use tokio::sync::Mutex;
use crate::CapabilityRootDiscoverRequest;
use crate::CapabilityRootDiscovery;
use crate::CapabilityRootsDiscoverParams;
use crate::Environment;
use crate::ExecutorCapabilityDiscoverySnapshot;
use crate::FileSystemSandboxContext;
use crate::ResolvedSelectedCapabilityRoot;
/// Thread-scoped cache shared by capability consumers using the high-level executor API.
///
/// A single miss batches every requested root by environment. Successful discoveries and
/// permanent failures remain cached by executor/session, root, and sandbox; transient failures are retried on the
/// next request. Recovery is reported so dependent MCP projections can be invalidated.
#[derive(Default)]
pub struct ExecutorCapabilityDiscoveryCache {
entries: Mutex<Vec<CachedRoot>>,
recovered_discovery: AtomicBool,
}
impl std::fmt::Debug for ExecutorCapabilityDiscoveryCache {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("ExecutorCapabilityDiscoveryCache")
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug)]
struct RootDiscoveryKey {
selected_root: SelectedCapabilityRoot,
sandbox: Option<FileSystemSandboxContext>,
environment: Weak<Environment>,
session_id: Option<String>,
}
impl PartialEq for RootDiscoveryKey {
fn eq(&self, other: &Self) -> bool {
self.selected_root == other.selected_root
&& self.sandbox == other.sandbox
&& self.environment.ptr_eq(&other.environment)
&& self.session_id == other.session_id
}
}
#[derive(Clone)]
struct RootDiscoveryRequest {
key: RootDiscoveryKey,
environment: Result<Arc<Environment>, String>,
}
struct CachedRoot {
key: RootDiscoveryKey,
result: Result<Arc<CapabilityRootDiscovery>, String>,
// Preserve transport classification after the public snapshot reduces errors to strings.
retryable: bool,
}
impl ExecutorCapabilityDiscoveryCache {
/// Reports whether a previously failed root has recovered since the last observation.
pub fn take_recovered_discovery(&self) -> bool {
self.recovered_discovery.swap(false, Ordering::AcqRel)
}
/// Returns discoveries in root order using only the captured environment handles.
#[tracing::instrument(
name = "capability_roots.discovery_cache.resolve",
skip_all,
fields(root_count = roots.len())
)]
pub async fn discover(
&self,
roots: &[ResolvedSelectedCapabilityRoot],
sandbox_contexts: &HashMap<String, FileSystemSandboxContext>,
) -> Vec<Result<Arc<CapabilityRootDiscovery>, String>> {
let environments = roots
.iter()
.map(|root| {
let CapabilityRootLocation::Environment { environment_id, .. } =
&root.selected_root().location;
(environment_id.clone(), Arc::clone(root.environment()))
})
.collect::<HashMap<_, _>>();
// Resolve a session once per captured environment, before matching cached results.
let bindings = futures::future::join_all(environments.into_iter().map(
|(id, environment)| async move {
let session = environment
.executor_session_id()
.await
.map_err(|error| error.to_string());
(id, (environment, session))
},
))
.await
.into_iter()
.collect::<HashMap<_, _>>();
let requests = roots
.iter()
.map(|root| {
let selected_root = root.selected_root();
let CapabilityRootLocation::Environment { environment_id, .. } =
&selected_root.location;
let (environment, session) = &bindings[environment_id];
RootDiscoveryRequest {
key: RootDiscoveryKey {
selected_root: selected_root.clone(),
sandbox: sandbox_contexts.get(environment_id).cloned(),
environment: Arc::downgrade(environment),
session_id: session.as_ref().ok().cloned().flatten(),
},
environment: session
.as_ref()
.map(|_| Arc::clone(environment))
.map_err(Clone::clone),
}
})
.collect::<Vec<_>>();
let keys = requests
.iter()
.map(|request| request.key.clone())
.collect::<Vec<_>>();
let mut results = {
let entries = self.entries.lock().await;
requests
.iter()
.map(|request| {
request.environment.as_ref().ok().and_then(|_| {
entries
.iter()
.find(|cached| cached.key == request.key && !cached.retryable)
.map(|cached| cached.result.clone())
})
})
.collect::<Vec<_>>()
};
let missing = requests
.into_iter()
.zip(&results)
.filter_map(|(request, result)| result.is_none().then_some(request))
.collect();
let discovered = self.discover_missing(missing).await;
let mut entries = self.entries.lock().await;
for discovered_root in discovered {
// Reuse a concurrent success only for the same captured binding.
let resolved = entries
.iter()
.find(|cached| cached.key == discovered_root.key && cached.result.is_ok())
.map_or(&discovered_root.result, |cached| &cached.result);
for (key, result) in keys.iter().zip(&mut results) {
if *key == discovered_root.key && result.is_none() {
*result = Some(resolved.clone());
}
}
if let Some(cached) = entries
.iter_mut()
.find(|cached| cached.key.selected_root == discovered_root.key.selected_root)
{
if cached.key != discovered_root.key || cached.result.is_err() {
if cached.result.is_err() && discovered_root.result.is_ok() {
self.recovered_discovery.store(true, Ordering::Release);
}
*cached = discovered_root;
}
} else {
entries.push(discovered_root);
}
}
keys.into_iter()
.zip(results)
.map(|(key, result)| {
result.unwrap_or_else(|| {
Err(format!(
"selected capability root `{}` was not discovered",
key.selected_root.id
))
})
})
.collect()
}
/// Freezes discoveries and sandbox contexts for the captured roots.
pub async fn snapshot(
&self,
roots: &[ResolvedSelectedCapabilityRoot],
sandbox_contexts: &HashMap<String, FileSystemSandboxContext>,
) -> ExecutorCapabilityDiscoverySnapshot {
let selected_roots = roots
.iter()
.map(|root| root.selected_root().clone())
.collect::<Vec<_>>();
let results = self.discover(roots, sandbox_contexts).await;
ExecutorCapabilityDiscoverySnapshot::new(&selected_roots, results, sandbox_contexts.clone())
}
async fn discover_missing(&self, missing: Vec<RootDiscoveryRequest>) -> Vec<CachedRoot> {
let mut grouped = BTreeMap::<String, Vec<RootDiscoveryRequest>>::new();
for selected_root in missing {
let CapabilityRootLocation::Environment { environment_id, .. } =
&selected_root.key.selected_root.location;
grouped
.entry(environment_id.clone())
.or_default()
.push(selected_root);
}
let batches = grouped.into_values().flat_map(|roots| {
roots
.chunks(crate::capability_discovery::MAX_ROOTS_PER_REQUEST)
.map(<[RootDiscoveryRequest]>::to_vec)
.collect::<Vec<_>>()
});
let discoveries = futures::future::join_all(batches.map(|selected_roots| async move {
let environment = match &selected_roots[0].environment {
Ok(environment) => Arc::clone(environment),
Err(error) => {
let error = error.clone();
return selected_roots
.into_iter()
.map(|request| CachedRoot {
key: request.key,
result: Err(error.clone()),
retryable: true,
})
.collect::<Vec<_>>();
}
};
let params = CapabilityRootsDiscoverParams {
roots: selected_roots
.iter()
.map(|request| {
let selected_root = &request.key.selected_root;
let CapabilityRootLocation::Environment { path, .. } =
&selected_root.location;
CapabilityRootDiscoverRequest {
id: selected_root.id.clone(),
path: path.clone(),
sandbox: request.key.sandbox.clone(),
}
})
.collect(),
};
let response = match environment.discover_capability_roots(params).await {
Ok(response) => response,
Err(error) => {
let retryable = crate::client::can_retry_connection_attempt(&error);
let error = error.to_string();
return selected_roots
.into_iter()
.map(|request| CachedRoot {
key: request.key,
result: Err(error.clone()),
retryable,
})
.collect();
}
};
if response.roots.len() != selected_roots.len() {
let error = format!(
"exec-server returned {} capability roots for {} requests",
response.roots.len(),
selected_roots.len()
);
return selected_roots
.into_iter()
.map(|request| CachedRoot {
key: request.key,
result: Err(error.clone()),
retryable: false,
})
.collect();
}
selected_roots
.into_iter()
.zip(response.roots)
.map(|(request, discovery)| {
let selected_root = &request.key.selected_root;
let CapabilityRootLocation::Environment { path, .. } = &selected_root.location;
let result = if discovery.id == selected_root.id && discovery.path == *path {
Ok(Arc::new(discovery))
} else {
Err(format!(
"exec-server returned mismatched capability root `{}` at {}",
discovery.id, discovery.path
))
};
CachedRoot {
key: request.key,
result,
retryable: false,
}
})
.collect()
}))
.await;
discoveries.into_iter().flatten().collect()
}
}

View File

@@ -0,0 +1,121 @@
//! Bounded lazy V2 responses, cached per environment, executor session, cwd, and sandbox.
//! Reports recovery from retryable failures so Core can refresh dependent MCP projections.
use std::sync::Arc;
use std::sync::Weak;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use tokio::sync::Mutex;
use tokio::sync::OnceCell;
use crate::DiscoverV2CapabilitiesRequest;
use crate::DiscoverV2CapabilitiesResponse;
use crate::Environment;
const MIN_CACHED_DISCOVERY_CONTEXTS: usize = 16;
/// Shared by turn and idle consumers; Core replaces its current cache at each turn start.
#[derive(Default)]
pub struct ExecutorCapabilityDiscoveryV2Cache {
entries: Mutex<Vec<Arc<CachedEnvironmentDiscovery>>>,
capacity: AtomicUsize,
recovered_discovery: AtomicBool,
}
struct CachedEnvironmentDiscovery {
request: DiscoverV2CapabilitiesRequest,
environment: Weak<Environment>,
session_id: Option<String>,
response: OnceCell<Result<Arc<DiscoverV2CapabilitiesResponse>, String>>,
retryable: Arc<AtomicBool>,
}
impl ExecutorCapabilityDiscoveryV2Cache {
/// Fits a complete environment selection; never shrinks until the cache is replaced.
pub fn ensure_capacity(&self, minimum: usize) {
self.capacity.fetch_max(minimum, Ordering::Relaxed);
}
/// Reports whether a failed discovery recovered since the last observation.
pub fn take_recovered_discovery(&self) -> bool {
self.recovered_discovery.swap(false, Ordering::AcqRel)
}
/// Reuses successes and non-retryable failures using V1's error classification.
/// Retryable failures and cancelled loads leave the cell available for retry.
pub async fn discover(
&self,
environment_id: &str,
environment: &Arc<Environment>,
request: DiscoverV2CapabilitiesRequest,
) -> Result<Arc<DiscoverV2CapabilitiesResponse>, String> {
// Resolve startup/replacement before lookup; a resumed session keeps its cache entries.
let session_id = environment.executor_session_id().await.map_err(|_| {
tracing::warn!(environment_id, "executor discovery V2 session unavailable");
"executor discovery V2 failed".to_string()
})?;
let entry = {
let mut entries = self.entries.lock().await;
let environment = Arc::downgrade(environment);
if let Some(entry) = entries.iter().find(|entry| {
entry.environment.ptr_eq(&environment)
&& entry.session_id == session_id
&& entry.request == request
}) {
Arc::clone(entry)
} else {
// Recovery belongs to the environment/request, not one executor session.
let retryable = entries
.iter()
.find(|entry| {
entry.environment.ptr_eq(&environment) && entry.request == request
})
.map(|entry| Arc::clone(&entry.retryable))
.unwrap_or_default();
let entry = Arc::new(CachedEnvironmentDiscovery {
request: request.clone(),
environment,
session_id,
response: OnceCell::new(),
retryable,
});
let capacity = self
.capacity
.load(Ordering::Relaxed)
.max(MIN_CACHED_DISCOVERY_CONTEXTS);
if entries.len() == capacity {
// Evict the oldest context (FIFO). In-flight requests retain their own Arc.
entries.remove(0);
}
entries.push(Arc::clone(&entry));
entry
}
};
let response = entry
.response
.get_or_try_init(|| async {
match environment.discover_capabilities_v2(request).await {
Ok(response) => Ok(Ok(Arc::new(response))),
Err(error) => {
let retryable = crate::client::can_retry_connection_attempt(&error);
tracing::warn!(environment_id, "executor discovery V2 failed");
let error = "executor discovery V2 failed".to_string();
if retryable {
entry.retryable.store(true, Ordering::Release);
Err(error)
} else {
Ok(Err(error))
}
}
}
})
.await?
.clone();
if response.is_ok() && entry.retryable.swap(false, Ordering::AcqRel) {
self.recovered_discovery.store(true, Ordering::Release);
}
response
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,267 @@
use std::sync::Arc;
use axum::extract::ws::WebSocket;
use futures::lock::Mutex;
use tokio::sync::OnceCell;
use tokio::sync::OwnedSemaphorePermit;
use tokio::sync::Semaphore;
use tokio::sync::mpsc;
use tokio::sync::watch;
use super::ConnectionStatus;
use super::ExecServerClient;
use super::Inner;
use super::LazyRemoteExecServerClient;
use crate::EnvironmentConnectionState;
use crate::ExecServerClientConnectOptions;
use crate::ExecServerError;
use crate::client_transport::ExecServerReconnectStrategy;
use crate::client_transport::ReconnectAttempt;
use crate::connection::JsonRpcConnection;
use codex_http_client::HttpClientFactory;
struct AcceptedReplacement {
connection: JsonRpcConnection,
permit: OwnedSemaphorePermit,
}
struct AcceptedConnectionSourceInner {
replacements_tx: mpsc::UnboundedSender<AcceptedReplacement>,
replacements_rx: Mutex<mpsc::UnboundedReceiver<AcceptedReplacement>>,
replacement_slots: Arc<Semaphore>,
}
/// Receives authenticated connections supplied by an embedding host.
///
/// The source owns serialization and cancellation cleanup for replacement
/// handoffs. The reconnect loop only asks it for the next connection.
#[derive(Clone)]
pub(crate) struct AcceptedConnectionSource {
inner: Arc<AcceptedConnectionSourceInner>,
options: ExecServerClientConnectOptions,
}
struct AcceptedReplacementSubmission {
source: AcceptedConnectionSource,
permit: OwnedSemaphorePermit,
}
impl AcceptedConnectionSource {
fn new(options: ExecServerClientConnectOptions) -> Self {
let (replacements_tx, replacements_rx) = mpsc::unbounded_channel();
Self {
inner: Arc::new(AcceptedConnectionSourceInner {
replacements_tx,
replacements_rx: Mutex::new(replacements_rx),
replacement_slots: Arc::new(Semaphore::new(1)),
}),
options,
}
}
fn begin_replacement(&self) -> Result<AcceptedReplacementSubmission, ExecServerError> {
let permit = Arc::clone(&self.inner.replacement_slots)
.try_acquire_owned()
.map_err(|_| {
ExecServerError::Protocol(
"an accepted exec-server replacement is already in progress".to_string(),
)
})?;
Ok(AcceptedReplacementSubmission {
source: self.clone(),
permit,
})
}
pub(crate) async fn next_connection(
&self,
session_id: &str,
) -> Result<ReconnectAttempt, ExecServerError> {
let replacement = self
.inner
.replacements_rx
.lock()
.await
.recv()
.await
.ok_or_else(|| {
ExecServerError::Disconnected(
"accepted exec-server replacement channel closed".to_string(),
)
})?;
let mut options = self.options.clone();
options.resume_session_id = Some(session_id.to_string());
Ok(ReconnectAttempt::with_attempt_permit(
replacement.connection,
options,
replacement.permit,
))
}
}
impl AcceptedReplacementSubmission {
fn submit(self, connection: JsonRpcConnection) -> Result<(), ExecServerError> {
self.source
.inner
.replacements_tx
.send(AcceptedReplacement {
connection,
permit: self.permit,
})
.map_err(|_| {
ExecServerError::Disconnected(
"accepted exec-server connection is no longer awaiting replacements"
.to_string(),
)
})
}
}
impl ExecServerClient {
/// Initializes an exec-server client over a WebSocket accepted by an Axum handler.
///
/// The caller owns accepting and authenticating replacement WebSockets.
pub(crate) async fn connect_accepted_websocket(
websocket: WebSocket,
options: ExecServerClientConnectOptions,
) -> Result<Self, ExecServerError> {
if options.resume_session_id.is_some() {
return Err(ExecServerError::Protocol(
"accepted exec-server initial connection cannot resume a session".to_string(),
));
}
let connection_source = AcceptedConnectionSource::new(options.clone());
Self::connect_with_recovery(
JsonRpcConnection::from_axum_websocket(
websocket,
"accepted exec-server websocket".to_string(),
),
options,
Some(ExecServerReconnectStrategy::Accepted(connection_source)),
)
.await
}
/// Supplies an authenticated replacement WebSocket for this accepted client.
///
/// Retires the old transport before resuming the saved session. Returns
/// after handoff; recovery continues asynchronously.
pub(crate) async fn replace_accepted_websocket(
&self,
websocket: WebSocket,
) -> Result<(), ExecServerError> {
self.inner
.accept_replacement_connection(JsonRpcConnection::from_axum_websocket(
websocket,
"accepted exec-server replacement websocket".to_string(),
))
.await
}
}
impl Inner {
/// Hands a replacement connection from the host to the existing accepted client.
///
/// This method coordinates the handoff in this order:
///
/// 1. Verify that this client uses the accepted connection source.
/// 2. Reserve the source so concurrent handoffs are rejected.
/// 3. If the old RPC transport is still connected, move the client into
/// recovery and close that transport before attaching the same session to
/// the replacement.
/// 4. Queue the raw connection for the recovery task. That task creates the
/// new RPC client, runs the initialize/resume handshake with the saved
/// session ID, and recovers the existing processes.
async fn accept_replacement_connection(
self: &Arc<Self>,
connection: JsonRpcConnection,
) -> Result<(), ExecServerError> {
if self.session_id.get().is_none() {
return Err(ExecServerError::Protocol(
"accepted exec-server connection is missing its session ID".to_string(),
));
}
let Some(ExecServerReconnectStrategy::Accepted(connection_source)) =
&self.reconnect_strategy
else {
return Err(ExecServerError::Protocol(
"only an accepted exec-server connection can be replaced directly".to_string(),
));
};
let (current_rpc_client, replacement_submission) = {
let connection = self
.connection
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let current_rpc_client = match &connection.status {
ConnectionStatus::Failed(message) => {
return Err(message.clone().into());
}
ConnectionStatus::Connected(rpc_client) => Some(Arc::clone(rpc_client)),
ConnectionStatus::Recovering => None,
};
let replacement_submission = connection_source.begin_replacement()?;
(current_rpc_client, replacement_submission)
};
if let Some(current_rpc_client) = current_rpc_client {
self.request_recovery(
Arc::clone(&current_rpc_client),
"exec-server connection replaced".to_string(),
);
current_rpc_client.close_transport().await;
}
// Synchronize the enqueue with terminal recovery. Recovery can time out
// while the handoff is waiting for the old transport to close; in that
// case the host must not receive success for a socket that no task will
// consume. Holding the connection lock through the synchronous send
// makes either the failure or the enqueue win the race unambiguously.
let connection_state = self
.connection
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let ConnectionStatus::Failed(message) = &connection_state.status {
return Err(message.clone().into());
}
replacement_submission.submit(connection)
}
}
#[cfg(test)]
#[path = "accepted_tests.rs"]
mod tests;
impl LazyRemoteExecServerClient {
pub(crate) fn from_connected(
client: ExecServerClient,
http_client_factory: HttpClientFactory,
) -> Self {
let environment_connection_state_tx =
watch::channel(EnvironmentConnectionState::Connected).0;
client.attach_environment_connection_state(environment_connection_state_tx.clone());
Self {
transport_params: None,
http_client_factory,
recovery_policy: super::RecoveryPolicy::Wait,
startup: std::sync::Arc::new(super::ConnectionAttempt {
result: OnceCell::new_with(Some(Ok(client.clone()))),
..Default::default()
}),
current_client: std::sync::Arc::new(std::sync::Mutex::new(Some(client))),
reconnect: std::sync::Arc::new(std::sync::Mutex::new(None)),
refresh_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
environment_connection_state_tx,
connection_observer: Default::default(),
}
}
pub(crate) async fn replace_accepted_websocket(
&self,
websocket: WebSocket,
) -> Result<(), ExecServerError> {
self.get()
.await?
.replace_accepted_websocket(websocket)
.await
}
}

View File

@@ -0,0 +1,34 @@
use tokio::sync::oneshot;
use super::AcceptedConnectionSource;
use crate::ExecServerClientConnectOptions;
#[tokio::test]
async fn replacement_claim_is_released_when_handoff_is_cancelled() {
let source = AcceptedConnectionSource::new(ExecServerClientConnectOptions::default());
let (claimed_tx, claimed_rx) = oneshot::channel();
let (_release_tx, release_rx) = oneshot::channel::<()>();
let handoff = tokio::spawn({
let source = source.clone();
async move {
let _submission = source
.begin_replacement()
.expect("the first replacement should claim the handoff");
claimed_tx
.send(())
.expect("the test should wait for the claim");
let _ = release_rx.await;
}
});
claimed_rx.await.expect("the handoff should be claimed");
assert!(source.begin_replacement().is_err());
handoff.abort();
let _ = handoff.await;
source
.begin_replacement()
.expect("a new replacement should be accepted after cancellation");
}

View File

@@ -0,0 +1,72 @@
//! Preserve policy denials and registry auth errors through terminal connection state.
use codex_http_client::NetworkPolicyDenied;
use codex_http_client::RouteAwareRequestError;
use super::ExecServerError;
#[derive(Clone, thiserror::Error, Debug)]
pub(super) enum ConnectionFailure {
#[error("{0}")]
Disconnected(String),
#[error(transparent)]
Policy(NetworkPolicyDenied),
#[error("environment registry authentication error: {0}")]
RegistryAuth(String),
}
impl From<ConnectionFailure> for ExecServerError {
fn from(failure: ConnectionFailure) -> Self {
match failure {
ConnectionFailure::Disconnected(message) => Self::Disconnected(message),
ConnectionFailure::Policy(denial) => Self::ApplicationNetworkPolicy(denial),
ConnectionFailure::RegistryAuth(message) => Self::EnvironmentRegistryAuth(message),
}
}
}
impl ExecServerError {
pub(crate) fn application_network_policy_denial(&self) -> Option<NetworkPolicyDenied> {
match self {
Self::ConnectionAttempt(error) => error.application_network_policy_denial(),
Self::ApplicationNetworkPolicy(denial)
| Self::EnvironmentRegistryRequest(RouteAwareRequestError::Policy(denial)) => {
Some(*denial)
}
Self::WebSocketConnect { source, .. } => {
codex_websocket_client::network_policy_denial(source)
}
Self::Spawn(_)
| Self::WebSocketConnectTimeout { .. }
| Self::WebSocketConfiguration(_)
| Self::InitializeTimedOut { .. }
| Self::RpcTimedOut { .. }
| Self::Closed
| Self::Disconnected(_)
| Self::ProvisioningFailed(_)
| Self::Json(_)
| Self::HttpRequest(_)
| Self::RequestNotSent(_)
| Self::Protocol(_)
| Self::AuthenticationRequired(_)
| Self::ProvisioningModeConflict { .. }
| Self::Server { .. }
| Self::EnvironmentRegistryHttp { .. }
| Self::EnvironmentRegistryConfig(_)
| Self::EnvironmentRegistryAuth(_)
| Self::EnvironmentRegistryRequest(
RouteAwareRequestError::Request(_)
| RouteAwareRequestError::Route(_)
| RouteAwareRequestError::Build(_)
| RouteAwareRequestError::UnsupportedRedirectScheme(_)
| RouteAwareRequestError::TooManyRedirects
| RouteAwareRequestError::Timeout,
) => None,
}
}
}
pub(crate) fn can_retry_connection_attempt(error: &ExecServerError) -> bool {
error.application_network_policy_denial().is_some()
|| super::recovery::is_retryable_recovery_error(error)
}

View File

@@ -0,0 +1,26 @@
//! HTTP client capability implementations shared by local and remote environments.
//!
//! This module is the facade for the environment-owned [`crate::HttpClient`]
//! capability:
//! - [`RouteAwareHttpClient`] executes requests through the shared transport
//! - [`ExecServerClient`] forwards requests over the JSON-RPC transport
//! - [`HttpResponseBodyStream`] presents buffered local bodies and streamed
//! remote `http/request/bodyDelta` notifications through one byte-stream API
//!
//! Runtime split:
//! - orchestrator process: holds an `Arc<dyn HttpClient>` and chooses local or
//! remote execution
//! - remote runtime: serves the `http/request` RPC and runs the concrete local
//! HTTP request there when the orchestrator uses [`ExecServerClient`]
#[path = "http_response_body_stream.rs"]
pub(crate) mod response_body_stream;
#[path = "route_aware_http_client.rs"]
mod route_aware_http_client;
#[path = "rpc_http_client.rs"]
mod rpc_http_client;
pub use response_body_stream::HttpResponseBodyStream;
pub(crate) use route_aware_http_client::PendingRouteAwareHttpBodyStream;
pub use route_aware_http_client::RouteAwareHttpClient;
pub(crate) use route_aware_http_client::RouteAwareHttpRequestRunner;

View File

@@ -0,0 +1,468 @@
//! Shared HTTP response-body stream plumbing for local and remote execution.
//!
//! This module owns the byte-stream type exposed by the `HttpClient`
//! capability plus the remote-side routing table used to turn
//! `http/request/bodyDelta` notifications back into per-request streams.
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use bytes::Bytes;
use codex_http_client::HttpError;
use codex_http_client::HttpResponse;
use futures::StreamExt;
use serde_json::Value;
use serde_json::from_value;
use tokio::runtime::Handle;
use tokio::sync::OwnedSemaphorePermit;
use tokio::sync::mpsc;
use tokio::sync::mpsc::error::TrySendError;
use tokio_util::sync::CancellationToken;
use tracing::debug;
use crate::client::ExecServerError;
use crate::client::Inner;
use crate::protocol::HTTP_REQUEST_BODY_DELTA_METHOD;
use crate::protocol::HttpRequestBodyDeltaNotification;
use crate::protocol::MAX_HTTP_BODY_DELTA_BYTES;
use crate::rpc::RpcNotificationSender;
pub(crate) const MAX_QUEUED_HTTP_BODY_BYTES: usize = 16 * 1024 * 1024;
const MAX_ENCODED_HTTP_BODY_DELTA_BYTES: usize = MAX_HTTP_BODY_DELTA_BYTES.div_ceil(3) * 4;
pub(crate) struct QueuedHttpBodyDelta {
notification: HttpRequestBodyDeltaNotification,
_byte_permit: Option<OwnedSemaphorePermit>,
}
impl QueuedHttpBodyDelta {
pub(crate) fn new(
notification: HttpRequestBodyDeltaNotification,
byte_permit: Option<OwnedSemaphorePermit>,
) -> Self {
Self {
notification,
_byte_permit: byte_permit,
}
}
}
pub(super) struct HttpBodyStreamRegistration {
inner: Arc<Inner>,
request_id: String,
active: bool,
}
enum HttpResponseBodyStreamInner {
Local {
body: Pin<Box<dyn futures::Stream<Item = Result<Bytes, HttpError>> + Send>>,
},
Remote {
inner: Arc<Inner>,
request_id: String,
next_seq: u64,
rx: mpsc::Receiver<QueuedHttpBodyDelta>,
pending_eof: bool,
closed: bool,
},
}
/// Request-scoped stream of body chunks for an HTTP response.
///
/// The initial `http/request` call returns status and headers. This stream then
/// receives the ordered `http/request/bodyDelta` notifications for that request
/// id until EOF or a terminal error.
pub struct HttpResponseBodyStream {
inner: HttpResponseBodyStreamInner,
cancellation: Option<CancellationToken>,
}
impl HttpResponseBodyStream {
/// Creates an in-memory response stream from pre-buffered chunks.
///
/// This is useful for [`crate::HttpClient`] implementations that already
/// own the response bytes, including lightweight test clients.
#[doc(hidden)]
pub fn from_chunks(chunks: Vec<Vec<u8>>) -> Self {
let body = futures::stream::iter(
chunks
.into_iter()
.map(|chunk| Ok::<Bytes, HttpError>(chunk.into())),
);
Self {
inner: HttpResponseBodyStreamInner::Local {
body: Box::pin(body),
},
cancellation: None,
}
}
pub(super) fn local(response: HttpResponse) -> Self {
Self {
inner: HttpResponseBodyStreamInner::Local {
body: Box::pin(response.bytes_stream()),
},
cancellation: None,
}
}
pub(super) fn remote(
inner: Arc<Inner>,
request_id: String,
rx: mpsc::Receiver<QueuedHttpBodyDelta>,
) -> Self {
Self {
inner: HttpResponseBodyStreamInner::Remote {
inner,
request_id,
next_seq: 1,
rx,
pending_eof: false,
closed: false,
},
cancellation: None,
}
}
/// Ends this stream when its owning request authority is revoked.
pub fn cancel_on(mut self, cancellation: CancellationToken) -> Self {
self.cancellation = Some(cancellation);
self
}
/// Receives the next response-body chunk.
///
/// Returns `Ok(None)` at EOF and converts sequence gaps or stream-side
/// stream errors into protocol errors.
pub async fn recv(&mut self) -> Result<Option<Vec<u8>>, ExecServerError> {
let Some(cancellation) = self.cancellation.clone() else {
return self.recv_inner().await;
};
tokio::select! {
biased;
() = cancellation.cancelled() => Ok(None),
result = self.recv_inner() => result,
}
}
async fn recv_inner(&mut self) -> Result<Option<Vec<u8>>, ExecServerError> {
match &mut self.inner {
HttpResponseBodyStreamInner::Local { body } => match body.next().await {
Some(chunk) => match chunk {
Ok(bytes) => Ok(Some(bytes.to_vec())),
Err(error) => Err(ExecServerError::HttpRequest(error.to_string())),
},
None => Ok(None),
},
HttpResponseBodyStreamInner::Remote {
inner,
request_id,
next_seq,
rx,
pending_eof,
closed,
} => {
if *pending_eof {
*pending_eof = false;
finish_remote_stream(inner, request_id, closed).await;
return Ok(None);
}
let Some(QueuedHttpBodyDelta {
notification: delta,
..
}) = rx.recv().await
else {
finish_remote_stream(inner, request_id, closed).await;
if let Some(error) = inner.take_http_body_stream_failure(request_id).await {
return Err(ExecServerError::Protocol(format!(
"http response stream `{request_id}` failed: {error}",
)));
}
return Ok(None);
};
if delta.seq != *next_seq {
finish_remote_stream(inner, request_id, closed).await;
return Err(ExecServerError::Protocol(format!(
"http response stream `{request_id}` received seq {}, expected {}",
delta.seq, *next_seq
)));
}
*next_seq += 1;
let chunk = delta.delta.into_inner();
if let Some(error) = delta.error {
finish_remote_stream(inner, request_id, closed).await;
return Err(ExecServerError::Protocol(format!(
"http response stream `{request_id}` failed: {error}",
)));
}
if delta.done {
finish_remote_stream(inner, request_id, closed).await;
if chunk.is_empty() {
return Ok(None);
}
*pending_eof = true;
}
Ok(Some(chunk))
}
}
}
}
impl Drop for HttpResponseBodyStream {
/// Schedules stream-route removal if the consumer drops before EOF.
fn drop(&mut self) {
if let HttpResponseBodyStreamInner::Remote {
inner,
request_id,
closed,
..
} = &mut self.inner
{
if *closed {
return;
}
*closed = true;
spawn_remove_http_body_stream(Arc::clone(inner), request_id.clone());
}
}
}
impl HttpBodyStreamRegistration {
pub(super) fn new(inner: Arc<Inner>, request_id: String) -> Self {
Self {
inner,
request_id,
active: true,
}
}
pub(super) fn disarm(&mut self) {
self.active = false;
}
}
impl Drop for HttpBodyStreamRegistration {
/// Removes the route if the stream request future is cancelled before headers return.
fn drop(&mut self) {
if self.active {
spawn_remove_http_body_stream(Arc::clone(&self.inner), self.request_id.clone());
}
}
}
async fn finish_remote_stream(inner: &Arc<Inner>, request_id: &str, closed: &mut bool) {
if *closed {
return;
}
*closed = true;
inner.remove_http_body_stream(request_id).await;
}
/// Schedules HTTP body route removal from synchronous drop paths.
fn spawn_remove_http_body_stream(inner: Arc<Inner>, request_id: String) {
if let Ok(handle) = Handle::try_current() {
handle.spawn(async move {
inner.remove_http_body_stream(&request_id).await;
});
}
}
pub(super) async fn send_body_delta(
notifications: &RpcNotificationSender,
delta: HttpRequestBodyDeltaNotification,
) -> bool {
notifications
.notify(HTTP_REQUEST_BODY_DELTA_METHOD, &delta)
.await
.is_ok()
}
impl Inner {
/// Routes one streamed HTTP body notification into its request-local receiver.
pub(crate) async fn handle_http_body_delta_notification(
&self,
params: Option<Value>,
) -> Result<(), ExecServerError> {
let params = params.unwrap_or(Value::Null);
if params
.get("deltaBase64")
.and_then(Value::as_str)
.is_some_and(|delta| delta.len() > MAX_ENCODED_HTTP_BODY_DELTA_BYTES)
{
return Err(ExecServerError::Protocol(format!(
"http response body delta exceeds {MAX_HTTP_BODY_DELTA_BYTES} bytes"
)));
}
let params: HttpRequestBodyDeltaNotification = from_value(params)?;
if params.delta.0.len() > MAX_HTTP_BODY_DELTA_BYTES {
return Err(ExecServerError::Protocol(format!(
"http response body delta exceeds {MAX_HTTP_BODY_DELTA_BYTES} bytes"
)));
}
// Unknown request ids are ignored intentionally: a stream may have already
// reached EOF and released its route.
if let Some(tx) = self
.http_body_streams
.load()
.get(&params.request_id)
.cloned()
{
let request_id = params.request_id.clone();
let terminal_delta = params.done || params.error.is_some();
let queued_bytes = params
.delta
.0
.len()
.saturating_add(params.error.as_deref().map_or(0, str::len));
let byte_permit = if queued_bytes == 0 {
None
} else {
u32::try_from(queued_bytes).ok().and_then(|queued_bytes| {
Arc::clone(&self.http_body_stream_byte_budget)
.try_acquire_many_owned(queued_bytes)
.ok()
})
};
if queued_bytes > 0 && byte_permit.is_none() {
self.record_http_body_stream_failure(
&request_id,
format!("queued body deltas exceed {MAX_QUEUED_HTTP_BODY_BYTES} bytes"),
)
.await;
self.remove_http_body_stream(&request_id).await;
debug!(
"closing http response stream `{request_id}` after exhausting the queued byte budget"
);
return Ok(());
}
match tx.try_send(QueuedHttpBodyDelta::new(params, byte_permit)) {
Ok(()) => {
if terminal_delta {
self.remove_http_body_stream(&request_id).await;
}
}
Err(TrySendError::Closed(_)) => {
self.remove_http_body_stream(&request_id).await;
debug!("http response stream receiver dropped before body delta delivery");
}
Err(TrySendError::Full(_)) => {
self.record_http_body_stream_failure(
&request_id,
"body delta channel filled before delivery".to_string(),
)
.await;
self.remove_http_body_stream(&request_id).await;
debug!(
"closing http response stream `{request_id}` after body delta backpressure"
);
}
}
}
Ok(())
}
/// Fails active streamed HTTP bodies so callers do not wait forever after a
/// transport disconnect or notification handling failure.
pub(crate) async fn fail_all_http_body_streams(&self, message: String) {
let _streams_write_guard = self.http_body_streams_write_lock.lock().await;
let streams = self.http_body_streams.load();
let streams = streams.as_ref().clone();
self.http_body_streams.store(Arc::new(HashMap::new()));
for (request_id, tx) in streams {
// Failure notifications must wake every stream even when no
// byte-budget permits remain.
if tx
.try_send(QueuedHttpBodyDelta::new(
HttpRequestBodyDeltaNotification {
request_id: request_id.clone(),
seq: 1,
delta: Vec::new().into(),
done: true,
error: Some(message.clone()),
},
/*byte_permit*/ None,
))
.is_err()
{
let mut next_failures = self.http_body_stream_failures.load().as_ref().clone();
next_failures.insert(request_id, message.clone());
self.http_body_stream_failures
.store(Arc::new(next_failures));
}
}
}
/// Allocates a connection-local streamed HTTP response id.
pub(super) fn next_http_body_stream_request_id(&self) -> String {
let id = self
.http_body_stream_next_id
.fetch_add(1, Ordering::Relaxed);
format!("http-{id}")
}
/// Registers a request id before issuing a streaming HTTP call.
pub(super) async fn insert_http_body_stream(
&self,
request_id: String,
tx: mpsc::Sender<QueuedHttpBodyDelta>,
) -> Result<(), ExecServerError> {
let _streams_write_guard = self.http_body_streams_write_lock.lock().await;
let streams = self.http_body_streams.load();
if streams.contains_key(&request_id) {
return Err(ExecServerError::Protocol(format!(
"http response stream already registered for request {request_id}"
)));
}
let mut next_streams = streams.as_ref().clone();
next_streams.insert(request_id.clone(), tx);
self.http_body_streams.store(Arc::new(next_streams));
let failures = self.http_body_stream_failures.load();
if failures.contains_key(&request_id) {
let mut next_failures = failures.as_ref().clone();
next_failures.remove(&request_id);
self.http_body_stream_failures
.store(Arc::new(next_failures));
}
Ok(())
}
/// Removes a request id after EOF, terminal error, or request failure.
pub(super) async fn remove_http_body_stream(
&self,
request_id: &str,
) -> Option<mpsc::Sender<QueuedHttpBodyDelta>> {
let _streams_write_guard = self.http_body_streams_write_lock.lock().await;
let streams = self.http_body_streams.load();
let stream = streams.get(request_id).cloned();
stream.as_ref()?;
let mut next_streams = streams.as_ref().clone();
next_streams.remove(request_id);
self.http_body_streams.store(Arc::new(next_streams));
stream
}
async fn record_http_body_stream_failure(&self, request_id: &str, message: String) {
let _streams_write_guard = self.http_body_streams_write_lock.lock().await;
let failures = self.http_body_stream_failures.load();
let mut next_failures = failures.as_ref().clone();
next_failures.insert(request_id.to_string(), message);
self.http_body_stream_failures
.store(Arc::new(next_failures));
}
async fn take_http_body_stream_failure(&self, request_id: &str) -> Option<String> {
let _streams_write_guard = self.http_body_streams_write_lock.lock().await;
let failures = self.http_body_stream_failures.load();
let error = failures.get(request_id).cloned();
error.as_ref()?;
let mut next_failures = failures.as_ref().clone();
next_failures.remove(request_id);
self.http_body_stream_failures
.store(Arc::new(next_failures));
error
}
}

View File

@@ -0,0 +1,81 @@
use super::NetworkPolicyAuditContext;
use crate::protocol::ExecServerNetworkProtocol;
use crate::protocol::MAX_NETWORK_POLICY_HOST_BYTES;
use crate::protocol::MAX_NETWORK_POLICY_PROCESS_ID_BYTES;
use crate::protocol::MAX_NETWORK_POLICY_REASON_BYTES;
use crate::protocol::NetworkPolicyDecisionNotification;
const MAX_NETWORK_POLICY_METHOD_BYTES: usize = 32;
const MAX_NETWORK_POLICY_CLIENT_BYTES: usize = 256;
const MAX_NETWORK_POLICY_TIMESTAMP_BYTES: usize = 64;
pub(super) fn emit_network_policy_decision(
context: &NetworkPolicyAuditContext,
decision: &NetworkPolicyDecisionNotification,
) -> bool {
if decision.process_id.is_empty()
|| decision.process_id.len() > MAX_NETWORK_POLICY_PROCESS_ID_BYTES
|| decision.host.is_empty()
|| decision.host.len() > MAX_NETWORK_POLICY_HOST_BYTES
|| decision.host.chars().any(char::is_control)
|| decision.host.chars().any(char::is_whitespace)
|| decision.reason.len() > MAX_NETWORK_POLICY_REASON_BYTES
|| decision.reason.chars().any(char::is_control)
|| !matches!(decision.scope.as_str(), "domain" | "non_domain")
|| !matches!(decision.decision.as_str(), "allow" | "deny" | "ask")
|| !matches!(
decision.source.as_str(),
"baseline_policy" | "mode_guard" | "proxy_state" | "decider"
)
|| decision.timestamp.is_empty()
|| decision.timestamp.len() > MAX_NETWORK_POLICY_TIMESTAMP_BYTES
|| decision.timestamp.chars().any(char::is_control)
|| decision.method.as_ref().is_some_and(|method| {
method.len() > MAX_NETWORK_POLICY_METHOD_BYTES
|| method.chars().any(char::is_control)
|| method.chars().any(char::is_whitespace)
})
|| decision.client.as_ref().is_some_and(|client| {
client.len() > MAX_NETWORK_POLICY_CLIENT_BYTES
|| client.chars().any(char::is_control)
|| client.chars().any(char::is_whitespace)
})
{
return false;
}
let protocol = match decision.protocol {
ExecServerNetworkProtocol::Http => "http",
ExecServerNetworkProtocol::HttpsConnect => "https_connect",
ExecServerNetworkProtocol::Socks5Tcp => "socks5_tcp",
ExecServerNetworkProtocol::Socks5Udp => "socks5_udp",
};
let metadata = &context.metadata;
tracing::event!(
target: "codex_otel.log_only",
tracing::Level::INFO,
event.name = "codex.network_proxy.policy_decision",
event.timestamp = decision.timestamp,
conversation.id = metadata.conversation_id.as_deref(),
app.version = metadata.app_version.as_deref(),
auth_mode = metadata.auth_mode.as_deref(),
originator = metadata.originator.as_deref(),
user.account_id = metadata.user_account_id.as_deref(),
user.email = metadata.user_email.as_deref(),
terminal.type = metadata.terminal_type.as_deref(),
model = metadata.model.as_deref(),
slug = metadata.slug.as_deref(),
network.policy.scope = decision.scope,
network.policy.decision = decision.decision,
network.policy.source = decision.source,
network.policy.reason = decision.reason,
network.transport.protocol = protocol,
server.address = decision.host,
server.port = decision.port,
http.request.method = decision.method.as_deref().unwrap_or("none"),
client.address = decision.client.as_deref().unwrap_or("unknown"),
execution.id = context.execution_id.as_deref(),
network.policy.override = decision.policy_override,
);
true
}

View File

@@ -0,0 +1,379 @@
//! Route-aware local HTTP capability implementation.
//!
//! This code runs wherever the real network request should originate:
//! - in a local environment, that means the orchestrator process
//! - in a remote environment, that means the remote runtime after the
//! orchestrator has forwarded `http/request` over JSON-RPC
use std::time::Duration;
use codex_exec_server_protocol::JSONRPCErrorError;
use codex_http_client::ClientRouteClass;
use codex_http_client::HttpClientFactory;
use codex_http_client::RouteAwareClientPool;
use codex_http_client::RouteAwareRequestError;
use codex_protocol::shell_environment::CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN_ENV_VAR;
use codex_protocol::shell_environment::OPENAI_FEDERATION_RULE_ID_ENV_VAR;
use codex_protocol::shell_environment::OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR;
use codex_protocol::shell_environment::OPENAI_WORKLOAD_IDENTITY_CONTEXT_ENV_VAR;
use futures::FutureExt;
use futures::StreamExt;
use futures::future::BoxFuture;
use http::HeaderMap;
use http::HeaderName;
use http::HeaderValue;
use http::Method;
use tracing::Instrument;
use url::Url;
use super::HttpResponseBodyStream;
use super::response_body_stream::send_body_delta;
use crate::HttpClient;
use crate::client::ExecServerError;
use crate::protocol::HttpHeader;
use crate::protocol::HttpRedirectPolicy;
use crate::protocol::HttpRequestBodyDeltaNotification;
use crate::protocol::HttpRequestParams;
use crate::protocol::HttpRequestResponse;
use crate::protocol::MAX_HTTP_BODY_DELTA_BYTES;
use crate::rpc::RpcNotificationSender;
use crate::rpc::internal_error;
use crate::rpc::invalid_params;
const HTTP_HEADER_ENV_DENYLIST: &[&str] = &[
CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN_ENV_VAR,
OPENAI_FEDERATION_RULE_ID_ENV_VAR,
OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR,
OPENAI_WORKLOAD_IDENTITY_CONTEXT_ENV_VAR,
"OPENAI_API_KEY",
"CODEX_GUARDIAN_DECISIONS_API_KEY",
"CODEX_API_KEY",
"CODEX_ACCESS_TOKEN",
"CODEX_CONNECTORS_TOKEN",
"AWS_ACCESS_KEY_ID",
"AWS_SECRET_ACCESS_KEY",
"AWS_SESSION_TOKEN",
"AZURE_CLIENT_SECRET",
"AZURE_FEDERATED_TOKEN_FILE",
"GOOGLE_APPLICATION_CREDENTIALS",
];
/// HTTP capability implementation backed by the shared route-aware transport.
#[derive(Clone)]
pub struct RouteAwareHttpClient {
follow_redirects: RouteAwareClientPool,
stop_redirects: RouteAwareClientPool,
}
/// Streaming response state held between the initial HTTP response and
/// downstream body-delta forwarding.
pub(crate) struct PendingRouteAwareHttpBodyStream {
pub(crate) request_id: String,
pub(crate) response: codex_http_client::HttpResponse,
}
/// Validates `http/request` parameters and runs the actual HTTP call used
/// by the exec-server route and the local [`HttpClient`] backend.
pub(crate) struct RouteAwareHttpRequestRunner {
client: RouteAwareClientPool,
}
impl RouteAwareHttpClient {
pub fn new(http_client_factory: HttpClientFactory) -> Self {
Self {
follow_redirects: RouteAwareClientPool::with_chatgpt_cloudflare_cookies_without_request_logging(
http_client_factory.clone(),
// Delegated HTTP targets arbitrary endpoints; route class only labels diagnostics.
ClientRouteClass::Other,
),
stop_redirects:
RouteAwareClientPool::with_chatgpt_cloudflare_cookies_without_redirects_or_request_logging(
http_client_factory,
// Proxy routing comes from the factory, not this diagnostic-only route class.
ClientRouteClass::Other,
),
}
}
/// Enables narrowly scoped TLS-backend fallback for both redirect policies.
pub fn with_tls_backend_fallback(mut self) -> Self {
self.follow_redirects = self.follow_redirects.with_tls_backend_fallback();
self.stop_redirects = self.stop_redirects.with_tls_backend_fallback();
self
}
pub(crate) fn runner(
&self,
redirect_policy: HttpRedirectPolicy,
) -> RouteAwareHttpRequestRunner {
let client = match redirect_policy {
HttpRedirectPolicy::Follow => self.follow_redirects.clone(),
HttpRedirectPolicy::Stop => self.stop_redirects.clone(),
};
RouteAwareHttpRequestRunner { client }
}
}
impl HttpClient for RouteAwareHttpClient {
fn http_request(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
async move {
let runner = self.runner(params.redirect_policy);
let (response, _) = runner
.run(HttpRequestParams {
stream_response: false,
..params
})
.await
.map_err(|error| ExecServerError::HttpRequest(error.message))?;
Ok(response)
}
.boxed()
}
fn http_request_stream(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
async move {
let runner = self.runner(params.redirect_policy);
let (response, pending_stream) = runner
.run(HttpRequestParams {
stream_response: true,
..params
})
.await
.map_err(|error| ExecServerError::HttpRequest(error.message))?;
let pending_stream = pending_stream.ok_or_else(|| {
ExecServerError::Protocol(
"http request stream did not return a response body stream".to_string(),
)
})?;
Ok((
response,
HttpResponseBodyStream::local(pending_stream.response),
))
}
.boxed()
}
}
impl RouteAwareHttpRequestRunner {
pub(crate) async fn run(
&self,
params: HttpRequestParams,
) -> Result<(HttpRequestResponse, Option<PendingRouteAwareHttpBodyStream>), JSONRPCErrorError>
{
let method = Method::from_bytes(params.method.as_bytes())
.map_err(|error| invalid_params(format!("http/request method is invalid: {error}")))?;
let url = Url::parse(&params.url)
.map_err(|error| invalid_params(format!("http/request url is invalid: {error}")))?;
match url.scheme() {
"http" | "https" => {}
scheme => {
return Err(invalid_params(format!(
"http/request only supports http and https URLs, got {scheme}"
)));
}
}
let request_span = tracing::info_span!(
"codex.exec_server.http_request",
otel.kind = "client",
http.request.method = method.as_str(),
server.address = url.host_str().unwrap_or_default(),
server.port = u64::from(url.port_or_known_default().unwrap_or_default()),
http.response.status_code = tracing::field::Empty,
error.type = tracing::field::Empty,
);
let mut headers = Self::build_headers(params.headers)?;
codex_otel::inject_span_w3c_trace_headers(&request_span, &mut headers);
let mut request = self.client.request(method.clone(), url).headers(headers);
if let Some(body) = params.body {
request = request.body(body.into_inner());
}
if let Some(timeout_ms) = params.timeout_ms {
request = request.timeout(Duration::from_millis(timeout_ms));
}
let response = match request.send().instrument(request_span.clone()).await {
Ok(response) => response,
Err(error) => {
request_span.record("error.type", "request");
let error_message = error.to_string();
log_send_error(&method, error);
return Err(internal_error(format!(
"http/request failed: {error_message}"
)));
}
};
let status = response.status().as_u16();
request_span.record("http.response.status_code", u64::from(status));
let headers = Self::response_headers(response.headers());
if params.stream_response {
return Ok((
HttpRequestResponse {
status,
headers,
body: Vec::new().into(),
},
Some(PendingRouteAwareHttpBodyStream {
request_id: params.request_id,
response,
}),
));
}
let body = response.bytes().await.map_err(|error| {
internal_error(format!(
"failed to read http/request response body: {error}"
))
})?;
Ok((
HttpRequestResponse {
status,
headers,
body: body.to_vec().into(),
},
None,
))
}
pub(crate) async fn stream_body(
pending_stream: PendingRouteAwareHttpBodyStream,
notifications: RpcNotificationSender,
) {
let PendingRouteAwareHttpBodyStream {
request_id,
response,
} = pending_stream;
let mut seq = 1;
let mut body = response.bytes_stream();
while let Some(chunk) = body.next().await {
match chunk {
Ok(bytes) => {
for chunk in bytes.chunks(MAX_HTTP_BODY_DELTA_BYTES) {
if !send_body_delta(
&notifications,
HttpRequestBodyDeltaNotification {
request_id: request_id.clone(),
seq,
delta: chunk.to_vec().into(),
done: false,
error: None,
},
)
.await
{
return;
}
seq += 1;
}
}
Err(error) => {
let _ = send_body_delta(
&notifications,
HttpRequestBodyDeltaNotification {
request_id,
seq,
delta: Vec::new().into(),
done: true,
error: Some(error.to_string()),
},
)
.await;
return;
}
}
}
let _ = send_body_delta(
&notifications,
HttpRequestBodyDeltaNotification {
request_id,
seq,
delta: Vec::new().into(),
done: true,
error: None,
},
)
.await;
}
fn build_headers(headers: Vec<HttpHeader>) -> Result<HeaderMap, JSONRPCErrorError> {
let mut header_map = HeaderMap::new();
for header in headers {
let name = HeaderName::from_bytes(header.name.as_bytes()).map_err(|error| {
invalid_params(format!("http/request header name is invalid: {error}"))
})?;
let value = match header.value_env_var {
Some(env_var) => {
if HTTP_HEADER_ENV_DENYLIST
.iter()
.any(|denied| denied.eq_ignore_ascii_case(&env_var))
{
return Err(invalid_params(format!(
"http/request header {} cannot use executor environment variable {env_var}",
header.name
)));
}
let env_value = std::env::var(&env_var).map_err(|_| {
invalid_params(format!(
"http/request header {} requires executor environment variable {env_var}",
header.name
))
})?;
if env_value.is_empty() {
return Err(invalid_params(format!(
"http/request header {} requires a non-empty executor environment variable {env_var}",
header.name
)));
}
format!("{}{env_value}", header.value)
}
None => header.value,
};
let value = HeaderValue::from_str(&value).map_err(|error| {
invalid_params(format!(
"http/request header value is invalid for {}: {error}",
header.name
))
})?;
header_map.append(name, value);
}
Ok(header_map)
}
fn response_headers(headers: &HeaderMap) -> Vec<HttpHeader> {
headers
.iter()
.filter_map(|(name, value)| {
Some(HttpHeader {
name: name.as_str().to_string(),
value: value.to_str().ok()?.to_string(),
value_env_var: None,
})
})
.collect()
}
}
fn log_send_error(method: &Method, error: RouteAwareRequestError) {
let error_is_timeout = error.is_timeout();
let error_is_connect = error.is_connect();
let error = match error {
RouteAwareRequestError::Request(error) => error.without_url().to_string(),
error => error.to_string(),
};
tracing::warn!(
http_method = method.as_str(),
error_is_timeout,
error_is_connect,
error = %error,
"http/request send failed"
);
}

View File

@@ -0,0 +1,92 @@
//! JSON-RPC-backed `HttpClient` implementation.
//!
//! This code runs in the orchestrator process. It does not issue network
//! requests directly; instead it forwards `http/request` to the remote runtime
//! and then reconstructs streamed bodies from `http/request/bodyDelta`
//! notifications on the shared connection.
use std::sync::Arc;
use futures::FutureExt;
use futures::future::BoxFuture;
use tokio::sync::mpsc;
use super::HttpResponseBodyStream;
use super::response_body_stream::HttpBodyStreamRegistration;
use crate::HttpClient;
use crate::client::ExecServerClient;
use crate::client::ExecServerError;
use crate::protocol::HTTP_REQUEST_METHOD;
use crate::protocol::HttpRequestParams;
use crate::protocol::HttpRequestResponse;
/// Maximum queued body frames per streamed HTTP response.
const HTTP_BODY_DELTA_CHANNEL_CAPACITY: usize = 256;
impl ExecServerClient {
/// Performs an HTTP request and buffers the response body.
pub async fn http_request(
&self,
mut params: HttpRequestParams,
) -> Result<HttpRequestResponse, ExecServerError> {
params.stream_response = false;
self.call(HTTP_REQUEST_METHOD, &params).await
}
/// Performs an HTTP request and returns a body stream.
///
/// The method sets `stream_response` and replaces any caller-supplied
/// `request_id` with a connection-local id, so late deltas from abandoned
/// streams cannot be confused with later requests.
pub async fn http_request_stream(
&self,
mut params: HttpRequestParams,
) -> Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError> {
let rpc_client = self.rpc_client().await?;
params.stream_response = true;
let request_id = self.inner.next_http_body_stream_request_id();
params.request_id = request_id.clone();
let (tx, rx) = mpsc::channel(HTTP_BODY_DELTA_CHANNEL_CAPACITY);
self.inner
.insert_http_body_stream(request_id.clone(), tx)
.await?;
let mut registration =
HttpBodyStreamRegistration::new(Arc::clone(&self.inner), request_id.clone());
let response = match self
.call_rpc(&rpc_client, HTTP_REQUEST_METHOD, &params)
.await
{
Ok(response) => response,
Err(error) => {
self.inner.remove_http_body_stream(&request_id).await;
registration.disarm();
return Err(error);
}
};
registration.disarm();
Ok((
response,
HttpResponseBodyStream::remote(Arc::clone(&self.inner), request_id, rx),
))
}
}
impl HttpClient for ExecServerClient {
/// Orchestrator-side adapter that forwards buffered HTTP requests to the
/// remote runtime over the shared JSON-RPC connection.
fn http_request(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
async move { ExecServerClient::http_request(self, params).await }.boxed()
}
/// Orchestrator-side adapter that forwards streamed HTTP requests to the
/// remote runtime and exposes body deltas as a byte stream.
fn http_request_stream(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
async move { ExecServerClient::http_request_stream(self, params).await }.boxed()
}
}

View File

@@ -0,0 +1,144 @@
//! Config-read deadlines must preserve non-reconnectable stdio connections.
use super::read_jsonrpc_line;
use super::write_jsonrpc_line;
use crate::ExecServerClient;
use crate::ExecServerClientConnectOptions;
use crate::ExecServerError;
use crate::connection::JsonRpcConnection;
use crate::protocol::ENVIRONMENT_CONFIG_READ_METHOD;
use crate::protocol::EnvironmentConfigLayerStack;
use crate::protocol::EnvironmentConfigReadParams;
use crate::protocol::EnvironmentConfigReadResponse;
use crate::protocol::INITIALIZE_METHOD;
use crate::protocol::INITIALIZED_METHOD;
use crate::protocol::InitializeResponse;
use codex_exec_server_protocol::JSONRPCMessage;
use codex_exec_server_protocol::JSONRPCResponse;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use tokio::io::AsyncBufReadExt;
use tokio::io::BufReader;
use tokio::io::duplex;
use tokio::time::Duration;
#[tokio::test(start_paused = true)]
async fn config_read_timeout_keeps_stdio_connection_usable() {
let (client_stdin, server_reader) = duplex(4096);
let (mut server_writer, client_stdout) = duplex(4096);
let mut lines = BufReader::new(server_reader).lines();
let connect = ExecServerClient::connect(
JsonRpcConnection::from_stdio(client_stdout, client_stdin, "config-timeout".to_string()),
ExecServerClientConnectOptions::default(),
);
tokio::pin!(connect);
assert!(futures::poll!(connect.as_mut()).is_pending());
let initialize = match read_jsonrpc_line(&mut lines).await {
JSONRPCMessage::Request(request) if request.method == INITIALIZE_METHOD => request,
other => panic!("expected initialize request, got {other:?}"),
};
write_jsonrpc_line(
&mut server_writer,
JSONRPCMessage::Response(JSONRPCResponse {
id: initialize.id,
result: serde_json::to_value(InitializeResponse {
session_id: "config-timeout".to_string(),
environment_info: None,
})
.expect("initialize response should serialize"),
}),
)
.await;
let client = connect.await.expect("stdio client should connect");
assert!(matches!(
read_jsonrpc_line(&mut lines).await,
JSONRPCMessage::Notification(notification) if notification.method == INITIALIZED_METHOD
));
let cwd = PathUri::from_host_native_path(std::env::current_dir().expect("current directory"))
.expect("current directory URI");
let params = EnvironmentConfigReadParams {
cwd: cwd.clone(),
config_paths: vec![vec!["features".to_string()]],
requirements_paths: Vec::new(),
};
let mut expected = EnvironmentConfigReadResponse {
user_home_dir: None,
codex_home_dir: cwd,
hostname: Some("original".to_string()),
config: EnvironmentConfigLayerStack {
layers: Vec::new(),
cloud_insertion_index: 0,
},
requirements: EnvironmentConfigLayerStack {
layers: Vec::new(),
cloud_insertion_index: 0,
},
};
// Model inline dispatch by holding valid work while the timed read queues behind it.
let original = client.read_environment_config(params.clone());
tokio::pin!(original);
assert!(futures::poll!(original.as_mut()).is_pending());
let original_request = match read_jsonrpc_line(&mut lines).await {
JSONRPCMessage::Request(request) if request.method == ENVIRONMENT_CONFIG_READ_METHOD => {
request
}
other => panic!("expected original config read, got {other:?}"),
};
let rpc_timeout = Duration::from_secs(1);
let timed = client.read_environment_config_with_timeout(params.clone(), rpc_timeout);
tokio::pin!(timed);
assert!(futures::poll!(timed.as_mut()).is_pending());
tokio::time::advance(rpc_timeout).await;
assert!(matches!(
timed.await,
Err(ExecServerError::RpcTimedOut { method, timeout })
if method == ENVIRONMENT_CONFIG_READ_METHOD && timeout == rpc_timeout
));
assert!(
futures::poll!(original.as_mut()).is_pending(),
"a queued config-read timeout must not disconnect valid in-flight work"
);
write_jsonrpc_line(
&mut server_writer,
JSONRPCMessage::Response(JSONRPCResponse {
id: original_request.id,
result: serde_json::to_value(&expected).expect("config response should serialize"),
}),
)
.await;
assert_eq!(
original.await.expect("original read should finish"),
expected
);
// Finish the expired request, then serve a fresh read over the same connection.
let retry = client.read_environment_config_with_timeout(params, rpc_timeout);
tokio::pin!(retry);
assert!(futures::poll!(retry.as_mut()).is_pending());
for hostname in ["late", "fresh"] {
let request = match read_jsonrpc_line(&mut lines).await {
JSONRPCMessage::Request(request)
if request.method == ENVIRONMENT_CONFIG_READ_METHOD =>
{
request
}
other => panic!("expected queued config read, got {other:?}"),
};
expected.hostname = Some(hostname.to_string());
write_jsonrpc_line(
&mut server_writer,
JSONRPCMessage::Response(JSONRPCResponse {
id: request.id,
result: serde_json::to_value(&expected).expect("config response should serialize"),
}),
)
.await;
}
assert_eq!(
retry.await.expect("stdio connection should be reusable"),
expected
);
}

View File

@@ -0,0 +1,544 @@
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use codex_exec_server_protocol::JSONRPCMessage;
use codex_exec_server_protocol::JSONRPCNotification;
use codex_exec_server_protocol::JSONRPCRequest;
use codex_exec_server_protocol::JSONRPCResponse;
use codex_exec_server_protocol::RequestId;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_network_proxy::NetworkDecision;
use codex_network_proxy::NetworkPolicyDecider;
use codex_network_proxy::NetworkPolicyRequest;
use codex_network_proxy::NetworkProxyAuditMetadata;
use codex_utils_path_uri::PathUri;
use http::HeaderMap;
use opentelemetry::trace::TracerProvider as _;
use opentelemetry_sdk::trace::InMemorySpanExporter;
use opentelemetry_sdk::trace::SdkTracerProvider;
use pretty_assertions::assert_eq;
use tokio::net::TcpListener;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::time::timeout;
use tracing::instrument::WithSubscriber;
use tracing_subscriber::filter::filter_fn;
use tracing_subscriber::prelude::*;
use super::super::LazyRemoteExecServerClient;
use super::super::NetworkPolicyAuditContext;
use super::super::NetworkPolicyDecisionController;
use super::super::SessionState;
use super::super::handle_server_notification;
use super::accept_websocket;
use super::complete_websocket_initialize;
use super::read_jsonrpc_websocket;
use super::write_jsonrpc_websocket;
use crate::ProcessId;
use crate::client_api::ExecServerTransportParams;
use crate::protocol::EXEC_METHOD;
use crate::protocol::EXEC_TERMINATE_METHOD;
use crate::protocol::ExecParams;
use crate::protocol::ExecServerNetworkPolicyDecision;
use crate::protocol::ExecServerNetworkPolicyRequest;
use crate::protocol::ExecServerNetworkProtocol;
use crate::protocol::NETWORK_POLICY_DECISION_METHOD;
use crate::protocol::NETWORK_POLICY_REQUEST_METHOD;
use crate::protocol::NetworkPolicyDecisionNotification;
use crate::protocol::NetworkPolicyRequestParams;
use crate::protocol::NetworkPolicyRequestResponse;
use crate::rpc_server_requests::MAX_IN_FLIGHT_SERVER_CALLS;
struct PendingDecisionGuard(mpsc::UnboundedSender<()>);
impl Drop for PendingDecisionGuard {
fn drop(&mut self) {
let _ = self.0.send(());
}
}
fn policy_request(request_id: i64, process_id: ProcessId, host: &str) -> JSONRPCMessage {
JSONRPCMessage::Request(JSONRPCRequest {
id: RequestId::Integer(request_id),
method: NETWORK_POLICY_REQUEST_METHOD.to_string(),
params: Some(
serde_json::to_value(NetworkPolicyRequestParams {
process_id,
request: ExecServerNetworkPolicyRequest {
protocol: ExecServerNetworkProtocol::HttpsConnect,
host: host.to_string(),
port: 443,
},
})
.expect("policy request should serialize"),
),
trace: None,
})
}
async fn read_decision(
websocket: &mut tokio_tungstenite::WebSocketStream<tokio::net::TcpStream>,
request_id: i64,
) -> ExecServerNetworkPolicyDecision {
let JSONRPCMessage::Response(response) = read_jsonrpc_websocket(websocket).await else {
panic!("expected network policy response");
};
assert_eq!(response.id, RequestId::Integer(request_id));
serde_json::from_value::<NetworkPolicyRequestResponse>(response.result)
.expect("policy response should deserialize")
.decision
}
#[tokio::test(flavor = "current_thread")]
async fn policy_decisions_reject_forged_process_and_use_trusted_controller_metadata() {
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("listener should bind");
let websocket_url = format!("ws://{}", listener.local_addr().expect("listener address"));
let (release_tx, release_rx) = oneshot::channel();
let (initialized_tx, initialized_rx) = oneshot::channel();
let server = tokio::spawn(async move {
let mut websocket = accept_websocket(&listener).await;
complete_websocket_initialize(
&mut websocket,
"audit-session",
/*expected_resume_session_id*/ None,
)
.await;
initialized_tx
.send(())
.expect("client should await completed WebSocket initialization");
release_rx.await.expect("server should be released");
});
let logs = Arc::new(Mutex::new(Vec::new()));
let writer_logs = Arc::clone(&logs);
let subscriber = tracing_subscriber::registry().with(
tracing_subscriber::fmt::layer()
.with_ansi(false)
.with_writer(move || AuditLogWriter(Arc::clone(&writer_logs))),
);
async move {
let client = LazyRemoteExecServerClient::new(
ExecServerTransportParams::websocket_url(websocket_url, Duration::from_secs(1)),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)
.get()
.await
.expect("client should connect");
initialized_rx
.await
.expect("server should complete WebSocket initialization");
let mut state = SessionState::new(/*recoverable*/ true);
state.network_policy.audit = Some(NetworkPolicyAuditContext {
metadata: NetworkProxyAuditMetadata {
conversation_id: Some("trusted-conversation".to_string()),
user_account_id: Some("trusted-account".to_string()),
..NetworkProxyAuditMetadata::default()
},
execution_id: Some("trusted-execution".to_string()),
});
client
.inner
.insert_session(&ProcessId::from("trusted-process"), Arc::new(state))
.expect("trusted process should register");
for (process_id, host) in [
("forged-process", "forged.example"),
("trusted-process", "trusted.example"),
] {
handle_server_notification(
&client.inner,
JSONRPCNotification {
method: NETWORK_POLICY_DECISION_METHOD.to_string(),
params: Some(
serde_json::to_value(NetworkPolicyDecisionNotification {
process_id: ProcessId::from(process_id),
timestamp: "2026-08-11T12:00:00.000Z".to_string(),
scope: "domain".to_string(),
decision: "deny".to_string(),
source: "baseline_policy".to_string(),
reason: "not_allowed".to_string(),
protocol: ExecServerNetworkProtocol::HttpsConnect,
host: host.to_string(),
port: 443,
method: None,
client: None,
policy_override: false,
})
.expect("network policy decision should serialize"),
),
},
)
.await
.expect("controller should handle network policy notification");
}
let output = String::from_utf8(
logs.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone(),
)
.expect("audit log should be UTF-8");
assert!(!output.contains("forged.example"));
for expected in [
"codex_otel.log_only",
"trusted-conversation",
"trusted-account",
"trusted-execution",
] {
assert!(
output.contains(expected),
"missing `{expected}` in {output}"
);
}
release_tx.send(()).expect("server should be released");
}
.with_subscriber(subscriber)
.await;
server.await.expect("server should finish");
}
struct AuditLogWriter(Arc<Mutex<Vec<u8>>>);
impl std::io::Write for AuditLogWriter {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[tokio::test]
async fn abandoned_process_start_unregisters_and_cleans_up() {
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("listener should bind");
let websocket_url = format!("ws://{}", listener.local_addr().expect("listener address"));
let (start_seen_tx, start_seen_rx) = oneshot::channel();
let (finish_start_tx, finish_start_rx) = oneshot::channel();
let server = tokio::spawn(async move {
let mut websocket = accept_websocket(&listener).await;
complete_websocket_initialize(&mut websocket, "p", Default::default()).await;
let JSONRPCMessage::Request(start) = read_jsonrpc_websocket(&mut websocket).await else {
panic!("expected process start request");
};
assert_eq!(start.method, EXEC_METHOD);
start_seen_tx.send(()).expect("start should be observed");
finish_start_rx.await.expect("start should be released");
write_jsonrpc_websocket(
&mut websocket,
JSONRPCMessage::Response(JSONRPCResponse {
id: start.id,
result: serde_json::json!({"processId": "pending-start"}),
}),
)
.await;
let JSONRPCMessage::Request(terminate) = read_jsonrpc_websocket(&mut websocket).await
else {
panic!("expected process terminate request");
};
assert_eq!(terminate.method, EXEC_TERMINATE_METHOD);
write_jsonrpc_websocket(
&mut websocket,
JSONRPCMessage::Response(JSONRPCResponse {
id: terminate.id,
result: serde_json::json!({"running": true}),
}),
)
.await;
});
let client = LazyRemoteExecServerClient::new(
ExecServerTransportParams::websocket_url(websocket_url, Duration::from_secs(1)),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)
.get()
.await
.expect("client should connect");
let process_id = ProcessId::from("pending-start");
let start_client = client.clone();
let start_process_id = process_id.clone();
let start = tokio::spawn(async move {
let params = ExecParams {
metadata: Default::default(),
process_id: start_process_id,
argv: vec!["true".to_string()],
cwd: PathUri::from_host_native_path(std::env::current_dir().expect("cwd"))
.expect("cwd URI"),
shell_snapshot: None,
env_policy: None,
env: Default::default(),
tty: false,
pipe_stdin: false,
arg0: None,
sandbox: None,
enforce_managed_network: false,
managed_network: None,
network_proxy: None,
};
start_client
.start_process(params, /*network_policy_decider*/ None)
.await
});
start_seen_rx.await.expect("start should be observed");
let state = client
.inner
.get_session(&process_id)
.expect("pending process should be registered");
let decider: Arc<dyn NetworkPolicyDecider> =
Arc::new(|_request: NetworkPolicyRequest| async { NetworkDecision::Allow });
let decider_weak = Arc::downgrade(&decider);
state
.network_policy
.controller
.store(Some(Arc::new(NetworkPolicyDecisionController {
decider,
timeout: Duration::from_secs(30),
})));
start.abort();
assert!(start.await.is_err_and(|error| error.is_cancelled()));
assert!(state.network_policy.cancelled.is_cancelled());
assert!(client.inner.get_session(&process_id).is_none());
assert!(decider_weak.upgrade().is_none());
finish_start_tx.send(()).expect("start should be released");
server.await.expect("server task should finish");
}
#[tokio::test]
async fn policy_requests_use_process_decider_and_cancel_on_unregister() {
let span_exporter = InMemorySpanExporter::default();
let tracer_provider = SdkTracerProvider::builder()
.with_simple_exporter(span_exporter.clone())
.build();
let subscriber = tracing_subscriber::registry().with(
tracing_opentelemetry::layer()
.with_tracer(tracer_provider.tracer("exec-server-test"))
.with_filter(filter_fn(codex_otel::OtelProvider::trace_export_filter)),
);
let _subscriber = tracing::subscriber::set_default(subscriber);
tracing::callsite::rebuild_interest_cache();
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("listener should bind");
let websocket_url = format!(
"ws://{}",
listener.local_addr().expect("listener should have address")
);
let process_id = ProcessId::from("policy-process");
let server_process_id = process_id.clone();
let (ready_tx, ready_rx) = oneshot::channel();
let (overflow_checked_tx, overflow_checked_rx) = oneshot::channel();
let (unregistered_tx, unregistered_rx) = oneshot::channel();
let server = tokio::spawn(async move {
let mut websocket = accept_websocket(&listener).await;
complete_websocket_initialize(
&mut websocket,
"policy-session",
/*expected_resume_session_id*/ None,
)
.await;
ready_rx.await.expect("process should be registered");
for (request_id, host, expected) in [
(0, "allowed.example", ExecServerNetworkPolicyDecision::Allow),
(
2,
"denied.example",
ExecServerNetworkPolicyDecision::Deny {
reason: "blocked".to_string(),
},
),
(
3,
"invalid host",
ExecServerNetworkPolicyDecision::Deny {
reason: "not_allowed".to_string(),
},
),
] {
write_jsonrpc_websocket(
&mut websocket,
policy_request(request_id, server_process_id.clone(), host),
)
.await;
assert_eq!(read_decision(&mut websocket, request_id).await, expected);
}
let first_pending_request_id = 100;
for offset in 0..MAX_IN_FLIGHT_SERVER_CALLS {
write_jsonrpc_websocket(
&mut websocket,
policy_request(
first_pending_request_id + offset as i64,
server_process_id.clone(),
"pending.example",
),
)
.await;
}
let overflow_request_id = first_pending_request_id + MAX_IN_FLIGHT_SERVER_CALLS as i64;
write_jsonrpc_websocket(
&mut websocket,
policy_request(
overflow_request_id,
server_process_id.clone(),
"pending.example",
),
)
.await;
assert_eq!(
read_decision(&mut websocket, overflow_request_id).await,
ExecServerNetworkPolicyDecision::Deny {
reason: "not_allowed".to_string(),
}
);
overflow_checked_tx.send(()).expect("overflow observed");
unregistered_rx
.await
.expect("process should be unregistered");
let post_unregister_request_id = 900;
write_jsonrpc_websocket(
&mut websocket,
policy_request(
post_unregister_request_id,
server_process_id,
"allowed.example",
),
)
.await;
assert_eq!(
read_decision(&mut websocket, post_unregister_request_id).await,
ExecServerNetworkPolicyDecision::Deny {
reason: "not_allowed".to_string(),
}
);
});
let client = LazyRemoteExecServerClient::new(
ExecServerTransportParams::WebSocketUrl {
websocket_url,
connect_timeout: Duration::from_secs(1),
initialize_timeout: Duration::from_secs(1),
http_headers: HeaderMap::new(),
},
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)
.get()
.await
.expect("client should connect");
let session = client
.register_session(&process_id)
.await
.expect("session should register");
let (started_tx, mut started_rx) = mpsc::unbounded_channel();
let (dropped_tx, mut dropped_rx) = mpsc::unbounded_channel();
let decider: Arc<dyn NetworkPolicyDecider> = Arc::new(move |request: NetworkPolicyRequest| {
let started_tx = started_tx.clone();
let dropped_tx = dropped_tx.clone();
async move {
assert_eq!(
tracing::Span::current()
.metadata()
.map(tracing::Metadata::name),
Some("codex.exec_server.request"),
"network policy decisions must run inside the inbound request span"
);
match request.host.as_str() {
"allowed.example" => NetworkDecision::Allow,
"denied.example" => NetworkDecision::deny("blocked"),
"pending.example" => {
started_tx.send(()).expect("decision should start");
let _drop_guard = PendingDecisionGuard(dropped_tx);
std::future::pending().await
}
host => panic!("unexpected policy host: {host}"),
}
}
});
session.state.network_policy.controller.store(Some(Arc::new(
NetworkPolicyDecisionController {
decider,
timeout: Duration::from_secs(30),
},
)));
ready_tx.send(()).expect("server should be waiting");
timeout(Duration::from_secs(5), async {
for _ in 0..MAX_IN_FLIGHT_SERVER_CALLS {
started_rx
.recv()
.await
.expect("pending decision should start");
}
})
.await
.expect("pending decisions should start");
overflow_checked_rx
.await
.expect("overflow should be observed");
session.unregister().await;
timeout(Duration::from_secs(5), async {
for _ in 0..MAX_IN_FLIGHT_SERVER_CALLS {
dropped_rx
.recv()
.await
.expect("unregistered decision should be dropped");
}
})
.await
.expect("unregistered decisions should be cancelled");
unregistered_tx
.send(())
.expect("server should verify late responses");
timeout(Duration::from_secs(2), server)
.await
.expect("policy routing should finish")
.expect("server task should finish");
tracer_provider.force_flush().expect("flush traces");
let spans = span_exporter.get_finished_spans().expect("span export");
let policy_spans = spans
.iter()
.filter(|span| span.name.as_ref() == NETWORK_POLICY_REQUEST_METHOD)
.collect::<Vec<_>>();
assert!(
!policy_spans.is_empty(),
"network policy requests should export server spans"
);
let outcomes = policy_spans
.iter()
.map(|span| {
span.attributes
.iter()
.find(|attribute| attribute.key.as_str() == "result")
.map(|attribute| attribute.value.as_str().into_owned())
})
.collect::<Vec<_>>();
assert!(
outcomes.iter().all(Option::is_some),
"completed, rejected, and cancelled policy requests must all record an outcome"
);
assert!(
outcomes
.iter()
.any(|outcome| outcome.as_deref() == Some("success")),
"completed and capacity-rejected requests should record successful responses"
);
assert!(
outcomes
.iter()
.any(|outcome| outcome.as_deref() == Some("disconnected")),
"cancelled requests should record disconnection"
);
}

View File

@@ -0,0 +1,187 @@
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use codex_http_client::HttpClientFactory;
use futures::future::BoxFuture;
use http::HeaderMap;
use tokio::sync::watch;
use crate::ExecServerError;
use crate::HttpRequestParams;
use crate::HttpRequestResponse;
use crate::HttpResponseBodyStream;
use crate::NoiseChannelIdentity;
use crate::NoiseChannelPublicKey;
pub(crate) const DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
pub(crate) const DEFAULT_REMOTE_EXEC_SERVER_INITIALIZE_TIMEOUT: Duration = Duration::from_secs(10);
/// Connection options for any exec-server client transport.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExecServerClientConnectOptions {
pub client_name: String,
pub initialize_timeout: Duration,
pub resume_session_id: Option<String>,
}
/// WebSocket connection arguments for a remote exec-server.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteExecServerConnectArgs {
pub websocket_url: String,
pub client_name: String,
pub connect_timeout: Duration,
pub initialize_timeout: Duration,
pub resume_session_id: Option<String>,
pub http_client_factory: HttpClientFactory,
}
/// Registry-authorized material for one Noise rendezvous connection attempt.
///
/// Treat this as an atomic, single-use bundle. The URL authorization, executor
/// registration, pinned executor key, and harness-key authorization describe one
/// physical connection attempt and must not be mixed with values from another
/// registry response.
pub struct NoiseRendezvousConnectBundle {
pub websocket_url: String,
pub environment_id: String,
pub executor_registration_id: String,
pub executor_public_key: NoiseChannelPublicKey,
pub harness_key_authorization: String,
}
/// Connection arguments for an authenticated Noise rendezvous exec-server.
///
/// `harness_identity` identifies the logical harness endpoint and may be reused
/// across reconnects. In contrast, callers must supply a fresh
/// [`NoiseRendezvousConnectBundle`] for each physical connection attempt.
pub struct NoiseRendezvousConnectArgs {
pub bundle: NoiseRendezvousConnectBundle,
pub harness_identity: NoiseChannelIdentity,
pub client_name: String,
pub connect_timeout: Duration,
pub initialize_timeout: Duration,
pub resume_session_id: Option<String>,
pub http_client_factory: HttpClientFactory,
}
/// Supplies fresh registry-authorized material for Noise rendezvous connections.
pub trait NoiseRendezvousConnectProvider: Send + Sync {
/// Fetch a bundle authorizing this harness key for one physical connection.
fn connect_bundle(
&self,
harness_public_key: NoiseChannelPublicKey,
) -> BoxFuture<'_, Result<NoiseRendezvousConnectBundle, ExecServerError>>;
}
/// Stdio connection arguments for a command-backed exec-server.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct StdioExecServerConnectArgs {
pub command: StdioExecServerCommand,
pub client_name: String,
pub initialize_timeout: Duration,
pub resume_session_id: Option<String>,
}
/// Structured process command used to start an exec-server over stdio.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct StdioExecServerCommand {
pub program: String,
pub args: Vec<String>,
pub env: HashMap<String, String>,
pub cwd: Option<PathBuf>,
}
pub(crate) type DeferredEnvironmentReadiness = watch::Receiver<Option<Result<(), String>>>;
#[derive(Clone)]
pub(crate) struct Deferred<T> {
pub readiness: DeferredEnvironmentReadiness,
pub transport: T,
}
/// Parameters used to connect to a remote exec-server environment.
#[derive(Clone)]
pub(crate) enum ExecServerTransportParams {
Deferred(Box<Deferred<ExecServerTransportParams>>),
WebSocketUrl {
websocket_url: String,
connect_timeout: Duration,
initialize_timeout: Duration,
http_headers: HeaderMap,
},
NoiseRendezvous {
provider: Arc<dyn NoiseRendezvousConnectProvider>,
identity: NoiseChannelIdentity,
},
#[allow(dead_code)]
StdioCommand {
command: StdioExecServerCommand,
initialize_timeout: Duration,
},
}
impl std::fmt::Debug for ExecServerTransportParams {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Deferred(deferred) => f
.debug_struct("Deferred")
.field("transport", &deferred.transport)
.finish_non_exhaustive(),
Self::WebSocketUrl {
websocket_url,
connect_timeout,
initialize_timeout,
..
} => f
.debug_struct("WebSocketUrl")
.field("websocket_url", websocket_url)
.field("connect_timeout", connect_timeout)
.field("initialize_timeout", initialize_timeout)
.field("http_headers", &"<redacted>")
.finish(),
Self::NoiseRendezvous { .. } => {
f.debug_struct("NoiseRendezvous").finish_non_exhaustive()
}
Self::StdioCommand {
command,
initialize_timeout,
} => f
.debug_struct("StdioCommand")
.field("command", command)
.field("initialize_timeout", initialize_timeout)
.finish(),
}
}
}
impl ExecServerTransportParams {
pub(crate) fn websocket_url(websocket_url: String, connect_timeout: Duration) -> Self {
Self::WebSocketUrl {
websocket_url,
connect_timeout,
initialize_timeout: DEFAULT_REMOTE_EXEC_SERVER_INITIALIZE_TIMEOUT,
http_headers: HeaderMap::new(),
}
}
}
/// Sends HTTP requests through a runtime-selected transport.
///
/// This is the HTTP capability counterpart to [`crate::ExecBackend`]. Callers
/// use it when they need environment-owned network requests but should not
/// depend on the concrete connection type or how that connection is established.
pub trait HttpClient: Send + Sync {
/// Perform an HTTP request and buffer the response body.
fn http_request(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>>;
/// Perform an HTTP request and return a streamed body handle.
fn http_request_stream(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>>;
}

View File

@@ -0,0 +1,68 @@
//! Classifies typed executor failures without treating error text as a retry signal.
use std::io::ErrorKind;
use http::StatusCode;
use tokio_tungstenite::tungstenite::Error as WebSocketError;
use tokio_tungstenite::tungstenite::error::ProtocolError;
use crate::ExecServerError;
use crate::client::is_retryable_registry_error;
use crate::rpc::SESSION_ALREADY_ATTACHED_ERROR_CODE;
impl ExecServerError {
/// Identifies transient failures that read-only preparation can retry.
///
/// Includes transient handshake responses and connection EOFs, including wrapped
/// failures. Authentication, TLS, and malformed protocol errors are excluded.
/// This is public because callers in `codex-core` also classify capability discovery.
pub fn is_retryable_preparation_error(&self) -> bool {
let mut error = self;
while let Self::ConnectionAttempt(source) = error {
error = source;
}
if is_retryable_registry_error(error) {
return true;
}
match error {
Self::Closed
| Self::Disconnected(_)
| Self::WebSocketConnectTimeout { .. }
| Self::RpcTimedOut { .. }
| Self::InitializeTimedOut { .. } => true,
Self::WebSocketConnect { source, .. } => match source {
WebSocketError::ConnectionClosed
| WebSocketError::AlreadyClosed
| WebSocketError::Protocol(
ProtocolError::HandshakeIncomplete
| ProtocolError::ResetWithoutClosingHandshake,
) => true,
WebSocketError::Http(response) => {
response.status().is_server_error()
|| matches!(
response.status(),
StatusCode::REQUEST_TIMEOUT
| StatusCode::CONFLICT
| StatusCode::TOO_MANY_REQUESTS
)
}
WebSocketError::Io(error) => matches!(
error.kind(),
ErrorKind::ConnectionRefused
| ErrorKind::ConnectionReset
| ErrorKind::ConnectionAborted
| ErrorKind::NetworkDown
| ErrorKind::NetworkUnreachable
| ErrorKind::HostUnreachable
| ErrorKind::BrokenPipe
| ErrorKind::NotConnected
| ErrorKind::UnexpectedEof
| ErrorKind::TimedOut
),
_ => false,
},
Self::Server { code, .. } if *code == SESSION_ALREADY_ATTACHED_ERROR_CODE => true,
_ => false,
}
}
}

View File

@@ -0,0 +1,40 @@
use codex_exec_server_protocol::EXEC_CLOSED_METHOD;
use codex_exec_server_protocol::EXEC_EXITED_METHOD;
use codex_exec_server_protocol::EXEC_OUTPUT_DELTA_METHOD;
use codex_exec_server_protocol::HTTP_REQUEST_BODY_DELTA_METHOD;
use codex_exec_server_protocol::JSONRPCMessage;
use codex_exec_server_protocol::MAX_HTTP_BODY_DELTA_BYTES;
// A transport may materialize one larger frame before its JSON-RPC kind is known.
pub(crate) const MAX_CLIENT_INBOUND_REQUEST_LEN: usize = 8 * 1024;
// Streamed HTTP bodies carry up to 1 MiB before base64 and JSON-RPC framing.
pub(crate) const MAX_CLIENT_INBOUND_NOTIFICATION_LEN: usize = 2 * MAX_HTTP_BODY_DELTA_BYTES;
pub(crate) fn client_inbound_message_exceeded_limit(
message: Result<&JSONRPCMessage, &serde_json::Error>,
encoded_len: usize,
max_request_len: usize,
) -> Option<usize> {
let max_len = match message {
Ok(JSONRPCMessage::Notification(notification))
if matches!(
notification.method.as_str(),
EXEC_OUTPUT_DELTA_METHOD
| EXEC_EXITED_METHOD
| EXEC_CLOSED_METHOD
| HTTP_REQUEST_BODY_DELTA_METHOD
) =>
{
MAX_CLIENT_INBOUND_NOTIFICATION_LEN
}
Ok(JSONRPCMessage::Request(_)) | Ok(JSONRPCMessage::Notification(_)) | Err(_) => {
max_request_len
}
Ok(JSONRPCMessage::Response(_)) | Ok(JSONRPCMessage::Error(_)) => return None,
};
(encoded_len > max_len).then_some(max_len)
}
#[cfg(test)]
#[path = "client_inbound_request_limit_tests.rs"]
mod tests;

View File

@@ -0,0 +1,115 @@
use codex_exec_server_protocol::EXEC_CLOSED_METHOD;
use codex_exec_server_protocol::EXEC_EXITED_METHOD;
use codex_exec_server_protocol::EXEC_OUTPUT_DELTA_METHOD;
use codex_exec_server_protocol::HTTP_REQUEST_BODY_DELTA_METHOD;
use codex_exec_server_protocol::HttpRequestBodyDeltaNotification;
use codex_exec_server_protocol::JSONRPCMessage;
use codex_exec_server_protocol::MAX_HTTP_BODY_DELTA_BYTES;
use super::MAX_CLIENT_INBOUND_NOTIFICATION_LEN;
use super::MAX_CLIENT_INBOUND_REQUEST_LEN;
use super::client_inbound_message_exceeded_limit;
#[test]
fn rejects_oversized_request_hidden_in_raw_value_wrapper() {
let request = serde_json::json!({
"method": "network/policyRequest",
"id": 1,
"params": { "padding": "x".repeat(MAX_CLIENT_INBOUND_REQUEST_LEN) },
});
let encoded = serde_json::to_vec(&serde_json::json!({
"$serde_json::private::RawValue": request.to_string(),
}))
.expect("wrapped request should serialize");
let message = serde_json::from_slice::<JSONRPCMessage>(&encoded);
assert!(matches!(&message, Ok(JSONRPCMessage::Request(_))));
assert_eq!(
client_inbound_message_exceeded_limit(
message.as_ref(),
encoded.len(),
MAX_CLIENT_INBOUND_REQUEST_LEN,
),
Some(MAX_CLIENT_INBOUND_REQUEST_LEN)
);
}
#[test]
fn bounds_notifications_without_rejecting_streamed_http_bodies() {
let streamed_body = serde_json::to_vec(&serde_json::json!({
"method": HTTP_REQUEST_BODY_DELTA_METHOD,
"params": HttpRequestBodyDeltaNotification {
request_id: "request".to_string(),
seq: 1,
delta: vec![0; MAX_HTTP_BODY_DELTA_BYTES].into(),
done: false,
error: None,
},
}))
.expect("streamed body notification should serialize");
let message = serde_json::from_slice::<JSONRPCMessage>(&streamed_body);
assert_eq!(
client_inbound_message_exceeded_limit(
message.as_ref(),
streamed_body.len(),
MAX_CLIENT_INBOUND_REQUEST_LEN,
),
None
);
for method in [
EXEC_OUTPUT_DELTA_METHOD,
EXEC_EXITED_METHOD,
EXEC_CLOSED_METHOD,
] {
let notification = serde_json::to_vec(&serde_json::json!({
"method": method,
"params": { "padding": "x".repeat(MAX_CLIENT_INBOUND_REQUEST_LEN) },
}))
.expect("process notification should serialize");
let message = serde_json::from_slice::<JSONRPCMessage>(&notification);
assert_eq!(
client_inbound_message_exceeded_limit(
message.as_ref(),
notification.len(),
MAX_CLIENT_INBOUND_REQUEST_LEN,
),
None
);
}
let oversized_notification = serde_json::to_vec(&serde_json::json!({
"method": "hostile/notification",
"params": { "padding": "x".repeat(MAX_CLIENT_INBOUND_REQUEST_LEN) },
}))
.expect("oversized notification should serialize");
assert!(oversized_notification.len() < MAX_CLIENT_INBOUND_NOTIFICATION_LEN);
let message = serde_json::from_slice::<JSONRPCMessage>(&oversized_notification);
assert_eq!(
client_inbound_message_exceeded_limit(
message.as_ref(),
oversized_notification.len(),
MAX_CLIENT_INBOUND_REQUEST_LEN,
),
Some(MAX_CLIENT_INBOUND_REQUEST_LEN)
);
}
#[test]
fn preserves_oversized_responses() {
let response = serde_json::to_vec(&serde_json::json!({
"id": 1,
"result": { "padding": "x".repeat(MAX_CLIENT_INBOUND_NOTIFICATION_LEN) },
}))
.expect("response should serialize");
let message = serde_json::from_slice::<JSONRPCMessage>(&response);
assert_eq!(
client_inbound_message_exceeded_limit(
message.as_ref(),
response.len(),
MAX_CLIENT_INBOUND_REQUEST_LEN,
),
None
);
}

View File

@@ -0,0 +1,979 @@
use std::collections::hash_map::DefaultHasher;
use std::hash::Hash;
use std::hash::Hasher;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Duration;
use codex_network_proxy::NetworkDecision;
use codex_network_proxy::NetworkPolicyDecision;
use codex_network_proxy::NetworkPolicyRequest;
use codex_network_proxy::NetworkProtocol;
use codex_network_proxy::NetworkRequestCancellation;
use codex_network_proxy::NetworkRequestCancellationReason;
use serde_json::Value;
use tokio::sync::mpsc;
use tokio::time::Instant;
use tokio::time::sleep;
use tokio::time::timeout;
use tokio::time::timeout_at;
use tokio_util::sync::CancellationToken;
use tracing::Instrument;
use tracing::debug;
use super::ConnectionStatus;
use super::ExecServerClient;
use super::ExecServerError;
use super::Inner;
use super::OrderedSessionEvents;
use super::RecoveryPolicy;
use super::SessionState;
use super::disconnected_message;
use super::fail_all_in_flight_work;
use super::handle_server_notification;
use super::is_transport_closed_error;
use crate::client_transport::ExecServerReconnectStrategy;
use crate::process::ExecProcessEvent;
use crate::protocol::EXEC_READ_METHOD;
use crate::protocol::EXEC_TERMINATE_METHOD;
use crate::protocol::ExecServerNetworkPolicyDecision;
use crate::protocol::ExecServerNetworkProtocol;
use crate::protocol::MAX_NETWORK_POLICY_HOST_BYTES;
use crate::protocol::MAX_NETWORK_POLICY_PROCESS_ID_BYTES;
use crate::protocol::MAX_NETWORK_POLICY_REASON_BYTES;
use crate::protocol::NETWORK_POLICY_REQUEST_METHOD;
use crate::protocol::NetworkPolicyRequestParams;
use crate::protocol::NetworkPolicyRequestResponse;
use crate::protocol::ReadParams;
use crate::protocol::ReadResponse;
use crate::protocol::TerminateParams;
use crate::protocol::TerminateResponse;
use crate::rpc::RpcClient;
use crate::rpc::RpcClientEvent;
use crate::rpc::RpcInboundRequestAdmissionError;
use crate::rpc::SESSION_ALREADY_ATTACHED_ERROR_CODE;
use crate::rpc::invalid_params;
use crate::rpc::method_not_found;
#[cfg(test)]
const SESSION_RECOVERY_TIMEOUT: Duration = Duration::from_millis(500);
#[cfg(not(test))]
const SESSION_RECOVERY_TIMEOUT: Duration = Duration::from_secs(50);
#[cfg(test)]
const SESSION_REPLAY_RESERVE: Duration = Duration::from_millis(100);
#[cfg(not(test))]
const SESSION_REPLAY_RESERVE: Duration = Duration::from_secs(5);
const SESSION_RECOVERY_RETRY_INTERVAL: Duration = Duration::from_millis(100);
const REGISTRY_RECOVERY_INITIAL_RETRY_INTERVAL: Duration = Duration::from_millis(500);
const REGISTRY_RECOVERY_MAX_RETRY_INTERVAL: Duration = Duration::from_secs(5);
const NETWORK_POLICY_DENIAL_REASON: &str = "not_allowed";
struct ClientRequestOutcome {
span: tracing::Span,
result: &'static str,
}
impl ClientRequestOutcome {
fn complete(&mut self, result: &'static str) {
self.result = result;
}
}
impl Drop for ClientRequestOutcome {
fn drop(&mut self) {
self.span.record("result", self.result);
}
}
impl SessionState {
fn last_published_seq(&self) -> u64 {
self.ordered_events
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.last_published_seq
}
fn recover_events(&self, response: ReadResponse) -> Result<bool, ExecServerError> {
let ReadResponse {
chunks,
next_seq,
exited,
exit_code,
closed,
failure,
sandbox_denied,
} = response;
if let Some(message) = failure {
return Err(ExecServerError::Protocol(format!(
"process failed while recovering: {message}"
)));
}
let target_seq = next_seq.saturating_sub(1);
let published_closed = {
let mut ordered_events = self
.ordered_events
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if ordered_events.failure.is_some()
|| ordered_events.closed_published
|| target_seq <= ordered_events.last_published_seq
{
return Ok(false);
}
let pending_exit = ordered_events.pending.range_mut(..=target_seq).find_map(
|(_, event)| match event {
ExecProcessEvent::Exited {
sandbox_denied: pending_sandbox_denied,
..
} => Some(pending_sandbox_denied),
_ => None,
},
);
let exit_pending = pending_exit.is_some();
if let Some(pending_sandbox_denied) = pending_exit {
*pending_sandbox_denied =
Some(pending_sandbox_denied.unwrap_or(false) || sandbox_denied);
}
let mut exit_known = ordered_events.exit_published || exit_pending;
if closed
&& (matches!(
ordered_events.pending.get(&target_seq),
Some(event) if !matches!(event, ExecProcessEvent::Closed { .. })
) || chunks.iter().any(|chunk| chunk.seq == target_seq))
{
return Err(ExecServerError::Protocol(format!(
"process close sequence {target_seq} conflicts with recovered output"
)));
}
let mut published_closed = false;
for chunk in chunks {
if chunk.seq > target_seq {
return Err(ExecServerError::Protocol(format!(
"recovered process output sequence {} exceeds target sequence {target_seq}",
chunk.seq
)));
}
let next_seq = ordered_events.last_published_seq.saturating_add(1);
if exited && !exit_known && chunk.seq > next_seq {
let exit_code = exit_code.ok_or_else(|| {
ExecServerError::Protocol(
"recovering exited process did not include its exit code".to_string(),
)
})?;
ordered_events
.insert_pending(ExecProcessEvent::Exited {
seq: next_seq,
exit_code,
sandbox_denied: Some(sandbox_denied),
})
.map_err(ExecServerError::Protocol)?;
published_closed |= self.publish_ready(&mut ordered_events);
exit_known = true;
}
if chunk.seq > ordered_events.last_published_seq {
ordered_events
.insert_pending(ExecProcessEvent::Output(chunk))
.map_err(ExecServerError::Protocol)?;
published_closed |= self.publish_ready(&mut ordered_events);
}
}
if closed
&& !ordered_events.closed_published
&& !matches!(
ordered_events.pending.get(&target_seq),
Some(ExecProcessEvent::Closed { .. })
)
{
ordered_events
.insert_pending(ExecProcessEvent::Closed { seq: target_seq })
.map_err(ExecServerError::Protocol)?;
}
let event_count = target_seq.saturating_sub(ordered_events.last_published_seq);
let first_unpublished_seq = ordered_events.last_published_seq.saturating_add(1);
let retained_count = if first_unpublished_seq <= target_seq {
ordered_events
.pending
.range(first_unpublished_seq..=target_seq)
.count() as u64
} else {
0
};
let missing_count = event_count.saturating_sub(retained_count);
if exited && !exit_known {
if missing_count != 1 {
return Err(recovery_gap_error(target_seq));
}
let seq = first_missing_seq(&ordered_events, target_seq);
let exit_code = exit_code.ok_or_else(|| {
ExecServerError::Protocol(
"recovering exited process did not include its exit code".to_string(),
)
})?;
ordered_events
.insert_pending(ExecProcessEvent::Exited {
seq,
exit_code,
sandbox_denied: Some(sandbox_denied),
})
.map_err(ExecServerError::Protocol)?;
} else if missing_count != 0 {
return Err(recovery_gap_error(target_seq));
}
published_closed |= self.publish_ready(&mut ordered_events);
published_closed
};
self.note_change(target_seq);
Ok(published_closed)
}
}
fn first_missing_seq(events: &OrderedSessionEvents, target_seq: u64) -> u64 {
let mut expected = events.last_published_seq.saturating_add(1);
for seq in events
.pending
.range(expected..=target_seq)
.map(|(seq, _)| *seq)
{
if seq != expected {
break;
}
expected = expected.saturating_add(1);
}
expected
}
fn recovery_gap_error(target_seq: u64) -> ExecServerError {
ExecServerError::Protocol(format!(
"process events are no longer retained while recovering through sequence {target_seq}"
))
}
impl Inner {
pub(super) async fn rpc_client(self: &Arc<Self>) -> Result<Arc<RpcClient>, ExecServerError> {
let mut connection_changed = self.connection_changed.subscribe();
loop {
if let Some(message) = self.connection_failure() {
return Err(message.into());
}
let rpc_client = {
let connection = self
.connection
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
match &connection.status {
ConnectionStatus::Connected(rpc_client) => Some(Arc::clone(rpc_client)),
ConnectionStatus::Recovering | ConnectionStatus::Failed(_) => None,
}
};
let Some(rpc_client) = rpc_client else {
let _ = connection_changed.changed().await;
continue;
};
if !rpc_client.is_disconnected() {
return Ok(rpc_client);
}
let _ = connection_changed.changed().await;
}
}
pub(super) fn begin_process_start(&self, expected: &Arc<RpcClient>) -> bool {
let mut connection = self
.connection
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let ConnectionStatus::Connected(current) = &connection.status else {
return false;
};
if !Arc::ptr_eq(current, expected) || expected.is_disconnected() {
return false;
}
connection.active_process_starts += 1;
true
}
pub(super) fn finish_process_start(&self) {
{
let mut connection = self
.connection
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if connection.active_process_starts == 0 {
tracing::error!("finished an exec-server process start that was not active");
return;
}
connection.active_process_starts -= 1;
}
self.notify_connection_changed();
}
pub(super) fn is_failed(&self) -> bool {
self.connection_failure().is_some()
}
pub(super) fn connection_failure(&self) -> Option<super::ConnectionFailure> {
let connection = self
.connection
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
match &connection.status {
ConnectionStatus::Failed(message) => Some(message.clone()),
ConnectionStatus::Connected(_) | ConnectionStatus::Recovering => None,
}
}
pub(super) fn request_recovery(
self: &Arc<Self>,
failed_rpc_client: Arc<RpcClient>,
disconnect_message: String,
) {
let should_recover = {
let mut connection = self
.connection
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
match &connection.status {
ConnectionStatus::Connected(current)
if Arc::ptr_eq(current, &failed_rpc_client) && !self.retired.is_cancelled() =>
{
connection.set_status(ConnectionStatus::Recovering);
true
}
ConnectionStatus::Connected(_)
| ConnectionStatus::Recovering
| ConnectionStatus::Failed(_) => false,
}
};
if !should_recover {
return;
}
let started_at = Instant::now();
self.notify_connection_changed();
let inner = Arc::clone(self);
tokio::spawn(async move {
tokio::select! {
biased;
_ = inner.retired.cancelled() => {},
_ = inner.recover(disconnect_message, started_at) => {},
}
});
}
async fn recover(self: &Arc<Self>, disconnect_message: String, started_at: Instant) {
let deadline = started_at + SESSION_RECOVERY_TIMEOUT;
let attach_deadline = deadline - SESSION_REPLAY_RESERVE;
let attach_timeout = attach_deadline - started_at;
let record_deadline = |stage: &str, deadline_owner: &str| {
tracing::event!(
name: "codex.exec_server.session_recovery_timeout",
target: "codex_otel.trace_safe",
tracing::Level::INFO,
event.name = "codex.exec_server.session_recovery_timeout",
stage,
deadline_owner,
elapsed_ms = started_at.elapsed().as_millis() as u64,
);
};
self.fail_all_http_body_streams(disconnect_message.clone())
.await;
if timeout_at(attach_deadline, self.wait_for_process_starts())
.await
.is_err()
{
record_deadline("process_start_drain", "attach_deadline");
let message = format!(
"{disconnect_message}; failed to resume exec-server session: recovery timed out after {attach_timeout:?}"
);
self.fail(super::ConnectionFailure::Disconnected(message))
.await;
return;
}
if self.reconnect_strategy.is_none() {
self.fail(super::ConnectionFailure::Disconnected(disconnect_message))
.await;
return;
}
let Some(session_id) = self.session_id.get().cloned() else {
let message = format!(
"{disconnect_message}; failed to resume exec-server session: missing session id"
);
self.fail(super::ConnectionFailure::Disconnected(message))
.await;
return;
};
let uses_registry_backoff = matches!(
self.reconnect_strategy.as_ref(),
Some(ExecServerReconnectStrategy::NoiseRendezvous { .. })
);
let mut registry_retry_attempt = 0;
let last_error = loop {
let mut stage = "transport";
let result = match timeout_at(
attach_deadline,
self.resume_once(&session_id, &mut stage),
)
.await
{
Ok(Ok((rpc_client, _attempt, executor_registration_id))) => {
stage = "process_replay";
match timeout_at(deadline, self.recover_processes(&rpc_client)).await {
Ok(Ok(())) => {
if self.install_recovered_client(rpc_client, executor_registration_id) {
return;
}
Ok(())
}
Ok(Err(error)) => Err(error),
Err(_) => {
record_deadline(stage, "recovery_deadline");
break format!("recovery timed out after {SESSION_RECOVERY_TIMEOUT:?}");
}
}
}
Ok(Err(error)) => Err(error),
Err(_) => {
record_deadline(stage, "attach_deadline");
break format!("recovery timed out after {attach_timeout:?}");
}
};
if let Err(error) = result {
match &error {
ExecServerError::EnvironmentRegistryRequest(error) if error.is_timeout() => {
record_deadline(stage, "registry_connect");
}
ExecServerError::WebSocketConnectTimeout { .. }
| ExecServerError::InitializeTimedOut { .. } => record_deadline(stage, stage),
_ => {}
}
if let Some(denial) = error.application_network_policy_denial() {
self.fail(super::ConnectionFailure::Policy(denial)).await;
return;
}
if !is_retryable_recovery_error(&error) {
if let ExecServerError::EnvironmentRegistryAuth(message) = error {
self.fail(super::ConnectionFailure::RegistryAuth(message))
.await;
return;
}
break error.to_string();
}
}
let retry_delay = if uses_registry_backoff {
let delay = registry_recovery_retry_delay(&session_id, registry_retry_attempt);
registry_retry_attempt = registry_retry_attempt.saturating_add(1);
delay
} else {
SESSION_RECOVERY_RETRY_INTERVAL
};
let now = Instant::now();
sleep(retry_delay.min(attach_deadline.saturating_duration_since(now))).await;
if Instant::now() >= attach_deadline {
record_deadline("backoff", "attach_deadline");
break format!("recovery timed out after {attach_timeout:?}");
}
};
let message =
format!("{disconnect_message}; failed to resume exec-server session: {last_error}");
self.fail(super::ConnectionFailure::Disconnected(message))
.await;
}
async fn wait_for_process_starts(&self) {
let mut connection_changed = self.connection_changed.subscribe();
loop {
let starts_are_done = self
.connection
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.active_process_starts
== 0;
if starts_are_done {
return;
}
let _ = connection_changed.changed().await;
}
}
fn install_recovered_client(
&self,
rpc_client: Arc<RpcClient>,
executor_registration_id: Option<String>,
) -> bool {
let installed = {
let mut connection = self
.connection
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if self.retired.is_cancelled()
|| !matches!(connection.status, ConnectionStatus::Recovering)
|| rpc_client.is_disconnected()
{
false
} else {
connection.executor_registration_id = executor_registration_id;
connection.set_status(ConnectionStatus::Connected(rpc_client));
true
}
};
if installed {
self.notify_connection_changed();
}
installed
}
fn notify_connection_changed(&self) {
self.connection_changed.send_replace(());
}
async fn resume_once(
self: &Arc<Self>,
session_id: &str,
stage: &mut &'static str,
) -> Result<
(
Arc<RpcClient>,
Option<tokio::sync::OwnedSemaphorePermit>,
Option<String>,
),
ExecServerError,
> {
let reconnect_strategy = self
.reconnect_strategy
.as_ref()
.ok_or_else(|| ExecServerError::Protocol("missing reconnect strategy".to_string()))?;
let attempt = reconnect_strategy.resume(session_id, stage).await?;
let (connection, options, attempt_permit, noise_context) = attempt.into_parts();
let executor_registration_id = noise_context
.as_ref()
.map(|context| context.executor_registration_id.clone());
let (rpc_client, events_rx) = RpcClient::new(connection);
let rpc_client = Arc::new(rpc_client);
let client = ExecServerClient {
inner: Arc::clone(self),
recovery_policy: RecoveryPolicy::Wait,
};
// Resuming a session redirects notifications from its running processes
// to this connection during initialize. Drain them immediately so a
// burst cannot fill the bounded event channel and block the initialize
// response behind it.
client.spawn_rpc_reader(&rpc_client, events_rx);
*stage = "initialize";
client
.initialize_rpc(&rpc_client, options, noise_context)
.await?;
Ok((rpc_client, attempt_permit, executor_registration_id))
}
async fn recover_processes(
self: &Arc<Self>,
rpc_client: &RpcClient,
) -> Result<(), ExecServerError> {
let sessions = self.sessions.load_full();
for (process_id, session) in sessions.iter() {
if !session.recoverable.load(Ordering::Acquire) {
continue;
}
let response = rpc_client
.call::<_, ReadResponse>(
EXEC_READ_METHOD,
&ReadParams {
process_id: process_id.clone(),
after_seq: Some(session.last_published_seq()),
max_bytes: None,
wait_ms: Some(0),
},
)
.await
.map_err(ExecServerError::from);
let recovered = match response {
Ok(response) => session.recover_events(response),
Err(error) if is_transport_closed_error(&error) => return Err(error),
Err(error) => Err(error),
};
match recovered {
Ok(true) => self.remove_session_if(process_id, session),
Ok(false) => {}
Err(error) => {
session
.network_policy
.cancellation
.record(NetworkRequestCancellationReason::ProcessCancelled);
let terminated: Result<TerminateResponse, ExecServerError> = rpc_client
.call_for_cleanup(
EXEC_TERMINATE_METHOD,
&TerminateParams {
process_id: process_id.clone(),
},
)
.await
.map_err(ExecServerError::from);
if let Err(terminate_error) = terminated
&& is_transport_closed_error(&terminate_error)
{
return Err(terminate_error);
}
self.remove_session_if(process_id, session);
session.set_failure(format!("failed to recover process {process_id}: {error}"));
}
}
}
Ok(())
}
async fn fail(self: &Arc<Self>, message: super::ConnectionFailure) {
let (message, newly_failed) = {
let mut connection = self
.connection
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
match &connection.status {
ConnectionStatus::Failed(existing) => (existing.clone(), false),
ConnectionStatus::Connected(_) | ConnectionStatus::Recovering => {
connection.set_status(ConnectionStatus::Failed(message.clone()));
(message, true)
}
}
};
if newly_failed {
self.notify_connection_changed();
fail_all_in_flight_work(self, message.to_string()).await;
}
}
}
impl ExecServerClient {
pub(super) fn spawn_rpc_reader(
&self,
rpc_client: &Arc<RpcClient>,
mut events_rx: mpsc::Receiver<RpcClientEvent>,
) {
let inner = Arc::downgrade(&self.inner);
let rpc_inbound_request_slots = Arc::clone(&self.inner.rpc_inbound_request_slots);
let rpc_client = Arc::downgrade(rpc_client);
let connection_cancelled = CancellationToken::new();
let connection_cancel_guard = connection_cancelled.clone().drop_guard();
tokio::spawn(async move {
let _connection_cancel_guard = connection_cancel_guard;
while let Some(event) = events_rx.recv().await {
let (Some(inner), Some(rpc_client)) = (inner.upgrade(), rpc_client.upgrade())
else {
return;
};
match event {
RpcClientEvent::Request {
request,
request_span,
} => {
let mut request_outcome = ClientRequestOutcome {
span: request_span,
result: "disconnected",
};
if request.method != NETWORK_POLICY_REQUEST_METHOD {
let error = method_not_found(format!(
"exec-server client does not implement `{}` yet",
request.method
));
if rpc_client.respond_error(request.id, error).await.is_err() {
inner.request_recovery(
rpc_client,
disconnected_message(/*reason*/ None),
);
return;
}
request_outcome.complete("error");
continue;
}
request_outcome
.span
.record("otel.name", NETWORK_POLICY_REQUEST_METHOD);
let request_guard = match rpc_client
.admit_inbound_request(&request.id, &rpc_inbound_request_slots)
{
Ok(request_guard) => request_guard,
Err(RpcInboundRequestAdmissionError::InvalidRequestId) => {
rpc_client.close_transport().await;
inner.request_recovery(
rpc_client,
"exec-server sent an invalid request ID".to_string(),
);
return;
}
Err(RpcInboundRequestAdmissionError::DuplicateRequestId) => {
rpc_client.close_transport().await;
inner.request_recovery(
rpc_client,
"exec-server reused an in-flight request ID".to_string(),
);
return;
}
Err(RpcInboundRequestAdmissionError::AtCapacity) => {
let response = NetworkPolicyRequestResponse {
decision: ExecServerNetworkPolicyDecision::Deny {
reason: NETWORK_POLICY_DENIAL_REASON.to_string(),
},
};
if rpc_client.respond(request.id, &response).await.is_err() {
inner.request_recovery(
rpc_client,
disconnected_message(/*reason*/ None),
);
return;
}
request_outcome.complete("success");
continue;
}
};
let request_id = request.id;
let params: NetworkPolicyRequestParams =
match serde_json::from_value(request.params.unwrap_or(Value::Null)) {
Ok(params) => params,
Err(_) => {
let error = invalid_params(
"invalid network policy request params".to_string(),
);
if rpc_client.respond_error(request_id, error).await.is_err() {
inner.request_recovery(
rpc_client,
disconnected_message(/*reason*/ None),
);
return;
}
request_outcome.complete("error");
continue;
}
};
let process_id = params.process_id;
let request = params.request;
let process_id_valid = !process_id.is_empty()
&& process_id.len() <= MAX_NETWORK_POLICY_PROCESS_ID_BYTES;
let host_valid = !request.host.is_empty()
&& request.host.len() <= MAX_NETWORK_POLICY_HOST_BYTES
&& !request.host.chars().any(char::is_control)
&& !request.host.chars().any(char::is_whitespace);
let session = (process_id_valid && host_valid)
.then(|| inner.get_session(&process_id))
.flatten();
let controller = session
.as_ref()
.and_then(|session| session.network_policy.controller.load_full());
let process_cancelled = session
.as_ref()
.map(|session| session.network_policy.cancelled.clone());
let process_cancellation = session
.as_ref()
.map(|session| session.network_policy.cancellation.clone());
let cancellation = NetworkRequestCancellation::default();
let expected_session = session.as_ref().map(Arc::downgrade);
let policy_request =
(process_id_valid && host_valid).then_some(NetworkPolicyRequest {
protocol: match request.protocol {
ExecServerNetworkProtocol::Http => NetworkProtocol::Http,
ExecServerNetworkProtocol::HttpsConnect => {
NetworkProtocol::HttpsConnect
}
ExecServerNetworkProtocol::Socks5Tcp => {
NetworkProtocol::Socks5Tcp
}
ExecServerNetworkProtocol::Socks5Udp => {
NetworkProtocol::Socks5Udp
}
},
host: request.host,
port: request.port,
environment_id: None,
client_addr: None,
method: None,
command: None,
exec_policy_hint: None,
execution_id: None,
disconnect: None,
cancellation: Some(cancellation.clone()),
});
let inner = Arc::downgrade(&inner);
let rpc_client = Arc::downgrade(&rpc_client);
let connection_cancelled = connection_cancelled.clone();
let task_span = request_outcome.span.clone();
let task = async move {
let _request_guard = request_guard;
let decision = match (controller, policy_request, process_cancelled) {
(Some(controller), Some(request), Some(process_cancelled)) => {
// Keep the decision future outside select/timeout so its
// guard sees the cancellation cause before it is dropped.
let mut decision = controller.decider.decide(request);
tokio::select! {
biased;
_ = connection_cancelled.cancelled() => {
cancellation.record(NetworkRequestCancellationReason::ConnectionClosed);
return;
},
_ = process_cancelled.cancelled() => {
cancellation.record(process_cancellation.as_ref()
.and_then(NetworkRequestCancellation::reason)
.unwrap_or(NetworkRequestCancellationReason::ProcessCancelled));
NetworkDecision::deny(NETWORK_POLICY_DENIAL_REASON)
}
result = timeout(
controller.timeout,
&mut decision,
) => result.unwrap_or_else(|_| {
cancellation.record(NetworkRequestCancellationReason::TimedOut);
NetworkDecision::deny(NETWORK_POLICY_DENIAL_REASON)
}),
}
}
(None, _, _) | (_, None, _) | (_, _, None) => {
NetworkDecision::deny(NETWORK_POLICY_DENIAL_REASON)
}
};
if let Some(expected_session) = expected_session {
let (Some(inner), Some(expected_session)) =
(inner.upgrade(), expected_session.upgrade())
else {
return;
};
if !inner
.get_session(&process_id)
.is_some_and(|session| Arc::ptr_eq(&session, &expected_session))
{
return;
}
}
let Some(rpc_client) = rpc_client.upgrade() else {
return;
};
let decision = match decision {
NetworkDecision::Allow => ExecServerNetworkPolicyDecision::Allow,
NetworkDecision::Deny {
reason, decision, ..
} if reason.len() <= MAX_NETWORK_POLICY_REASON_BYTES
&& !reason.chars().any(char::is_control) =>
{
match decision {
NetworkPolicyDecision::Deny => {
ExecServerNetworkPolicyDecision::Deny { reason }
}
NetworkPolicyDecision::Ask => {
ExecServerNetworkPolicyDecision::Ask { reason }
}
}
}
NetworkDecision::Deny { .. } => {
ExecServerNetworkPolicyDecision::Deny {
reason: NETWORK_POLICY_DENIAL_REASON.to_string(),
}
}
};
if let Err(error) = rpc_client
.respond(request_id, &NetworkPolicyRequestResponse { decision })
.await
{
debug!(
?error,
"failed to send network policy decision to exec-server"
);
} else {
request_outcome.complete("success");
}
};
tokio::spawn(task.instrument(task_span));
}
RpcClientEvent::Notification(notification) => {
if let Err(error) = handle_server_notification(&inner, notification).await {
rpc_client.close_transport().await;
inner.request_recovery(
rpc_client,
format!("exec-server notification handling failed: {error}"),
);
return;
}
}
RpcClientEvent::Disconnected { reason } => {
inner.request_recovery(rpc_client, disconnected_message(reason.as_deref()));
return;
}
}
}
});
}
}
pub(crate) fn is_retryable_recovery_error(error: &ExecServerError) -> bool {
if error.application_network_policy_denial().is_some() {
return false;
}
if let ExecServerError::ConnectionAttempt(error) = error {
return is_retryable_recovery_error(error.as_ref());
}
is_transport_closed_error(error)
|| matches!(
error,
ExecServerError::ProvisioningFailed(_)
| ExecServerError::WebSocketConnectTimeout { .. }
| ExecServerError::WebSocketConnect { .. }
| ExecServerError::InitializeTimedOut { .. }
)
|| is_retryable_registry_error(error)
|| matches!(
error,
ExecServerError::Server { code, .. }
if *code == SESSION_ALREADY_ATTACHED_ERROR_CODE
)
}
pub(crate) fn is_retryable_registry_error(error: &ExecServerError) -> bool {
matches!(
error,
ExecServerError::EnvironmentRegistryRequest(error)
if error.is_connect()
|| error.is_timeout()
|| error.is_body()
|| matches!(
error,
codex_http_client::RouteAwareRequestError::Request(error)
if error.is_decode()
)
) || matches!(
error,
ExecServerError::EnvironmentRegistryHttp { status, .. }
if status.is_server_error()
|| *status == http::StatusCode::REQUEST_TIMEOUT
|| *status == http::StatusCode::TOO_MANY_REQUESTS
) || is_environment_offline_error(error)
}
pub(crate) fn is_environment_offline_error(error: &ExecServerError) -> bool {
matches!(
error,
ExecServerError::EnvironmentRegistryHttp { status, code, .. }
if *status == http::StatusCode::CONFLICT
&& code.as_deref() == Some("environment_offline")
)
}
pub(crate) fn registry_recovery_retry_delay(retry_key: &str, attempt: u32) -> Duration {
let multiplier = 1_u32.checked_shl(attempt.min(4)).unwrap_or(u32::MAX);
let base_delay = REGISTRY_RECOVERY_INITIAL_RETRY_INTERVAL
.saturating_mul(multiplier)
.min(REGISTRY_RECOVERY_MAX_RETRY_INTERVAL);
let base_millis = base_delay.as_millis() as u64;
let mut hasher = DefaultHasher::new();
retry_key.hash(&mut hasher);
attempt.hash(&mut hasher);
Duration::from_millis(base_millis + hasher.finish() % (base_millis / 2 + 1))
}
#[cfg(test)]
#[path = "client_recovery_tests.rs"]
mod tests;

View File

@@ -0,0 +1,262 @@
use std::time::Duration;
use pretty_assertions::assert_eq;
use super::*;
use crate::protocol::ExecOutputStream;
use crate::protocol::ProcessOutputChunk;
fn registry_error(status: http::StatusCode, code: Option<&str>) -> ExecServerError {
ExecServerError::EnvironmentRegistryHttp {
status,
code: code.map(str::to_string),
message: "registry unavailable".to_string(),
}
}
#[test]
fn registry_recovery_retry_delay_exponentially_backs_off_and_caps() {
let cases = [
(0, Duration::from_millis(500)),
(1, Duration::from_secs(1)),
(2, Duration::from_secs(2)),
(3, Duration::from_secs(4)),
(4, Duration::from_secs(5)),
(20, Duration::from_secs(5)),
];
for (attempt, base) in cases {
let delay = registry_recovery_retry_delay("session-1", attempt);
assert!(delay >= base, "delay {delay:?} for attempt {attempt}");
assert!(
delay <= base + base / 2,
"delay {delay:?} for attempt {attempt}"
);
}
}
#[test]
fn recovery_retries_transient_registry_errors() {
for status in [
http::StatusCode::REQUEST_TIMEOUT,
http::StatusCode::TOO_MANY_REQUESTS,
http::StatusCode::INTERNAL_SERVER_ERROR,
http::StatusCode::BAD_GATEWAY,
http::StatusCode::SERVICE_UNAVAILABLE,
] {
let error = registry_error(status, /*code*/ None);
assert!(is_retryable_registry_error(&error));
assert!(is_retryable_recovery_error(&error));
assert!(is_retryable_recovery_error(
&ExecServerError::ConnectionAttempt(Arc::new(error))
));
}
}
#[test]
fn recovery_retries_registry_request_timeouts() {
let error = ExecServerError::EnvironmentRegistryRequest(
codex_http_client::RouteAwareRequestError::Timeout,
);
assert!(is_retryable_registry_error(&error));
assert!(is_retryable_recovery_error(&error));
}
#[test]
fn recovery_retries_environment_offline_conflicts() {
let error = registry_error(http::StatusCode::CONFLICT, Some("environment_offline"));
assert!(is_retryable_registry_error(&error));
assert!(is_retryable_recovery_error(&error));
}
#[test]
fn recovery_does_not_retry_other_registry_conflicts() {
let error = registry_error(http::StatusCode::CONFLICT, Some("registration_conflict"));
assert!(!is_retryable_registry_error(&error));
assert!(!is_retryable_recovery_error(&error));
assert!(!is_retryable_recovery_error(
&ExecServerError::ConnectionAttempt(Arc::new(error))
));
}
#[test]
fn process_event_reorder_rejects_oversized_output() {
let state = SessionState::new(/*recoverable*/ true);
let error = state
.publish_ordered_event(ExecProcessEvent::Output(ProcessOutputChunk {
seq: 1,
stream: ExecOutputStream::Stdout,
chunk: vec![0; super::super::MAX_PENDING_PROCESS_EVENT_BYTES + 1].into(),
}))
.expect_err("oversized pending process output should be rejected");
assert!(error.contains("bytes"));
}
#[test]
fn process_event_reorder_accepts_gap_closing_event_at_limits() {
let state = SessionState::new(/*recoverable*/ true);
let chunk_size =
super::super::MAX_PENDING_PROCESS_EVENT_BYTES / super::super::MAX_PENDING_PROCESS_EVENTS;
let last_seq = super::super::MAX_PENDING_PROCESS_EVENTS as u64 + 1;
for seq in 2..=last_seq {
assert!(
!state
.publish_ordered_event(ExecProcessEvent::Output(ProcessOutputChunk {
seq,
stream: ExecOutputStream::Stdout,
chunk: vec![0; chunk_size].into(),
}))
.expect("future output should fit within reorder limits")
);
}
assert!(
!state
.publish_ordered_event(ExecProcessEvent::Output(ProcessOutputChunk {
seq: 1,
stream: ExecOutputStream::Stdout,
chunk: b"x".to_vec().into(),
}))
.expect("gap-closing output should drain the reorder buffer")
);
let ordered_events = state
.ordered_events
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
assert_eq!(
(
ordered_events.last_published_seq,
ordered_events.pending.len(),
ordered_events.pending_bytes,
),
(last_seq, 0, 0)
);
}
#[test]
fn recovery_handles_dense_tail_output_and_newer_notification() {
let state = SessionState::new(/*recoverable*/ true);
let last_seq = super::super::MAX_PENDING_PROCESS_EVENTS as u64 + 2;
let live_seq = last_seq + 1;
assert!(
!state
.publish_ordered_event(ExecProcessEvent::Output(ProcessOutputChunk {
seq: live_seq,
stream: ExecOutputStream::Stdout,
chunk: b"live".to_vec().into(),
}))
.expect("live output should remain bounded while recovery fills the gap")
);
let chunks = (2..=last_seq)
.map(|seq| ProcessOutputChunk {
seq,
stream: ExecOutputStream::Stdout,
chunk: b"x".to_vec().into(),
})
.collect();
assert!(
!state
.recover_events(ReadResponse {
chunks,
next_seq: last_seq + 1,
exited: true,
exit_code: Some(17),
closed: false,
failure: None,
sandbox_denied: false,
})
.expect("dense retained output should recover")
);
let ordered_events = state
.ordered_events
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
assert_eq!(
(
ordered_events.last_published_seq,
ordered_events.pending.len(),
ordered_events.pending_bytes,
),
(live_seq, 0, 0)
);
}
#[test]
fn recovery_rejects_output_at_closed_sequence() {
let state = SessionState::new(/*recoverable*/ true);
let error = state
.recover_events(ReadResponse {
chunks: vec![ProcessOutputChunk {
seq: 1,
stream: ExecOutputStream::Stdout,
chunk: b"output".to_vec().into(),
}],
next_seq: 2,
exited: false,
exit_code: None,
closed: true,
failure: None,
sandbox_denied: false,
})
.expect_err("output should not occupy the closed sequence");
assert!(
error
.to_string()
.contains("conflicts with recovered output")
);
}
#[tokio::test]
async fn recovery_adds_sandbox_denial_to_pending_exit_event() {
let state = SessionState::new(/*recoverable*/ true);
assert!(
!state
.publish_ordered_event(ExecProcessEvent::Exited {
seq: 2,
exit_code: 1,
sandbox_denied: None,
})
.expect("pending exit should fit within reorder limits")
);
state
.recover_events(ReadResponse {
chunks: vec![ProcessOutputChunk {
seq: 1,
stream: ExecOutputStream::Stderr,
chunk: b"sandbox denied".to_vec().into(),
}],
next_seq: 3,
exited: true,
exit_code: Some(1),
closed: false,
failure: None,
sandbox_denied: true,
})
.expect("recovery should publish the pending exit");
let mut events = state.subscribe_events();
assert!(matches!(
events.recv().await,
Ok(ExecProcessEvent::Output(_))
));
assert_eq!(
events.recv().await,
Ok(ExecProcessEvent::Exited {
seq: 2,
exit_code: 1,
sandbox_denied: Some(true),
})
);
}

View File

@@ -0,0 +1,316 @@
//! Explicit connection refresh after a planned executor replacement.
//!
//! Ordinary recovery tries to resume the same executor session after a transient
//! disconnect. Replacement needs a fresh session, without waiting for old recovery
//! to give up. The caller supplies the ordering: register the replacement first,
//! then refresh. Executor identity stays inside this connection layer.
//!
//! Flow: fresh registry lookup -> reuse or retire session -> connect if needed ->
//! live status probe. The lazy client and its `Environment` remain the same objects;
//! only the underlying `ExecServerClient` may change. The public caller contract is on
//! `Environment::refresh_connection`.
//!
//! Two races determine the synchronization here. A client installed during the
//! lookup makes that lookup stale, so refresh checks again. A connection attempt
//! cancelled by refresh must never install later. Cancellation and installation
//! synchronize on the `current_client` lock; acquire `reconnect` first when both are needed.
//! `refresh_lock` serializes only explicit refreshes; ordinary connection and recovery
//! work can continue concurrently. Retired sessions cannot publish environment state.
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use futures::future::BoxFuture;
use tokio::sync::OnceCell;
use tokio::sync::watch;
use tokio::time::Instant;
use tokio::time::timeout;
use tokio_util::sync::CancellationToken;
use super::ConnectionResult;
use super::ConnectionStatus;
use super::ExecServerClient;
use super::ExecServerError;
use super::Inner;
use super::LazyRemoteExecServerClient;
use super::fail_all_in_flight_work;
use crate::ConnectionAttemptOutcome;
use crate::EnvironmentConnectionState;
use crate::NoiseChannelPublicKey;
use crate::client_api::DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT;
use crate::client_api::ExecServerTransportParams;
use crate::client_api::NoiseRendezvousConnectBundle;
use crate::client_api::NoiseRendezvousConnectProvider;
use crate::client_transport::ExecServerReconnectStrategy;
/// Shared startup/reconnect result plus cancellation for work superseded by refresh.
/// The optional transport carries a refresh lookup's bundle into the normal connector.
#[derive(Default)]
pub(super) struct ConnectionAttempt {
pub(super) result: OnceCell<ConnectionResult>,
pub(super) cancelled: CancellationToken,
pub(super) transport: Option<ExecServerTransportParams>,
}
struct ConnectionObservation<'a> {
started: Option<Instant>,
outcome: ConnectionAttemptOutcome,
observer: Option<&'a super::ConnectionObserver>,
}
impl Drop for ConnectionObservation<'_> {
fn drop(&mut self) {
if let (Some(started), Some(observer)) = (self.started, self.observer) {
observer(started.elapsed(), self.outcome);
}
}
}
// Use the compared bundle intact for the first connection: address, key and authorization
// belong together. Later lookups, including authorization refresh, use the real provider.
struct PrefetchedConnectProvider {
bundle: StdMutex<Option<NoiseRendezvousConnectBundle>>,
provider: Arc<dyn NoiseRendezvousConnectProvider>,
}
impl NoiseRendezvousConnectProvider for PrefetchedConnectProvider {
fn connect_bundle(
&self,
harness_public_key: NoiseChannelPublicKey,
) -> BoxFuture<'_, Result<NoiseRendezvousConnectBundle, ExecServerError>> {
Box::pin(async move {
let bundle = self
.bundle
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take();
match bundle {
Some(bundle) => Ok(bundle),
None => self.provider.connect_bundle(harness_public_key).await,
}
})
}
}
impl LazyRemoteExecServerClient {
#[expect(
clippy::await_holding_invalid_type,
reason = "serialize explicit refreshes, not ordinary connection or recovery attempts"
)]
pub(crate) async fn refresh_connection(&self) -> Result<(), ExecServerError> {
let _refresh = self.refresh_lock.lock().await;
let (previous, attempt) = loop {
let observed = self.cached_client();
let observed_registration = observed
.as_ref()
.and_then(ExecServerClient::executor_registration_id);
let mut transport = self.transport_params.clone().ok_or_else(|| {
ExecServerError::Protocol(
"connection refresh requires a Noise registry".to_string(),
)
})?;
let target = match &mut transport {
ExecServerTransportParams::Deferred(deferred) => &mut deferred.transport,
transport => transport,
};
let ExecServerTransportParams::NoiseRendezvous { provider, identity } = target else {
return Err(ExecServerError::Protocol(
"connection refresh requires a Noise registry".to_string(),
));
};
// This lookup is independent of the old session and its recovery deadline.
let bundle = timeout(
DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT,
provider.connect_bundle(identity.public_key()),
)
.await
.map_err(|_| {
ExecServerError::EnvironmentRegistryRequest(
codex_http_client::RouteAwareRequestError::Timeout,
)
})??;
let executor_public_key = bundle.executor_public_key.clone();
let executor_registration_id = bundle.executor_registration_id.clone();
*provider = Arc::new(PrefetchedConnectProvider {
bundle: StdMutex::new(Some(bundle)),
provider: Arc::clone(provider),
});
let mut reconnect = self
.reconnect
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let current = self
.current_client
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
// A new client makes the lookup stale. Recovery can also renew the
// registration on the same client, so compare it under the connection lock.
if !match (&observed, &*current) {
(Some(observed), Some(current)) => Arc::ptr_eq(&observed.inner, &current.inner),
(None, None) => true,
_ => false,
} {
continue;
}
if let Some(client) = current.as_ref() {
let connection = client
.inner
.connection
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if connection.executor_registration_id != observed_registration {
continue;
}
// Preserve same-executor recovery; the final probe fails fast if still recovering.
if !matches!(connection.status, ConnectionStatus::Failed(_))
&& connection.executor_registration_id.as_ref()
== Some(&executor_registration_id)
&& matches!(
client.inner.reconnect_strategy.as_ref(),
Some(ExecServerReconnectStrategy::NoiseRendezvous {
executor_public_key: key, ..
}) if key == &executor_public_key
)
{
break (current.clone(), None);
}
// Claim retirement before recovery can install another registration.
// Transport shutdown and pending-work cleanup happen outside these locks.
client.inner.retired.cancel();
}
// Cancellation and connection installation use the same lock. A late
// handshake cannot install a client after its attempt has been superseded.
self.startup.cancelled.cancel();
if let Some(attempt) = reconnect.as_ref() {
attempt.cancelled.cancel();
}
self.environment_connection_state_tx
.send_replace(EnvironmentConnectionState::Disconnected);
let attempt = Arc::new(ConnectionAttempt {
transport: Some(transport),
..Default::default()
});
*reconnect = Some(Arc::clone(&attempt));
break (current.clone(), Some(attempt));
};
let client = match attempt {
Some(attempt) => {
if let Some(previous) = previous {
previous.inner.retire().await;
}
let result = attempt
.result
.get_or_init(|| self.connect_once(&attempt))
.await
.clone();
let mut reconnect = self
.reconnect
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if reconnect
.as_ref()
.is_some_and(|current| Arc::ptr_eq(current, &attempt))
{
*reconnect = None;
}
result.map_err(ExecServerError::ConnectionAttempt)?
}
None => previous.ok_or_else(|| {
ExecServerError::Protocol("current executor session is missing".to_string())
})?,
};
// Metadata may be cached; readiness requires a live, non-recovering probe.
client.environment_status().await.map(drop)
}
#[tracing::instrument(name = "codex.exec_server.remote.connect", skip_all)]
pub(super) fn connect_once<'a>(
&'a self,
attempt: &'a ConnectionAttempt,
) -> BoxFuture<'a, ConnectionResult> {
// Keep the transport future out of every caller's async layout, including
// the CLI entry point, which otherwise exceeds rustc's query-depth limit.
Box::pin(async move {
let transport = attempt
.transport
.as_ref()
.or(self.transport_params.as_ref())
.ok_or_else(|| {
Arc::new(ExecServerError::Protocol(
"missing transport params for lazy exec-server connection".to_string(),
))
})?;
let mut observation = ConnectionObservation {
started: None,
outcome: ConnectionAttemptOutcome::Cancelled,
observer: (self.cached_client().is_none() && attempt.transport.is_none())
.then(|| self.connection_observer.get())
.flatten(),
};
let result = tokio::select! {
biased;
_ = attempt.cancelled.cancelled() => return Err(Arc::new(ExecServerError::Disconnected("connection attempt was superseded".to_string()))),
result = ExecServerClient::connect_for_transport(transport.clone(), self.http_client_factory.clone(), &mut observation.started) => result,
};
let client = result.map_err(|error| {
observation.outcome = ConnectionAttemptOutcome::Failure;
Arc::new(error)
})?;
// Cancellation can race with a completed handshake. Recheck before attaching
// state or installing the client, under the same lock used by refresh.
{
let mut current = self
.current_client
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if !attempt.cancelled.is_cancelled() {
client.attach_environment_connection_state(
self.environment_connection_state_tx.clone(),
);
*current = Some(client.clone());
observation.outcome = ConnectionAttemptOutcome::Success;
return Ok(client);
}
}
client.inner.retire().await;
Err(Arc::new(ExecServerError::Disconnected(
"connection attempt was superseded".to_string(),
)))
})
}
}
impl Inner {
async fn retire(self: &Arc<Self>) {
let message = "exec-server executor was replaced".to_string();
let rpc_client = {
let mut connection = self
.connection
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
// Detach before a later transport completion can publish stale state.
connection.environment_connection_state_tx =
watch::channel(EnvironmentConnectionState::Disconnected).0;
let rpc_client = match &connection.status {
ConnectionStatus::Connected(client) => Some(Arc::clone(client)),
ConnectionStatus::Recovering | ConnectionStatus::Failed(_) => None,
};
self.retired.cancel();
connection.set_status(ConnectionStatus::Failed(
super::ConnectionFailure::Disconnected(message.clone()),
));
rpc_client
};
self.connection_changed.send_replace(());
// Drain pending RPCs before stream cleanup, which may wait for other work.
if let Some(rpc_client) = rpc_client {
rpc_client.close_transport().await;
}
fail_all_in_flight_work(self, message).await;
}
}
#[cfg(test)]
#[path = "client_refresh_tests.rs"]
mod tests;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,23 @@
//! Caller-side RPC attempt counts using the client's protocol method names, independent of tracing.
use codex_otel::EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC;
use codex_otel::MetricsClient;
pub(crate) fn record_client_request(metrics: Option<&MetricsClient>, method: &str) {
let Some(metrics) = metrics else {
return;
};
// Record before local admission so failures and cancelled calls still count
// as attempts. Notifications and responses never enter these call paths.
if metrics
.counter_with_description(
EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC,
"Total number of client-side exec-server RPC attempts, including local failures.",
/*inc*/ 1,
&[("method", method)],
)
.is_err()
{
tracing::warn!("failed to emit exec-server client request counter");
}
}

View File

@@ -0,0 +1,915 @@
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncReadExt;
use tokio::io::BufReader;
use tokio::process::Command;
use tokio::sync::OwnedSemaphorePermit;
use tokio::time::Instant;
use tokio::time::sleep;
use tokio::time::timeout;
use tokio::time::timeout_at;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_util::task::AbortOnDropHandle;
use tracing::debug;
use tracing::warn;
use codex_api::AuthError;
use codex_api::AuthProvider;
use codex_http_client::HttpClientFactory;
use codex_http_client::Request;
use codex_http_client::RequestCompression;
use codex_protocol::shell_environment::scrub_non_inheritable_env_vars;
use codex_utils_rustls_provider::ensure_rustls_crypto_provider;
use codex_websocket_client::WebSocketConnection;
use codex_websocket_client::WebSocketConnector;
use codex_websocket_client::WebSocketTlsMode;
use http::HeaderMap;
use crate::ExecServerClient;
use crate::ExecServerError;
use crate::client::NoiseInitializeContext;
use crate::client::accepted::AcceptedConnectionSource;
use crate::client::is_environment_offline_error;
use crate::client::is_retryable_registry_error;
use crate::client::registry_recovery_retry_delay;
use crate::client_api::DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT;
use crate::client_api::DEFAULT_REMOTE_EXEC_SERVER_INITIALIZE_TIMEOUT;
use crate::client_api::ExecServerClientConnectOptions;
use crate::client_api::ExecServerTransportParams;
use crate::client_api::NoiseRendezvousConnectArgs;
use crate::client_api::NoiseRendezvousConnectBundle;
use crate::client_api::NoiseRendezvousConnectProvider;
use crate::client_api::RemoteExecServerConnectArgs;
use crate::client_api::StdioExecServerCommand;
use crate::client_api::StdioExecServerConnectArgs;
use crate::connection::JsonRpcConnection;
use crate::connection::JsonRpcConnectionEvent;
use crate::noise_channel::NoiseChannelIdentity;
use crate::noise_relay::NoiseHarnessConnectionArgs;
use crate::noise_relay::noise_harness_connection_from_websocket_with_readiness;
use crate::noise_relay::noise_relay_websocket_config;
use crate::relay::HARNESS_KEY_VALIDATION_TIMEOUT;
use crate::relay::harness_connection_from_websocket;
use crate::trace_context::current_rendezvous_headers;
const MAX_STDIO_STDERR_LOG_LINE_LEN: u64 = 8 * 1024;
const ENVIRONMENT_CLIENT_NAME: &str = "codex-environment";
const INITIAL_REGISTRY_MAX_RETRIES: u32 = 4;
const REGISTRY_REQUEST_TIMEOUT: Duration = Duration::from_secs(6);
const INITIAL_REGISTRY_OPERATION_TIMEOUT: Duration = Duration::from_secs(14);
const PROVISIONED_ENVIRONMENT_CONNECT_TIMEOUT: Duration = Duration::from_secs(5 * 60);
// Leave time after executor validation for relay transit and RPC initialize.
const NOISE_RECOVERY_INITIALIZE_TIMEOUT: Duration =
HARNESS_KEY_VALIDATION_TIMEOUT.saturating_add(Duration::from_secs(10));
async fn connect_noise_bundle(
provider: &dyn NoiseRendezvousConnectProvider,
identity: &NoiseChannelIdentity,
) -> Result<NoiseRendezvousConnectBundle, ExecServerError> {
timeout(
REGISTRY_REQUEST_TIMEOUT,
provider.connect_bundle(identity.public_key()),
)
.await
.map_err(|_| {
ExecServerError::EnvironmentRegistryRequest(
codex_http_client::RouteAwareRequestError::Timeout,
)
})?
}
pub(crate) async fn connect_websocket_request(
request: http::Request<()>,
diagnostic_url: String,
connector: WebSocketConnector,
connect_timeout: Duration,
use_loopback_direct: bool,
) -> Result<WebSocketConnection, ExecServerError> {
let websocket_config = tokio_tungstenite::tungstenite::protocol::WebSocketConfig::default();
timeout(connect_timeout, async {
if use_loopback_direct {
connector
.connect_loopback_direct(request, websocket_config)
.await
} else {
connector.connect(request, websocket_config).await
}
})
.await
.map_err(|_| ExecServerError::WebSocketConnectTimeout {
url: diagnostic_url.clone(),
timeout: connect_timeout,
})?
.map(|(websocket, _)| websocket)
.map_err(|source| ExecServerError::WebSocketConnect {
url: diagnostic_url,
source,
})
}
pub(crate) async fn authenticate_websocket_request(
request: &mut http::Request<()>,
auth_provider: &dyn AuthProvider,
) -> Result<(), AuthError> {
let url = request.uri().to_string();
let signing_url = if let Some(rest) = url.strip_prefix("wss://") {
format!("https://{rest}")
} else if let Some(rest) = url.strip_prefix("ws://") {
format!("http://{rest}")
} else {
url
};
let mut auth_request = Request::new(request.method().clone(), signing_url);
// Intermediaries may rewrite WebSocket and hop-by-hop headers after signing.
if let Some(host) = request.headers().get(http::header::HOST) {
auth_request
.headers
.insert(http::header::HOST, host.clone());
}
let authenticated = auth_provider.apply_auth(auth_request).await?;
if authenticated.method != *request.method() {
return Err(AuthError::Build(
"authentication changed the WebSocket request method".to_string(),
));
}
if authenticated.body.is_some() || authenticated.compression != RequestCompression::None {
return Err(AuthError::Build(
"authentication added a body or compression to the WebSocket request".to_string(),
));
}
let authenticated_websocket_url = websocket_url_from_authenticated_url(&authenticated.url)?;
let authenticated_uri = authenticated_websocket_url.parse().map_err(|error| {
AuthError::Build(format!("invalid authenticated WebSocket URL: {error}"))
})?;
let original_host = request.headers().get(http::header::HOST).cloned();
for (name, value) in &authenticated.headers {
if is_websocket_handshake_header(name) {
if name == http::header::HOST && original_host.as_ref() == Some(value) {
continue;
}
return Err(AuthError::Build(format!(
"authentication changed WebSocket handshake header {name}"
)));
}
request.headers_mut().insert(name, value.clone());
}
*request.uri_mut() = authenticated_uri;
Ok(())
}
fn websocket_url_from_authenticated_url(url: &str) -> Result<String, AuthError> {
let mut url = url::Url::parse(url)
.map_err(|error| AuthError::Build(format!("invalid authenticated request URL: {error}")))?;
let websocket_scheme = match url.scheme() {
"https" => "wss",
"http" => "ws",
scheme => {
return Err(AuthError::Build(format!(
"authentication returned unsupported WebSocket URL scheme: {scheme}"
)));
}
};
url.set_scheme(websocket_scheme).map_err(|_| {
AuthError::Build("failed to convert authenticated URL to WebSocket scheme".to_string())
})?;
Ok(url.into())
}
fn is_websocket_handshake_header(name: &http::header::HeaderName) -> bool {
name == http::header::HOST
|| name == http::header::CONNECTION
|| name == http::header::UPGRADE
|| name == http::header::CONTENT_LENGTH
|| name == http::header::TRANSFER_ENCODING
|| name.as_str().starts_with("sec-websocket-")
}
/// Everything the recovery loop needs for one connection attempt.
///
/// An attempt may also carry a permit whose lifetime must extend until the
/// attempt finishes.
pub(crate) struct ReconnectAttempt {
connection: JsonRpcConnection,
options: ExecServerClientConnectOptions,
attempt_permit: Option<OwnedSemaphorePermit>,
noise_context: Option<NoiseInitializeContext>,
}
struct OpenNoiseRendezvousConnection {
environment_id: String,
executor_registration_id: String,
stream_id: String,
handshake_started: Instant,
connection: JsonRpcConnection,
pending_tasks: Vec<AbortOnDropHandle<()>>,
options: ExecServerClientConnectOptions,
handshake_ready: tokio::sync::oneshot::Receiver<Result<(), ExecServerError>>,
}
struct ReadyNoiseRendezvousConnection {
connection: JsonRpcConnection,
options: ExecServerClientConnectOptions,
noise_context: NoiseInitializeContext,
}
impl ReconnectAttempt {
pub(crate) fn new(
connection: JsonRpcConnection,
options: ExecServerClientConnectOptions,
) -> Self {
Self {
connection,
options,
attempt_permit: None,
noise_context: None,
}
}
fn with_noise_context(
connection: JsonRpcConnection,
options: ExecServerClientConnectOptions,
noise_context: NoiseInitializeContext,
) -> Self {
Self {
connection,
options,
attempt_permit: None,
noise_context: Some(noise_context),
}
}
pub(crate) fn with_attempt_permit(
connection: JsonRpcConnection,
options: ExecServerClientConnectOptions,
attempt_permit: OwnedSemaphorePermit,
) -> Self {
Self {
connection,
options,
attempt_permit: Some(attempt_permit),
noise_context: None,
}
}
pub(crate) fn into_parts(
self,
) -> (
JsonRpcConnection,
ExecServerClientConnectOptions,
Option<OwnedSemaphorePermit>,
Option<NoiseInitializeContext>,
) {
(
self.connection,
self.options,
self.attempt_permit,
self.noise_context,
)
}
}
/// Reopens the transport for one logical exec-server client session.
///
/// URL connections reuse their configured endpoint. Noise connections retain
/// the harness identity but fetch a fresh single-use authorization bundle for
/// every physical connection attempt.
#[derive(Clone)]
pub(crate) enum ExecServerReconnectStrategy {
Accepted(AcceptedConnectionSource),
WebSocket {
args: RemoteExecServerConnectArgs,
http_headers: HeaderMap,
},
NoiseRendezvous {
// Registration can renew; recovery still pins the executor's Noise identity.
executor_public_key: crate::NoiseChannelPublicKey,
provider: Arc<dyn NoiseRendezvousConnectProvider>,
identity: NoiseChannelIdentity,
client_name: String,
connect_timeout: Duration,
http_client_factory: HttpClientFactory,
},
}
impl ExecServerReconnectStrategy {
pub(crate) async fn resume(
&self,
session_id: &str,
stage: &mut &'static str,
) -> Result<ReconnectAttempt, ExecServerError> {
match self {
Self::Accepted(source) => source.next_connection(session_id).await,
Self::WebSocket { args, http_headers } => {
*stage = "websocket_upgrade";
let mut args = args.clone();
args.resume_session_id = Some(session_id.to_string());
let connection =
ExecServerClient::open_websocket_connection(&args, http_headers).await?;
Ok(ReconnectAttempt::new(connection, args.into()))
}
Self::NoiseRendezvous {
executor_public_key,
provider,
identity,
client_name,
connect_timeout,
http_client_factory,
} => {
*stage = "registry_connect";
let bundle = connect_noise_bundle(provider.as_ref(), identity).await?;
if &bundle.executor_public_key != executor_public_key {
return Err(ExecServerError::Protocol(
"executor key changed during session recovery".to_string(),
));
}
// An expired rendezvous URL can make the same executor register again.
// Initialization must still resume the original session on that executor.
*stage = "websocket_upgrade";
let opened = ExecServerClient::open_noise_rendezvous_connection(
NoiseRendezvousConnectArgs {
bundle,
harness_identity: identity.clone(),
client_name: client_name.clone(),
connect_timeout: *connect_timeout,
initialize_timeout: NOISE_RECOVERY_INITIALIZE_TIMEOUT,
resume_session_id: Some(session_id.to_string()),
http_client_factory: http_client_factory.clone(),
},
)
.await?;
*stage = "noise_handshake";
let ready = ExecServerClient::finish_noise_rendezvous_connection(opened).await?;
Ok(ReconnectAttempt::with_noise_context(
ready.connection,
ready.options,
ready.noise_context,
))
}
}
}
}
impl ExecServerClient {
/// Open the selected transport and run the common JSON-RPC initialization.
/// Noise connection details are fetched here so reconnects get a fresh URL
/// and authorization without replacing the harness identity.
pub(crate) async fn connect_for_transport(
transport_params: ExecServerTransportParams,
http_client_factory: HttpClientFactory,
started: &mut Option<Instant>,
) -> Result<Self, ExecServerError> {
let (transport_params, deferred_readiness) = match transport_params {
ExecServerTransportParams::Deferred(deferred) => {
(deferred.transport, Some(deferred.readiness))
}
transport_params => (transport_params, None),
};
let provisioning_deadline = if let Some(mut readiness) = deferred_readiness {
let provisioning_result = readiness
.wait_for(Option::is_some)
.await
.map_err(|_| {
ExecServerError::Disconnected(
"environment unavailable: environment provisioning ended before completion"
.to_string(),
)
})?
.clone()
.ok_or_else(|| {
ExecServerError::Disconnected(
"environment unavailable: provisioning remained pending after completion"
.to_string(),
)
})?;
provisioning_result.map_err(ExecServerError::ProvisioningFailed)?;
Some(Instant::now() + PROVISIONED_ENVIRONMENT_CONNECT_TIMEOUT)
} else {
None
};
*started = Some(Instant::now());
let websocket = match transport_params {
ExecServerTransportParams::Deferred(_) => {
return Err(ExecServerError::Protocol(
"nested deferred exec-server transports are unsupported".to_string(),
));
}
ExecServerTransportParams::WebSocketUrl {
websocket_url,
connect_timeout,
initialize_timeout,
http_headers,
} => (
websocket_url,
connect_timeout,
initialize_timeout,
http_headers,
),
ExecServerTransportParams::NoiseRendezvous { provider, identity } => {
let (ready, executor_public_key) = Self::open_initial_noise_rendezvous_connection(
&provider,
&identity,
http_client_factory.clone(),
provisioning_deadline,
)
.await?;
let reconnect_strategy = ExecServerReconnectStrategy::NoiseRendezvous {
executor_public_key,
provider,
identity,
client_name: ENVIRONMENT_CLIENT_NAME.to_string(),
connect_timeout: DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT,
http_client_factory,
};
return Self::connect_with_recovery_and_noise_context(
ready.connection,
ready.options,
Some(reconnect_strategy),
ready.noise_context,
)
.await;
}
ExecServerTransportParams::StdioCommand {
command,
initialize_timeout,
} => {
return Self::connect_stdio_command(StdioExecServerConnectArgs {
command,
client_name: ENVIRONMENT_CLIENT_NAME.to_string(),
initialize_timeout,
resume_session_id: None,
})
.await;
}
};
let (websocket_url, connect_timeout, initialize_timeout, http_headers) = websocket;
Self::connect_websocket_with_headers(
RemoteExecServerConnectArgs {
websocket_url,
client_name: ENVIRONMENT_CLIENT_NAME.to_string(),
connect_timeout,
initialize_timeout,
resume_session_id: None,
http_client_factory,
},
http_headers,
)
.await
}
#[tracing::instrument(name = "codex.exec_server.remote.noise.connect", skip_all)]
async fn open_initial_noise_rendezvous_connection(
provider: &Arc<dyn NoiseRendezvousConnectProvider>,
identity: &NoiseChannelIdentity,
http_client_factory: HttpClientFactory,
provisioning_deadline: Option<Instant>,
) -> Result<(ReadyNoiseRendezvousConnection, crate::NoiseChannelPublicKey), ExecServerError>
{
let open_connection = |bundle: NoiseRendezvousConnectBundle| {
Self::open_noise_rendezvous_connection(NoiseRendezvousConnectArgs {
bundle,
harness_identity: identity.clone(),
client_name: ENVIRONMENT_CLIENT_NAME.to_string(),
connect_timeout: DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT,
initialize_timeout: DEFAULT_REMOTE_EXEC_SERVER_INITIALIZE_TIMEOUT,
resume_session_id: None,
http_client_factory: http_client_factory.clone(),
})
};
let mut deadline = Instant::now() + INITIAL_REGISTRY_OPERATION_TIMEOUT;
let retry_key = uuid::Uuid::new_v4().to_string();
let mut retries = 0;
let mut refreshed_unauthorized_bundle = false;
let connect_bundle = || connect_noise_bundle(provider.as_ref(), identity);
let mut result = connect_bundle().await;
loop {
let bundle = match result {
Ok(bundle) => bundle,
Err(error) => {
// A provisioned executor may be resuming after an earlier ready
// report. Only offline responses get the longer, fixed deadline.
let retry_deadline = match provisioning_deadline {
Some(deadline) if is_environment_offline_error(&error) => deadline,
_ if is_retryable_registry_error(&error)
&& retries < INITIAL_REGISTRY_MAX_RETRIES =>
{
deadline
}
_ => return Err(error),
};
// Session resumption owns its separate recovery deadline.
let delay = registry_recovery_retry_delay(&retry_key, retries);
retries += 1;
result = match timeout_at(retry_deadline, async {
sleep(delay).await;
connect_bundle().await
})
.await
{
Ok(result) => result,
Err(_) => return Err(error),
};
continue;
}
};
let executor_public_key = bundle.executor_public_key.clone();
match open_connection(bundle).await {
Err(error)
if !refreshed_unauthorized_bundle
&& matches!(
&error,
ExecServerError::WebSocketConnect { source, .. }
if matches!(
source,
tokio_tungstenite::tungstenite::Error::Http(response)
if response.status().as_u16() == 401
)
) =>
{
refreshed_unauthorized_bundle = true;
deadline = Instant::now() + INITIAL_REGISTRY_OPERATION_TIMEOUT;
retries = 0;
result = connect_bundle().await;
}
result => {
let opened = result?;
let ready = Self::finish_noise_rendezvous_connection(opened).await?;
return Ok((ready, executor_public_key));
}
}
}
}
pub async fn connect_websocket(
args: RemoteExecServerConnectArgs,
) -> Result<Self, ExecServerError> {
Self::connect_websocket_with_headers(args, HeaderMap::new()).await
}
async fn connect_websocket_with_headers(
args: RemoteExecServerConnectArgs,
http_headers: HeaderMap,
) -> Result<Self, ExecServerError> {
let connection = Self::open_websocket_connection(&args, &http_headers).await?;
let options = args.clone().into();
Self::connect_with_recovery(
connection,
options,
Some(ExecServerReconnectStrategy::WebSocket { args, http_headers }),
)
.await
}
pub(crate) async fn open_websocket_connection(
args: &RemoteExecServerConnectArgs,
http_headers: &HeaderMap,
) -> Result<JsonRpcConnection, ExecServerError> {
ensure_rustls_crypto_provider();
let websocket_url = args.websocket_url.clone();
let connect_timeout = args.connect_timeout;
let mut request = websocket_url
.as_str()
.into_client_request()
.map_err(|source| ExecServerError::WebSocketConnect {
url: websocket_url.clone(),
source,
})?;
request.headers_mut().extend(http_headers.clone());
let connector = WebSocketConnector::new_with_tls_mode(
&args.http_client_factory,
WebSocketTlsMode::TungsteniteDefault,
)
.map_err(|error| ExecServerError::WebSocketConfiguration(error.to_string()))?;
let stream = connect_websocket_request(
request,
websocket_url.clone(),
connector,
connect_timeout,
!http_headers.is_empty() && websocket_url.starts_with("ws://"),
)
.await?;
let connection_label = format!("exec-server websocket {websocket_url}");
let connection = if is_rendezvous_harness_url(&websocket_url) {
harness_connection_from_websocket(stream, connection_label)
} else {
JsonRpcConnection::from_websocket(stream, connection_label)
};
Ok(connection)
}
/// Connect to one exec-server through an authenticated rendezvous stream
/// using a caller-supplied single-use authorization bundle.
///
/// The executor key is pinned before JSON-RPC starts; the websocket carries
/// only ciphertext after that. Environment-managed connections use a
/// retained [`NoiseRendezvousConnectProvider`] so recovery can fetch a fresh
/// bundle for each reconnect.
#[tracing::instrument(
name = "codex.exec_server.remote.harness.connect",
skip_all,
fields(
otel.kind = "client",
otel.name = "codex.exec_server.remote.harness.connect",
)
)]
pub async fn connect_noise_rendezvous(
args: NoiseRendezvousConnectArgs,
) -> Result<Self, ExecServerError> {
let opened = Self::open_noise_rendezvous_connection(args).await?;
let ready = Self::finish_noise_rendezvous_connection(opened).await?;
Self::connect_with_recovery_and_noise_context(
ready.connection,
ready.options,
/*reconnect_strategy*/ None,
ready.noise_context,
)
.await
}
#[tracing::instrument(
name = "codex.exec_server.remote.noise.websocket_connect",
skip_all,
fields(
otel.kind = "client",
otel.name = "codex.exec_server.remote.noise.websocket_connect",
environment_id = %args.bundle.environment_id,
executor_registration_id = %args.bundle.executor_registration_id,
)
)]
async fn open_noise_rendezvous_connection(
args: NoiseRendezvousConnectArgs,
) -> Result<OpenNoiseRendezvousConnection, ExecServerError> {
ensure_rustls_crypto_provider();
// Keep the registry-issued URL, key, and authorization together for this
// connection attempt.
let NoiseRendezvousConnectArgs {
bundle,
harness_identity,
client_name,
connect_timeout,
initialize_timeout,
resume_session_id,
http_client_factory,
} = args;
let NoiseRendezvousConnectBundle {
websocket_url,
environment_id,
executor_registration_id,
executor_public_key,
harness_key_authorization,
} = bundle;
let diagnostic_url = websocket_url
.split(['?', '#'])
.next()
.unwrap_or(websocket_url.as_str())
.to_string();
let mut request = websocket_url
.as_str()
.into_client_request()
.map_err(|source| ExecServerError::WebSocketConnect {
url: diagnostic_url.clone(),
source,
})?;
request.headers_mut().extend(current_rendezvous_headers());
let (stream, _) = timeout(
connect_timeout,
WebSocketConnector::new_with_tls_mode(
&http_client_factory,
WebSocketTlsMode::TungsteniteDefault,
)
.map_err(|error| ExecServerError::WebSocketConfiguration(error.to_string()))?
.with_tcp_nodelay()
.connect(request, noise_relay_websocket_config()),
)
.await
.map_err(|_| ExecServerError::WebSocketConnectTimeout {
url: diagnostic_url.clone(),
timeout: connect_timeout,
})?
.map_err(|source| ExecServerError::WebSocketConnect {
url: diagnostic_url.clone(),
source,
})?;
let connection_label = format!("Noise exec-server rendezvous websocket {diagnostic_url}");
let mut connection = noise_harness_connection_from_websocket_with_readiness(
stream,
NoiseHarnessConnectionArgs {
connection_label,
environment_id: environment_id.clone(),
executor_registration_id: executor_registration_id.clone(),
identity: harness_identity,
responder_public_key: executor_public_key,
harness_key_authorization,
},
);
// Until RpcClient can take ownership, close the socket if the handshake
// fails or an enclosing deadline cancels the attempt.
let pending_tasks = connection
.connection
.task_handles
.drain(..)
.map(AbortOnDropHandle::new)
.collect();
Ok(OpenNoiseRendezvousConnection {
environment_id,
executor_registration_id,
stream_id: connection.stream_id,
handshake_started: connection.handshake_started,
connection: connection.connection,
pending_tasks,
options: ExecServerClientConnectOptions {
client_name,
initialize_timeout,
resume_session_id,
},
handshake_ready: connection.handshake_ready,
})
}
#[tracing::instrument(
name = "codex.exec_server.remote.noise.handshake",
skip_all,
parent = initialize_span,
fields(
otel.kind = "client",
otel.name = "codex.exec_server.remote.noise.handshake",
)
)]
async fn wait_for_noise_handshake(
connection: &mut OpenNoiseRendezvousConnection,
deadline: Instant,
initialize_timeout: Duration,
initialize_span: &tracing::Span,
) -> Result<(), ExecServerError> {
match timeout_at(deadline, &mut connection.handshake_ready).await {
Ok(Ok(result)) => result,
Ok(Err(_)) => Err(ExecServerError::Disconnected(
"Noise harness handshake failed before connection became ready".to_string(),
)),
Err(_) => {
tracing::event!(
name: "codex.exec_server.noise_handshake_failed",
target: "codex_otel.trace_safe",
tracing::Level::WARN,
event.name = "codex.exec_server.noise_handshake_failed",
noise_event = "handshake",
noise_outcome = "failed",
noise_side = "harness",
noise_reason = "timeout",
timeout_ms = initialize_timeout.as_millis() as u64,
elapsed_ms = connection.handshake_started.elapsed().as_millis() as u64,
environment_id = %connection.environment_id,
executor_registration_id = %connection.executor_registration_id,
stream_id = %connection.stream_id,
);
Err(ExecServerError::InitializeTimedOut {
timeout: initialize_timeout,
})
}
}
}
async fn finish_noise_rendezvous_connection(
mut connection: OpenNoiseRendezvousConnection,
) -> Result<ReadyNoiseRendezvousConnection, ExecServerError> {
// Preserve the legacy initialize request span as the post-WebSocket
// startup parent while making its two child operations visible.
let initialize_timeout = connection.options.initialize_timeout;
let noise_context = NoiseInitializeContext {
executor_registration_id: connection.executor_registration_id.clone(),
span: tracing::info_span!(
"codex.exec_server.request",
otel.kind = "client",
otel.name = "initialize",
method = "initialize",
),
timeout_for_error: initialize_timeout,
};
let deadline = Instant::now() + initialize_timeout;
let readiness = Self::wait_for_noise_handshake(
&mut connection,
deadline,
initialize_timeout,
&noise_context.span,
)
.await;
if let Err(mut error) = readiness {
// Before readiness, the transport reports the reason through the
// connection event channel, but no RpcClient is reading it yet.
if matches!(error, ExecServerError::Disconnected(_))
&& let Ok(JsonRpcConnectionEvent::Disconnected {
reason: Some(reason),
}) = connection.connection.incoming_rx.try_recv()
{
error = ExecServerError::Disconnected(format!(
"Noise harness handshake failed before connection became ready: {reason}"
));
}
return Err(error);
}
connection.connection.task_handles.extend(
connection
.pending_tasks
.into_iter()
.map(AbortOnDropHandle::detach),
);
let mut options = connection.options;
options.initialize_timeout = deadline.saturating_duration_since(Instant::now());
Ok(ReadyNoiseRendezvousConnection {
connection: connection.connection,
options,
noise_context,
})
}
pub(crate) async fn connect_stdio_command(
args: StdioExecServerConnectArgs,
) -> Result<Self, ExecServerError> {
let mut child = stdio_command_process(&args.command)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(ExecServerError::Spawn)?;
let stdin = child.stdin.take().ok_or_else(|| {
ExecServerError::Protocol("spawned exec-server command has no stdin".to_string())
})?;
let stdout = child.stdout.take().ok_or_else(|| {
ExecServerError::Protocol("spawned exec-server command has no stdout".to_string())
})?;
if let Some(stderr) = child.stderr.take() {
tokio::spawn(async move {
let mut reader = BufReader::new(stderr);
let mut line = Vec::new();
loop {
line.clear();
match (&mut reader)
.take(MAX_STDIO_STDERR_LOG_LINE_LEN)
.read_until(b'\n', &mut line)
.await
{
Ok(0) => break,
Ok(_) => {
let line = line.strip_suffix(b"\n").unwrap_or(&line);
let line = line.strip_suffix(b"\r").unwrap_or(line);
let line = String::from_utf8_lossy(line);
debug!("exec-server stdio stderr: {line}");
}
Err(err) => {
warn!("failed to read exec-server stdio stderr: {err}");
break;
}
}
}
});
}
Self::connect(
JsonRpcConnection::client_from_stdio(
stdout,
stdin,
"exec-server stdio command".to_string(),
)
.with_child_process(child),
args.into(),
)
.await
}
}
fn is_rendezvous_harness_url(websocket_url: &str) -> bool {
let Some((_path, query)) = websocket_url.split_once('?') else {
return false;
};
query
.split('&')
.filter_map(|pair| pair.split_once('='))
.any(|(key, value)| key == "role" && value == "harness")
}
fn stdio_command_process(stdio_command: &StdioExecServerCommand) -> Command {
let mut command = Command::from(codex_utils_process::background_command(
&stdio_command.program,
));
command.args(&stdio_command.args);
command.envs(&stdio_command.env);
scrub_non_inheritable_env_vars(command.as_std_mut());
if let Some(cwd) = &stdio_command.cwd {
command.current_dir(cwd);
}
#[cfg(unix)]
command.process_group(0);
command
}
#[cfg(test)]
#[path = "client_transport_tests.rs"]
mod tests;

View File

@@ -0,0 +1,900 @@
use std::collections::VecDeque;
use std::future::Future;
use std::sync::Arc;
use std::sync::Mutex;
use anyhow::Result;
use codex_exec_server_protocol::JSONRPCMessage;
use futures::FutureExt;
use futures::SinkExt;
use futures::StreamExt;
use futures::future::BoxFuture;
use pretty_assertions::assert_eq;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::io::duplex;
use tokio::net::TcpListener;
use tokio_tungstenite::accept_async;
use tokio_tungstenite::tungstenite::Message;
use tracing::instrument::WithSubscriber;
use tracing_subscriber::layer::SubscriberExt;
use super::ExecServerClient;
use super::ExecServerReconnectStrategy;
use super::INITIAL_REGISTRY_MAX_RETRIES;
use super::INITIAL_REGISTRY_OPERATION_TIMEOUT;
use super::PROVISIONED_ENVIRONMENT_CONNECT_TIMEOUT;
use super::REGISTRY_REQUEST_TIMEOUT;
use crate::ExecServerError;
use crate::NoiseChannelIdentity;
use crate::NoiseChannelPublicKey;
use crate::NoiseRendezvousConnectArgs;
use crate::NoiseRendezvousConnectBundle;
use crate::NoiseRendezvousConnectProvider;
use crate::client::NoiseInitializeContext;
use crate::client_api::DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT;
use crate::client_api::DEFAULT_REMOTE_EXEC_SERVER_INITIALIZE_TIMEOUT;
use crate::client_api::Deferred;
use crate::client_api::ExecServerClientConnectOptions;
use crate::client_api::ExecServerTransportParams;
use crate::connection::JsonRpcConnection;
use crate::noise_channel::PendingResponderHandshake;
use crate::noise_channel::noise_channel_prologue;
use crate::protocol::INITIALIZE_METHOD;
use crate::relay::RelayFrameBodyKind;
use crate::relay::decode_relay_message_frame;
use crate::relay::encode_relay_message_frame;
use crate::relay_proto::RelayMessageFrame;
#[derive(Default)]
struct SequenceNoiseConnectProvider {
bundles:
Mutex<VecDeque<BoxFuture<'static, Result<NoiseRendezvousConnectBundle, ExecServerError>>>>,
returned_urls: Mutex<Vec<String>>,
requested_keys: Mutex<Vec<NoiseChannelPublicKey>>,
}
impl SequenceNoiseConnectProvider {
fn push_response(
&self,
response: impl Future<Output = Result<NoiseRendezvousConnectBundle, ExecServerError>>
+ Send
+ 'static,
) {
self.bundles.lock().unwrap().push_back(response.boxed());
}
fn push_error(&self, error: ExecServerError) {
self.push_response(futures::future::ready(Err(error)));
}
fn push_pending(&self) {
self.push_response(futures::future::pending());
}
fn requested_keys(&self) -> Vec<NoiseChannelPublicKey> {
self.requested_keys.lock().unwrap().clone()
}
fn assert_requested_identity(&self, identity: &NoiseChannelIdentity, requests: usize) {
assert_eq!(self.requested_keys(), vec![identity.public_key(); requests]);
}
fn returned_urls(&self) -> Vec<String> {
self.returned_urls
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
async fn connect(
self: &Arc<Self>,
identity: &NoiseChannelIdentity,
) -> Result<
(
super::JsonRpcConnection,
super::ExecServerClientConnectOptions,
),
ExecServerError,
> {
let provider: Arc<dyn NoiseRendezvousConnectProvider> = self.clone();
ExecServerClient::open_initial_noise_rendezvous_connection(
&provider,
identity,
codex_http_client::HttpClientFactory::new(
codex_http_client::OutboundProxyPolicy::ReqwestDefault,
),
/*provisioning_deadline*/ None,
)
.await
.map(|(ready, _)| (ready.connection, ready.options))
}
async fn connect_provisioned(
self: &Arc<Self>,
identity: &NoiseChannelIdentity,
) -> Result<ExecServerClient, ExecServerError> {
let (_readiness_tx, readiness) = tokio::sync::watch::channel(Some(Ok(())));
ExecServerClient::connect_for_transport(
ExecServerTransportParams::Deferred(Box::new(Deferred {
readiness,
transport: ExecServerTransportParams::NoiseRendezvous {
provider: self.clone(),
identity: identity.clone(),
},
})),
codex_http_client::HttpClientFactory::new(
codex_http_client::OutboundProxyPolicy::ReqwestDefault,
),
/*started*/ &mut None,
)
.await
}
}
impl NoiseRendezvousConnectProvider for SequenceNoiseConnectProvider {
fn connect_bundle(
&self,
harness_public_key: NoiseChannelPublicKey,
) -> BoxFuture<'_, Result<NoiseRendezvousConnectBundle, ExecServerError>> {
self.requested_keys.lock().unwrap().push(harness_public_key);
let response = self
.bundles
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.pop_front()
.expect("test Noise provider exhausted");
Box::pin(async move {
let result = response.await;
if let Ok(bundle) = &result {
self.returned_urls
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(bundle.websocket_url.clone());
}
result
})
}
}
fn test_bundle(websocket_url: String) -> Result<NoiseRendezvousConnectBundle> {
Ok(NoiseRendezvousConnectBundle {
websocket_url,
environment_id: "environment".to_string(),
executor_registration_id: "registration".to_string(),
executor_public_key: NoiseChannelIdentity::generate()?.public_key(),
harness_key_authorization: "authorization".to_string(),
})
}
fn registry_error(status: http::StatusCode, code: &str) -> ExecServerError {
ExecServerError::EnvironmentRegistryHttp {
status,
code: Some(code.to_string()),
message: "registry unavailable".to_string(),
}
}
#[tokio::test]
async fn noise_handshake_reports_disconnect_reason() -> Result<()> {
for (send_reset, expected_reason) in [
(
false,
"Noise relay transport expects binary protobuf frames",
),
(true, "Noise relay stream reset"),
] {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let websocket_url = format!("ws://{}", listener.local_addr()?);
let server = tokio::spawn(async move {
let (socket, _) = listener.accept().await?;
let mut websocket = accept_async(socket).await?;
let Message::Binary(resume) = websocket.next().await.unwrap()? else {
anyhow::bail!("expected resume frame");
};
let stream_id = decode_relay_message_frame(&resume)?.stream_id;
let _handshake = websocket.next().await.unwrap()?;
let response = if send_reset {
let frame = RelayMessageFrame::reset(stream_id, "untrusted reason".to_string());
Message::Binary(encode_relay_message_frame(&frame).into())
} else {
Message::Text("untrusted text".into())
};
websocket.send(response).await?;
anyhow::Ok(())
});
let opened =
ExecServerClient::open_noise_rendezvous_connection(NoiseRendezvousConnectArgs {
bundle: test_bundle(websocket_url)?,
harness_identity: NoiseChannelIdentity::generate()?,
client_name: "test".to_string(),
connect_timeout: DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT,
initialize_timeout: DEFAULT_REMOTE_EXEC_SERVER_INITIALIZE_TIMEOUT,
resume_session_id: None,
http_client_factory: codex_http_client::HttpClientFactory::new(
codex_http_client::OutboundProxyPolicy::ReqwestDefault,
),
})
.await?;
let error = ExecServerClient::finish_noise_rendezvous_connection(opened)
.await
.err()
.expect("invalid handshake response must fail");
let ExecServerError::Disconnected(reason) = error else {
anyhow::bail!("expected disconnect, got {error:?}");
};
assert_eq!(
reason,
format!(
"Noise harness handshake failed before connection became ready: {expected_reason}"
)
);
server.await??;
}
Ok(())
}
#[tokio::test]
async fn noise_handshake_uses_initialize_timeout() -> Result<()> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let websocket_url = format!("ws://{}", listener.local_addr()?);
let server = tokio::spawn(async move {
let (socket, _) = listener.accept().await?;
let mut websocket = accept_async(socket).await?;
// Drain the frames sent before the harness waits for the responder,
// then verify that a timed-out readiness wait closes the socket.
let Some(Ok(Message::Binary(resume))) = websocket.next().await else {
anyhow::bail!("expected resume frame");
};
let stream_id = decode_relay_message_frame(&resume)?.stream_id;
assert!(websocket.next().await.is_some());
let closed =
tokio::time::timeout(std::time::Duration::from_secs(1), websocket.next()).await?;
assert!(
matches!(closed, None | Some(Ok(Message::Close(_))) | Some(Err(_))),
"timed-out Noise handshake must close its websocket"
);
anyhow::Ok(stream_id)
});
let initialize_timeout = std::time::Duration::from_millis(1);
let opened = ExecServerClient::open_noise_rendezvous_connection(NoiseRendezvousConnectArgs {
bundle: NoiseRendezvousConnectBundle {
websocket_url,
environment_id: "environment".to_string(),
executor_registration_id: "registration".to_string(),
executor_public_key: NoiseChannelIdentity::generate()?.public_key(),
harness_key_authorization: "authorization".to_string(),
},
harness_identity: NoiseChannelIdentity::generate()?,
client_name: "test".to_string(),
connect_timeout: DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT,
initialize_timeout,
resume_session_id: None,
http_client_factory: codex_http_client::HttpClientFactory::new(
codex_http_client::OutboundProxyPolicy::ReqwestDefault,
),
})
.await?;
let stream_id = opened.stream_id.clone();
let mut log_file = tempfile::tempfile()?;
let writer = log_file.try_clone()?;
let subscriber = tracing_subscriber::registry().with(
tracing_subscriber::fmt::layer()
.with_ansi(false)
.with_writer(move || writer.try_clone().expect("clone log file")),
);
let error = ExecServerClient::finish_noise_rendezvous_connection(opened)
.with_subscriber(subscriber)
.await
.err()
.expect("stalled Noise handshake must time out");
assert!(matches!(
error,
ExecServerError::InitializeTimedOut { timeout } if timeout == initialize_timeout
));
assert_eq!(server.await??, stream_id);
std::io::Seek::rewind(&mut log_file)?;
let mut logs = String::new();
std::io::Read::read_to_string(&mut log_file, &mut logs)?;
for field in [
"noise_reason=\"timeout\"",
"environment_id=environment",
"executor_registration_id=registration",
"elapsed_ms=",
&stream_id,
] {
assert!(logs.contains(field), "missing {field} in {logs}");
}
Ok(())
}
#[tokio::test]
async fn cancelling_noise_handshake_closes_websocket() -> Result<()> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let websocket_url = format!("ws://{}", listener.local_addr()?);
let (handshake_seen_tx, handshake_seen_rx) = tokio::sync::oneshot::channel();
let server = tokio::spawn(async move {
let (socket, _) = listener.accept().await?;
let mut websocket = accept_async(socket).await?;
for _ in 0..2 {
assert!(matches!(
websocket.next().await,
Some(Ok(Message::Binary(_)))
));
}
handshake_seen_tx
.send(())
.expect("handshake should be pending");
let closed =
tokio::time::timeout(std::time::Duration::from_secs(1), websocket.next()).await?;
assert!(matches!(
closed,
None | Some(Ok(Message::Close(_))) | Some(Err(_))
));
anyhow::Ok(())
});
let opened = ExecServerClient::open_noise_rendezvous_connection(NoiseRendezvousConnectArgs {
bundle: test_bundle(websocket_url)?,
harness_identity: NoiseChannelIdentity::generate()?,
client_name: "test".to_string(),
connect_timeout: DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT,
initialize_timeout: DEFAULT_REMOTE_EXEC_SERVER_INITIALIZE_TIMEOUT,
resume_session_id: Some("session".to_string()),
http_client_factory: codex_http_client::HttpClientFactory::new(
codex_http_client::OutboundProxyPolicy::ReqwestDefault,
),
})
.await?;
{
let handshake = ExecServerClient::finish_noise_rendezvous_connection(opened);
tokio::pin!(handshake);
tokio::select! {
biased;
_ = &mut handshake => anyhow::bail!("expected a pending Noise handshake"),
result = handshake_seen_rx => result?,
}
}
server.await??;
Ok(())
}
#[tokio::test]
async fn deferred_initialize_timeout_reports_configured_budget() {
let (client_stdin, server_reader) = duplex(1 << 20);
let (server_writer, client_stdout) = duplex(1 << 20);
let server = tokio::spawn(async move {
let _server_writer = server_writer;
let mut lines = BufReader::new(server_reader).lines();
let line = lines
.next_line()
.await
.expect("initialize read should succeed")
.expect("initialize request should arrive");
let request: JSONRPCMessage =
serde_json::from_str(&line).expect("initialize request should parse");
assert!(
matches!(
request,
JSONRPCMessage::Request(ref request) if request.method == INITIALIZE_METHOD
),
"expected initialize request, got {request:?}"
);
futures::future::pending::<()>().await;
});
let configured_timeout = std::time::Duration::from_secs(10);
let error = ExecServerClient::connect_with_recovery_and_noise_context(
JsonRpcConnection::from_stdio(
client_stdout,
client_stdin,
"timeout-test-client".to_string(),
),
ExecServerClientConnectOptions {
client_name: "timeout-test-client".to_string(),
initialize_timeout: std::time::Duration::from_millis(1),
resume_session_id: None,
},
/*reconnect_strategy*/ None,
NoiseInitializeContext {
executor_registration_id: "registration".to_string(),
span: tracing::info_span!("codex.exec_server.request"),
timeout_for_error: configured_timeout,
},
)
.await
.err()
.expect("initialize RPC must time out");
assert!(matches!(
error,
ExecServerError::InitializeTimedOut { timeout } if timeout == configured_timeout
));
server.abort();
let _ = server.await;
}
#[tokio::test(start_paused = true)]
async fn initial_noise_connection_bounds_offline_retries() -> Result<()> {
let sequence = Arc::new(SequenceNoiseConnectProvider::default());
for _ in 0..=INITIAL_REGISTRY_MAX_RETRIES {
sequence.push_error(registry_error(
http::StatusCode::CONFLICT,
"environment_offline",
));
}
let identity = NoiseChannelIdentity::generate()?;
let started = tokio::time::Instant::now();
let error = sequence
.connect(&identity)
.await
.err()
.expect("offline retries must end");
assert!(crate::client::is_environment_offline_error(&error));
let requests = sequence.requested_keys().len();
assert!((4..=INITIAL_REGISTRY_MAX_RETRIES as usize + 1).contains(&requests));
sequence.assert_requested_identity(&identity, requests);
assert!(started.elapsed() <= INITIAL_REGISTRY_OPERATION_TIMEOUT);
Ok(())
}
#[tokio::test(start_paused = true)]
async fn initial_noise_connection_bounds_a_stalled_retry_request() -> Result<()> {
let sequence = Arc::new(SequenceNoiseConnectProvider::default());
sequence.push_error(registry_error(
http::StatusCode::CONFLICT,
"environment_offline",
));
for _ in 0..INITIAL_REGISTRY_MAX_RETRIES {
sequence.push_pending();
}
let identity = NoiseChannelIdentity::generate()?;
let started = tokio::time::Instant::now();
let error = sequence
.connect(&identity)
.await
.err()
.expect("stalled retry must time out");
assert!(matches!(
error,
ExecServerError::EnvironmentRegistryRequest(error) if error.is_timeout()
));
assert_eq!(started.elapsed(), INITIAL_REGISTRY_OPERATION_TIMEOUT);
let requests = sequence.requested_keys().len();
assert!((2..=3).contains(&requests));
sequence.assert_requested_identity(&identity, requests);
Ok(())
}
#[tokio::test(start_paused = true)]
async fn initial_noise_connection_bounds_a_stalled_initial_request() -> Result<()> {
let sequence = Arc::new(SequenceNoiseConnectProvider::default());
for _ in 0..=INITIAL_REGISTRY_MAX_RETRIES {
sequence.push_pending();
}
let identity = NoiseChannelIdentity::generate()?;
let started = tokio::time::Instant::now();
let error = sequence
.connect(&identity)
.await
.err()
.expect("stalled initial request must time out");
assert!(matches!(
error,
ExecServerError::EnvironmentRegistryRequest(error) if error.is_timeout()
));
assert_eq!(started.elapsed(), INITIAL_REGISTRY_OPERATION_TIMEOUT);
let requests = sequence.requested_keys().len();
assert!((2..=3).contains(&requests));
sequence.assert_requested_identity(&identity, requests);
Ok(())
}
#[tokio::test(start_paused = true)]
async fn initial_noise_connection_retries_a_stalled_initial_request() -> Result<()> {
let sequence = Arc::new(SequenceNoiseConnectProvider::default());
sequence.push_pending();
sequence.push_error(registry_error(http::StatusCode::FORBIDDEN, "forbidden"));
let identity = NoiseChannelIdentity::generate()?;
let started = tokio::time::Instant::now();
let error = sequence
.connect(&identity)
.await
.err()
.expect("terminal response must stop the retry sequence");
assert!(matches!(
error,
ExecServerError::EnvironmentRegistryHttp {
status: http::StatusCode::FORBIDDEN,
..
}
));
assert!(started.elapsed() >= REGISTRY_REQUEST_TIMEOUT);
assert!(started.elapsed() < INITIAL_REGISTRY_OPERATION_TIMEOUT);
sequence.assert_requested_identity(&identity, /*requests*/ 2);
Ok(())
}
#[tokio::test(start_paused = true)]
async fn initial_noise_connection_retries_transient_registry_statuses() -> Result<()> {
for status in [
http::StatusCode::REQUEST_TIMEOUT,
http::StatusCode::TOO_MANY_REQUESTS,
http::StatusCode::INTERNAL_SERVER_ERROR,
http::StatusCode::BAD_GATEWAY,
http::StatusCode::SERVICE_UNAVAILABLE,
] {
let sequence = Arc::new(SequenceNoiseConnectProvider::default());
sequence.push_error(registry_error(status, "temporarily_unavailable"));
sequence.push_error(registry_error(http::StatusCode::FORBIDDEN, "forbidden"));
let identity = NoiseChannelIdentity::generate()?;
let error = sequence
.connect(&identity)
.await
.err()
.expect("terminal response must stop the retry sequence");
assert!(matches!(
error,
ExecServerError::EnvironmentRegistryHttp {
status: http::StatusCode::FORBIDDEN,
..
}
));
sequence.assert_requested_identity(&identity, /*requests*/ 2);
}
Ok(())
}
#[tokio::test(start_paused = true)]
async fn initial_noise_connection_retries_registry_request_timeouts() -> Result<()> {
let sequence = Arc::new(SequenceNoiseConnectProvider::default());
sequence.push_error(ExecServerError::EnvironmentRegistryRequest(
codex_http_client::RouteAwareRequestError::Timeout,
));
sequence.push_error(registry_error(http::StatusCode::FORBIDDEN, "forbidden"));
let identity = NoiseChannelIdentity::generate()?;
let error = sequence
.connect(&identity)
.await
.err()
.expect("terminal response must stop the retry sequence");
assert!(matches!(
error,
ExecServerError::EnvironmentRegistryHttp {
status: http::StatusCode::FORBIDDEN,
..
}
));
sequence.assert_requested_identity(&identity, /*requests*/ 2);
Ok(())
}
#[tokio::test(start_paused = true)]
async fn initial_noise_connection_does_not_retry_permanent_registry_errors() -> Result<()> {
for (status, code) in [
(http::StatusCode::UNAUTHORIZED, "unauthorized"),
(http::StatusCode::FORBIDDEN, "forbidden"),
(http::StatusCode::BAD_REQUEST, "bad_request"),
(http::StatusCode::NOT_FOUND, "environment_not_found"),
(http::StatusCode::CONFLICT, "registration_conflict"),
(http::StatusCode::CONFLICT, "route_unavailable"),
] {
// A terminal error must also stop a retry sequence already in progress.
for initial_offline in [false, true] {
let sequence = Arc::new(SequenceNoiseConnectProvider::default());
if initial_offline {
sequence.push_error(registry_error(
http::StatusCode::CONFLICT,
"environment_offline",
));
}
sequence.push_error(registry_error(status, code));
let identity = NoiseChannelIdentity::generate()?;
let error = sequence
.connect(&identity)
.await
.err()
.expect("other errors must propagate");
assert!(
matches!(error, ExecServerError::EnvironmentRegistryHttp { status: actual_status, code: Some(actual_code), .. } if actual_status == status && actual_code == code)
);
sequence.assert_requested_identity(&identity, 1 + usize::from(initial_offline));
}
}
Ok(())
}
#[tokio::test(start_paused = true)]
async fn provisioned_noise_connection_bounds_offline_retries() -> Result<()> {
let sequence = Arc::new(SequenceNoiseConnectProvider::default());
// Enough responses to reach the deadline even at the shortest retry interval.
for _ in 0..1024 {
sequence.push_error(registry_error(
http::StatusCode::CONFLICT,
"environment_offline",
));
}
let identity = NoiseChannelIdentity::generate()?;
let started = tokio::time::Instant::now();
let error = sequence
.connect_provisioned(&identity)
.await
.err()
.expect("a provisioned executor that stays offline must time out");
assert!(crate::client::is_environment_offline_error(&error));
assert_eq!(started.elapsed(), PROVISIONED_ENVIRONMENT_CONNECT_TIMEOUT);
let requests = sequence.requested_keys().len();
assert!(requests > INITIAL_REGISTRY_MAX_RETRIES as usize + 1);
sequence.assert_requested_identity(&identity, requests);
Ok(())
}
#[tokio::test(start_paused = true)]
async fn provisioned_noise_connection_keeps_other_registry_retry_limits() -> Result<()> {
let sequence = Arc::new(SequenceNoiseConnectProvider::default());
for _ in 0..=INITIAL_REGISTRY_MAX_RETRIES {
sequence.push_error(registry_error(
http::StatusCode::SERVICE_UNAVAILABLE,
"unavailable",
));
}
let identity = NoiseChannelIdentity::generate()?;
let started = tokio::time::Instant::now();
let error = sequence
.connect_provisioned(&identity)
.await
.err()
.expect("only an offline executor receives the provisioning grace");
assert!(matches!(
error,
ExecServerError::EnvironmentRegistryHttp {
status: http::StatusCode::SERVICE_UNAVAILABLE,
..
}
));
assert!(started.elapsed() <= INITIAL_REGISTRY_OPERATION_TIMEOUT);
assert!(sequence.requested_keys().len() <= INITIAL_REGISTRY_MAX_RETRIES as usize + 1);
Ok(())
}
#[tokio::test(start_paused = true)]
async fn provisioned_noise_connection_bounds_a_stalled_retry_request() -> Result<()> {
let sequence = Arc::new(SequenceNoiseConnectProvider::default());
sequence.push_error(registry_error(
http::StatusCode::CONFLICT,
"environment_offline",
));
for _ in 0..INITIAL_REGISTRY_MAX_RETRIES {
sequence.push_pending();
}
let identity = NoiseChannelIdentity::generate()?;
let started = tokio::time::Instant::now();
let error = sequence
.connect_provisioned(&identity)
.await
.err()
.expect("a stalled registry request must keep the ordinary timeout");
assert!(matches!(
error,
ExecServerError::EnvironmentRegistryRequest(error) if error.is_timeout()
));
assert_eq!(started.elapsed(), INITIAL_REGISTRY_OPERATION_TIMEOUT);
let requests = sequence.requested_keys().len();
assert!((2..=3).contains(&requests));
sequence.assert_requested_identity(&identity, requests);
Ok(())
}
#[tokio::test(start_paused = true)]
async fn provisioned_noise_connection_stops_on_a_late_permanent_error() -> Result<()> {
let sequence = Arc::new(SequenceNoiseConnectProvider::default());
for _ in 0..10 {
sequence.push_error(registry_error(
http::StatusCode::CONFLICT,
"environment_offline",
));
}
sequence.push_error(registry_error(http::StatusCode::FORBIDDEN, "forbidden"));
let identity = NoiseChannelIdentity::generate()?;
let started = tokio::time::Instant::now();
let error = sequence
.connect_provisioned(&identity)
.await
.err()
.expect("a permanent error must stop provisioning retries");
assert!(matches!(
error,
ExecServerError::EnvironmentRegistryHttp {
status: http::StatusCode::FORBIDDEN,
code: Some(code),
..
} if code == "forbidden"
));
sequence.assert_requested_identity(&identity, /*requests*/ 11);
assert!(started.elapsed() > INITIAL_REGISTRY_OPERATION_TIMEOUT);
Ok(())
}
#[tokio::test]
async fn noise_session_resume_rejects_a_changed_noise_key_before_connecting() -> Result<()> {
let sequence = Arc::new(SequenceNoiseConnectProvider::default());
let bundle = test_bundle("ws://must-not-connect.invalid".to_string())?;
let executor_public_key = NoiseChannelIdentity::generate()?.public_key();
sequence.push_response(futures::future::ready(Ok(bundle)));
let strategy = ExecServerReconnectStrategy::NoiseRendezvous {
executor_public_key,
provider: sequence,
identity: NoiseChannelIdentity::generate()?,
client_name: "test".to_string(),
connect_timeout: DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT,
http_client_factory: codex_http_client::HttpClientFactory::new(
codex_http_client::OutboundProxyPolicy::ReqwestDefault,
),
};
assert!(
matches!(strategy.resume("session", &mut "transport").await, Err(ExecServerError::Protocol(message)) if message == "executor key changed during session recovery")
);
Ok(())
}
#[tokio::test(start_paused = true)]
async fn noise_session_resume_leaves_registry_retries_to_recovery() -> Result<()> {
let sequence = Arc::new(SequenceNoiseConnectProvider::default());
sequence.push_pending();
sequence.push_error(registry_error(
http::StatusCode::CONFLICT,
"environment_offline",
));
let identity = NoiseChannelIdentity::generate()?;
let strategy = ExecServerReconnectStrategy::NoiseRendezvous {
executor_public_key: NoiseChannelIdentity::generate()?.public_key(),
provider: sequence.clone(),
identity: identity.clone(),
client_name: "test".to_string(),
connect_timeout: DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT,
http_client_factory: codex_http_client::HttpClientFactory::new(
codex_http_client::OutboundProxyPolicy::ReqwestDefault,
),
};
let started = tokio::time::Instant::now();
let mut stage = "transport";
let error = strategy
.resume("session", &mut stage)
.await
.err()
.expect("a stalled registry request must time out");
assert!(matches!(
&error,
ExecServerError::EnvironmentRegistryRequest(error) if error.is_timeout()
));
assert!(crate::client::is_retryable_recovery_error(&error));
assert_eq!(stage, "registry_connect");
assert_eq!(started.elapsed(), REGISTRY_REQUEST_TIMEOUT);
sequence.assert_requested_identity(&identity, /*requests*/ 1);
let started = tokio::time::Instant::now();
let error = strategy
.resume("session", &mut "transport")
.await
.err()
.expect("resume must return the offline error");
assert!(crate::client::is_environment_offline_error(&error));
assert_eq!(started.elapsed(), std::time::Duration::ZERO);
sequence.assert_requested_identity(&identity, /*requests*/ 2);
Ok(())
}
#[tokio::test]
async fn initial_noise_connection_refreshes_bundle_after_exhausting_initial_retries() -> Result<()>
{
let unauthorized_listener = TcpListener::bind("127.0.0.1:0").await?;
let unauthorized_url = format!("ws://{}", unauthorized_listener.local_addr()?);
let unauthorized_server = tokio::spawn(async move {
let (mut socket, _) = unauthorized_listener.accept().await?;
let mut request = [0_u8; 4096];
let _ = socket.read(&mut request).await?;
socket
.write_all(
b"HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
)
.await?;
socket.shutdown().await?;
anyhow::Ok(())
});
let accepted_listener = TcpListener::bind("127.0.0.1:0").await?;
let accepted_url = format!("ws://{}", accepted_listener.local_addr()?);
let executor_identity = NoiseChannelIdentity::generate()?;
let executor_public_key = executor_identity.public_key();
let accepted_server = tokio::spawn(async move {
let (socket, _) = accepted_listener.accept().await?;
let mut websocket = accept_async(socket).await?;
let Message::Binary(resume_payload) = websocket.next().await.unwrap()? else {
anyhow::bail!("expected Noise relay resume frame");
};
let resume = decode_relay_message_frame(resume_payload.as_ref())?;
assert_eq!(resume.validate()?, RelayFrameBodyKind::Resume);
let Message::Binary(handshake_payload) = websocket.next().await.unwrap()? else {
anyhow::bail!("expected Noise relay handshake frame");
};
let handshake = decode_relay_message_frame(handshake_payload.as_ref())?;
let stream_id = handshake.stream_id.clone();
let prologue = noise_channel_prologue("environment", "registration", &stream_id);
let pending = PendingResponderHandshake::read_request(
&executor_identity,
&prologue,
&handshake.into_handshake_payload()?,
)?;
let (_transport, response) = pending.complete()?;
websocket
.send(Message::Binary(
encode_relay_message_frame(&RelayMessageFrame::handshake(stream_id, response))
.into(),
))
.await?;
anyhow::Ok(())
});
let sequence = Arc::new(SequenceNoiseConnectProvider::default());
let unauthorized_bundle = test_bundle(unauthorized_url.clone())?;
let mut accepted_bundle = test_bundle(accepted_url.clone())?;
accepted_bundle.executor_public_key = executor_public_key;
sequence.push_response(async {
tokio::time::pause();
Err(registry_error(
http::StatusCode::CONFLICT,
"environment_offline",
))
});
for _ in 1..INITIAL_REGISTRY_MAX_RETRIES {
sequence.push_error(registry_error(
http::StatusCode::CONFLICT,
"environment_offline",
));
}
sequence.push_response(async move {
tokio::time::resume();
Ok(unauthorized_bundle)
});
sequence.push_response(async {
tokio::time::pause();
Err(registry_error(
http::StatusCode::CONFLICT,
"environment_offline",
))
});
sequence.push_response(async move {
tokio::time::resume();
Ok(accepted_bundle)
});
let identity = NoiseChannelIdentity::generate()?;
let _connection = sequence.connect(&identity).await?;
assert_eq!(
sequence.returned_urls(),
vec![unauthorized_url, accepted_url]
);
sequence.assert_requested_identity(&identity, INITIAL_REGISTRY_MAX_RETRIES as usize + 3);
unauthorized_server.await??;
accepted_server.await??;
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,470 @@
//! Loads metadata within the request's sandbox and builds a bounded response.
use std::collections::HashMap;
use std::io;
use std::sync::Arc;
use codex_file_system::ExecutorFileSystem;
use codex_skills::parse_skill_frontmatter_metadata;
use codex_skills::parse_skill_metadata;
use futures::StreamExt;
use serde::Deserialize;
use serde::Serialize;
use crate::CapabilityRootDiscoverRequest;
use crate::CapabilityRootDiscovery;
use crate::CapabilityTextFile;
use crate::DiscoverV2CapabilitiesResponse;
use crate::ExecutorPlugin;
use crate::ExecutorSkill;
use crate::LocalFileSystem;
use crate::SkillDiscoveryRoot;
use crate::capability_discovery::MAX_CONCURRENT_ROOTS;
use crate::capability_discovery::discover_root;
use crate::discover_v2::capability_locations::CapabilityLocation;
use crate::discover_v2::capability_locations::CapabilityLocations;
const MAX_RESPONSE_BYTES: usize = 4 * 1024 * 1024;
const MAX_CAPABILITIES: usize = 2_048;
const MAX_WARNINGS: usize = 64;
// Match V1: namespace, separator, and skill name.
const MAX_QUALIFIED_NAME_LEN: usize = 64 * 2 + 1;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
enum DiscoveredSource {
Plugin(Box<ExecutorPlugin>),
Skills(Vec<ExecutorSkill>),
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct CapabilityDiscovery {
content: DiscoveredSource,
warnings: Vec<String>,
}
// Only the metadata V2 returns or needs to materialize discovered configuration.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct PluginManifestMetadata {
#[serde(default)]
name: String,
interface: Option<PluginManifestInterface>,
mcp_servers: Option<serde_json::Value>,
apps: Option<String>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct PluginManifestInterface {
display_name: Option<String>,
}
impl Default for CapabilityDiscovery {
fn default() -> Self {
Self {
content: DiscoveredSource::Skills(Vec::new()),
warnings: Vec::new(),
}
}
}
pub(super) async fn load_capability_discoveries(
file_system: &LocalFileSystem,
locations: &CapabilityLocations,
sandbox: Option<&crate::FileSystemSandboxContext>,
) -> io::Result<Arc<DiscoverV2CapabilitiesResponse>> {
let sandbox = sandbox.filter(|sandbox| sandbox.should_read_from_sandbox());
let warnings = if !locations.warnings.is_empty() {
vec!["some capability locations could not be resolved; discovery may be incomplete".into()]
} else {
Vec::new()
};
let response = match sandbox {
Some(sandbox) if !locations.locations.is_empty() => {
file_system
.sandboxed()?
.load_sandboxed_capability_discoveries(
locations.locations.clone(),
warnings,
sandbox,
)
.await?
}
_ => load_capability_discovery_batch(file_system, &locations.locations, warnings).await?,
};
Ok(Arc::new(response))
}
/// Loads roots concurrently and bounds the combined response.
pub(crate) async fn load_capability_discovery_batch(
file_system: &LocalFileSystem,
locations: &[CapabilityLocation],
warnings: Vec<String>,
) -> io::Result<DiscoverV2CapabilitiesResponse> {
let mut response = DiscoverV2CapabilitiesResponse {
warnings,
..Default::default()
};
let mut budget = ResponseBudget::default();
// Use V1 concurrency; admit results in location order.
// Yield owned locations to satisfy the RPC router's Send future bound.
let mut discoveries = futures::stream::iter(locations.iter().cloned())
.map(|location| load_capability_discovery(file_system, location))
.buffered(MAX_CONCURRENT_ROOTS)
.enumerate();
while let Some((index, discovery)) = discoveries.next().await {
let mut discovery = discovery?;
if !discovery.warnings.is_empty() {
discovery.warnings = vec![
"some capability metadata could not be loaded; discovery may be incomplete".into(),
];
}
append_capability_discovery(&mut response, discovery, &mut budget)?;
// A rejected oversized entry alone does not rule out smaller entries later.
if (budget.capabilities == MAX_CAPABILITIES || budget.bytes == MAX_RESPONSE_BYTES)
&& index + 1 < locations.len()
{
budget.truncated = true;
break;
}
}
finish_response(response, budget.truncated)
}
async fn load_capability_discovery(
file_system: &LocalFileSystem,
location: CapabilityLocation,
) -> io::Result<CapabilityDiscovery> {
// Missing roots are normal.
match file_system
.get_metadata(&location.root, Default::default(), /*sandbox*/ None)
.await
{
Ok(metadata) if metadata.is_directory => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => {
return Ok(CapabilityDiscovery::default());
}
Ok(_) => return Ok(CapabilityDiscovery::default()),
Err(error) if error.kind() == io::ErrorKind::PermissionDenied => {
return Ok(CapabilityDiscovery::default());
}
Err(error) => {
return Ok(CapabilityDiscovery {
warnings: vec![format!(
"could not inspect capability root {}: {error}",
location.root
)],
..Default::default()
});
}
}
let discovery = discover_root(
file_system,
CapabilityRootDiscoverRequest {
id: location
.plugin
.as_ref()
.map(|plugin| plugin.id.clone())
.unwrap_or_default(),
path: location.root.clone(),
sandbox: None,
},
)
.await;
Ok(parse_root(location, discovery))
}
fn parse_root(
location: CapabilityLocation,
discovery: CapabilityRootDiscovery,
) -> CapabilityDiscovery {
let mut warnings = discovery.warnings;
warnings.extend(discovery.error);
if location.plugin.is_some() && discovery.plugin.is_none() {
warnings.push(format!(
"installed plugin at {} has no readable manifest",
location.root
));
return CapabilityDiscovery {
warnings,
..Default::default()
};
}
// V1 precedence: first manifest per root, nearest root per skill.
let mut plugin_namespaces = HashMap::new();
for manifest in &discovery.namespace_manifests {
#[derive(Deserialize)]
struct ManifestName {
#[serde(default)]
name: String,
}
let Some(root) = manifest.path.parent().and_then(|path| path.parent()) else {
continue;
};
let Ok(parsed) = serde_json::from_str::<ManifestName>(&manifest.contents) else {
continue;
};
let name = if parsed.name.trim().is_empty() {
let Some(name) = root.basename() else {
continue;
};
name
} else {
parsed.name
};
plugin_namespaces.entry(root).or_insert(name);
}
// Reuse the contents already read by V1.
let mut skills = Vec::new();
'skills: for skill in discovery.skills {
let parsed = parse_skill_frontmatter_metadata(&skill.instructions.contents, || {
skill
.instructions
.path
.parent()
.and_then(|path| path.basename())
.map(|name| name.split_whitespace().collect::<Vec<_>>().join(" "))
.filter(|name| !name.is_empty())
.unwrap_or_else(|| "skill".to_string())
});
let parsed = match parsed {
Ok(parsed) => parsed,
Err(error) => {
warnings.push(format!(
"invalid skill metadata at {}: {error}",
skill.instructions.path
));
continue;
}
};
let path = skill.instructions.path;
let mut ancestor = path.parent();
let mut namespace = None;
while let Some(root) = ancestor {
if let Some(name) = plugin_namespaces.get(&root) {
// Check V1's name limit before cloning the namespace.
if name.chars().take(MAX_QUALIFIED_NAME_LEN + 1).count()
+ 1
+ parsed.name.chars().count()
> MAX_QUALIFIED_NAME_LEN
{
warnings.push(format!(
"invalid skill metadata at {path}: qualified name exceeds {MAX_QUALIFIED_NAME_LEN} characters"
));
continue 'skills;
}
namespace = Some(name.clone());
break;
}
ancestor = root.parent();
}
let metadata = skill.metadata.as_ref().and_then(|metadata| {
parse_skill_metadata(&metadata.contents).map_err(|error| {
tracing::warn!(path = %metadata.path, %error, "ignoring invalid discovered skill metadata");
}).ok()
}).unwrap_or_default();
skills.push(ExecutorSkill {
name: namespace
.map(|namespace| format!("{namespace}:{}", parsed.name))
.unwrap_or(parsed.name),
description: parsed.description,
short_description: parsed.short_description,
path,
discovery_root: location
.standalone_root_id
.as_ref()
.map(|id| SkillDiscoveryRoot {
id: id.clone(),
path: location.root.clone(),
}),
dependencies: metadata.dependencies,
policy: metadata.policy,
});
}
let content = if let (Some(plugin), Some(mut files)) = (location.plugin, discovery.plugin) {
let manifest =
match serde_json::from_str::<PluginManifestMetadata>(&files.manifest.contents) {
Ok(manifest) => manifest,
Err(_) => {
warnings.push(format!(
"invalid plugin manifest at {}",
files.manifest.path
));
return CapabilityDiscovery {
warnings,
..Default::default()
};
}
};
let name = if manifest.name.trim().is_empty() {
location.root.basename().unwrap_or(manifest.name)
} else {
manifest.name
};
let display_name = manifest
.interface
.and_then(|interface| interface.display_name)
.map(|display_name| display_name.trim().to_string())
.filter(|display_name| !display_name.is_empty())
.unwrap_or(name);
// V2 materializes inline declarations; the path identifies their source manifest.
if files.mcp_config.is_none() {
if let Some(contents) = manifest
.mcp_servers
.as_ref()
.filter(|value| value.is_object())
{
files.mcp_config = Some(CapabilityTextFile {
path: files.manifest.path.clone(),
contents: contents.to_string(),
});
} else if manifest
.mcp_servers
.as_ref()
.is_some_and(serde_json::Value::is_string)
{
warnings.push(format!(
"plugin `{}` at {} declares an MCP configuration file, but discovery returned no contents",
plugin.id, location.root
));
}
}
if files.apps_config.is_none() && manifest.apps.is_some() {
warnings.push(format!(
"plugin `{}` at {} declares an Apps configuration file, but discovery returned no contents",
plugin.id, location.root
));
}
DiscoveredSource::Plugin(Box::new(ExecutorPlugin {
id: plugin.id,
display_name,
remote_plugin_id: plugin.remote_plugin_id,
version: plugin.version,
root: location.root,
files,
skills,
}))
} else {
DiscoveredSource::Skills(skills)
};
CapabilityDiscovery { content, warnings }
}
#[derive(Default)]
struct ResponseBudget {
capabilities: usize,
bytes: usize,
truncated: bool,
}
impl ResponseBudget {
fn admit(&mut self, capabilities: usize, bytes: usize) -> bool {
if self.capabilities + capabilities > MAX_CAPABILITIES
|| self.bytes + bytes > MAX_RESPONSE_BYTES
{
self.truncated = true;
return false;
}
self.capabilities += capabilities;
self.bytes += bytes;
true
}
}
/// Appends within budget; duplicate skills count until consumers deduplicate them.
fn append_capability_discovery(
response: &mut DiscoverV2CapabilitiesResponse,
discovery: CapabilityDiscovery,
budget: &mut ResponseBudget,
) -> io::Result<()> {
response.warnings.extend(
discovery
.warnings
.into_iter()
.take(MAX_WARNINGS.saturating_sub(response.warnings.len())),
);
match discovery.content {
DiscoveredSource::Plugin(plugin) => {
let remaining = MAX_CAPABILITIES - budget.capabilities;
if remaining == 0 {
budget.truncated = true;
return Ok(());
}
let mut plugin = *plugin;
budget.truncated |= plugin.skills.len() > remaining - 1;
plugin.skills.truncate(remaining - 1); // The plugin itself also counts.
let size = serde_json::to_vec(&plugin).map_err(io::Error::other)?.len();
if budget.admit(1 + plugin.skills.len(), size) {
response.plugins.push(plugin);
}
}
DiscoveredSource::Skills(skills) => {
for skill in skills {
if budget.capabilities == MAX_CAPABILITIES {
budget.truncated = true;
break;
}
let size = serde_json::to_vec(&skill).map_err(io::Error::other)?.len();
if budget.admit(/*capabilities*/ 1, size) {
response.skills.push(skill);
}
}
}
}
Ok(())
}
fn finish_response(
mut response: DiscoverV2CapabilitiesResponse,
truncated: bool,
) -> io::Result<DiscoverV2CapabilitiesResponse> {
response.plugins.sort_unstable_by(|left, right| {
left.id
.cmp(&right.id)
.then_with(|| left.root.to_string().cmp(&right.root.to_string()))
});
// Keep standalone skill precedence.
response.warnings.truncate(MAX_WARNINGS);
enforce_response_size(&mut response, truncated)?;
Ok(response)
}
// Include JSON overhead and warnings in the final size check.
fn enforce_response_size(
response: &mut DiscoverV2CapabilitiesResponse,
truncated: bool,
) -> io::Result<()> {
if truncated
|| serde_json::to_vec(&*response)
.map_err(io::Error::other)?
.len()
> MAX_RESPONSE_BYTES
{
response.warnings.truncate(MAX_WARNINGS - 1);
response
.warnings
.insert(0, "capability discovery size limit reached".to_string());
while serde_json::to_vec(&*response)
.map_err(io::Error::other)?
.len()
> MAX_RESPONSE_BYTES
{
// Drop extra warnings first; keep the limit warning.
if response.warnings.len() > 1 {
response.warnings.truncate(1);
} else if response.skills.pop().is_none() && response.plugins.pop().is_none() {
break;
}
}
}
Ok(())
}
#[cfg(test)]
#[path = "tests/capability_discoveries_tests.rs"]
mod tests;

View File

@@ -0,0 +1,219 @@
//! Prewarms installed cache packages and fixed standalone skill locations before discovery.
mod candidates;
use candidates::CandidateCapabilityLocations;
use std::collections::BTreeMap;
use std::io;
use crate::LocalFileSystem;
use crate::protocol::FsOpenMode;
use codex_file_system::ExecutorFileSystem;
use codex_file_system::WalkEntryKind;
use codex_file_system::WalkOptions;
use codex_file_watcher::WatchPath;
use codex_utils_path_uri::PathUri;
use serde::Deserialize;
use serde::Serialize;
use codex_core_plugin_common::installed::PLUGINS_CACHE_DIR;
use codex_core_plugin_common::installed::REMOTE_PLUGIN_INSTALL_METADATA_FILE;
use codex_core_plugin_common::installed::active_plugin_version;
use codex_core_plugin_common::installed::parse_remote_plugin_id;
use codex_core_plugin_common::plugin_id::PluginId;
use tokio::io::AsyncReadExt;
/// Fixed paths are supplied by the executor, not read from the sandbox helper's sanitized env.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct CapabilityLocationRequest {
pub codex_home: PathUri,
pub user_home: Option<PathUri>,
pub system_skills_root: Option<PathUri>,
}
const MAX_LOCATIONS: usize = 512;
const MAX_REMOTE_INSTALL_METADATA_BYTES: u64 = 16 * 1024;
const MAX_REMOTE_PLUGIN_ID_BYTES: usize = 1024;
const AGENTS_SKILLS_SUFFIX: &str = ".agents/skills";
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct CapabilityLocation {
pub root: PathUri,
pub standalone_root_id: Option<String>,
pub plugin: Option<InstalledPlugin>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct InstalledPlugin {
pub id: String,
pub version: String,
pub remote_plugin_id: Option<String>,
}
/// Selected locations; membership does not authorize capability reads.
#[derive(Clone, Default)]
pub(crate) struct CapabilityLocations {
pub locations: Vec<CapabilityLocation>,
pub watches: Vec<WatchPath>,
pub warnings: Vec<String>,
}
/// Resolves fixed home/cache roots on the executor without reading configuration or using a cwd.
pub(crate) async fn prewarm_locations(
fs: &LocalFileSystem,
request: &CapabilityLocationRequest,
) -> io::Result<CapabilityLocations> {
let codex_home = request.codex_home.to_abs_path()?;
let user_home = request
.user_home
.as_ref()
.map(PathUri::to_abs_path)
.transpose()?;
// Fixed standalone roots extend Flora's V1 root; project skill discovery is deferred.
let mut skill_roots = vec![("codex-home-skills", codex_home.join("skills"))];
if let Some(home) = user_home {
skill_roots.push(("user-agent-skills", home.join(AGENTS_SKILLS_SUFFIX)));
}
if let Some(system_root) = &request.system_skills_root {
skill_roots.push(("system-skills", system_root.to_abs_path()?));
}
CandidateCapabilityLocations::resolve(
fs,
Some(PathUri::from_abs_path(&codex_home.join(PLUGINS_CACHE_DIR))),
skill_roots
.into_iter()
.map(|(id, root)| crate::SkillDiscoveryRoot {
id: id.to_string(),
path: PathUri::from_abs_path(&root),
})
.collect(),
)
.await
}
async fn discover_cached_plugins(
fs: &LocalFileSystem,
cache: &PathUri,
) -> io::Result<CapabilityLocations> {
let mut locations = CapabilityLocations::default();
// Enumerate packages; the shared selector scans their version directories.
let walk = match fs
.walk(
cache,
WalkOptions {
max_depth: 1,
max_directories: 2_000,
max_entries: 20_000,
follow_directory_symlinks: true,
prune_hidden_directories: false,
},
/*sandbox*/ None,
)
.await
{
Ok(walk) => walk,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(locations),
Err(error) => return Err(error),
};
// Reported walk errors must not become a cached partial inventory.
if let Some(error) = walk.errors.into_iter().next() {
return Err(io::Error::other(format!(
"failed to scan plugin cache path {}: {}",
error.path, error.message
)));
}
if walk.truncated {
locations
.warnings
.push("plugin cache traversal limit reached".to_string());
}
let mut packages = BTreeMap::new();
for entry in walk.entries {
if entry.kind != WalkEntryKind::Directory {
continue;
}
let Some(relative) = entry.path.relative_path_from(cache) else {
continue;
};
let parts = relative.split(['/', '\\']).collect::<Vec<_>>();
let [marketplace, name] = parts.as_slice() else {
continue;
};
let Ok(id) = PluginId::new((*name).to_string(), (*marketplace).to_string()) else {
continue;
};
packages.insert(id.as_key(), entry.path.to_abs_path()?);
}
let installed = tokio::task::spawn_blocking(move || {
packages
.into_iter()
.filter_map(|(id, package_root)| {
let version = active_plugin_version(&package_root)?;
Some((id, package_root, version))
})
.collect::<Vec<_>>()
})
.await
.map_err(io::Error::other)?;
for (id, package_root, version) in installed {
// Avoid reading metadata for plugin locations the final assembly would discard.
if locations.locations.len() == MAX_LOCATIONS {
locations.warnings.push(format!(
"plugin cache reached its {MAX_LOCATIONS}-location limit"
));
break;
}
let metadata_path = package_root.join(REMOTE_PLUGIN_INSTALL_METADATA_FILE);
let remote_plugin_id = match read_remote_plugin_id(metadata_path.as_path()).await {
Ok(remote_plugin_id) => remote_plugin_id,
Err(error) => {
locations.warnings.push(format!(
"could not read remote installation metadata for {id}: {error}"
));
None
}
};
locations.locations.push(CapabilityLocation {
root: PathUri::from_abs_path(&package_root.join(&version)),
standalone_root_id: None,
plugin: Some(InstalledPlugin {
id,
version,
remote_plugin_id,
}),
});
}
Ok(locations)
}
async fn read_remote_plugin_id(path: &std::path::Path) -> io::Result<Option<String>> {
// Nonblocking open and handle validation reject FIFOs and other non-regular files.
let file = match crate::regular_file::open(path, FsOpenMode::Read).await {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error),
};
let mut contents = Vec::new();
file.take(MAX_REMOTE_INSTALL_METADATA_BYTES + 1)
.read_to_end(&mut contents)
.await?;
if contents.len() as u64 > MAX_REMOTE_INSTALL_METADATA_BYTES {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"remote installation metadata exceeds its byte limit",
));
}
let contents = std::str::from_utf8(&contents).map_err(io::Error::other)?;
let id = parse_remote_plugin_id(contents).map_err(io::Error::other)?;
if id.len() > MAX_REMOTE_PLUGIN_ID_BYTES {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"remote plugin ID exceeds its byte limit",
));
}
Ok(Some(id))
}
#[cfg(test)]
#[path = "tests/capability_locations_tests.rs"]
pub(crate) mod tests;

View File

@@ -0,0 +1,125 @@
//! Retains installed-cache and standalone-skill candidates and assembles their locations.
use super::CapabilityLocation;
use super::CapabilityLocations;
use super::MAX_LOCATIONS;
use super::discover_cached_plugins;
use crate::LocalFileSystem;
use crate::SkillDiscoveryRoot;
use codex_file_system::ExecutorFileSystem;
use codex_file_watcher::WatchPath;
use codex_utils_path_uri::PathUri;
use std::io;
const MAX_LOCATION_WARNINGS: usize = 64;
/// Existing candidates plus watch paths for existing and not-yet-created roots.
pub(super) struct CandidateCapabilityLocations {
candidates: Vec<CandidateCapabilityLocation>,
watches: Vec<WatchPath>,
}
/// An installed cache or standalone skill root whose locations can be resolved.
#[derive(Clone, Debug, PartialEq, Eq)]
enum CandidateCapabilityLocation {
Cache(PathUri),
Standalone(SkillDiscoveryRoot),
}
impl CandidateCapabilityLocations {
/// Resolves existing cache and skill roots into one bounded location inventory.
pub(super) async fn resolve(
fs: &LocalFileSystem,
cache_root: Option<PathUri>,
skill_roots: Vec<SkillDiscoveryRoot>,
) -> io::Result<CapabilityLocations> {
let mut candidates = cache_root
.into_iter()
.map(CandidateCapabilityLocation::Cache)
.collect::<Vec<_>>();
let mut standalone = skill_roots;
let mut seen = std::collections::HashSet::new();
standalone.retain(|root| seen.insert(root.path.clone()));
candidates.extend(
standalone
.into_iter()
.map(CandidateCapabilityLocation::Standalone),
);
let mut watches = Vec::new();
let mut retained_candidates = Vec::new();
for candidate in candidates {
let root = match &candidate {
CandidateCapabilityLocation::Cache(root) => root,
CandidateCapabilityLocation::Standalone(root) => &root.path,
};
let exists = match fs
.get_metadata(root, Default::default(), /*sandbox*/ None)
.await
{
Ok(metadata) => metadata.is_directory,
Err(error) if error.kind() == io::ErrorKind::NotFound => false,
Err(error) => return Err(error),
};
// Missing roots use the watcher's ancestor fallback until they are created.
watches.push(WatchPath {
path: root.to_abs_path()?.into_path_buf(),
recursive: true,
});
if exists {
retained_candidates.push(candidate);
}
}
let candidates = Self {
candidates: retained_candidates,
watches,
};
let mut resolved = Vec::new();
for candidate in &candidates.candidates {
resolved.push(candidates.resolve_candidates(fs, candidate).await?);
}
Ok(candidates.assemble(resolved))
}
async fn resolve_candidates(
&self,
fs: &LocalFileSystem,
candidate: &CandidateCapabilityLocation,
) -> io::Result<CapabilityLocations> {
match candidate {
CandidateCapabilityLocation::Cache(root) => discover_cached_plugins(fs, root).await,
// Standalone roots need no manifest or version selection.
CandidateCapabilityLocation::Standalone(root) => Ok(CapabilityLocations {
locations: vec![CapabilityLocation {
root: root.path.clone(),
standalone_root_id: Some(root.id.clone()),
plugin: None,
}],
..Default::default()
}),
}
}
/// Combines and bounds inventory; Core applies plugin enablement.
fn assemble(&self, resolved_candidates: Vec<CapabilityLocations>) -> CapabilityLocations {
let mut result = CapabilityLocations {
watches: self.watches.clone(),
..Default::default()
};
// Combine installed plugin and standalone skill locations in discovery order.
for candidate in resolved_candidates {
result.locations.extend(candidate.locations);
result.warnings.extend(candidate.warnings);
}
if result.locations.len() > MAX_LOCATIONS {
result.warnings.truncate(MAX_LOCATION_WARNINGS - 1);
result.warnings.push(format!(
"capability discovery reached its {MAX_LOCATIONS}-location limit"
));
result.locations.truncate(MAX_LOCATIONS);
}
result.warnings.truncate(MAX_LOCATION_WARNINGS);
result
}
}

View File

@@ -0,0 +1,179 @@
//! Retains watched global locations and sandbox-scoped response snapshots.
//! Replacement snapshots isolate in-flight loads; failed watch registration forces request-time reloads.
use crate::DiscoverV2CapabilitiesRequest;
use crate::DiscoverV2CapabilitiesResponse;
use crate::FileSystemSandboxContext;
use crate::LocalFileSystem;
use crate::discover_v2::capability_discoveries::load_capability_discoveries;
use crate::discover_v2::capability_locations::CapabilityLocationRequest;
use crate::discover_v2::capability_locations::CapabilityLocations;
use crate::discover_v2::capability_locations::prewarm_locations;
use codex_config::loader::system_config_toml_file;
use codex_file_watcher::WatchRegistration;
use codex_utils_path_uri::PathUri;
use std::io;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use tokio::sync::Mutex;
use tokio::sync::OnceCell;
use tokio::sync::Semaphore;
mod capability_watchers;
use capability_watchers::CapabilityWatchers;
const MAX_CACHED_SANDBOX_CONTEXTS: usize = 16;
pub(crate) struct CapabilityManager {
file_system: LocalFileSystem,
prewarmed_locations: OnceCell<(CapabilityLocationRequest, CapabilityLocations)>,
current_state: Mutex<Option<Arc<LocationState>>>,
location_refresh_lock: Semaphore,
watchers: CapabilityWatchers,
}
struct LocationState {
dirty: AtomicBool,
locations: CapabilityLocations,
sandbox_discoveries: Mutex<Vec<Arc<CachedSandboxDiscovery>>>,
registration: WatchRegistration,
}
struct CachedSandboxDiscovery {
sandbox: Option<FileSystemSandboxContext>,
response: OnceCell<Arc<DiscoverV2CapabilitiesResponse>>,
}
impl CapabilityManager {
pub(crate) fn new(file_system: LocalFileSystem) -> Arc<Self> {
Arc::new(Self {
file_system,
prewarmed_locations: OnceCell::new(),
current_state: Mutex::default(),
location_refresh_lock: Semaphore::new(/*permits*/ 1),
watchers: CapabilityWatchers::new(),
})
}
/// Resolves fixed paths on first initialization and reuses the prewarmed locations.
pub(crate) async fn prewarm_locations(
self: &Arc<Self>,
) -> io::Result<&(CapabilityLocationRequest, CapabilityLocations)> {
let cached = self
.prewarmed_locations
.get_or_try_init(|| async {
let request = CapabilityLocationRequest {
codex_home: PathUri::from_abs_path(&codex_utils_home_dir::find_codex_home()?),
user_home: dirs::home_dir()
.and_then(|home| PathUri::from_host_native_path(home).ok()),
system_skills_root: system_config_toml_file()?
.parent()
.map(|root| PathUri::from_abs_path(&root.join("skills"))),
};
let locations = prewarm_locations(&self.file_system, &request).await?;
Ok::<_, io::Error>((request, locations))
})
.await?;
self.initialize_watchers(&cached.1).await;
Ok(cached)
}
/// Reuses startup locations, retrying prewarming if the background scan failed.
pub(crate) async fn get_or_refresh_discovery(
self: &Arc<Self>,
params: DiscoverV2CapabilitiesRequest,
) -> io::Result<Arc<DiscoverV2CapabilitiesResponse>> {
let (location_request, _) = self.prewarm_locations().await?;
let location_state = self.get_or_refresh_locations(location_request).await?;
let discovery = {
let mut discoveries = location_state.sandbox_discoveries.lock().await;
if let Some(discovery) = discoveries
.iter()
.find(|discovery| discovery.sandbox == params.sandbox)
{
Arc::clone(discovery)
} else {
let discovery = Arc::new(CachedSandboxDiscovery {
sandbox: params.sandbox,
response: OnceCell::new(),
});
if discoveries.len() == MAX_CACHED_SANDBOX_CONTEXTS {
// Evict the oldest context (FIFO); in-flight requests retain their own Arc.
discoveries.remove(0);
}
discoveries.push(Arc::clone(&discovery));
discovery
}
};
if location_state.registration.registration_succeeded() {
return discovery
.response
.get_or_try_init(|| {
load_capability_discoveries(
&self.file_system,
&location_state.locations,
discovery.sandbox.as_ref(),
)
})
.await
.map(Arc::clone);
}
load_capability_discoveries(
&self.file_system,
&location_state.locations,
discovery.sandbox.as_ref(),
)
.await
}
async fn get_or_refresh_locations(
&self,
request: &CapabilityLocationRequest,
) -> io::Result<Arc<LocationState>> {
if let Some(location_state) = self.location_snapshot().await
&& location_state.registration.registration_succeeded()
&& !location_state.dirty.load(Ordering::Relaxed)
{
return Ok(location_state);
}
let _refresh = self
.location_refresh_lock
.acquire()
.await
.map_err(io::Error::other)?;
if let Some(location_state) = self.location_snapshot().await
&& location_state.registration.registration_succeeded()
&& !location_state.dirty.load(Ordering::Relaxed)
{
return Ok(location_state);
}
// Retry dirty locations; failed watch registration reloads on every request.
let locations = match prewarm_locations(&self.file_system, request).await {
Ok(locations) => locations,
Err(error) => {
if let Some(location_state) = self.location_snapshot().await {
tracing::warn!(error_kind = ?error.kind(), "capability refresh failed; retrying on the next request");
return Ok(location_state);
}
return Err(error);
}
};
let next = Arc::new(LocationState {
dirty: AtomicBool::new(false),
registration: self.watchers.register_paths(&locations),
locations,
sandbox_discoveries: Mutex::default(),
});
*self.current_state.lock().await = Some(Arc::clone(&next));
Ok(next)
}
async fn location_snapshot(&self) -> Option<Arc<LocationState>> {
self.current_state.lock().await.clone()
}
}
#[cfg(test)]
#[path = "tests/capability_manager_tests.rs"]
mod tests;

View File

@@ -0,0 +1,142 @@
//! Refreshes global locations and invalidates sandbox responses through one watcher subscription.
//! In-flight readers retain the previous snapshot while a replacement is prepared.
use super::CapabilityManager;
use super::LocationState;
use crate::discover_v2::capability_locations::CapabilityLocations;
use crate::discover_v2::capability_locations::prewarm_locations;
use codex_file_watcher::FileWatcher;
use codex_file_watcher::FileWatcherSubscriber;
use codex_file_watcher::ThrottledWatchReceiver;
use codex_file_watcher::WatchRegistration;
use std::sync::Arc;
use std::sync::OnceLock;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::time::Duration;
use tokio::sync::Mutex;
use tokio_util::task::AbortOnDropHandle;
#[cfg(not(test))]
const WATCHER_THROTTLE_INTERVAL: Duration = Duration::from_secs(10);
#[cfg(test)]
const WATCHER_THROTTLE_INTERVAL: Duration = Duration::from_millis(50);
pub(super) struct CapabilityWatchers {
file_watcher: Option<Arc<FileWatcher>>,
subscription: OnceLock<RootSubscription>,
}
struct RootSubscription {
subscriber: FileWatcherSubscriber,
_listener: AbortOnDropHandle<()>,
}
impl CapabilityWatchers {
pub(super) fn new() -> Self {
let file_watcher = match FileWatcher::new() {
Ok(watcher) => Some(Arc::new(watcher)),
Err(error) => {
tracing::warn!(%error, "capability watcher unavailable; using uncached discovery");
None
}
};
Self {
file_watcher,
subscription: OnceLock::new(),
}
}
/// Registers fixed roots, including missing ones, without separate watches for symlink targets.
pub(super) fn register_paths(&self, locations: &CapabilityLocations) -> WatchRegistration {
let Some(subscription) = self.subscription.get() else {
return WatchRegistration::default();
};
subscription
.subscriber
.register_paths(locations.watches.clone())
}
}
impl CapabilityManager {
pub(super) async fn initialize_watchers(self: &Arc<Self>, prewarmed: &CapabilityLocations) {
let Some(watcher) = &self.watchers.file_watcher else {
return;
};
if self.watchers.subscription.get().is_some() {
return;
}
let Ok(_refresh) = self.location_refresh_lock.acquire().await else {
return;
};
if self.watchers.subscription.get().is_some() {
return;
}
let (subscriber, events) = watcher.add_subscriber();
let mut events = ThrottledWatchReceiver::new(events, WATCHER_THROTTLE_INTERVAL);
let registration = subscriber.register_paths(prewarmed.watches.clone());
let next = Arc::new(LocationState {
dirty: AtomicBool::new(false),
locations: prewarmed.clone(),
sandbox_discoveries: Mutex::default(),
registration,
});
let mut current_state = self.current_state.lock().await;
let weak = Arc::downgrade(self);
let listener = tokio::spawn(async move {
while events.recv().await.is_some() {
let Some(manager) = weak.upgrade() else { break };
manager.refresh_locations().await;
}
});
// No await between retaining the subscription and publishing its snapshot.
if self
.watchers
.subscription
.set(RootSubscription {
subscriber,
_listener: AbortOnDropHandle::new(listener),
})
.is_err()
{
return;
}
*current_state = Some(next);
}
pub(super) async fn refresh_locations(&self) {
let result: std::io::Result<()> = async {
let _refresh = self
.location_refresh_lock
.acquire()
.await
.map_err(std::io::Error::other)?;
let Some((request, _)) = self.prewarmed_locations.get() else {
return Ok(());
};
// Keep failed or cancelled refreshes retryable without discarding the last snapshot.
if let Some(location_state) = self.location_snapshot().await {
location_state.dirty.store(true, Ordering::Relaxed);
}
let locations = prewarm_locations(&self.file_system, request).await?;
let registration = self.watchers.register_paths(&locations);
let next = Arc::new(LocationState {
dirty: AtomicBool::new(false),
locations,
sandbox_discoveries: Mutex::default(),
registration,
});
// Requests populate the new cache lazily; in-flight loads retain their old snapshot.
*self.current_state.lock().await = Some(next);
Ok(())
}
.await;
if let Err(error) = result {
tracing::warn!(error_kind = ?error.kind(), "capability refresh failed; keeping previous complete snapshot");
}
}
}
#[cfg(test)]
#[path = "../tests/capability_watchers_tests.rs"]
pub(super) mod tests;

View File

@@ -0,0 +1,6 @@
//! Executor-side V2 capability discovery.
//! Connection and RPC routing stay outside this module; legacy V1 scanning remains separate.
pub(crate) mod capability_discoveries;
pub(crate) mod capability_locations;
pub(crate) mod capability_manager;

View File

@@ -0,0 +1,407 @@
//! Covers metadata parity and inventory discovery independent of plugin enablement.
use pretty_assertions::assert_eq;
use super::MAX_CAPABILITIES;
use super::MAX_RESPONSE_BYTES;
use super::MAX_WARNINGS;
use crate::CapabilityRootDiscoverRequest;
use crate::DiscoverV2CapabilitiesRequest;
use crate::ExecutorSkill;
use crate::LocalFileSystem;
use crate::SkillDiscoveryRoot;
use crate::capability_discovery::discover_root;
use crate::discover_v2::capability_locations::tests::MANIFEST;
use crate::discover_v2::capability_locations::tests::request;
use crate::discover_v2::capability_locations::tests::write;
use crate::discover_v2::capability_manager::CapabilityManager;
use codex_utils_path_uri::PathUri;
const SKILL: &str =
"---\nname: deploy\ndescription: Deploy the service.\n---\nPRIVATE_INSTRUCTION_BODY_SENTINEL\n";
#[tokio::test]
async fn discovery_preserves_inventory_and_v1_metadata() -> anyhow::Result<()> {
let temp = tempfile::tempdir()?;
let request = request(temp.path())?;
write(
temp.path(),
"codex/config.toml",
"[plugins.\"demo@test\"]\n[plugins.\"disabled@test\"]\nenabled = false\n",
)?;
// Inventory includes disabled and unconfigured plugins; Core applies enablement.
for name in ["disabled", "unconfigured"] {
write(
temp.path(),
&format!("codex/plugins/cache/test/{name}/local/.codex-plugin/plugin.json"),
MANIFEST,
)?;
}
let inline_root = "codex/plugins/cache/test/unconfigured/local";
write(
temp.path(),
"codex/plugins/cache/test/disabled/local/.codex-plugin/plugin.json",
r#"{"name":" ","interface":{"displayName":" "},"mcpServers":"./missing-mcp.json","apps":"./missing-apps.json"}"#,
)?;
let inline_manifest = r#"{"name":"inline","interface":{"displayName":" Inline Plugin "},"mcpServers":{"inline":{"command":"node"}}}"#;
write(
temp.path(),
&format!("{inline_root}/.codex-plugin/plugin.json"),
inline_manifest,
)?;
// Inline declarations take precedence over a conventional MCP file.
write(
temp.path(),
&format!("{inline_root}/.mcp.json"),
r#"{"wrong":{"command":"wrong"}}"#,
)?;
let root = "codex/plugins/cache/test/demo/local";
write(
temp.path(),
&format!("{root}/.codex-plugin/plugin.json"),
r#"{"name":"demo","skills":"./skills"}"#,
)?;
let mcp_path = ".mcp.json";
write(
temp.path(),
&format!("{root}/{mcp_path}"),
r#"{"mcpServers":{}}"#,
)?;
for relative in [
"skills/deploy/SKILL.md",
"examples/deploy/SKILL.md",
".codex-plugin/migrated-command-skills/deploy/SKILL.md",
"skills/a/b/c/d/e/f/deploy/SKILL.md",
] {
write(temp.path(), &format!("{root}/{relative}"), SKILL)?;
}
write(
temp.path(),
"codex/skills/deploy skill/SKILL.md",
&SKILL.replace("name: deploy\n", ""),
)?;
for nested in [format!("{root}/nested"), "codex/skills/nested".to_string()] {
write(
temp.path(),
&format!("{nested}/.codex-plugin/plugin.json"),
r#"{"name":"team"}"#,
)?;
write(
temp.path(),
&format!("{nested}/skills/deploy/SKILL.md"),
SKILL,
)?;
}
let file_system = LocalFileSystem::unsandboxed();
let plugin_root = request.codex_home.join("plugins/cache/test/demo/local")?;
let v1 = discover_root(
&file_system,
CapabilityRootDiscoverRequest {
id: "demo@test".to_string(),
path: plugin_root.clone(),
sandbox: None,
},
)
.await;
// V1 keeps undeclared/migrated skills and excludes the skill beyond its depth limit.
assert_eq!(v1.skills.len(), 4);
let inline_v1 = discover_root(
&file_system,
CapabilityRootDiscoverRequest {
id: "unconfigured@test".to_string(),
path: PathUri::from_host_native_path(temp.path().join(inline_root))?,
sandbox: None,
},
)
.await;
let inline_v1_files = inline_v1.plugin.expect("inline plugin");
assert_eq!(inline_v1_files.mcp_config, None);
let manager = CapabilityManager::new(file_system);
manager.seed_prewarmed_locations(request.clone()).await?;
let response = manager
.get_or_refresh_discovery(DiscoverV2CapabilitiesRequest {
cwd: PathUri::from_host_native_path(temp.path().join("project"))?,
sandbox: None,
})
.await?;
assert_eq!(
response
.plugins
.iter()
.map(|plugin| plugin.id.as_str())
.collect::<Vec<_>>(),
vec!["demo@test", "disabled@test", "unconfigured@test"],
);
assert_eq!(
response
.plugins
.iter()
.map(|plugin| plugin.display_name.as_str())
.collect::<Vec<_>>(),
vec!["demo", "local", "Inline Plugin"],
);
let plugin = response
.plugins
.first()
.ok_or_else(|| anyhow::anyhow!("missing demo plugin"))?;
assert_eq!(
plugin.files.manifest.path,
plugin_root.join(".codex-plugin/plugin.json")?,
);
assert_eq!(
plugin.files.mcp_config.as_ref().map(|file| &file.path),
Some(&plugin_root.join(mcp_path)?),
);
assert_eq!(plugin.root, plugin_root);
assert_eq!(plugin.version, "local");
assert_eq!(Some(&plugin.files), v1.plugin.as_ref());
assert_eq!(
plugin.skills,
v1.skills
.into_iter()
.map(|skill| {
let name = if skill
.instructions
.path
.starts_with(&plugin.root.join("nested")?)
{
"team:deploy"
} else {
"demo:deploy"
};
Ok(expected_skill(skill.instructions.path, name))
})
.collect::<anyhow::Result<Vec<_>>>()?
);
assert_eq!(
response.skills,
vec![
expected_skill(
request.codex_home.join("skills/deploy skill/SKILL.md")?,
"deploy skill",
),
expected_skill(
request
.codex_home
.join("skills/nested/skills/deploy/SKILL.md")?,
"team:deploy"
),
]
.into_iter()
.map(|mut skill| {
skill.discovery_root = Some(SkillDiscoveryRoot {
id: "codex-home-skills".to_string(),
path: request.codex_home.join("skills").expect("skills root"),
});
skill
})
.collect::<Vec<_>>(),
);
let inline_plugin = response
.plugins
.iter()
.find(|plugin| plugin.id == "unconfigured@test")
.expect("inline plugin");
assert_eq!(inline_plugin.files.manifest, inline_v1_files.manifest);
assert_eq!(
inline_plugin.files.mcp_config,
Some(crate::CapabilityTextFile {
path: inline_v1_files.manifest.path,
contents: serde_json::json!({"inline": {"command": "node"}}).to_string(),
})
);
assert_eq!(
response.warnings,
vec!["some capability metadata could not be loaded; discovery may be incomplete"],
);
let json = serde_json::to_string(&response)?;
assert!(
response.plugins.len() + plugin.skills.len() + response.skills.len() <= MAX_CAPABILITIES
);
assert!(json.len() <= MAX_RESPONSE_BYTES);
assert!(response.warnings.len() <= MAX_WARNINGS);
assert!(!json.contains("PRIVATE_INSTRUCTION_BODY_SENTINEL"));
Ok(())
}
fn expected_skill(path: PathUri, name: &str) -> ExecutorSkill {
ExecutorSkill {
name: name.to_string(),
description: "Deploy the service.".to_string(),
short_description: None,
path,
discovery_root: None,
dependencies: None,
policy: None,
}
}
#[tokio::test]
async fn discovery_reports_location_failures_without_paths() -> anyhow::Result<()> {
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::NetworkSandboxPolicy;
let temp = tempfile::tempdir()?;
request(temp.path())?;
let locations = crate::discover_v2::capability_locations::CapabilityLocations {
warnings: vec!["could not scan plugin cache /private/plugins/cache".into()],
..Default::default()
};
let sandbox = crate::FileSystemSandboxContext::from_permission_profile(
PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy::restricted(Vec::new()),
NetworkSandboxPolicy::Restricted,
),
PathUri::from_host_native_path(temp.path().join("project"))?,
);
for sandbox in [None, Some(&sandbox)] {
let response = super::load_capability_discoveries(
&LocalFileSystem::unsandboxed(),
&locations,
sandbox,
)
.await?;
assert_eq!(
*response,
crate::DiscoverV2CapabilitiesResponse {
warnings: vec![
"some capability locations could not be resolved; discovery may be incomplete"
.into(),
],
..Default::default()
}
);
}
Ok(())
}
#[tokio::test]
async fn discovery_resolves_optional_skill_metadata() -> anyhow::Result<()> {
use codex_protocol::protocol::Product;
use codex_skills::SkillDependencies;
use codex_skills::SkillPolicy;
use codex_skills::SkillToolDependency;
let dependencies = Some(SkillDependencies {
tools: vec![SkillToolDependency {
r#type: "mcp".into(),
value: "deploy".into(),
description: None,
transport: Some("stdio".into()),
command: Some("deploy-mcp".into()),
url: None,
oauth_callback_port: Some(3118),
}],
});
let policy = Some(SkillPolicy {
allow_implicit_invocation: Some(false),
products: vec![Product::Codex, Product::Chatgpt],
});
for (yaml, dependencies, policy) in [
(None, None, None),
(Some("interface: [invalid]"), None, None),
(Some("dependencies:\n tools: [{type: mcp}]"), None, None),
(Some("dependencies: {tools: []}"), None, None),
(
Some(
r#"dependencies:
tools:
- type: " mcp "
value: " deploy "
transport: stdio
command: deploy-mcp
oauth: {callback_port: 3118}
- type: mcp
value: " "
policy:
allow_implicit_invocation: false
products: [codex, CHATGPT]
"#,
),
dependencies,
policy,
),
] {
let temp = tempfile::tempdir()?;
let request = request(temp.path())?;
let plugin_root = "codex/plugins/cache/test/demo/local";
write(
temp.path(),
&format!("{plugin_root}/.codex-plugin/plugin.json"),
MANIFEST,
)?;
for root in [
"codex/skills/deploy".to_string(),
format!("{plugin_root}/skills/deploy"),
] {
write(temp.path(), &format!("{root}/SKILL.md"), SKILL)?;
if let Some(yaml) = yaml {
write(temp.path(), &format!("{root}/agents/openai.yaml"), yaml)?;
}
}
let manager = CapabilityManager::new(LocalFileSystem::unsandboxed());
manager.seed_prewarmed_locations(request.clone()).await?;
let response = manager
.get_or_refresh_discovery(DiscoverV2CapabilitiesRequest {
cwd: PathUri::from_host_native_path(temp.path().join("project"))?,
sandbox: None,
})
.await?;
let mut expected =
expected_skill(request.codex_home.join("skills/deploy/SKILL.md")?, "deploy");
expected.dependencies = dependencies;
expected.policy = policy;
expected.discovery_root = Some(SkillDiscoveryRoot {
id: "codex-home-skills".to_string(),
path: request.codex_home.join("skills")?,
});
assert_eq!(response.skills, vec![expected.clone()]);
expected.path = request
.codex_home
.join("plugins/cache/test/demo/local/skills/deploy/SKILL.md")?;
expected.name = "demo:deploy".into();
expected.discovery_root = None;
assert_eq!(response.plugins[0].skills, vec![expected]);
assert_eq!(response.warnings, Vec::<String>::new());
}
Ok(())
}
#[tokio::test]
async fn standalone_skills_retain_their_search_roots() -> anyhow::Result<()> {
let temp = tempfile::tempdir()?;
let request = request(temp.path())?;
let roots = [
("codex-home-skills", "codex/skills"),
("user-agent-skills", "home/.agents/skills"),
("system-skills", "etc/codex/skills"),
];
let mut expected = Vec::new();
for (id, root) in roots {
for relative in ["deploy/SKILL.md", "nested/deploy/SKILL.md"] {
let path = format!("{root}/{relative}");
write(temp.path(), &path, SKILL)?;
let mut skill = expected_skill(
PathUri::from_host_native_path(temp.path().join(path))?,
"deploy",
);
skill.discovery_root = Some(SkillDiscoveryRoot {
id: id.to_string(),
path: PathUri::from_host_native_path(temp.path().join(root))?,
});
expected.push(skill);
}
}
let manager = CapabilityManager::new(LocalFileSystem::unsandboxed());
manager.seed_prewarmed_locations(request.clone()).await?;
let query = DiscoverV2CapabilitiesRequest {
cwd: PathUri::from_host_native_path(temp.path().join("project"))?,
sandbox: None,
};
let response = manager.get_or_refresh_discovery(query.clone()).await?;
assert_eq!(response.skills, expected);
// Cached discovery must retain the same root metadata.
assert_eq!(manager.get_or_refresh_discovery(query).await?, response);
Ok(())
}

View File

@@ -0,0 +1,135 @@
//! Exercises installed-package and fixed skill location prewarming on real filesystem fixtures.
use pretty_assertions::assert_eq;
use std::path::Path;
use codex_utils_path_uri::PathUri;
use super::CapabilityLocation;
use super::CapabilityLocationRequest;
use super::InstalledPlugin;
use super::prewarm_locations;
use crate::LocalFileSystem;
pub(crate) const MANIFEST: &str = r#"{"name":"demo","version":"1.10.0"}"#;
pub(crate) fn request(root: &Path) -> anyhow::Result<CapabilityLocationRequest> {
for path in ["codex", "home", "project", "etc/codex"] {
std::fs::create_dir_all(root.join(path))?;
}
Ok(CapabilityLocationRequest {
codex_home: PathUri::from_host_native_path(root.join("codex"))?,
user_home: Some(PathUri::from_host_native_path(root.join("home"))?),
system_skills_root: Some(PathUri::from_host_native_path(
root.join("etc/codex/skills"),
)?),
})
}
pub(crate) fn write(root: &Path, relative: &str, contents: &str) -> anyhow::Result<()> {
let path = root.join(relative);
let parent = path
.parent()
.ok_or_else(|| anyhow::anyhow!("test fixture path has no parent"))?;
std::fs::create_dir_all(parent)?;
std::fs::write(path, contents)?;
Ok(())
}
#[tokio::test]
async fn prewarming_resolves_global_locations_without_cwd_or_config() -> anyhow::Result<()> {
let temp = tempfile::tempdir()?;
let request = request(temp.path())?;
// Prewarming must not read configuration.
write(temp.path(), "codex/config.toml", "invalid TOML [")?;
for root in [
"codex/skills",
"home/.agents/skills",
"etc/codex/skills",
"project/.agents/skills",
] {
write(temp.path(), &format!("{root}/demo/SKILL.md"), "unparsed")?;
}
for version in ["1.9.0", "1.10.0"] {
write(
temp.path(),
&format!("codex/plugins/cache/team/demo/{version}/.codex-plugin/plugin.json"),
MANIFEST,
)?;
}
write(
temp.path(),
"codex/plugins/cache/team/demo/.codex-remote-plugin-install.json",
r#"{"schema_version":1,"remote_plugin_id":"plugins~demo"}"#,
)?;
let locations = prewarm_locations(&LocalFileSystem::unsandboxed(), &request).await?;
let mut actual = locations.locations;
actual.sort_unstable_by_key(|location| location.root.to_string());
let mut expected = vec![CapabilityLocation {
root: request.codex_home.join("plugins/cache/team/demo/1.10.0")?,
standalone_root_id: None,
plugin: Some(InstalledPlugin {
id: "demo@team".to_string(),
version: "1.10.0".to_string(),
remote_plugin_id: Some("plugins~demo".to_string()),
}),
}];
for (id, root) in [
("codex-home-skills", "codex/skills"),
("user-agent-skills", "home/.agents/skills"),
("system-skills", "etc/codex/skills"),
] {
expected.push(CapabilityLocation {
root: PathUri::from_host_native_path(temp.path().join(root))?,
standalone_root_id: Some(id.to_string()),
plugin: None,
});
}
expected.sort_unstable_by_key(|location| location.root.to_string());
assert_eq!(actual, expected);
assert!(locations.warnings.is_empty());
let metadata = "codex/plugins/cache/team/demo/.codex-remote-plugin-install.json";
for contents in [
"invalid JSON".to_string(),
" ".repeat(super::MAX_REMOTE_INSTALL_METADATA_BYTES as usize + 1),
] {
write(temp.path(), metadata, &contents)?;
let locations = prewarm_locations(&LocalFileSystem::unsandboxed(), &request).await?;
assert!(locations.warnings.iter().any(|warning| {
warning.contains("could not read remote installation metadata for demo@team")
}));
assert!(locations.locations.iter().any(|location| {
location
.plugin
.as_ref()
.is_some_and(|plugin| plugin.id == "demo@team" && plugin.remote_plugin_id.is_none())
}));
}
// Missing remote metadata is valid for locally installed plugins.
std::fs::remove_file(temp.path().join(metadata))?;
let locations = prewarm_locations(&LocalFileSystem::unsandboxed(), &request).await?;
assert!(locations.warnings.is_empty());
assert!(locations.locations.iter().any(|location| {
location
.plugin
.as_ref()
.is_some_and(|plugin| plugin.id == "demo@team" && plugin.remote_plugin_id.is_none())
}));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let directory = temp.path().join("codex/plugins/cache/team");
let permissions = std::fs::metadata(&directory)?.permissions();
std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o000))?;
let result = prewarm_locations(&LocalFileSystem::unsandboxed(), &request).await;
std::fs::set_permissions(&directory, permissions)?;
assert!(
result.is_err(),
"cache traversal failure must not retain partial locations"
);
}
Ok(())
}

View File

@@ -0,0 +1,196 @@
//! Covers bounded context caching, shared initialization, cancellation retry, and cached warnings.
use super::*;
use crate::discover_v2::capability_locations::tests::request;
use crate::discover_v2::capability_locations::tests::write;
use codex_protocol::models::PermissionProfile;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
impl CapabilityManager {
// Supply fixture paths through the existing cell, without production override state.
pub(crate) async fn seed_prewarmed_locations(
self: &Arc<Self>,
request: CapabilityLocationRequest,
) -> io::Result<()> {
self.prewarmed_locations
.get_or_try_init(|| async {
let locations = prewarm_locations(&self.file_system, &request).await?;
Ok::<_, io::Error>((request, locations))
})
.await?;
self.prewarm_locations().await.map(|_| ())
}
}
async fn setup() -> anyhow::Result<(tempfile::TempDir, Arc<CapabilityManager>)> {
let directory = tempfile::tempdir()?;
write(
directory.path(),
"codex/skills/demo/SKILL.md",
"---\nname: demo\ndescription: original\n---\nbody never cached",
)?;
let request = request(&std::fs::canonicalize(directory.path())?)?;
let file_system = LocalFileSystem::unsandboxed();
let manager = CapabilityManager::new(file_system);
manager.seed_prewarmed_locations(request).await?;
capability_watchers::tests::stop_listener(&manager).await?;
Ok((directory, manager))
}
#[tokio::test]
async fn discovery_responses_are_cached_by_sandbox_context() -> anyhow::Result<()> {
let (directory, manager) = setup().await?;
let (first_locations, second_locations) =
tokio::try_join!(manager.prewarm_locations(), manager.prewarm_locations())?;
assert!(std::ptr::eq(first_locations, second_locations));
let cwd = PathUri::from_host_native_path(directory.path().join("project"))?;
let other_cwd = PathUri::from_host_native_path(directory.path().join("other"))?;
let params = DiscoverV2CapabilitiesRequest {
cwd: cwd.clone(),
sandbox: None,
};
let first = manager.get_or_refresh_discovery(params.clone()).await?;
assert_eq!(first.skills.len(), 1);
let snapshot = manager
.location_snapshot()
.await
.ok_or_else(|| anyhow::anyhow!("missing snapshot"))?;
let other = manager
.get_or_refresh_discovery(DiscoverV2CapabilitiesRequest {
cwd: other_cwd.clone(),
..params.clone()
})
.await?;
assert!(Arc::ptr_eq(&first, &other));
// The full sandbox context, including its own cwd, still identifies a separate cache.
let mut previous = Arc::clone(&first);
for index in 0..MAX_CACHED_SANDBOX_CONTEXTS {
let sandbox_cwd = cwd.join(&format!("context-{index}"))?;
let sandbox = DiscoverV2CapabilitiesRequest {
sandbox: Some(FileSystemSandboxContext::from_permission_profile(
PermissionProfile::Disabled,
sandbox_cwd,
)),
..params.clone()
};
let response = manager.get_or_refresh_discovery(sandbox.clone()).await?;
assert_eq!(response, previous);
assert!(!Arc::ptr_eq(&response, &previous));
assert!(Arc::ptr_eq(
&response,
&manager.get_or_refresh_discovery(sandbox).await?
));
previous = response;
}
assert_eq!(
snapshot.sandbox_discoveries.lock().await.len(),
MAX_CACHED_SANDBOX_CONTEXTS
);
// The oldest context is evicted, but its previously returned response stays valid.
let reloaded = manager.get_or_refresh_discovery(params).await?;
assert_eq!(reloaded, first);
assert!(!Arc::ptr_eq(&reloaded, &first));
assert_eq!(
snapshot.sandbox_discoveries.lock().await.len(),
MAX_CACHED_SANDBOX_CONTEXTS
);
Ok(())
}
#[test]
fn cancelled_initialization_retries_and_warning_responses_are_cached() -> anyhow::Result<()> {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.max_blocking_threads(1)
.build()?
.block_on(async {
let (directory, manager) = setup().await?;
let params = DiscoverV2CapabilitiesRequest {
cwd: PathUri::from_host_native_path(directory.path().join("project"))?,
sandbox: None,
};
let snapshot = manager
.location_snapshot()
.await
.ok_or_else(|| anyhow::anyhow!("missing snapshot"))?;
// Hold the only blocking worker so discovery's filesystem read cannot finish early.
// Dropping the sender also releases the worker if an assertion unwinds.
let (release, wait) = std::sync::mpsc::channel::<()>();
let (started, ready) = tokio::sync::oneshot::channel();
let blocker = tokio::task::spawn_blocking(move || {
let _ = started.send(());
let _ = wait.recv();
});
ready.await?;
let mut first = Box::pin(manager.get_or_refresh_discovery(params.clone()));
assert!(futures::poll!(&mut first).is_pending());
let discovery = snapshot
.sandbox_discoveries
.lock()
.await
.first()
.cloned()
.ok_or_else(|| anyhow::anyhow!("missing sandbox discovery"))?;
let mut second = Box::pin(manager.get_or_refresh_discovery(params.clone()));
assert!(futures::poll!(&mut second).is_pending());
assert!(discovery.response.get().is_none());
assert!(snapshot.sandbox_discoveries.try_lock().is_ok());
// Cancel the initializer; the waiting request must be able to initialize instead.
drop(first);
drop(release);
blocker.await?;
let original = second.await?;
assert_eq!(original.skills.len(), 1);
assert!(Arc::ptr_eq(
&original,
&manager.get_or_refresh_discovery(params.clone()).await?,
));
write(
directory.path(),
"codex/skills/demo/SKILL.md",
"invalid skill metadata",
)?;
// Invalidation drops entries instead of overwriting their initialized responses.
snapshot.sandbox_discoveries.lock().await.clear();
let (partial, concurrent) = tokio::try_join!(
manager.get_or_refresh_discovery(params.clone()),
manager.get_or_refresh_discovery(params.clone()),
)?;
assert!(Arc::ptr_eq(&partial, &concurrent));
assert!(partial.skills.is_empty());
assert!(!partial.warnings.is_empty());
assert!(Arc::ptr_eq(
&partial,
&manager.get_or_refresh_discovery(params.clone()).await?
));
write(
directory.path(),
"codex/skills/demo/SKILL.md",
"---\nname: demo\ndescription: recovered\n---\n",
)?;
assert!(Arc::ptr_eq(
&partial,
&manager.get_or_refresh_discovery(params.clone()).await?
));
snapshot.sandbox_discoveries.lock().await.clear();
let recovered = manager.get_or_refresh_discovery(params.clone()).await?;
assert!(recovered.warnings.is_empty());
assert_eq!(
recovered
.skills
.iter()
.map(|skill| skill.description.as_str())
.collect::<Vec<_>>(),
vec!["recovered"]
);
assert!(Arc::ptr_eq(
&recovered,
&manager.get_or_refresh_discovery(params).await?
));
Ok(())
})
}

View File

@@ -0,0 +1,334 @@
//! Watch events invalidate discovery; no subscription keeps requests uncached.
use super::*;
use crate::DiscoverV2CapabilitiesRequest;
use crate::LocalFileSystem;
use crate::discover_v2::capability_locations::tests::request;
use crate::discover_v2::capability_locations::tests::write;
use anyhow::Context;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use std::time::Duration;
// Keep native events from racing deterministic cache assertions.
pub(in crate::discover_v2::capability_manager) async fn stop_listener(
manager: &CapabilityManager,
) -> anyhow::Result<()> {
manager
.watchers
.subscription
.get()
.context("watcher unavailable")?
._listener
.abort();
drop(manager.location_refresh_lock.acquire().await?);
Ok(())
}
#[tokio::test]
async fn watch_events_invalidate_discovery_and_no_subscription_disables_caching()
-> anyhow::Result<()> {
let directory = tempfile::tempdir()?;
let root = std::fs::canonicalize(directory.path())?;
write(
&root,
"codex/skills/demo/SKILL.md",
"---\nname: demo\ndescription: original\n---\n",
)?;
let request = request(&root)?;
let demo_skill = request.codex_home.join("skills/demo/SKILL.md")?;
let manager = CapabilityManager::new(LocalFileSystem::unsandboxed());
manager.seed_prewarmed_locations(request.clone()).await?;
let params = DiscoverV2CapabilitiesRequest {
cwd: PathUri::from_host_native_path(&root)?,
sandbox: None,
};
let original = manager.get_or_refresh_discovery(params.clone()).await?;
assert!(
original
.skills
.iter()
.any(|skill| skill.path == demo_skill && skill.description == "original")
);
let initial = manager
.location_snapshot()
.await
.context("missing initial snapshot")?;
// Wait for native delivery before testing one-shot creation of missing roots.
tokio::time::timeout(Duration::from_secs(10), async {
let mut interval = tokio::time::interval(Duration::from_millis(50));
loop {
interval.tick().await;
write(
&root,
"codex/skills/demo/SKILL.md",
"---\nname: demo\ndescription: ready\n---\n",
)?;
let snapshot = manager
.location_snapshot()
.await
.context("missing snapshot")?;
if !Arc::ptr_eq(&initial, &snapshot) {
assert!(snapshot.sandbox_discoveries.lock().await.is_empty());
break anyhow::Ok(());
}
}
})
.await
.context("native watcher did not deliver its first content event")??;
// Neither the plugin cache nor the user skills directory existed at startup.
write(
&root,
"codex/plugins/cache/acme/gmail/1.0.0/.codex-plugin/plugin.json",
r#"{"name":"gmail"}"#,
)?;
write(
&root,
"home/.agents/skills/added/SKILL.md",
"---\nname: added\ndescription: new global root\n---\n",
)?;
let home_skills = PathUri::from_host_native_path(root.join("home/.agents/skills"))?;
tokio::time::timeout(Duration::from_secs(10), async {
let mut interval = tokio::time::interval(Duration::from_millis(50));
loop {
interval.tick().await;
// Inspect only locations: a request-time rescan must not hide a missed event.
let snapshot = manager
.location_snapshot()
.await
.context("missing snapshot")?;
if snapshot
.locations
.locations
.iter()
.any(|location| location.root == home_skills)
&& snapshot.locations.locations.iter().any(|location| {
location
.plugin
.as_ref()
.is_some_and(|plugin| plugin.id == "gmail@acme")
})
{
assert!(snapshot.sandbox_discoveries.lock().await.is_empty());
break anyhow::Ok(());
}
}
})
.await
.context("native watcher missed creation of a global root")??;
// Drive subsequent refreshes explicitly so native delivery cannot race cache assertions.
stop_listener(&manager).await?;
let refreshed = manager.get_or_refresh_discovery(params.clone()).await?;
let added_skill = home_skills.join("added/SKILL.md")?;
assert!(
refreshed
.skills
.iter()
.any(|skill| skill.path == added_skill)
);
assert_eq!(refreshed.plugins.len(), 1);
assert!(
refreshed
.skills
.iter()
.any(|skill| skill.path == demo_skill && skill.description == "ready")
);
let sandbox_params = DiscoverV2CapabilitiesRequest {
sandbox: Some(crate::FileSystemSandboxContext::from_permission_profile(
codex_protocol::models::PermissionProfile::Disabled,
params.cwd.clone(),
)),
..params.clone()
};
manager.get_or_refresh_discovery(sandbox_params).await?;
let retained = manager
.location_snapshot()
.await
.context("missing populated snapshot")?;
assert_eq!(retained.sandbox_discoveries.lock().await.len(), 2);
write(
&root,
"codex/plugins/cache/acme/gmail/2.0.0/.codex-plugin/plugin.json",
r#"{"name":"gmail"}"#,
)?;
write(
&root,
"codex/skills/demo/SKILL.md",
"---\nname: demo\ndescription: refreshed\n---\n",
)?;
manager.refresh_locations().await;
let next = manager
.location_snapshot()
.await
.context("missing refreshed snapshot")?;
assert_eq!(
next.locations
.locations
.iter()
.filter_map(|location| location.plugin.as_ref())
.find(|plugin| plugin.id == "gmail@acme")
.map(|plugin| plugin.version.as_str()),
Some("2.0.0")
);
assert!(next.sandbox_discoveries.lock().await.is_empty());
assert_eq!(retained.sandbox_discoveries.lock().await.len(), 2);
assert_eq!(
retained
.locations
.locations
.iter()
.filter_map(|location| location.plugin.as_ref())
.find(|plugin| plugin.id == "gmail@acme")
.map(|plugin| plugin.version.as_str()),
Some("1.0.0")
);
let after = manager.get_or_refresh_discovery(params.clone()).await?;
assert!(
after
.skills
.iter()
.any(|skill| skill.path == demo_skill && skill.description == "refreshed")
);
// Only the requested context is rebuilt; subsequent requests reuse it.
assert_eq!(next.sandbox_discoveries.lock().await.len(), 1);
assert!(Arc::ptr_eq(
&after,
&manager.get_or_refresh_discovery(params.clone()).await?
));
#[cfg(unix)]
{
// A failed event refresh retains the response but retries without another event.
let cache = root.join("codex/plugins/cache");
let saved_cache = root.join("codex/plugins/saved-cache");
std::fs::rename(&cache, &saved_cache)?;
std::os::unix::fs::symlink(&cache, &cache)?;
manager.refresh_locations().await;
let fallback = manager.get_or_refresh_discovery(params.clone()).await?;
assert!(Arc::ptr_eq(&after, &fallback));
std::fs::remove_file(&cache)?;
std::fs::rename(&saved_cache, &cache)?;
write(
&root,
"codex/skills/recovered/SKILL.md",
"---\nname: recovered\ndescription: recovered after failed refresh\n---\n",
)?;
let recovered = manager.get_or_refresh_discovery(params.clone()).await?;
assert!(
recovered
.skills
.iter()
.any(|skill| skill.name == "recovered")
);
assert!(!Arc::ptr_eq(&fallback, &recovered));
assert!(Arc::ptr_eq(
&recovered,
&manager.get_or_refresh_discovery(params.clone()).await?
));
}
// Without a subscription, requests reload both membership and content.
let mut uncached = CapabilityManager::new(LocalFileSystem::unsandboxed());
Arc::get_mut(&mut uncached)
.context("new manager unexpectedly shared")?
.watchers
.file_watcher = None;
uncached.seed_prewarmed_locations(request.clone()).await?;
let before = uncached.get_or_refresh_discovery(params.clone()).await?;
assert!(uncached.watchers.subscription.get().is_none());
write(
&root,
"codex/skills/demo/SKILL.md",
"---\nname: demo\ndescription: uncached edit\n---\n",
)?;
write(
&root,
"codex/plugins/cache/acme/calendar/1.0.0/.codex-plugin/plugin.json",
r#"{"name":"calendar"}"#,
)?;
let after = uncached.get_or_refresh_discovery(params.clone()).await?;
assert_eq!(after.plugins.len(), before.plugins.len() + 1);
assert!(
after
.plugins
.iter()
.any(|plugin| plugin.id == "calendar@acme")
);
assert!(
after
.skills
.iter()
.any(|skill| skill.path == demo_skill && skill.description == "uncached edit")
);
let repeated = uncached.get_or_refresh_discovery(params).await?;
assert_eq!(after, repeated);
assert!(!Arc::ptr_eq(&after, &repeated));
Ok(())
}
#[tokio::test]
async fn failed_watch_registration_reloads_locations_and_contents() -> anyhow::Result<()> {
let directory = tempfile::tempdir()?;
let root = std::fs::canonicalize(directory.path())?;
write(
&root,
"codex/skills/demo/SKILL.md",
"---\nname: demo\ndescription: original\n---\n",
)?;
let request = request(&root)?;
let params = DiscoverV2CapabilitiesRequest {
cwd: PathUri::from_host_native_path(&root)?,
sandbox: None,
};
let mut manager = CapabilityManager::new(LocalFileSystem::unsandboxed());
// A subscriber exists, but no OS watches can be registered.
Arc::get_mut(&mut manager)
.context("new manager unexpectedly shared")?
.watchers
.file_watcher = Some(Arc::new(FileWatcher::noop()));
manager.seed_prewarmed_locations(request.clone()).await?;
let before = manager.get_or_refresh_discovery(params.clone()).await?;
assert_eq!(before.skills.len(), 1);
assert!(before.plugins.is_empty());
assert!(manager.watchers.subscription.get().is_some());
let initial = manager
.location_snapshot()
.await
.context("missing snapshot")?;
assert!(!initial.registration.registration_succeeded());
write(
&root,
"codex/skills/demo/SKILL.md",
"---\nname: demo\ndescription: edited\n---\n",
)?;
write(
&root,
"codex/plugins/cache/acme/calendar/1.0.0/.codex-plugin/plugin.json",
r#"{"name":"calendar"}"#,
)?;
let after = manager.get_or_refresh_discovery(params.clone()).await?;
assert_eq!(after.skills.len(), 1);
assert_eq!(after.skills[0].description, "edited");
assert_eq!(after.plugins.len(), 1);
assert_eq!(after.plugins[0].id, "calendar@acme");
let snapshot = manager
.location_snapshot()
.await
.context("missing refreshed snapshot")?;
assert!(!Arc::ptr_eq(&initial, &snapshot));
assert!(
snapshot
.sandbox_discoveries
.lock()
.await
.iter()
.all(|discovery| discovery.response.get().is_none())
);
let repeated = manager.get_or_refresh_discovery(params).await?;
assert_eq!(after, repeated);
assert!(!Arc::ptr_eq(&after, &repeated));
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,67 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::RwLock;
use super::Environment;
use super::EnvironmentManager;
use super::validate_environment_id;
use crate::ExecServerClient;
use crate::ExecServerClientConnectOptions;
use crate::ExecServerError;
use crate::client::LazyRemoteExecServerClient;
use axum::extract::ws::WebSocket;
use codex_config::ScopedSkillsConfig;
use codex_http_client::HttpClientFactory;
impl EnvironmentManager {
/// Builds a manager around a WebSocket already accepted and authenticated by its host.
///
/// The manager owns client construction, session initialization, and later
/// recovery. The host only supplies the initial socket and authenticated
/// replacement sockets through [`Self::replace_accepted_websocket`].
pub async fn from_accepted_websocket(
environment_id: String,
websocket: WebSocket,
options: ExecServerClientConnectOptions,
http_client_factory: HttpClientFactory,
) -> Result<Self, ExecServerError> {
validate_environment_id(&environment_id)?;
let client = ExecServerClient::connect_accepted_websocket(websocket, options).await?;
let client =
LazyRemoteExecServerClient::from_connected(client, http_client_factory.clone());
let environment = Arc::new(Environment::remote_with_client(
client,
/*local_runtime_paths*/ None,
ScopedSkillsConfig::default(),
));
Ok(Self {
default_environment: Some(environment_id.clone()),
environments: RwLock::new(HashMap::from([(environment_id, environment)])),
local_environment: None,
local_runtime_paths: None,
http_client_factory,
})
}
/// Hands a replacement WebSocket to an existing accepted environment.
/// Returns after handoff; recovery continues asynchronously.
pub async fn replace_accepted_websocket(
&self,
environment_id: &str,
websocket: WebSocket,
) -> Result<(), ExecServerError> {
let environment = self.get_environment(environment_id).ok_or_else(|| {
ExecServerError::Protocol(format!("environment `{environment_id}` is not configured"))
})?;
environment
.remote_client
.as_ref()
.ok_or_else(|| {
ExecServerError::Protocol(
"local environment does not have a replaceable exec-server client".to_string(),
)
})?
.replace_accepted_websocket(websocket)
.await
}
}

View File

@@ -0,0 +1,116 @@
//! Host-owned WebSocket connection options whose trusted headers remain private and redacted.
use std::collections::HashMap;
use std::time::Duration;
use http::HeaderMap;
use http::HeaderName;
use http::HeaderValue;
use crate::ExecServerError;
use crate::client_api::DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT;
use crate::client_api::DEFAULT_REMOTE_EXEC_SERVER_INITIALIZE_TIMEOUT;
use crate::client_api::ExecServerTransportParams;
use crate::environment_provider::normalize_exec_server_url;
/// Host-owned connection settings for a named remote execution environment.
///
/// Headers are sent only on the direct WebSocket upgrade request and subsequent
/// reconnects. The embedding host must derive them from trusted request or
/// session context, including app-server environment registration or environment configuration.
#[derive(Clone, Eq, PartialEq)]
pub struct RemoteEnvironmentOptions {
/// Direct `ws://` or `wss://` endpoint for the remote environment.
pub exec_server_url: String,
/// Optional connection timeout; the standard exec-server default applies when omitted.
pub connect_timeout: Option<Duration>,
/// Additional trusted headers for every physical WebSocket connection.
pub http_headers: HashMap<String, String>,
}
impl std::fmt::Debug for RemoteEnvironmentOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RemoteEnvironmentOptions")
.field("exec_server_url", &self.exec_server_url)
.field("connect_timeout", &self.connect_timeout)
.field("http_headers", &"<redacted>")
.finish()
}
}
impl RemoteEnvironmentOptions {
pub(crate) fn into_transport_params(
self,
) -> Result<ExecServerTransportParams, ExecServerError> {
let (exec_server_url, disabled) = normalize_exec_server_url(Some(self.exec_server_url));
if disabled {
return Err(ExecServerError::Protocol(
"remote environment cannot use disabled exec-server url".to_string(),
));
}
let exec_server_url = exec_server_url.ok_or_else(|| {
ExecServerError::Protocol("remote environment requires an exec-server url".to_string())
})?;
if !self.http_headers.is_empty() {
let url = url::Url::parse(&exec_server_url).map_err(|error| {
ExecServerError::Protocol(format!("invalid exec-server WebSocket URL: {error}"))
})?;
let is_loopback = match url.host() {
Some(url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"),
Some(url::Host::Ipv4(address)) => address.is_loopback(),
Some(url::Host::Ipv6(address)) => address.is_loopback(),
None => false,
};
if url.scheme() != "wss" && !is_loopback {
return Err(ExecServerError::Protocol(
"exec-server WebSocket headers require wss:// or a loopback destination"
.to_string(),
));
}
}
let mut http_headers = HeaderMap::with_capacity(self.http_headers.len());
for (name, value) in self.http_headers {
let header_name = HeaderName::from_bytes(name.as_bytes()).map_err(|_| {
ExecServerError::Protocol(format!(
"invalid exec-server WebSocket header name `{name}`"
))
})?;
if matches!(
header_name.as_str(),
"connection" | "content-length" | "host" | "transfer-encoding" | "upgrade"
) || header_name.as_str().starts_with("sec-websocket-")
{
return Err(ExecServerError::Protocol(format!(
"exec-server WebSocket header `{header_name}` is controlled by the connection"
)));
}
let mut header_value = HeaderValue::from_str(&value).map_err(|_| {
ExecServerError::Protocol(format!(
"invalid value for exec-server WebSocket header `{header_name}`"
))
})?;
if http_headers.contains_key(&header_name) {
return Err(ExecServerError::Protocol(format!(
"duplicate exec-server WebSocket header `{header_name}`"
)));
}
header_value.set_sensitive(true);
http_headers.insert(header_name, header_value);
}
Ok(ExecServerTransportParams::WebSocketUrl {
websocket_url: exec_server_url,
connect_timeout: self
.connect_timeout
.unwrap_or(DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT),
initialize_timeout: DEFAULT_REMOTE_EXEC_SERVER_INITIALIZE_TIMEOUT,
http_headers,
})
}
}
#[cfg(test)]
#[path = "connect_options_tests.rs"]
mod tests;

View File

@@ -0,0 +1,343 @@
use std::collections::HashMap;
use std::time::Duration;
use codex_config::ScopedSkillsConfig;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use futures::SinkExt;
use futures::StreamExt;
use http::HeaderValue;
use pretty_assertions::assert_eq;
use tokio::net::TcpListener;
use tokio::net::TcpStream;
use tokio::sync::oneshot;
use tokio::time::timeout;
use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::accept_hdr_async;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::handshake::server::Request;
use tokio_tungstenite::tungstenite::handshake::server::Response;
use super::RemoteEnvironmentOptions;
use crate::EnvironmentManager;
use crate::InitializeParams;
use crate::InitializeResponse;
use crate::protocol::INITIALIZE_METHOD;
use crate::protocol::INITIALIZED_METHOD;
use crate::protocol::JSONRPCMessage;
use crate::protocol::JSONRPCResponse;
#[test]
fn remote_environment_options_redact_header_values() {
let options = RemoteEnvironmentOptions {
exec_server_url: "wss://relay.example/environment".to_string(),
connect_timeout: Some(Duration::from_secs(5)),
http_headers: HashMap::from([(
"authorization".to_string(),
"Bearer secret-customer-token".to_string(),
)]),
};
let debug = format!("{options:?}");
assert!(debug.contains("<redacted>"));
assert!(!debug.contains("secret-customer-token"));
}
#[test]
fn trusted_headers_require_tls_for_non_loopback_destinations() {
let manager = EnvironmentManager::without_environments(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
));
let error = manager
.upsert_environment_with_options(
"customer-environment".to_string(),
RemoteEnvironmentOptions {
exec_server_url: "ws://relay.example/environment".to_string(),
connect_timeout: None,
http_headers: HashMap::from([(
"x-session-id".to_string(),
"customer-session".to_string(),
)]),
},
ScopedSkillsConfig::default(),
)
.expect_err("trusted headers must not be sent over an insecure remote connection");
assert_eq!(
error.to_string(),
"exec-server protocol error: exec-server WebSocket headers require wss:// or a loopback destination"
);
assert!(manager.get_environment("customer-environment").is_none());
}
#[test]
fn duplicate_case_insensitive_websocket_headers_fail_before_registration() {
let manager = EnvironmentManager::without_environments(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
));
let error = manager
.upsert_environment_with_options(
"customer-environment".to_string(),
RemoteEnvironmentOptions {
exec_server_url: "ws://127.0.0.1:8765".to_string(),
connect_timeout: None,
http_headers: HashMap::from([
("X-Session-Id".to_string(), "first-session".to_string()),
("x-session-id".to_string(), "second-session".to_string()),
]),
},
ScopedSkillsConfig::default(),
)
.expect_err("duplicate header names must fail regardless of case");
assert_eq!(
error.to_string(),
"exec-server protocol error: duplicate exec-server WebSocket header `x-session-id`"
);
assert!(manager.get_environment("customer-environment").is_none());
}
#[test]
fn invalid_websocket_header_names_fail_before_registration() {
let manager = EnvironmentManager::without_environments(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
));
let error = manager
.upsert_environment_with_options(
"customer-environment".to_string(),
RemoteEnvironmentOptions {
exec_server_url: "ws://127.0.0.1:8765".to_string(),
connect_timeout: None,
http_headers: HashMap::from([("bad header".to_string(), "value".to_string())]),
},
ScopedSkillsConfig::default(),
)
.expect_err("invalid header name should fail");
assert_eq!(
error.to_string(),
"exec-server protocol error: invalid exec-server WebSocket header name `bad header`"
);
assert!(manager.get_environment("customer-environment").is_none());
}
#[test]
fn invalid_websocket_header_values_fail_before_registration() {
let manager = EnvironmentManager::without_environments(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
));
let error = manager
.upsert_environment_with_options(
"customer-environment".to_string(),
RemoteEnvironmentOptions {
exec_server_url: "ws://127.0.0.1:8765".to_string(),
connect_timeout: None,
http_headers: HashMap::from([(
"x-session-id".to_string(),
"customer\nspoofed".to_string(),
)]),
},
ScopedSkillsConfig::default(),
)
.expect_err("invalid header value should fail");
assert_eq!(
error.to_string(),
"exec-server protocol error: invalid value for exec-server WebSocket header `x-session-id`"
);
assert!(manager.get_environment("customer-environment").is_none());
}
#[test]
fn websocket_controlled_headers_fail_before_registration() {
let manager = EnvironmentManager::without_environments(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
));
for header in ["host", "connection", "upgrade", "sec-websocket-key"] {
let error = manager
.upsert_environment_with_options(
"customer-environment".to_string(),
RemoteEnvironmentOptions {
exec_server_url: "ws://127.0.0.1:8765".to_string(),
connect_timeout: None,
http_headers: HashMap::from([(header.to_string(), "overridden".to_string())]),
},
ScopedSkillsConfig::default(),
)
.expect_err("connection-controlled header should fail");
assert_eq!(
error.to_string(),
format!(
"exec-server protocol error: exec-server WebSocket header `{header}` is controlled by the connection"
)
);
assert!(manager.get_environment("customer-environment").is_none());
}
}
#[tokio::test]
async fn trusted_headers_are_sent_on_initial_websocket_and_session_reconnect() {
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("listener should bind");
let websocket_url = format!(
"ws://{}",
listener.local_addr().expect("listener should have address")
);
let (resumed_tx, resumed_rx) = oneshot::channel();
let (finish_tx, finish_rx) = oneshot::channel();
let server = tokio::spawn(async move {
let mut first = accept_routing_headers_websocket(&listener).await;
complete_websocket_initialize(&mut first, /*expected_resume_session_id*/ None).await;
first
.close(None)
.await
.expect("first websocket should close");
let mut resumed = accept_routing_headers_websocket(&listener).await;
complete_websocket_initialize(&mut resumed, Some("session-1")).await;
resumed_tx.send(()).expect("resume should signal");
finish_rx.await.expect("test should finish");
});
let manager = EnvironmentManager::without_environments(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
));
manager
.upsert_environment_with_options(
"customer-environment".to_string(),
RemoteEnvironmentOptions {
exec_server_url: websocket_url,
connect_timeout: Some(Duration::from_secs(1)),
http_headers: HashMap::from([
(
"authorization".to_string(),
"Bearer reconnect-capability".to_string(),
),
(
"x-account-id".to_string(),
"customer-account-456".to_string(),
),
(
"x-session-id".to_string(),
"customer-session-123".to_string(),
),
(
"x-environment-id".to_string(),
"customer-environment-789".to_string(),
),
]),
},
ScopedSkillsConfig::default(),
)
.expect("environment with routing headers should register");
let environment = manager
.get_environment("customer-environment")
.expect("environment with routing headers should exist");
environment
.wait_until_ready()
.await
.expect("environment with routing headers should initialize");
timeout(Duration::from_secs(3), resumed_rx)
.await
.expect("routing-header session resume should not time out")
.expect("routing-header session resume should signal");
finish_tx.send(()).expect("test should finish");
server.await.expect("server task should finish");
}
async fn accept_routing_headers_websocket(listener: &TcpListener) -> WebSocketStream<TcpStream> {
let (stream, _) = listener.accept().await.expect("listener should accept");
accept_hdr_async(stream, |request: &Request, response: Response| {
assert_eq!(
request.headers().get(http::header::AUTHORIZATION),
Some(&HeaderValue::from_static("Bearer reconnect-capability"))
);
assert_eq!(
request.headers().get("x-account-id"),
Some(&HeaderValue::from_static("customer-account-456"))
);
assert_eq!(
request.headers().get("x-session-id"),
Some(&HeaderValue::from_static("customer-session-123"))
);
assert_eq!(
request.headers().get("x-environment-id"),
Some(&HeaderValue::from_static("customer-environment-789"))
);
Ok(response)
})
.await
.expect("routing-header websocket handshake should succeed")
}
async fn complete_websocket_initialize(
websocket: &mut WebSocketStream<TcpStream>,
expected_resume_session_id: Option<&str>,
) {
let message = websocket
.next()
.await
.expect("initialize request should arrive")
.expect("initialize websocket message should succeed");
let Message::Text(encoded) = message else {
panic!("expected initialize text message");
};
let JSONRPCMessage::Request(request) =
serde_json::from_str::<JSONRPCMessage>(&encoded).expect("initialize request should parse")
else {
panic!("expected initialize request");
};
assert_eq!(request.method, INITIALIZE_METHOD);
let params: InitializeParams = serde_json::from_value(
request
.params
.expect("initialize request should contain parameters"),
)
.expect("initialize parameters should parse");
assert_eq!(
params.resume_session_id.as_deref(),
expected_resume_session_id
);
let response = JSONRPCMessage::Response(JSONRPCResponse {
id: request.id,
result: serde_json::to_value(InitializeResponse {
session_id: "session-1".to_string(),
environment_info: None,
})
.expect("initialize response should serialize"),
});
websocket
.send(Message::Text(
serde_json::to_string(&response)
.expect("initialize response should encode")
.into(),
))
.await
.expect("initialize response should send");
let message = websocket
.next()
.await
.expect("initialized notification should arrive")
.expect("initialized websocket message should succeed");
let Message::Text(encoded) = message else {
panic!("expected initialized text message");
};
let JSONRPCMessage::Notification(notification) =
serde_json::from_str::<JSONRPCMessage>(&encoded)
.expect("initialized notification should parse")
else {
panic!("expected initialized notification");
};
assert_eq!(notification.method, INITIALIZED_METHOD);
}

View File

@@ -0,0 +1,49 @@
//! Shared recovery for idempotent V1 and V2 discovery requests.
use super::Environment;
use super::EnvironmentConnectionState;
use crate::ExecServerError;
use crate::client::is_retryable_recovery_error;
use std::future::Future;
use std::time::Duration;
use tokio::sync::watch;
impl Environment {
/// Replays discovery once after recovery; callers subscribe before obtaining the client.
pub(super) async fn discover_with_recovery<T, F, Fut>(
&self,
mut connection_state: watch::Receiver<EnvironmentConnectionState>,
discover: F,
) -> Result<T, ExecServerError>
where
F: Fn() -> Fut,
Fut: Future<Output = Result<T, ExecServerError>>,
{
match discover().await {
Err(error) if is_retryable_recovery_error(&error) => {
tracing::warn!(%error, "replaying capability discovery after executor recovery");
let recovered = tokio::time::timeout(Duration::from_secs(8), async {
loop {
match self.readiness_result() {
Some(Ok(())) => return Some(Ok(())),
Some(Err(error)) if !is_retryable_recovery_error(&error) => {
return Some(Err(error));
}
Some(Err(_)) | None => {}
}
if connection_state.changed().await.is_err() {
return None;
}
}
})
.await;
match recovered {
Ok(Some(Ok(()))) => discover().await,
Ok(Some(Err(error))) => Err(error),
Ok(None) | Err(_) => Err(error),
}
}
response => response,
}
}
}

View File

@@ -0,0 +1,62 @@
//! Acquires executor inventories without activation and replays safe reads after recovery.
use super::Environment;
use crate::DiscoverV2CapabilitiesRequest;
use crate::DiscoverV2CapabilitiesResponse;
use crate::EnvironmentInfo;
use crate::ExecServerError;
use codex_build_info::BuildInfo;
/// The final DiscoveryV2 contract starts at stable 0.164.0.
pub fn supports_capability_discovery_v2(info: &EnvironmentInfo) -> bool {
let build = BuildInfo::from_version(&info.executor_version);
let minimum = BuildInfo::from_version("0.164.0");
info.capabilities.capability_discovery_v2 && build.version() >= minimum.version()
}
impl Environment {
/// Identifies the initialized executor session; transport recovery preserves this ID.
pub(crate) async fn executor_session_id(&self) -> Result<Option<String>, ExecServerError> {
match &self.remote_client {
Some(client) => Ok(client.get().await?.session_id()),
None => Ok(None),
}
}
/// Returns metadata for the caller's cwd from the remote session's V2 lifecycle.
/// Local environments and older executors retain the V1 selected-root API.
pub async fn discover_capabilities_v2(
&self,
params: DiscoverV2CapabilitiesRequest,
) -> Result<DiscoverV2CapabilitiesResponse, ExecServerError> {
let Some(client) = &self.remote_client else {
return Err(ExecServerError::Protocol(
"capabilities/discoverV2 requires a remote environment".to_string(),
));
};
let connection_state = client.subscribe_connection_state();
let client = client.get().await?;
let discover = || async {
let info = client.environment_info().await?;
if !supports_capability_discovery_v2(&info) {
return Err(ExecServerError::Protocol(
"capabilities/discoverV2 is unavailable in this environment session"
.to_string(),
));
}
if params.sandbox.as_ref().is_some_and(|sandbox| {
sandbox.windows_sandbox_selection == crate::WindowsSandboxSelection::Mxc
}) {
crate::sandbox_selection::validate_remote_mxc(&info)
.map_err(|error| ExecServerError::Protocol(error.to_string()))?;
}
client.discover_capabilities_v2(params.clone()).await
};
self.discover_with_recovery(connection_state, discover)
.await
}
}
#[cfg(test)]
#[path = "discovery_v2_tests.rs"]
mod tests;

View File

@@ -0,0 +1,139 @@
//! Version compatibility gates discovery RPCs; supported clients retain transport recovery.
use super::DiscoverV2CapabilitiesRequest;
use super::DiscoverV2CapabilitiesResponse;
use super::Environment;
use crate::CAPABILITIES_DISCOVER_V2_METHOD;
use crate::client_api::ExecServerTransportParams;
use codex_config::ScopedSkillsConfig;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_utils_path_uri::PathUri;
use futures::SinkExt;
use futures::StreamExt;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::sync::Arc;
use std::time::Duration;
use tokio::net::TcpListener;
use tokio::sync::Mutex;
use tokio_tungstenite::accept_async;
use tokio_tungstenite::tungstenite::Message;
use tokio_util::task::AbortOnDropHandle;
#[test_case::test_case("0.164.0", true; "minimum_stable")]
#[test_case::test_case("0.168.0+build", true; "newer_stable")]
#[test_case::test_case("0.163.0", false; "older")]
#[test_case::test_case("0.164.0-alpha.1", false; "prerelease_before_cutoff")]
#[test_case::test_case("0.165.0-alpha.1", true; "next_minor_prerelease")]
#[test_case::test_case("", false; "missing")]
#[test_case::test_case("invalid", false; "malformed")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn discovery_checks_version_and_retries_disconnect(
version: &'static str,
supported: bool,
) -> anyhow::Result<()> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let url = format!("ws://{}", listener.local_addr()?);
let attempts = Arc::new(Mutex::new(Vec::new()));
let recorded = Arc::clone(&attempts);
let _server = AbortOnDropHandle::new(tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
let mut socket = accept_async(stream).await?;
while let Some(message) = socket.next().await {
let Message::Text(text) = message? else {
continue;
};
let request: serde_json::Value = serde_json::from_str(text.as_ref())?;
if request.get("id").is_none() {
continue;
}
let mut info = json!({
"shell":{"name":"bash","path":"/bin/bash"},
"capabilities":{"capabilityDiscoveryV2":true}
});
if !version.is_empty() {
info["executorVersion"] = json!(version);
}
let result = match request["method"].as_str() {
Some("initialize") => {
// V2 support is advertised by the executor, not negotiated by the client.
assert!(request["params"].get("capabilityDiscoveryV2").is_none());
json!({"sessionId":"discovery-recovery", "environmentInfo":info})
}
Some("environment/info") => info,
Some(CAPABILITIES_DISCOVER_V2_METHOD) => {
let first = {
let mut attempts = recorded.lock().await;
attempts.push(request["params"].clone());
attempts.len() == 1
};
if first {
break;
}
serde_json::to_value(DiscoverV2CapabilitiesResponse::default())?
}
method => anyhow::bail!("unexpected executor method: {method:?}"),
};
socket
.send(Message::Text(
json!({"id":request["id"],"result":result})
.to_string()
.into(),
))
.await?;
}
}
anyhow::Ok(())
}));
let environment = Environment::remote_with_transport(
ExecServerTransportParams::websocket_url(url, Duration::from_secs(5)),
/*local_runtime_paths*/ None,
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
ScopedSkillsConfig::default(),
);
let params = DiscoverV2CapabilitiesRequest {
cwd: PathUri::parse("file:///caller/project-b")?,
sandbox: None,
};
let response = tokio::time::timeout(
Duration::from_secs(12),
environment.discover_capabilities_v2(params.clone()),
)
.await?;
if !supported {
assert!(
matches!(&response, Err(crate::ExecServerError::Protocol(message))
if message == "capabilities/discoverV2 is unavailable in this environment session"),
"unexpected discovery response: {response:?}"
);
assert_eq!(*attempts.lock().await, Vec::<serde_json::Value>::new());
return Ok(());
}
assert_eq!(response?, DiscoverV2CapabilitiesResponse::default());
let mut sandbox = crate::FileSystemSandboxContext::from_permission_profile(
codex_protocol::models::PermissionProfile::read_only(),
params.cwd.clone(),
);
sandbox.windows_sandbox_selection = crate::WindowsSandboxSelection::Mxc;
let error = environment
.discover_capabilities_v2(DiscoverV2CapabilitiesRequest {
sandbox: Some(sandbox),
..params.clone()
})
.await
.expect_err("MXC must not be sent to an executor that cannot enforce it");
assert!(
error
.to_string()
.contains("does not support the requested MXC Windows sandbox")
);
assert_eq!(
*attempts.lock().await,
vec![
serde_json::to_value(&params)?,
serde_json::to_value(&params)?
]
);
Ok(())
}

View File

@@ -0,0 +1,66 @@
use codex_http_client::HttpClientFactory;
use crate::EnvironmentManager;
use crate::ExecServerError;
use crate::ExecServerRuntimeOptions;
use crate::environment_provider::EnvironmentDefault;
use crate::environment_provider::EnvironmentProviderSnapshot;
use crate::remote::NoiseRendezvousEnvironmentConfig;
#[derive(Debug)]
pub(crate) enum PreparedEnvironmentSource {
Noise(NoiseRendezvousEnvironmentConfig),
Snapshot(EnvironmentProviderSnapshot),
}
/// Holds discovered execution environments before their HTTP policy is resolved.
///
/// Preparing environments does not start remote connections. Callers can inspect
/// the default environment to choose config-loading behavior and then build the
/// manager with the effective outbound HTTP policy.
#[derive(Debug)]
pub struct PreparedEnvironmentManager {
pub(crate) source: PreparedEnvironmentSource,
}
impl PreparedEnvironmentManager {
/// Returns whether the discovered default environment is remote.
pub fn default_environment_is_remote(&self) -> bool {
match &self.source {
PreparedEnvironmentSource::Noise(_) => true,
PreparedEnvironmentSource::Snapshot(snapshot) => match &snapshot.default {
EnvironmentDefault::Disabled => false,
EnvironmentDefault::EnvironmentId(default_id) => snapshot
.environments
.iter()
.any(|entry| &entry.id == default_id),
},
}
}
/// Builds the manager and starts remote connections using the supplied policy.
pub fn build(
self,
local_runtime_paths: Option<ExecServerRuntimeOptions>,
http_client_factory: HttpClientFactory,
) -> Result<EnvironmentManager, ExecServerError> {
match self.source {
PreparedEnvironmentSource::Noise(config) => {
EnvironmentManager::from_noise_environment_config(
config,
local_runtime_paths,
http_client_factory,
)
}
PreparedEnvironmentSource::Snapshot(snapshot) => EnvironmentManager::from_snapshot(
snapshot,
local_runtime_paths,
http_client_factory,
),
}
}
}
#[cfg(test)]
#[path = "environment_bootstrap_tests.rs"]
mod tests;

View File

@@ -0,0 +1,162 @@
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use pretty_assertions::assert_eq;
use super::PreparedEnvironmentManager;
use super::PreparedEnvironmentSource;
use crate::DefaultEnvironmentProvider;
use crate::LOCAL_ENVIRONMENT_ID;
use crate::REMOTE_ENVIRONMENT_ID;
use crate::client_api::DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT;
use crate::client_api::ExecServerTransportParams;
use crate::environment_provider::EnvironmentDefault;
use crate::environment_provider::EnvironmentProviderEntry;
use crate::environment_provider::EnvironmentProviderSnapshot;
use crate::remote::NoiseRendezvousEnvironmentConfig;
#[test]
fn prepared_remote_environment_is_detected_without_constructing_a_connection() {
let prepared = PreparedEnvironmentManager {
source: PreparedEnvironmentSource::Snapshot(EnvironmentProviderSnapshot {
environments: vec![EnvironmentProviderEntry {
id: REMOTE_ENVIRONMENT_ID.to_string(),
transport: ExecServerTransportParams::websocket_url(
"ws://username:password@executor.example/private?token=secret".to_string(),
DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT,
),
skills: Default::default(),
}],
default: EnvironmentDefault::EnvironmentId(REMOTE_ENVIRONMENT_ID.to_string()),
include_local: false,
}),
};
assert!(prepared.default_environment_is_remote());
let debug = format!("{prepared:?}");
assert!(!debug.contains("username"));
assert!(!debug.contains("password"));
assert!(!debug.contains("executor.example"));
assert!(!debug.contains("secret"));
}
#[test]
fn prepared_noise_environment_is_detected_before_http_policy_is_resolved() {
let config = NoiseRendezvousEnvironmentConfig::new(
"https://registry-user:registry-password@registry.example/api?access_token=query-secret#fragment-secret"
.to_string(),
"environment-requested".to_string(),
"registry-token".to_string(),
Some("workspace-123".to_string()),
)
.expect("Noise environment configuration");
let prepared = PreparedEnvironmentManager {
source: PreparedEnvironmentSource::Noise(config),
};
assert!(prepared.default_environment_is_remote());
let debug = format!("{prepared:?}");
assert!(debug.contains("<redacted>"));
assert!(!debug.contains("registry-token"));
assert!(!debug.contains("workspace-123"));
assert!(!debug.contains("registry-user"));
assert!(!debug.contains("registry-password"));
assert!(!debug.contains("registry.example"));
assert!(!debug.contains("query-secret"));
assert!(!debug.contains("fragment-secret"));
}
#[test]
fn prepared_noise_environment_rejects_invalid_configuration() {
let invalid_configs = [
("", "environment-requested", "registry-token", None),
("https://registry.example", "", "registry-token", None),
(
"https://registry.example",
"environment-requested",
"",
None,
),
(
"https://registry.example",
"environment-requested",
"registry\ntoken",
None,
),
(
"https://registry.example",
"environment-requested",
"registry-token",
Some("workspace\n123"),
),
];
for (registry_url, environment_id, auth_token, chatgpt_account_id) in invalid_configs {
let result = NoiseRendezvousEnvironmentConfig::new(
registry_url.to_string(),
environment_id.to_string(),
auth_token.to_string(),
chatgpt_account_id.map(str::to_string),
);
assert!(result.is_err());
}
}
#[test]
fn prepared_local_and_disabled_environments_are_not_remote() {
let local = PreparedEnvironmentManager {
source: PreparedEnvironmentSource::Snapshot(EnvironmentProviderSnapshot {
environments: Vec::new(),
default: EnvironmentDefault::EnvironmentId(LOCAL_ENVIRONMENT_ID.to_string()),
include_local: true,
}),
};
let disabled = PreparedEnvironmentManager {
source: PreparedEnvironmentSource::Snapshot(EnvironmentProviderSnapshot {
environments: Vec::new(),
default: EnvironmentDefault::Disabled,
include_local: false,
}),
};
assert_eq!(
[
local.default_environment_is_remote(),
disabled.default_environment_is_remote()
],
[false, false]
);
}
#[tokio::test]
async fn prepared_environment_manager_builds_with_the_explicit_http_policy() {
let prepared = PreparedEnvironmentManager {
source: PreparedEnvironmentSource::Snapshot(
DefaultEnvironmentProvider::new(Some("ws://127.0.0.1:8765".to_string()))
.snapshot_inner(),
),
};
let manager = prepared
.build(
/*local_runtime_paths*/ None,
HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy),
)
.expect("environment manager");
assert_eq!(
manager.default_environment_id(),
Some(REMOTE_ENVIRONMENT_ID)
);
assert!(
manager
.default_environment()
.expect("remote environment")
.is_remote()
);
assert_eq!(
manager.http_client_factory().outbound_proxy_policy(),
OutboundProxyPolicy::RespectSystemProxy
);
}

View File

@@ -0,0 +1,224 @@
use std::collections::HashMap;
use codex_config::CONFIG_TOML_FILE;
use codex_config::ConfigLayerSource;
use codex_config::McpServerConfig;
use codex_config::McpServerDisabledReason;
use codex_config::RequirementSource;
use codex_config::RequirementsLayerEntry;
use codex_config::compose_requirements_for_hostname;
use codex_config::format_config_layer_source;
use codex_config::host_name;
use codex_config::loader::LocalConfigLayers;
use codex_config::loader::LocalTomlLayer;
use codex_config::loader::LocalTomlLayerStack;
use codex_config::loader::load_local_config_layers;
use codex_exec_server_protocol::EnvironmentConfigLayer;
use codex_exec_server_protocol::EnvironmentConfigLayerStack;
use codex_exec_server_protocol::EnvironmentConfigReadParams;
use codex_exec_server_protocol::EnvironmentConfigReadResponse;
use codex_file_system::ExecutorFileSystem;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_home_dir::find_codex_home;
use codex_utils_path_uri::PathUri;
use crate::Environment;
use crate::ExecServerError;
#[derive(Debug, thiserror::Error)]
pub(crate) enum ReadEnvironmentConfigError {
#[error("{0}")]
InvalidParams(String),
#[error("{0}")]
Internal(String),
}
pub(crate) async fn read_environment_config(
file_system: &dyn ExecutorFileSystem,
params: EnvironmentConfigReadParams,
prefer_mxc: Option<bool>,
) -> Result<EnvironmentConfigReadResponse, ReadEnvironmentConfigError> {
validate_paths(&params)?;
let cwd = params
.cwd
.to_abs_path()
.map_err(|error| ReadEnvironmentConfigError::InvalidParams(error.to_string()))?;
let codex_home = find_codex_home().map_err(|error| {
ReadEnvironmentConfigError::Internal(format!("failed to find Codex home: {error}"))
})?;
let mut layers = load_local_config_layers(file_system, codex_home.as_path(), &cwd)
.await
.map_err(|error| {
ReadEnvironmentConfigError::Internal(format!(
"failed to load executor-local config: {error}"
))
})?;
include_startup_preference(&mut layers, &cwd, prefer_mxc);
let layers = layers.project(&params.config_paths, &params.requirements_paths);
Ok(EnvironmentConfigReadResponse {
user_home_dir: dirs::home_dir()
.and_then(|home_dir| PathUri::from_host_native_path(home_dir).ok()),
codex_home_dir: PathUri::from_abs_path(&codex_home),
hostname: host_name(),
config: serialize_layer_stack(layers.config, |source| {
format_config_layer_source(source, CONFIG_TOML_FILE)
})?,
requirements: serialize_layer_stack(layers.requirements, ToString::to_string)?,
})
}
fn include_startup_preference(
layers: &mut LocalConfigLayers,
cwd: &AbsolutePathBuf,
prefer_mxc: Option<bool>,
) {
if let Some(prefer_mxc) = prefer_mxc {
// CLI flags follow project layers, but never outrank legacy managed/MDM.
// Insert before projection, which also adjusts the cloud insertion index.
let index = layers
.config
.layers
.partition_point(|layer| layer.source <= ConfigLayerSource::SessionFlags);
layers.config.layers.insert(
index,
LocalTomlLayer {
source: ConfigLayerSource::SessionFlags,
base_dir: cwd.clone(),
toml: codex_config::build_cli_overrides_layer(&[(
"features.prefer_mxc".to_string(),
toml::Value::Boolean(prefer_mxc),
)]),
},
);
}
}
impl Environment {
/// Reads executor-owned HTTP MCP servers from the selected project's current config.
pub async fn discover_http_mcp_servers(
&self,
cwd: PathUri,
) -> Result<Vec<(String, McpServerConfig)>, ExecServerError> {
let (response, http_header_env_vars) =
tokio::time::timeout(std::time::Duration::from_secs(10), async {
let capabilities = self.info().await?.capabilities;
if !capabilities.environment_config_read {
return Ok((None, false));
}
self.read_environment_config(EnvironmentConfigReadParams {
cwd,
config_paths: vec![vec!["mcp_servers".to_string()]],
requirements_paths: vec![vec!["mcp_servers".to_string()]],
})
.await
.map(|response| (Some(response), capabilities.http_header_env_vars))
})
.await
.map_err(|_| {
ExecServerError::Protocol("executor MCP discovery timed out".to_string())
})??;
let Some(response) = response else {
return Ok(Vec::new());
};
let requirements = compose_requirements_for_hostname(
response.requirements.layers.into_iter().map(|layer| {
RequirementsLayerEntry::from_toml(RequirementSource::Unknown, layer.toml)
}),
response.hostname.as_deref(),
)
.map_err(|error| {
ExecServerError::Protocol(format!("invalid executor-local MCP requirements: {error}"))
})?
.and_then(|requirements| requirements.mcp_servers);
let mut merged = toml::Value::Table(toml::map::Map::new());
for layer in response.config.layers {
let config = toml::from_str::<toml::Value>(&layer.toml).map_err(|error| {
ExecServerError::Protocol(format!("invalid executor-local MCP config: {error}"))
})?;
codex_config::merge_toml_values(&mut merged, &config);
}
let mut servers = merged
.get("mcp_servers")
.cloned()
.unwrap_or_else(|| toml::Value::Table(toml::map::Map::new()));
if let Some(servers) = servers.as_table_mut() {
servers.retain(|_, server| {
server.get("url").is_some()
&& (http_header_env_vars || server.get("bearer_token_env_var").is_none())
});
}
let servers = servers
.try_into::<HashMap<String, McpServerConfig>>()
.map_err(|error| {
ExecServerError::Protocol(format!("invalid executor-local MCP servers: {error}"))
})?;
Ok(servers
.into_iter()
.map(|(name, mut server)| {
if let Some(requirements) = requirements.as_ref()
&& !requirements
.value
.get(&name)
.is_some_and(|requirement| server.matches_requirement(requirement))
{
server.enabled = false;
server.disabled_reason = Some(McpServerDisabledReason::Requirements {
source: requirements.source.clone(),
});
}
(name, server)
})
.collect())
}
}
fn validate_paths(params: &EnvironmentConfigReadParams) -> Result<(), ReadEnvironmentConfigError> {
if params.config_paths.is_empty() && params.requirements_paths.is_empty() {
return Err(ReadEnvironmentConfigError::InvalidParams(
"at least one config or requirements path is required".to_string(),
));
}
if params
.config_paths
.iter()
.chain(&params.requirements_paths)
.any(Vec::is_empty)
{
return Err(ReadEnvironmentConfigError::InvalidParams(
"TOML paths must contain at least one key segment".to_string(),
));
}
Ok(())
}
fn serialize_layer_stack<S>(
stack: LocalTomlLayerStack<S>,
source_name: impl Fn(&S) -> String,
) -> Result<EnvironmentConfigLayerStack, ReadEnvironmentConfigError> {
let layers = stack
.layers
.into_iter()
.map(|layer| {
let toml = toml::to_string(&layer.toml).map_err(|error| {
ReadEnvironmentConfigError::Internal(format!(
"failed to serialize executor-local config: {error}"
))
})?;
Ok(EnvironmentConfigLayer {
source: source_name(&layer.source),
base_dir: PathUri::from_abs_path(&layer.base_dir),
toml,
})
})
.collect::<Result<Vec<_>, ReadEnvironmentConfigError>>()?;
Ok(EnvironmentConfigLayerStack {
layers,
cloud_insertion_index: stack.cloud_insertion_index,
})
}
#[cfg(test)]
#[path = "environment_config_tests.rs"]
mod tests;

View File

@@ -0,0 +1,52 @@
use super::*;
use pretty_assertions::assert_eq;
/// Legacy file and MDM values must still win after a CLI preference is projected.
#[test]
fn startup_preference_stays_below_both_managed_layers() -> anyhow::Result<()> {
let temp = tempfile::tempdir()?;
let cwd = AbsolutePathBuf::from_absolute_path(temp.path())?;
let project = ConfigLayerSource::Project {
dot_codex_folder: cwd.join(".codex"),
};
let file = ConfigLayerSource::LegacyManagedConfigTomlFromFile {
file: cwd.join("managed_config.toml"),
};
for managed in [file, ConfigLayerSource::LegacyManagedConfigTomlFromMdm] {
let mut layers = LocalConfigLayers {
config: LocalTomlLayerStack {
layers: vec![project.clone(), managed.clone()]
.into_iter()
.map(|source| LocalTomlLayer {
source,
base_dir: cwd.clone(),
toml: toml::Value::Table(toml::toml! { [features] prefer_mxc = false }),
})
.collect(),
cloud_insertion_index: 0,
},
requirements: LocalTomlLayerStack {
layers: Vec::new(),
cloud_insertion_index: 0,
},
};
include_startup_preference(&mut layers, &cwd, Some(true));
let projected = layers.project(&[vec!["features".into(), "prefer_mxc".into()]], &[]);
assert_eq!(
projected
.config
.layers
.iter()
.map(|l| &l.source)
.collect::<Vec<_>>(),
[&project, &ConfigLayerSource::SessionFlags, &managed],
);
let mut effective = toml::Value::Table(toml::map::Map::new());
for layer in projected.config.layers {
codex_config::merge_toml_values(&mut effective, &layer.toml);
}
assert_eq!(effective["features"]["prefer_mxc"].as_bool(), Some(false));
assert_eq!(projected.config.cloud_insertion_index, 0);
}
Ok(())
}

View File

@@ -0,0 +1,234 @@
use std::future::Future;
use std::pin::Pin;
use codex_config::ScopedSkillsConfig;
use crate::ExecServerError;
use crate::client_api::DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT;
use crate::client_api::ExecServerTransportParams;
use crate::environment::CODEX_EXEC_SERVER_URL_ENV_VAR;
use crate::environment::LOCAL_ENVIRONMENT_ID;
use crate::environment::REMOTE_ENVIRONMENT_ID;
/// Lists the remote environment transports available to Codex.
///
/// Implementations own a startup snapshot containing both the available
/// environment transport list in configured order and the default environment
/// selection. Providers return transport descriptions before the effective HTTP
/// policy is available; `include_local` controls whether `EnvironmentManager`
/// should add the local environment when the snapshot is built.
pub trait EnvironmentProvider: Send + Sync {
/// Returns the provider-owned environment startup snapshot.
fn snapshot(&self) -> EnvironmentProviderFuture<'_>;
}
pub type EnvironmentProviderFuture<'a> =
Pin<Box<dyn Future<Output = Result<EnvironmentProviderSnapshot, ExecServerError>> + Send + 'a>>;
#[derive(Clone)]
pub struct EnvironmentProviderSnapshot {
pub(crate) environments: Vec<EnvironmentProviderEntry>,
pub default: EnvironmentDefault,
pub include_local: bool,
}
/// Keeps each configured environment's requirements with its transport.
#[derive(Clone, Debug)]
pub(crate) struct EnvironmentProviderEntry {
pub(crate) id: String,
pub(crate) transport: ExecServerTransportParams,
pub(crate) skills: ScopedSkillsConfig,
}
impl std::fmt::Debug for EnvironmentProviderSnapshot {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let environment_ids: Vec<_> = self.environments.iter().map(|entry| &entry.id).collect();
f.debug_struct("EnvironmentProviderSnapshot")
.field("environments", &environment_ids)
.field("default", &self.default)
.field("include_local", &self.include_local)
.finish()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EnvironmentDefault {
Disabled,
EnvironmentId(String),
}
/// Default provider backed by `CODEX_EXEC_SERVER_URL`.
#[derive(Clone, Debug)]
pub struct DefaultEnvironmentProvider {
exec_server_url: Option<String>,
}
impl DefaultEnvironmentProvider {
/// Builds a provider from an already-read raw `CODEX_EXEC_SERVER_URL` value.
pub fn new(exec_server_url: Option<String>) -> Self {
Self { exec_server_url }
}
/// Builds a provider by reading `CODEX_EXEC_SERVER_URL`.
pub fn from_env() -> Self {
Self::new(std::env::var(CODEX_EXEC_SERVER_URL_ENV_VAR).ok())
}
pub(crate) fn snapshot_inner(&self) -> EnvironmentProviderSnapshot {
let mut environments = Vec::new();
let (exec_server_url, disabled) = normalize_exec_server_url(self.exec_server_url.clone());
if let Some(exec_server_url) = exec_server_url {
environments.push(EnvironmentProviderEntry {
id: REMOTE_ENVIRONMENT_ID.to_string(),
transport: ExecServerTransportParams::websocket_url(
exec_server_url,
DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT,
),
skills: ScopedSkillsConfig::default(),
});
}
let has_remote = environments
.iter()
.any(|entry| entry.id == REMOTE_ENVIRONMENT_ID);
let include_local = !disabled && !has_remote;
let default = if disabled {
EnvironmentDefault::Disabled
} else if has_remote {
EnvironmentDefault::EnvironmentId(REMOTE_ENVIRONMENT_ID.to_string())
} else {
EnvironmentDefault::EnvironmentId(LOCAL_ENVIRONMENT_ID.to_string())
};
EnvironmentProviderSnapshot {
environments,
default,
include_local,
}
}
}
impl EnvironmentProvider for DefaultEnvironmentProvider {
fn snapshot(&self) -> EnvironmentProviderFuture<'_> {
Box::pin(async { Ok(self.snapshot_inner()) })
}
}
pub(crate) fn normalize_exec_server_url(exec_server_url: Option<String>) -> (Option<String>, bool) {
match exec_server_url.as_deref().map(str::trim) {
None | Some("") => (None, false),
Some(url) if url.eq_ignore_ascii_case("none") => (None, true),
Some(url) => (Some(url.to_string()), false),
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use pretty_assertions::assert_eq;
use super::*;
#[tokio::test]
async fn default_provider_requests_local_environment_when_url_is_missing() {
let provider = DefaultEnvironmentProvider::new(/*exec_server_url*/ None);
let snapshot = provider.snapshot().await.expect("environments");
let EnvironmentProviderSnapshot {
environments,
default,
include_local,
} = snapshot;
let environments: HashMap<_, _> = environments
.into_iter()
.map(|entry| (entry.id, entry.transport))
.collect();
assert!(include_local);
assert!(!environments.contains_key(LOCAL_ENVIRONMENT_ID));
assert!(!environments.contains_key(REMOTE_ENVIRONMENT_ID));
assert_eq!(
default,
EnvironmentDefault::EnvironmentId(LOCAL_ENVIRONMENT_ID.to_string())
);
}
#[tokio::test]
async fn default_provider_requests_local_environment_when_url_is_empty() {
let provider = DefaultEnvironmentProvider::new(Some(String::new()));
let snapshot = provider.snapshot().await.expect("environments");
let EnvironmentProviderSnapshot {
environments,
default,
include_local,
} = snapshot;
let environments: HashMap<_, _> = environments
.into_iter()
.map(|entry| (entry.id, entry.transport))
.collect();
assert!(include_local);
assert!(!environments.contains_key(LOCAL_ENVIRONMENT_ID));
assert!(!environments.contains_key(REMOTE_ENVIRONMENT_ID));
assert_eq!(
default,
EnvironmentDefault::EnvironmentId(LOCAL_ENVIRONMENT_ID.to_string())
);
}
#[tokio::test]
async fn default_provider_omits_local_environment_for_none_value() {
let provider = DefaultEnvironmentProvider::new(Some("none".to_string()));
let snapshot = provider.snapshot().await.expect("environments");
let EnvironmentProviderSnapshot {
environments,
default,
include_local,
} = snapshot;
let environments: HashMap<_, _> = environments
.into_iter()
.map(|entry| (entry.id, entry.transport))
.collect();
assert!(!include_local);
assert!(!environments.contains_key(LOCAL_ENVIRONMENT_ID));
assert!(!environments.contains_key(REMOTE_ENVIRONMENT_ID));
assert_eq!(default, EnvironmentDefault::Disabled);
}
#[tokio::test]
async fn default_provider_adds_remote_environment_for_websocket_url() {
let provider = DefaultEnvironmentProvider::new(Some("ws://127.0.0.1:8765".to_string()));
let snapshot = provider.snapshot().await.expect("environments");
let EnvironmentProviderSnapshot {
environments,
default,
include_local,
} = snapshot;
let environments: HashMap<_, _> = environments
.into_iter()
.map(|entry| (entry.id, entry.transport))
.collect();
assert!(!include_local);
assert!(!environments.contains_key(LOCAL_ENVIRONMENT_ID));
assert!(matches!(
&environments[REMOTE_ENVIRONMENT_ID],
ExecServerTransportParams::WebSocketUrl { websocket_url, .. }
if websocket_url == "ws://127.0.0.1:8765"
));
assert_eq!(
default,
EnvironmentDefault::EnvironmentId(REMOTE_ENVIRONMENT_ID.to_string())
);
}
#[test]
fn normalizes_exec_server_url() {
assert_eq!(
normalize_exec_server_url(Some(" ws://127.0.0.1:8765 ".to_string())),
(Some("ws://127.0.0.1:8765".to_string()), false)
);
}
}

View File

@@ -0,0 +1,68 @@
use serde::Deserialize;
use serde::Serialize;
use crate::NoiseChannelPublicKey;
/// Request body for registering an executor with the environment registry.
#[derive(Clone, Deserialize, Eq, PartialEq, Serialize)]
pub struct EnvironmentRegistryRegistrationRequest {
pub security_profile: String,
pub executor_public_key: NoiseChannelPublicKey,
}
/// Environment registry response returned after executor registration.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct EnvironmentRegistryRegistrationResponse {
pub environment_id: String,
pub url: String,
pub security_profile: String,
pub executor_registration_id: String,
}
/// Request body for connecting a harness key with the environment registry.
#[derive(Clone, Deserialize, Eq, PartialEq, Serialize)]
pub struct EnvironmentRegistryConnectRequest {
pub harness_public_key: NoiseChannelPublicKey,
}
/// Environment registry response returned after connecting a harness key.
#[derive(Clone, Deserialize, Eq, PartialEq, Serialize)]
pub struct EnvironmentRegistryConnectResponse {
pub environment_id: String,
pub url: String,
pub security_profile: String,
pub executor_registration_id: String,
pub executor_public_key: NoiseChannelPublicKey,
pub harness_key_authorization: String,
}
impl std::fmt::Debug for EnvironmentRegistryConnectResponse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EnvironmentRegistryConnectResponse")
.field("environment_id", &self.environment_id)
.field("url", &"<redacted>")
.field("security_profile", &self.security_profile)
.field("executor_registration_id", &self.executor_registration_id)
.field("executor_public_key", &self.executor_public_key)
.field("harness_key_authorization", &"<redacted>")
.finish()
}
}
/// Request body for authorizing a harness key with the environment registry.
#[derive(Clone, Deserialize, Eq, PartialEq, Serialize)]
pub struct EnvironmentRegistryHarnessKeyValidationRequest {
pub executor_registration_id: String,
pub harness_public_key: NoiseChannelPublicKey,
pub harness_key_authorization: String,
}
/// Environment registry response returned after harness key validation.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct EnvironmentRegistryHarnessKeyValidationResponse {
pub valid: bool,
}
#[cfg(test)]
#[path = "environment_registry_tests.rs"]
mod tests;

View File

@@ -0,0 +1,22 @@
use crate::EnvironmentRegistryConnectResponse;
use crate::NoiseChannelIdentity;
#[test]
fn connect_response_debug_redacts_authorizations() {
let response = EnvironmentRegistryConnectResponse {
environment_id: "environment-1".to_string(),
url: "wss://rendezvous.test?sig=secret-url-authorization".to_string(),
security_profile: "noise_hybrid_ik_v1".to_string(),
executor_registration_id: "registration-1".to_string(),
executor_public_key: NoiseChannelIdentity::generate()
.expect("identity")
.public_key(),
harness_key_authorization: "secret-harness-authorization".to_string(),
};
let debug = format!("{response:?}");
assert!(debug.contains("<redacted>"));
assert!(!debug.contains("secret-url-authorization"));
assert!(!debug.contains("secret-harness-authorization"));
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,232 @@
//! Connection-scoped file handles with bounded positional reads and writes.
//! Semaphore permits bound open handles and in-flight opens; table locks never cross an await.
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::fs::File;
use std::future::Future;
use std::io;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use codex_file_system::FILE_READ_CHUNK_SIZE;
use codex_file_system::FILE_WRITE_CHUNK_SIZE;
use tokio::sync::OwnedSemaphorePermit;
use tokio::sync::Semaphore;
const MAX_OPEN_FILES: usize = 128;
#[derive(Debug, Eq, PartialEq)]
pub(crate) struct FileReadBlock {
pub(crate) bytes: Vec<u8>,
pub(crate) eof: bool,
}
#[derive(Clone)]
pub(crate) struct FileHandleManager {
handles: Arc<Mutex<HashMap<String, FileHandleEntry>>>,
slots: Arc<Semaphore>,
}
impl Default for FileHandleManager {
fn default() -> Self {
Self {
handles: Arc::default(),
slots: Arc::new(Semaphore::new(MAX_OPEN_FILES)),
}
}
}
impl FileHandleManager {
pub(crate) async fn open(
&self,
handle_id: String,
open_file: impl Future<Output = io::Result<tokio::fs::File>>,
) -> io::Result<String> {
if self.lock_handles().contains_key(&handle_id) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("file handle `{handle_id}` already exists"),
));
}
let permit = Arc::clone(&self.slots).try_acquire_owned().map_err(|_| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("at most {MAX_OPEN_FILES} file handles may be open per connection"),
)
})?;
let file = Arc::new(open_file.await?.into_std().await);
let mut handles = self.lock_handles();
let Entry::Vacant(entry) = handles.entry(handle_id.clone()) else {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("file handle `{handle_id}` already exists"),
));
};
entry.insert(FileHandleEntry {
file,
_permit: permit,
});
Ok(handle_id)
}
pub(crate) async fn read_block(
&self,
handle_id: &str,
offset: u64,
len: usize,
) -> io::Result<FileReadBlock> {
validate_read_block_len(len)?;
let file = self.get(handle_id)?;
let result =
match tokio::task::spawn_blocking(move || read_block_at(&file, offset, len)).await {
Ok(result) => result,
Err(error) => Err(io::Error::other(format!(
"file read task stopped unexpectedly: {error}"
))),
};
if result.is_err() {
self.close(handle_id);
}
result
}
pub(crate) async fn write_block(
&self,
handle_id: &str,
offset: u64,
bytes: Vec<u8>,
) -> io::Result<()> {
if !(1..=FILE_WRITE_CHUNK_SIZE).contains(&bytes.len()) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("file write block length must be between 1 and {FILE_WRITE_CHUNK_SIZE}"),
));
}
// Native file offsets are signed; Windows interprets negative offsets as sentinels.
let end = offset
.checked_add(bytes.len() as u64)
.and_then(|end| i64::try_from(end).ok())
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"file write range exceeds the signed 64-bit file offset limit",
)
})? as u64;
let file = self.get(handle_id)?;
tokio::task::spawn_blocking(move || {
let mut position = offset;
while position < end {
let written = (position - offset) as usize;
#[cfg(unix)]
let result = std::os::unix::fs::FileExt::write_at(
file.as_ref(),
&bytes[written..],
position,
);
#[cfg(windows)]
let result = std::os::windows::fs::FileExt::seek_write(
file.as_ref(),
&bytes[written..],
position,
);
match result {
Ok(0) => {
return Err(io::Error::new(
io::ErrorKind::WriteZero,
"failed to write file block",
));
}
Ok(count) => position += count as u64,
Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
Err(error) => return Err(error),
}
}
Ok(())
})
.await
.map_err(|error| {
io::Error::other(format!("file write task stopped unexpectedly: {error}"))
})?
}
fn get(&self, handle_id: &str) -> io::Result<Arc<File>> {
self.lock_handles()
.get(handle_id)
.map(|entry| Arc::clone(&entry.file))
.ok_or_else(|| unknown_handle_error(handle_id))
}
pub(crate) fn close(&self, handle_id: &str) {
self.lock_handles().remove(handle_id);
}
pub(crate) fn close_all(&self) {
self.lock_handles().clear();
}
fn lock_handles(&self) -> MutexGuard<'_, HashMap<String, FileHandleEntry>> {
self.handles
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
struct FileHandleEntry {
file: Arc<File>,
// Closing an entry releases capacity even if a read or write still holds the file.
_permit: OwnedSemaphorePermit,
}
fn read_block_at(file: &File, offset: u64, len: usize) -> io::Result<FileReadBlock> {
let mut bytes = vec![0; len];
let mut bytes_read = 0;
while bytes_read < len {
let read_offset = offset.checked_add(bytes_read as u64).ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidInput, "file read offset overflowed")
})?;
match read_file_at(file, &mut bytes[bytes_read..], read_offset) {
Ok(0) => break,
Ok(read) => bytes_read += read,
Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
Err(error) => return Err(error),
}
}
bytes.truncate(bytes_read);
Ok(FileReadBlock {
eof: bytes_read < len,
bytes,
})
}
#[cfg(unix)]
fn read_file_at(file: &File, bytes: &mut [u8], offset: u64) -> io::Result<usize> {
std::os::unix::fs::FileExt::read_at(file, bytes, offset)
}
#[cfg(windows)]
fn read_file_at(file: &File, bytes: &mut [u8], offset: u64) -> io::Result<usize> {
std::os::windows::fs::FileExt::seek_read(file, bytes, offset)
}
fn validate_read_block_len(len: usize) -> io::Result<()> {
if !(1..=FILE_READ_CHUNK_SIZE).contains(&len) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("file read block length must be between 1 and {FILE_READ_CHUNK_SIZE}"),
));
}
Ok(())
}
fn unknown_handle_error(handle_id: &str) -> io::Error {
io::Error::new(
io::ErrorKind::NotFound,
format!("unknown file handle `{handle_id}`"),
)
}
#[cfg(test)]
#[path = "file_handle_tests.rs"]
mod tests;

View File

@@ -0,0 +1,134 @@
//! Exercises permit cleanup and progress without relying on I/O timing.
use std::future::pending;
use std::future::ready;
use std::io;
use std::io::Write;
use std::task::Poll;
use anyhow::Result;
use pretty_assertions::assert_eq;
use tokio::fs::File;
use tokio::sync::oneshot;
use super::FileHandleManager;
use super::FileReadBlock;
use super::MAX_OPEN_FILES;
/// A stalled open must let unrelated handles open and read without waiting for it.
#[tokio::test]
async fn stalled_open_does_not_block_other_handles() -> Result<()> {
let manager = FileHandleManager::default();
let mut stalled = Box::pin(manager.open("stalled".to_string(), pending()));
assert!(futures::poll!(stalled.as_mut()).is_pending());
let mut other = Box::pin(manager.open(
"other".to_string(),
ready(Ok(File::from_std(tempfile::tempfile()?))),
));
let Poll::Ready(result) = futures::poll!(other.as_mut()) else {
anyhow::bail!("an unrelated open was blocked by the stalled open");
};
assert_eq!(result?, "other");
manager.read_block("other", /*offset*/ 0, /*len*/ 1).await?;
Ok(())
}
/// Pending opens consume capacity before polling another file open.
#[tokio::test]
async fn pending_opens_reserve_capacity() -> Result<()> {
let manager = FileHandleManager::default();
let mut opens = Vec::new();
for index in 0..MAX_OPEN_FILES {
let mut open = Box::pin(manager.open(index.to_string(), pending()));
assert!(futures::poll!(open.as_mut()).is_pending());
opens.push(open);
}
let mut rejected = Box::pin(manager.open("overflow".to_string(), pending()));
let Poll::Ready(Err(error)) = futures::poll!(rejected.as_mut()) else {
anyhow::bail!("admission must fail before polling the file open");
};
assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
Ok(())
}
/// Failed and cancelled opens must return their permits for reuse.
#[test_case::test_case(true; "cancelled")]
#[test_case::test_case(false; "failed")]
#[tokio::test]
async fn unfinished_opens_release_capacity(cancelled: bool) -> Result<()> {
let manager = FileHandleManager::default();
for _ in 0..=MAX_OPEN_FILES {
let mut open = Box::pin(manager.open("reused".to_string(), async {
if cancelled {
pending::<()>().await;
}
Err(io::Error::other("open failed"))
}));
let result = futures::poll!(open.as_mut());
if cancelled {
assert!(result.is_pending());
} else {
let Poll::Ready(Err(error)) = result else {
anyhow::bail!("the open error must reach the caller");
};
assert_eq!(error.kind(), io::ErrorKind::Other);
}
drop(open);
}
Ok(())
}
/// Closing an entry frees capacity even while an operation retains its file descriptor.
#[tokio::test]
async fn close_releases_capacity_while_the_file_is_still_in_use() -> Result<()> {
let manager = FileHandleManager::default();
let file = tempfile::tempfile()?;
for index in 0..MAX_OPEN_FILES {
manager
.open(
index.to_string(),
ready(Ok(File::from_std(file.try_clone()?))),
)
.await?;
}
let retained = manager.get("0")?;
manager.close("0");
manager
.open("next".to_string(), ready(Ok(File::from_std(file))))
.await?;
drop(retained);
Ok(())
}
/// Concurrent opens of one ID must reject the loser without changing the winning file.
#[tokio::test]
async fn concurrent_opens_reject_duplicate_ids_without_replacing_the_file() -> Result<()> {
let manager = FileHandleManager::default();
let (send, receive) = oneshot::channel();
let mut late = Box::pin(manager.open("shared".to_string(), async {
receive.await.map_err(io::Error::other)
}));
assert!(futures::poll!(late.as_mut()).is_pending());
let mut file = tempfile::tempfile()?;
file.write_all(b"first")?;
manager
.open("shared".to_string(), ready(Ok(File::from_std(file))))
.await?;
send.send(File::from_std(tempfile::tempfile()?))
.map_err(|_| anyhow::anyhow!("the pending open dropped its receiver"))?;
let error = late.await.expect_err("the duplicate open must fail");
assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
assert_eq!(
manager
.read_block("shared", /*offset*/ 0, /*len*/ 6)
.await?,
FileReadBlock {
bytes: b"first".to_vec(),
eof: true,
}
);
Ok(())
}

View File

@@ -0,0 +1,195 @@
use std::time::Duration;
use bytes::Bytes;
use codex_http_client::HttpClientFactory;
use codex_websocket_client::WebSocketConnector;
use futures::Sink;
use futures::SinkExt;
use futures::StreamExt;
use tokio::time::timeout;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
use tokio_tungstenite::tungstenite::protocol::frame::Frame;
use tokio_tungstenite::tungstenite::protocol::frame::coding::Data;
use tokio_tungstenite::tungstenite::protocol::frame::coding::OpCode;
use tokio_util::task::AbortOnDropHandle;
use tracing::warn;
use crate::ExecServerError;
use crate::ExecServerTelemetry;
use crate::client_api::DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT;
use crate::noise_relay::message_framing::MAX_NOISE_JSONRPC_MESSAGE_LEN;
use crate::noise_relay::message_framing::frame_message;
use crate::noise_relay::stream_handler::NoiseOutboundMessage;
use crate::noise_relay::stream_handler::NoiseStreamConnection;
use crate::noise_relay::stream_handler::NoiseStreamHandler;
use crate::telemetry::ConnectionTransport;
// Existing exec-server listeners accept 64 MiB messages but only 16 MiB frames.
const WEBSOCKET_FRAGMENT_LEN: usize = 8 * 1024 * 1024;
const WEBSOCKET_CLOSE_TIMEOUT: Duration = Duration::from_secs(1);
async fn send_websocket_message<S>(websocket: &mut S, mut payload: Bytes) -> Result<(), S::Error>
where
S: Sink<Message> + Unpin,
{
if payload.len() <= WEBSOCKET_FRAGMENT_LEN {
return websocket.send(Message::Binary(payload)).await;
}
let mut opcode = OpCode::Data(Data::Binary);
while !payload.is_empty() {
let chunk = payload.split_to(payload.len().min(WEBSOCKET_FRAGMENT_LEN));
let is_final = payload.is_empty();
websocket
.send(Message::Frame(Frame::message(chunk, opcode, is_final)))
.await?;
opcode = OpCode::Data(Data::Continue);
}
Ok(())
}
/// Copies authenticated remote messages to an independently owned executor.
#[derive(Clone)]
pub(crate) struct Forwarder {
websocket_url: String,
connector: WebSocketConnector,
telemetry: ExecServerTelemetry,
}
impl Forwarder {
pub(crate) fn new(
websocket_url: String,
http_client_factory: &HttpClientFactory,
telemetry: ExecServerTelemetry,
) -> Result<Self, ExecServerError> {
let url = url::Url::parse(&websocket_url)
.map_err(|error| ExecServerError::WebSocketConfiguration(error.to_string()))?;
if !matches!(url.scheme(), "ws" | "wss") || url.host_str().is_none() {
return Err(ExecServerError::WebSocketConfiguration(
"forward destination must be a ws:// or wss:// URL".to_string(),
));
}
let connector = WebSocketConnector::new(http_client_factory)
.map_err(|error| ExecServerError::WebSocketConfiguration(error.to_string()))?
.with_tcp_nodelay();
Ok(Self {
websocket_url,
connector,
telemetry,
})
}
pub(crate) async fn run_connection(self, mut remote: NoiseStreamConnection<Bytes, Bytes>) {
let mut writer_task = AbortOnDropHandle::new(remote.writer_task);
let _metrics = self
.telemetry
.connection_started(ConnectionTransport::Relay);
let connect = async {
let request = self.websocket_url.as_str().into_client_request()?;
self.connector
.connect(
request,
WebSocketConfig::default()
.max_message_size(Some(MAX_NOISE_JSONRPC_MESSAGE_LEN))
.max_frame_size(Some(MAX_NOISE_JSONRPC_MESSAGE_LEN)),
)
.await
};
let connected = tokio::select! {
biased;
_ = remote.disconnected_rx.wait_for(|disconnected| *disconnected) => None,
result = timeout(DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT, connect) => {
match result {
Ok(Ok((websocket, _))) => Some(websocket),
Ok(Err(_)) => {
warn!("failed to connect to forwarded exec-server");
None
}
Err(_) => {
warn!("timed out connecting to forwarded exec-server");
None
}
}
}
};
let drain_outgoing = if let Some(websocket) = connected {
let (mut destination_tx, mut destination_rx) = websocket.split();
let to_destination = async {
while let Some(payload) = remote.incoming_rx.recv().await {
if send_websocket_message(&mut destination_tx, payload)
.await
.is_err()
{
break;
}
}
};
let from_destination = async {
while let Some(Ok(message)) = destination_rx.next().await {
let payload = match message {
Message::Text(_) | Message::Binary(_) => message.into_data(),
Message::Close(_) => return true,
Message::Ping(_) | Message::Pong(_) | Message::Frame(_) => continue,
};
if remote.outgoing_tx.send(payload).await.is_err() {
break;
}
}
false
};
let (drain_outgoing, received_close) = tokio::select! {
_ = remote.disconnected_rx.wait_for(|disconnected| *disconnected) => (false, false),
_ = to_destination => (false, false),
received_close = from_destination => (true, received_close),
};
if received_close && let Ok(mut websocket) = destination_tx.reunite(destination_rx) {
// Reuniting drops any canceled application send before flushing
// Tungstenite's automatically queued Close acknowledgement.
tokio::select! {
_ = timeout(WEBSOCKET_CLOSE_TIMEOUT, websocket.flush()) => {},
_ = remote.disconnected_rx.wait_for(|disconnected| *disconnected) => {},
}
}
drain_outgoing
} else {
false
};
// Preserve messages received before the destination's Close. Never wait
// for a dead remote, and let owner shutdown interrupt a blocked drain.
drop(remote.outgoing_tx);
if drain_outgoing {
tokio::select! {
_ = &mut writer_task => return,
_ = remote.disconnected_rx.wait_for(|disconnected| *disconnected) => {},
}
}
writer_task.abort();
let _ = writer_task.await;
}
}
impl NoiseStreamHandler for Forwarder {
type Incoming = Bytes;
type Outgoing = Bytes;
fn decode(payload: Bytes) -> Result<Bytes, ExecServerError> {
Ok(payload)
}
fn encode(payload: Bytes) -> Result<NoiseOutboundMessage, ExecServerError> {
Ok(NoiseOutboundMessage {
framed: frame_message(&payload)?,
trace: None,
})
}
async fn run_connection(self, connection: NoiseStreamConnection<Bytes, Bytes>) {
Forwarder::run_connection(self, connection).await;
}
}
#[cfg(test)]
#[path = "forward_tests.rs"]
mod tests;

View File

@@ -0,0 +1,89 @@
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use bytes::Bytes;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use futures::SinkExt;
use futures::StreamExt;
use pretty_assertions::assert_eq;
use tokio::io::AsyncReadExt;
use tokio::net::TcpListener;
use tokio::sync::mpsc;
use tokio::sync::watch;
use tokio::time::timeout;
use tokio_tungstenite::accept_async;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::protocol::CloseFrame;
use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode;
use super::Forwarder;
use crate::ExecServerTelemetry;
use crate::noise_relay::stream_handler::NoiseStreamConnection;
#[tokio::test]
async fn transport_disconnect_cancels_an_unfinished_websocket_handshake() -> Result<()> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let forwarder = Forwarder::new(
format!("ws://{}", listener.local_addr()?),
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
ExecServerTelemetry::default(),
)?;
let (_incoming, incoming_rx) = mpsc::channel(1);
let (outgoing_tx, _outgoing) = mpsc::channel(1);
let (disconnected, disconnected_rx) = watch::channel(false);
let connection = NoiseStreamConnection {
incoming_rx,
outgoing_tx,
disconnected_rx,
writer_task: tokio::spawn(async {}),
executor_registration: None,
};
let task = tokio::spawn(forwarder.run_connection(connection));
let deadline = Duration::from_secs(5);
let (mut socket, _) = timeout(deadline, listener.accept()).await??;
disconnected.send(true)?;
timeout(deadline, task).await??;
timeout(deadline, socket.read_to_end(&mut Vec::new())).await??;
Ok(())
}
#[tokio::test]
async fn destination_close_is_acknowledged() -> Result<()> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let forwarder = Forwarder::new(
format!("ws://{}", listener.local_addr()?),
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
ExecServerTelemetry::default(),
)?;
let (_incoming, incoming_rx) = mpsc::channel(1);
let (outgoing_tx, mut outgoing) = mpsc::channel(1);
let (_disconnected, disconnected_rx) = watch::channel(false);
let task = tokio::spawn(forwarder.run_connection(NoiseStreamConnection {
incoming_rx,
outgoing_tx,
disconnected_rx,
writer_task: tokio::spawn(async {}),
executor_registration: None,
}));
let deadline = Duration::from_secs(5);
let (socket, _) = timeout(deadline, listener.accept()).await??;
let mut socket = timeout(deadline, accept_async(socket)).await??;
let response = Bytes::from_static(b"final response");
socket.send(Message::Binary(response.clone())).await?;
let close = CloseFrame {
code: CloseCode::Normal,
reason: "finished".into(),
};
socket.close(Some(close.clone())).await?;
let reply = timeout(deadline, socket.next())
.await?
.context("destination should receive the Close acknowledgement")??;
assert_eq!(reply, Message::Close(Some(close)));
timeout(deadline, task).await??;
assert_eq!(outgoing.recv().await, Some(response));
assert_eq!(outgoing.recv().await, None);
Ok(())
}

View File

@@ -0,0 +1,511 @@
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use codex_exec_server_protocol::JSONRPCErrorError;
use codex_utils_path_uri::PathUri;
use serde::Deserialize;
use serde::Serialize;
use tokio::io;
use crate::CapabilityRootsDiscoverParams;
use crate::CapabilityRootsDiscoverResponse;
use crate::CopyOptions;
use crate::CreateDirectoryOptions;
use crate::DiscoverV2CapabilitiesResponse;
use crate::ExecutorFileSystem;
use crate::GetMetadataOptions;
use crate::LocalFileSystem;
use crate::ReadFileOptions;
use crate::RemoveOptions;
use crate::WriteFileOptions;
use crate::discover_v2::capability_discoveries::load_capability_discovery_batch;
use crate::discover_v2::capability_locations::CapabilityLocation;
use crate::local_file_system::DirectFileSystem;
use crate::protocol::CAPABILITY_ROOTS_DISCOVER_METHOD;
use crate::protocol::FS_CANONICALIZE_METHOD;
use crate::protocol::FS_COPY_METHOD;
use crate::protocol::FS_CREATE_DIRECTORY_METHOD;
use crate::protocol::FS_GET_METADATA_METHOD;
use crate::protocol::FS_OPEN_METHOD;
use crate::protocol::FS_READ_DIRECTORY_METHOD;
use crate::protocol::FS_READ_FILE_METHOD;
use crate::protocol::FS_REMOVE_METHOD;
use crate::protocol::FS_WALK_METHOD;
use crate::protocol::FS_WRITE_FILE_METHOD;
use crate::protocol::FsCanonicalizeParams;
use crate::protocol::FsCanonicalizeResponse;
use crate::protocol::FsCopyParams;
use crate::protocol::FsCopyResponse;
use crate::protocol::FsCreateDirectoryParams;
use crate::protocol::FsCreateDirectoryResponse;
use crate::protocol::FsGetMetadataParams;
use crate::protocol::FsGetMetadataResponse;
use crate::protocol::FsOpenMode;
use crate::protocol::FsReadDirectoryEntry;
use crate::protocol::FsReadDirectoryParams;
use crate::protocol::FsReadDirectoryResponse;
use crate::protocol::FsReadFileParams;
use crate::protocol::FsReadFileResponse;
use crate::protocol::FsRemoveParams;
use crate::protocol::FsRemoveResponse;
use crate::protocol::FsWalkParams;
use crate::protocol::FsWalkResponse;
use crate::protocol::FsWriteFileParams;
use crate::protocol::FsWriteFileResponse;
use crate::rpc::internal_error;
use crate::rpc::invalid_request;
use crate::rpc::not_found;
pub const CODEX_FS_HELPER_ARG1: &str = "--codex-run-as-fs-helper";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "operation", content = "params")]
pub(crate) enum FsHelperRequest {
#[serde(rename = "capabilities/loadDiscoveries")]
LoadCapabilityDiscoveries {
locations: Vec<CapabilityLocation>,
warnings: Vec<String>,
},
#[serde(rename = "capabilityRoots/discoverV1")]
DiscoverCapabilityRoots(CapabilityRootsDiscoverParams),
#[serde(rename = "fs/open")]
Open(FsHelperOpenParams),
#[serde(rename = "fs/readFile")]
ReadFile(FsReadFileParams),
#[serde(rename = "fs/writeFile")]
WriteFile(FsWriteFileParams),
#[serde(rename = "fs/createDirectory")]
CreateDirectory(FsCreateDirectoryParams),
#[serde(rename = "fs/getMetadata")]
GetMetadata(FsGetMetadataParams),
#[serde(rename = "fs/canonicalize")]
Canonicalize(FsCanonicalizeParams),
#[serde(rename = "fs/readDirectory")]
ReadDirectory(FsReadDirectoryParams),
#[serde(rename = "fs/walk")]
Walk(FsWalkParams),
#[serde(rename = "fs/remove")]
Remove(FsRemoveParams),
#[serde(rename = "fs/copy")]
Copy(FsCopyParams),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct FsHelperOpenParams {
pub(crate) path: PathUri,
#[serde(default)]
pub(crate) mode: FsOpenMode,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "status", content = "payload", rename_all = "camelCase")]
pub(crate) enum FsHelperResponse {
Ok(FsHelperPayload),
Error(JSONRPCErrorError),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct FsHelperOpenResponse {
// Windows duplicates the handle from the helper process.
#[cfg(windows)]
pub(crate) process_id: u32,
// Unix passes the fd directly instead.
#[cfg(windows)]
pub(crate) file_handle: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "operation", content = "response")]
pub(crate) enum FsHelperPayload {
#[serde(rename = "capabilities/loadDiscoveries")]
LoadCapabilityDiscoveries(DiscoverV2CapabilitiesResponse),
#[serde(rename = "capabilityRoots/discoverV1")]
DiscoverCapabilityRoots(CapabilityRootsDiscoverResponse),
#[serde(rename = "fs/open")]
Open(FsHelperOpenResponse),
#[serde(rename = "fs/readFile")]
ReadFile(FsReadFileResponse),
#[serde(rename = "fs/writeFile")]
WriteFile(FsWriteFileResponse),
#[serde(rename = "fs/createDirectory")]
CreateDirectory(FsCreateDirectoryResponse),
#[serde(rename = "fs/getMetadata")]
GetMetadata(FsGetMetadataResponse),
#[serde(rename = "fs/canonicalize")]
Canonicalize(FsCanonicalizeResponse),
#[serde(rename = "fs/readDirectory")]
ReadDirectory(FsReadDirectoryResponse),
#[serde(rename = "fs/walk")]
Walk(FsWalkResponse),
#[serde(rename = "fs/remove")]
Remove(FsRemoveResponse),
#[serde(rename = "fs/copy")]
Copy(FsCopyResponse),
}
impl FsHelperPayload {
fn operation(&self) -> &'static str {
match self {
Self::LoadCapabilityDiscoveries(_) => "capabilities/loadDiscoveries",
Self::DiscoverCapabilityRoots(_) => CAPABILITY_ROOTS_DISCOVER_METHOD,
Self::Open(_) => FS_OPEN_METHOD,
Self::ReadFile(_) => FS_READ_FILE_METHOD,
Self::WriteFile(_) => FS_WRITE_FILE_METHOD,
Self::CreateDirectory(_) => FS_CREATE_DIRECTORY_METHOD,
Self::GetMetadata(_) => FS_GET_METADATA_METHOD,
Self::Canonicalize(_) => FS_CANONICALIZE_METHOD,
Self::ReadDirectory(_) => FS_READ_DIRECTORY_METHOD,
Self::Walk(_) => FS_WALK_METHOD,
Self::Remove(_) => FS_REMOVE_METHOD,
Self::Copy(_) => FS_COPY_METHOD,
}
}
pub(crate) fn expect_capability_discoveries(
self,
) -> Result<DiscoverV2CapabilitiesResponse, JSONRPCErrorError> {
match self {
Self::LoadCapabilityDiscoveries(discovery) => Ok(discovery),
other => Err(unexpected_response(
"capabilities/loadDiscoveries",
other.operation(),
)),
}
}
pub(crate) fn expect_capability_roots_discover(
self,
) -> Result<CapabilityRootsDiscoverResponse, JSONRPCErrorError> {
match self {
Self::DiscoverCapabilityRoots(response) => Ok(response),
other => Err(unexpected_response(
CAPABILITY_ROOTS_DISCOVER_METHOD,
other.operation(),
)),
}
}
pub(crate) fn expect_read_file(self) -> Result<FsReadFileResponse, JSONRPCErrorError> {
match self {
Self::ReadFile(response) => Ok(response),
other => Err(unexpected_response(FS_READ_FILE_METHOD, other.operation())),
}
}
pub(crate) fn expect_write_file(self) -> Result<FsWriteFileResponse, JSONRPCErrorError> {
match self {
Self::WriteFile(response) => Ok(response),
other => Err(unexpected_response(FS_WRITE_FILE_METHOD, other.operation())),
}
}
pub(crate) fn expect_create_directory(
self,
) -> Result<FsCreateDirectoryResponse, JSONRPCErrorError> {
match self {
Self::CreateDirectory(response) => Ok(response),
other => Err(unexpected_response(
FS_CREATE_DIRECTORY_METHOD,
other.operation(),
)),
}
}
pub(crate) fn expect_get_metadata(self) -> Result<FsGetMetadataResponse, JSONRPCErrorError> {
match self {
Self::GetMetadata(response) => Ok(response),
other => Err(unexpected_response(
FS_GET_METADATA_METHOD,
other.operation(),
)),
}
}
pub(crate) fn expect_canonicalize(self) -> Result<FsCanonicalizeResponse, JSONRPCErrorError> {
match self {
Self::Canonicalize(response) => Ok(response),
other => Err(unexpected_response(
FS_CANONICALIZE_METHOD,
other.operation(),
)),
}
}
pub(crate) fn expect_read_directory(
self,
) -> Result<FsReadDirectoryResponse, JSONRPCErrorError> {
match self {
Self::ReadDirectory(response) => Ok(response),
other => Err(unexpected_response(
FS_READ_DIRECTORY_METHOD,
other.operation(),
)),
}
}
pub(crate) fn expect_walk(self) -> Result<FsWalkResponse, JSONRPCErrorError> {
match self {
Self::Walk(response) => Ok(response),
other => Err(unexpected_response(FS_WALK_METHOD, other.operation())),
}
}
pub(crate) fn expect_remove(self) -> Result<FsRemoveResponse, JSONRPCErrorError> {
match self {
Self::Remove(response) => Ok(response),
other => Err(unexpected_response(FS_REMOVE_METHOD, other.operation())),
}
}
pub(crate) fn expect_copy(self) -> Result<FsCopyResponse, JSONRPCErrorError> {
match self {
Self::Copy(response) => Ok(response),
other => Err(unexpected_response(FS_COPY_METHOD, other.operation())),
}
}
}
fn unexpected_response(expected: &str, actual: &str) -> JSONRPCErrorError {
internal_error(format!(
"unexpected fs sandbox helper response: expected {expected}, got {actual}"
))
}
pub(crate) async fn run_direct_request(
request: FsHelperRequest,
) -> Result<FsHelperPayload, JSONRPCErrorError> {
let file_system = DirectFileSystem;
match request {
FsHelperRequest::LoadCapabilityDiscoveries {
locations,
warnings,
} => {
let file_system = LocalFileSystem::unsandboxed();
let response = load_capability_discovery_batch(&file_system, &locations, warnings)
.await
.map_err(map_fs_error)?;
Ok(FsHelperPayload::LoadCapabilityDiscoveries(response))
}
FsHelperRequest::DiscoverCapabilityRoots(params) => {
let response = crate::discover_capability_roots(&file_system, params)
.await
.map_err(|error| invalid_request(error.to_string()))?;
Ok(FsHelperPayload::DiscoverCapabilityRoots(response))
}
FsHelperRequest::Open(_) => Err(invalid_request(
"opening a file requires descriptor handoff".to_string(),
)),
FsHelperRequest::ReadFile(params) => {
let data = file_system
.read_file(
&params.path,
ReadFileOptions {
follow_symlinks: params.follow_symlinks.unwrap_or(true),
},
/*sandbox*/ None,
)
.await
.map_err(map_fs_error)?;
Ok(FsHelperPayload::ReadFile(FsReadFileResponse {
data_base64: STANDARD.encode(data),
}))
}
FsHelperRequest::WriteFile(params) => {
let bytes = STANDARD.decode(params.data_base64).map_err(|err| {
invalid_request(format!(
"{FS_WRITE_FILE_METHOD} requires valid base64 dataBase64: {err}"
))
})?;
file_system
.write_file(
&params.path,
bytes,
WriteFileOptions {
follow_symlinks: params.follow_symlinks.unwrap_or(true),
},
/*sandbox*/ None,
)
.await
.map_err(map_fs_error)?;
Ok(FsHelperPayload::WriteFile(FsWriteFileResponse {}))
}
FsHelperRequest::CreateDirectory(params) => {
file_system
.create_directory(
&params.path,
CreateDirectoryOptions {
recursive: params.recursive.unwrap_or(true),
follow_symlinks: params.follow_symlinks.unwrap_or(true),
},
/*sandbox*/ None,
)
.await
.map_err(map_fs_error)?;
Ok(FsHelperPayload::CreateDirectory(
FsCreateDirectoryResponse {},
))
}
FsHelperRequest::GetMetadata(params) => {
let metadata = file_system
.get_metadata(
&params.path,
GetMetadataOptions {
follow_symlinks: params.follow_symlinks.unwrap_or(true),
},
/*sandbox*/ None,
)
.await
.map_err(map_fs_error)?;
Ok(FsHelperPayload::GetMetadata(FsGetMetadataResponse {
is_directory: metadata.is_directory,
is_file: metadata.is_file,
is_symlink: metadata.is_symlink,
size: metadata.size,
created_at_ms: metadata.created_at_ms,
modified_at_ms: metadata.modified_at_ms,
}))
}
FsHelperRequest::Canonicalize(params) => {
let path = file_system
.canonicalize(&params.path, /*sandbox*/ None)
.await
.map_err(map_fs_error)?;
Ok(FsHelperPayload::Canonicalize(FsCanonicalizeResponse {
path,
}))
}
FsHelperRequest::ReadDirectory(params) => {
let entries = file_system
.read_directory(&params.path, /*sandbox*/ None)
.await
.map_err(map_fs_error)?
.into_iter()
.map(|entry| FsReadDirectoryEntry {
file_name: entry.file_name,
is_directory: entry.is_directory,
is_file: entry.is_file,
})
.collect();
Ok(FsHelperPayload::ReadDirectory(FsReadDirectoryResponse {
entries,
}))
}
FsHelperRequest::Walk(params) => {
let outcome = file_system
.walk(&params.path, params.options, /*sandbox*/ None)
.await
.map_err(map_fs_error)?;
Ok(FsHelperPayload::Walk(outcome))
}
FsHelperRequest::Remove(params) => {
file_system
.remove(
&params.path,
RemoveOptions {
recursive: params.recursive.unwrap_or(true),
force: params.force.unwrap_or(true),
follow_symlinks: params.follow_symlinks.unwrap_or(true),
},
/*sandbox*/ None,
)
.await
.map_err(map_fs_error)?;
Ok(FsHelperPayload::Remove(FsRemoveResponse {}))
}
FsHelperRequest::Copy(params) => {
file_system
.copy(
&params.source_path,
&params.destination_path,
CopyOptions {
recursive: params.recursive,
},
/*sandbox*/ None,
)
.await
.map_err(map_fs_error)?;
Ok(FsHelperPayload::Copy(FsCopyResponse {}))
}
}
}
pub(crate) fn map_fs_error(err: io::Error) -> JSONRPCErrorError {
match err.kind() {
io::ErrorKind::NotFound => not_found(err.to_string()),
io::ErrorKind::InvalidInput | io::ErrorKind::PermissionDenied => {
invalid_request(err.to_string())
}
_ => internal_error(err.to_string()),
}
}
#[cfg(test)]
mod tests {
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use serde_json::json;
use super::*;
#[test]
fn helper_protocol_uses_path_uris() -> serde_json::Result<()> {
let local_path =
PathUri::from_host_native_path(std::env::current_dir().expect("cwd").join("file"))
.expect("path URI");
let paths = [
local_path,
PathUri::parse("file://server/share/file").expect("path URI"),
];
for path in paths {
let expected_path = path.to_string();
let request = serde_json::to_value(FsHelperRequest::WriteFile(FsWriteFileParams {
path: path.clone(),
data_base64: String::new(),
follow_symlinks: None,
sandbox: None,
}))?;
assert_eq!(
request,
json!({
"operation": FS_WRITE_FILE_METHOD,
"params": {
"path": expected_path.as_str(),
"dataBase64": "",
"sandbox": null,
},
}),
);
let request_path = request["params"]["path"]
.as_str()
.expect("request path should be a string");
assert_eq!(request_path, expected_path);
assert!(request_path.starts_with("file:"));
let response = serde_json::to_value(FsHelperResponse::Ok(
FsHelperPayload::Canonicalize(FsCanonicalizeResponse { path }),
))?;
assert_eq!(
response,
json!({
"status": "ok",
"payload": {
"operation": FS_CANONICALIZE_METHOD,
"response": {
"path": expected_path.as_str(),
},
},
}),
);
let response_path = response["payload"]["response"]["path"]
.as_str()
.expect("canonicalize response path should be a string");
assert_eq!(response_path, expected_path);
assert!(response_path.starts_with("file:"));
}
Ok(())
}
}

View File

@@ -0,0 +1,91 @@
use std::error::Error;
use tokio::io;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use crate::fs_helper::FsHelperOpenResponse;
use crate::fs_helper::FsHelperPayload;
use crate::fs_helper::FsHelperRequest;
use crate::fs_helper::FsHelperResponse;
use crate::fs_helper::map_fs_error;
use crate::fs_helper::run_direct_request;
use crate::regular_file;
pub fn main() -> ! {
let exit_code = match tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
{
Ok(runtime) => match runtime.block_on(run_main()) {
Ok(()) => 0,
Err(err) => {
eprintln!("fs sandbox helper failed: {err}");
1
}
},
Err(err) => {
eprintln!("failed to start fs sandbox helper runtime: {err}");
1
}
};
std::process::exit(exit_code);
}
async fn run_main() -> Result<(), Box<dyn Error + Send + Sync>> {
let mut stdin = BufReader::new(io::stdin());
let mut input = String::new();
stdin.read_line(&mut input).await?;
let request: FsHelperRequest = serde_json::from_str(&input)?;
let mut opened_file = None;
let result = match request {
FsHelperRequest::Open(params) => {
let result: io::Result<_> = async {
let path = params.path.to_abs_path()?;
let file = regular_file::open(path.as_path(), params.mode).await?;
// Unix can hand the opened fd directly to the parent.
#[cfg(unix)]
crate::sandboxed_file_open::transfer_file(&file)?;
let response = FsHelperOpenResponse {
// Windows duplicates from the helper process instead.
#[cfg(windows)]
process_id: std::process::id(),
// The parent needs the raw handle to duplicate it.
#[cfg(windows)]
file_handle: {
use std::os::windows::io::AsRawHandle;
file.as_raw_handle() as usize as u64
},
};
opened_file = Some(file);
Ok(FsHelperPayload::Open(response))
}
.await;
result.map_err(map_fs_error)
}
request => run_direct_request(request).await,
};
let response = match result {
Ok(payload) => FsHelperResponse::Ok(payload),
Err(error) => FsHelperResponse::Error(error),
};
let mut stdout = io::stdout();
stdout
.write_all(serde_json::to_string(&response)?.as_bytes())
.await?;
stdout.write_all(b"\n").await?;
stdout.flush().await?;
// Keep the Windows handle alive until the parent duplicates it.
#[cfg(windows)]
if opened_file.is_some() {
use tokio::io::AsyncReadExt;
let mut acknowledgement = Vec::new();
stdin.read_to_end(&mut acknowledgement).await?;
}
drop(opened_file);
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,261 @@
#[cfg(windows)]
use std::collections::HashMap;
#[cfg(windows)]
use std::path::Path;
use std::time::Duration;
#[cfg(windows)]
use codex_protocol::config_types::WindowsSandboxLevel;
#[cfg(windows)]
use codex_protocol::models::PermissionProfile;
#[cfg(windows)]
use codex_protocol::sandbox::SandboxOverride;
#[cfg(windows)]
use codex_sandboxing::SandboxExecRequest;
#[cfg(windows)]
use codex_sandboxing::SandboxType;
#[cfg(windows)]
use codex_utils_path_uri::PathUri;
use codex_utils_pty::Command;
use pretty_assertions::assert_eq;
#[cfg(windows)]
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use super::drain_helper_stderr;
use super::read_helper_response;
use super::reap_helper_after_response;
#[cfg(windows)]
use super::run_command;
#[cfg(windows)]
use crate::fs_helper::FsHelperPayload;
#[cfg(windows)]
use crate::protocol::FsReadFileResponse;
#[cfg(windows)]
use crate::protocol::FsWriteFileResponse;
#[tokio::test(start_paused = true)]
async fn filesystem_operation_is_not_limited_by_helper_response_deadline() {
let (reader, mut writer) = tokio::io::duplex(/*max_buf_size*/ 256);
let response = tokio::spawn(async move { read_helper_response(reader).await });
tokio::task::yield_now().await;
tokio::time::advance(Duration::from_secs(/*secs*/ 31)).await;
tokio::task::yield_now().await;
assert!(
!response.is_finished(),
"a filesystem operation must not time out before the helper responds"
);
writer
.write_all(b"completed after the old deadline\n")
.await
.expect("helper response");
assert_eq!(
response
.await
.expect("response task")
.expect("unbounded filesystem operation"),
b"completed after the old deadline\n"
);
}
#[tokio::test]
async fn noisy_failing_helper_preserves_exit_status_and_bounded_stderr() {
#[cfg(unix)]
let mut command = {
let mut command = Command::new("sh");
command.arg("-c").arg(
"printf 'expected helper diagnostic' >&2; i=0; while [ \"$i\" -lt 1024 ]; do printf '%0128d' 0 >&2; i=$((i + 1)); done; printf 'response before failure\\n'; exit 7",
);
command
};
#[cfg(windows)]
let mut command = {
let system_root = std::env::var("SystemRoot").expect("Windows system root");
let powershell = Path::new(&system_root)
.join("System32")
.join("WindowsPowerShell")
.join("v1.0")
.join("powershell.exe");
let mut command = Command::new(powershell);
command
.arg("-NoProfile")
.arg("-Command")
.arg("[Console]::Error.Write('expected helper diagnostic' + ('x' * 131072)); [Console]::Out.WriteLine('response before failure'); exit 7");
command
};
command.envs(std::env::vars_os());
let mut child = command.spawn().expect("noisy helper process");
let stdout = child.stdout.take().expect("helper stdout");
let stderr = drain_helper_stderr(&mut child);
let error = tokio::time::timeout(Duration::from_secs(/*secs*/ 8), async {
// Cleanup starts after the response, not during slow helper startup.
read_helper_response(stdout).await?;
reap_helper_after_response(child, stderr).await
})
.await
.expect("helper stderr must be drained during bounded cleanup")
.expect_err("nonzero helper exit should fail after its stderr pipe fills");
assert!(error.message.contains('7'), "{}", error.message);
assert!(
error.message.contains("expected helper diagnostic"),
"{}",
error.message
);
assert!(error.message.len() < 4400, "{}", error.message.len());
}
#[tokio::test]
async fn helper_stderr_is_drained_before_the_response() {
#[cfg(unix)]
let mut command = {
let mut command = Command::new("sh");
command.arg("-c").arg(
"printf 'expected pre-response diagnostic' >&2; i=0; while [ \"$i\" -lt 1024 ]; do printf '%0128d' 0 >&2; i=$((i + 1)); done; printf 'completed after noisy stderr\\n'",
);
command
};
#[cfg(windows)]
let mut command = {
let system_root = std::env::var("SystemRoot").expect("Windows system root");
let powershell = Path::new(&system_root)
.join("System32")
.join("WindowsPowerShell")
.join("v1.0")
.join("powershell.exe");
let mut command = Command::new(powershell);
command.arg("-NoProfile").arg("-Command").arg(
"[Console]::Error.Write('expected pre-response diagnostic' + ('x' * 131072)); [Console]::Out.WriteLine('completed after noisy stderr')",
);
command
};
command.envs(std::env::vars_os());
let mut child = command.spawn().expect("noisy helper process");
let stdout = child.stdout.take().expect("helper stdout");
let stderr = drain_helper_stderr(&mut child);
let response = tokio::time::timeout(
Duration::from_secs(/*secs*/ 2),
read_helper_response(stdout),
)
.await
.expect("helper stderr must be drained before awaiting its response")
.expect("helper response");
assert_eq!(response.trim_ascii_end(), b"completed after noisy stderr");
reap_helper_after_response(child, stderr)
.await
.expect("noisy helper should be cleaned up after its response");
}
#[cfg(windows)]
#[tokio::test]
async fn completed_windows_image_read_does_not_wait_for_a_stuck_helper() {
let directory = tempfile::tempdir().expect("temporary directory");
let path = directory.path().join("image.png");
let operations = [
(
r#"[IO.File]::WriteAllText($env:CODEX_FS_HELPER_TEST_PATH, 'image')
[Console]::Out.WriteLine('{"status":"ok","payload":{"operation":"fs/writeFile","response":{}}}')"#,
FsHelperPayload::WriteFile(FsWriteFileResponse {}),
),
(
r#"$data = [Convert]::ToBase64String([IO.File]::ReadAllBytes($env:CODEX_FS_HELPER_TEST_PATH))
[Console]::Out.WriteLine('{"status":"ok","payload":{"operation":"fs/readFile","response":{"dataBase64":"' + $data + '"}}}')"#,
FsHelperPayload::ReadFile(FsReadFileResponse {
data_base64: "aW1hZ2U=".to_string(),
}),
),
];
for (operation, expected) in operations {
let script = format!(
"[Console]::In.ReadLine() | Out-Null\n{operation}\n[Console]::Out.Flush()\n[Threading.Thread]::Sleep(30000)"
);
let command = powershell_command(&script, &path).expect("PowerShell helper command");
let result = tokio::time::timeout(
Duration::from_secs(/*secs*/ 8),
run_command(command, b"{}".to_vec()),
)
.await
.expect("the completed operation must not wait for helper termination")
.expect("helper response");
assert_eq!(result, expected);
}
assert_eq!(std::fs::read(&path).expect("created file"), b"image");
}
#[cfg(windows)]
#[tokio::test]
async fn duplicated_windows_file_handle_survives_bounded_helper_cleanup() {
let directory = tempfile::tempdir().expect("temporary directory");
let path = directory.path().join("image.png");
std::fs::write(&path, b"image").expect("image file");
let command = powershell_command(
r#"[Console]::In.ReadLine() | Out-Null
$file = [IO.File]::OpenRead($env:CODEX_FS_HELPER_TEST_PATH)
$handle = $file.SafeFileHandle.DangerousGetHandle().ToInt64()
[Console]::Out.WriteLine('{"status":"ok","payload":{"operation":"fs/open","response":{"processId":' + $PID + ',"fileHandle":' + $handle + '}}}')
[Console]::Out.Flush()
[Threading.Thread]::Sleep(30000)"#,
&path,
)
.expect("PowerShell helper command");
let mut file = tokio::time::timeout(
Duration::from_secs(/*secs*/ 8),
crate::sandboxed_file_open::open(
command,
PathUri::from_host_native_path(&path).expect("image path URI"),
crate::protocol::FsOpenMode::Read,
),
)
.await
.expect("the opened file must not wait for helper termination")
.expect("duplicated file handle");
let mut data = Vec::new();
file.read_to_end(&mut data).await.expect("image contents");
assert_eq!(data, b"image");
}
#[cfg(windows)]
fn powershell_command(script: &str, path: &Path) -> anyhow::Result<SandboxExecRequest> {
let system_root = std::env::var("SystemRoot")?;
let powershell = Path::new(&system_root)
.join("System32")
.join("WindowsPowerShell")
.join("v1.0")
.join("powershell.exe");
let cwd = PathUri::from_host_native_path(std::env::current_dir()?)?;
Ok(SandboxExecRequest {
sandbox_override: SandboxOverride::NoOverride,
command: vec![
powershell.to_string_lossy().into_owned(),
"-NoProfile".to_string(),
"-Command".to_string(),
script.to_string(),
],
cwd: cwd.clone(),
sandbox_policy_cwd: cwd,
env: HashMap::from([
("SystemRoot".to_string(), system_root),
(
"CODEX_FS_HELPER_TEST_PATH".to_string(),
path.to_string_lossy().into_owned(),
),
]),
network: None,
network_environment_id: None,
sandbox: SandboxType::None,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
permission_profile: PermissionProfile::Disabled,
arg0: None,
})
}

View File

@@ -0,0 +1,262 @@
mod arg0_exec_helper;
mod capability_discovery;
mod capability_discovery_cache;
mod capability_discovery_v2_cache;
mod client;
mod client_api;
mod client_error;
mod client_telemetry;
mod client_transport;
mod connection;
#[path = "discoverV2/mod.rs"]
mod discover_v2;
mod environment;
mod environment_bootstrap;
mod environment_config;
mod environment_provider;
mod environment_registry;
mod environment_toml;
mod file_handle;
mod forward;
mod fs_helper;
mod fs_helper_main;
mod fs_sandbox;
mod local_file_system;
mod local_file_system_read;
mod local_process;
mod network_policy_decisions;
mod no_follow;
mod noise_channel;
mod noise_relay;
mod process;
mod process_sandbox;
mod process_telemetry;
mod regular_file;
mod relay;
mod relay_proto;
mod remote;
mod remote_file_system;
mod remote_process;
mod resolved_capability;
mod rpc;
mod rpc_server_requests;
mod rpc_timing;
mod runtime_options;
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
mod sandbox_integrity;
mod sandbox_selection;
mod sandboxed_file_open;
mod sandboxed_file_system;
mod server;
#[cfg(unix)]
mod shell_snapshot;
#[cfg(unix)]
mod shell_snapshot_file;
#[cfg(unix)]
mod shell_snapshot_process;
mod telemetry;
mod trace_context;
mod websocket_pong_watchdog;
// Shared limits for inbound executor messages across all transports.
mod client_inbound_request_limit;
use codex_exec_server_protocol as protocol;
/// Process-local opt-in for tying a remote executor to its parent's stdin pipe.
pub const CODEX_EXEC_SERVER_EXIT_ON_STDIN_CLOSE_ENV_VAR: &str =
"CODEX_EXEC_SERVER_EXIT_ON_STDIN_CLOSE";
pub use arg0_exec_helper::CODEX_ARG0_EXEC_HELPER_ARG1;
pub use arg0_exec_helper::main as run_arg0_exec_helper_main;
pub use capability_discovery::CapabilityDiscoveryError;
pub use capability_discovery::discover_capability_roots;
pub use capability_discovery_cache::ExecutorCapabilityDiscoveryCache;
pub use capability_discovery_v2_cache::ExecutorCapabilityDiscoveryV2Cache;
pub use client::ExecServerClient;
pub use client::ExecServerError;
pub use client::http_client::HttpResponseBodyStream;
pub use client::http_client::RouteAwareHttpClient;
pub use client_api::ExecServerClientConnectOptions;
pub use client_api::HttpClient;
pub use client_api::NoiseRendezvousConnectArgs;
pub use client_api::NoiseRendezvousConnectBundle;
pub use client_api::NoiseRendezvousConnectProvider;
pub use client_api::RemoteExecServerConnectArgs;
pub use codex_exec_server_protocol::ExecutorCapabilityDiscoverySnapshot;
pub use codex_exec_server_protocol::ProcessId;
pub use codex_file_system::CopyOptions;
pub use codex_file_system::CreateDirectoryOptions;
pub use codex_file_system::EnvironmentAccess;
pub use codex_file_system::EnvironmentAccessExt;
pub use codex_file_system::EnvironmentAccessKey;
pub use codex_file_system::ExecutorFileSystem;
pub use codex_file_system::ExecutorFileSystemFuture;
pub use codex_file_system::FILE_READ_CHUNK_SIZE;
pub use codex_file_system::FILE_WRITE_CHUNK_SIZE;
pub use codex_file_system::FileMetadata;
pub use codex_file_system::FileSystemEnvironmentAccessor;
pub use codex_file_system::FileSystemReadStream;
pub use codex_file_system::FileSystemResult;
pub use codex_file_system::FileSystemSandboxContext;
pub use codex_file_system::GetMetadataOptions;
pub use codex_file_system::ReadDirectoryEntry;
pub use codex_file_system::ReadFileOptions;
pub use codex_file_system::RemoveOptions;
pub use codex_file_system::WalkEntry;
pub use codex_file_system::WalkEntryKind;
pub use codex_file_system::WalkError;
pub use codex_file_system::WalkOptions;
pub use codex_file_system::WalkOutcome;
pub use codex_file_system::WindowsSandboxSelection;
pub use codex_file_system::WriteFileOptions;
pub use codex_protocol::shell_environment::CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN_ENV_VAR;
pub use environment::CODEX_EXEC_SERVER_NOISE_CHATGPT_ACCOUNT_ID_ENV_VAR;
pub use environment::CODEX_EXEC_SERVER_NOISE_ENVIRONMENT_ID_ENV_VAR;
pub use environment::CODEX_EXEC_SERVER_NOISE_REGISTRY_URL_ENV_VAR;
pub use environment::CODEX_EXEC_SERVER_URL_ENV_VAR;
pub use environment::ConnectionAttemptOutcome;
pub use environment::Environment;
pub use environment::EnvironmentConnectionState;
pub use environment::EnvironmentManager;
pub use environment::EnvironmentObservedStatus;
pub use environment::EnvironmentReadyInfo;
pub use environment::LOCAL_ENVIRONMENT_ID;
pub use environment::MAX_SELECTED_CAPABILITY_ROOTS;
pub use environment::REMOTE_ENVIRONMENT_ID;
pub use environment::RemoteEnvironmentOptions;
pub use environment::supports_capability_discovery_v2;
pub use environment_bootstrap::PreparedEnvironmentManager;
pub use environment_provider::DefaultEnvironmentProvider;
pub use environment_provider::EnvironmentProvider;
pub use environment_provider::EnvironmentProviderFuture;
pub use environment_registry::EnvironmentRegistryConnectRequest;
pub use environment_registry::EnvironmentRegistryConnectResponse;
pub use environment_registry::EnvironmentRegistryHarnessKeyValidationRequest;
pub use environment_registry::EnvironmentRegistryHarnessKeyValidationResponse;
pub use environment_registry::EnvironmentRegistryRegistrationRequest;
pub use environment_registry::EnvironmentRegistryRegistrationResponse;
pub use fs_helper::CODEX_FS_HELPER_ARG1;
pub use fs_helper_main::main as run_fs_helper_main;
pub use local_file_system::LOCAL_FS;
pub use local_file_system::LocalFileSystem;
pub use no_follow::BoundOutput;
pub use noise_channel::NoiseChannelError;
pub use noise_channel::NoiseChannelIdentity;
pub use noise_channel::NoiseChannelPublicKey;
pub use process::ExecBackend;
pub use process::ExecBackendFuture;
pub use process::ExecProcess;
pub use process::ExecProcessEvent;
pub use process::ExecProcessEventReceiver;
pub use process::ExecProcessFuture;
pub use process::StartedExecProcess;
pub use protocol::ByteChunk;
pub use protocol::CAPABILITIES_DISCOVER_V2_METHOD;
pub use protocol::CAPABILITY_ROOTS_DISCOVER_METHOD;
pub use protocol::CapabilityRootDiscoverRequest;
pub use protocol::CapabilityRootDiscovery;
pub use protocol::CapabilityRootsDiscoverParams;
pub use protocol::CapabilityRootsDiscoverResponse;
pub use protocol::CapabilityTextFile;
pub use protocol::DiscoverV2CapabilitiesRequest;
pub use protocol::DiscoverV2CapabilitiesResponse;
pub use protocol::DiscoveredPluginFiles;
pub use protocol::DiscoveredSkillFiles;
pub use protocol::EnvironmentCapabilities;
pub use protocol::EnvironmentConfigLayer;
pub use protocol::EnvironmentConfigLayerStack;
pub use protocol::EnvironmentConfigReadParams;
pub use protocol::EnvironmentConfigReadResponse;
pub use protocol::EnvironmentInfo;
pub use protocol::EnvironmentStatus;
pub use protocol::EnvironmentStatusKind;
pub use protocol::ExecClosedNotification;
pub use protocol::ExecEnvPolicy;
pub use protocol::ExecExitedNotification;
pub use protocol::ExecMetadata;
pub use protocol::ExecOutputDeltaNotification;
pub use protocol::ExecOutputStream;
pub use protocol::ExecParams;
pub use protocol::ExecResponse;
pub use protocol::ExecServerNetworkPolicyDecision;
pub use protocol::ExecServerNetworkPolicyRequest;
pub use protocol::ExecServerNetworkProtocol;
pub use protocol::ExecutorCapabilityDiscoveryV2Snapshot;
pub use protocol::ExecutorPlugin;
pub use protocol::ExecutorSkill;
pub use protocol::FsCanonicalizeParams;
pub use protocol::FsCanonicalizeResponse;
pub use protocol::FsCloseParams;
pub use protocol::FsCloseResponse;
pub use protocol::FsCopyParams;
pub use protocol::FsCopyResponse;
pub use protocol::FsCreateDirectoryParams;
pub use protocol::FsCreateDirectoryResponse;
pub use protocol::FsGetMetadataParams;
pub use protocol::FsGetMetadataResponse;
pub use protocol::FsOpenMode;
pub use protocol::FsOpenParams;
pub use protocol::FsOpenResponse;
pub use protocol::FsReadBlockParams;
pub use protocol::FsReadBlockResponse;
pub use protocol::FsReadDirectoryEntry;
pub use protocol::FsReadDirectoryParams;
pub use protocol::FsReadDirectoryResponse;
pub use protocol::FsReadFileParams;
pub use protocol::FsReadFileResponse;
pub use protocol::FsRemoveParams;
pub use protocol::FsRemoveResponse;
pub use protocol::FsWalkParams;
pub use protocol::FsWalkResponse;
pub use protocol::FsWriteBlockParams;
pub use protocol::FsWriteBlockResponse;
pub use protocol::FsWriteFileParams;
pub use protocol::FsWriteFileResponse;
pub use protocol::HttpHeader;
pub use protocol::HttpRedirectPolicy;
pub use protocol::HttpRequestBodyDeltaNotification;
pub use protocol::HttpRequestParams;
pub use protocol::HttpRequestResponse;
pub use protocol::InitializeParams;
pub use protocol::InitializeResponse;
pub use protocol::NetworkPolicyRequestParams;
pub use protocol::NetworkPolicyRequestResponse;
pub use protocol::ProcessOutputChunk;
pub use protocol::ProcessSignal;
pub use protocol::ReadParams;
pub use protocol::ReadResponse;
pub use protocol::ShellInfo;
pub use protocol::ShellSnapshotRequest;
pub use protocol::SignalParams;
pub use protocol::SignalResponse;
pub use protocol::SkillDiscoveryRoot;
pub use protocol::TerminateParams;
pub use protocol::TerminateResponse;
pub use protocol::WriteParams;
pub use protocol::WriteResponse;
pub use protocol::WriteStatus;
pub use regular_file::read_sensitive_file_to_string;
pub use remote::RemoteEnvironmentConfig;
pub use remote::RemoteEnvironmentTransport;
pub use remote::credential_stdin;
pub use remote::registration_auth_from_stdin;
pub use remote::run_remote_environment;
pub use remote::run_remote_environment_forward_until_shutdown;
pub use remote::run_remote_environment_until_shutdown;
pub use resolved_capability::ResolvedSelectedCapabilityRoot;
pub use resolved_capability::SelectedCapabilityRootsStatus;
pub use runtime_options::ExecServerRuntimeOptions;
pub use server::ConcurrentRequestLimit;
pub use server::DEFAULT_LISTEN_URL;
pub use server::ExecServerListenUrlParseError;
pub use server::RequestDispatchMode;
pub use server::run_main;
pub use server::run_main_with_telemetry;
pub use telemetry::ExecServerTelemetry;
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
pub use sandbox_integrity::run_integrity_checks;
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
pub async fn run_integrity_checks(_request: &codex_sandboxing::SandboxExecRequest) {}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,27 @@
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use tokio::io;
use super::*;
#[tokio::test]
async fn direct_file_system_rejects_non_native_uri_as_invalid_input() {
let error = DirectFileSystem
.read_file(&non_native_uri(), Default::default(), /*sandbox*/ None)
.await
.expect_err("non-native URI should be rejected");
assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
}
fn non_native_uri() -> PathUri {
#[cfg(unix)]
let uri = "file://server/share/file.txt";
#[cfg(windows)]
let uri = "file:///usr/local/file.txt";
match PathUri::parse(uri) {
Ok(uri) => uri,
Err(err) => panic!("valid non-native URI should parse: {err}"),
}
}

View File

@@ -0,0 +1,74 @@
//! Bounded blocking file reads that stop between chunks when their async caller is dropped.
use crate::FILE_READ_CHUNK_SIZE;
use crate::ReadFileOptions;
use crate::no_follow;
use crate::protocol::FsOpenMode;
use crate::regular_file;
use codex_utils_absolute_path::AbsolutePathBuf;
use std::io;
use std::io::Read;
use tokio_util::sync::CancellationToken;
const MAX_READ_FILE_BYTES: u64 = 512 * 1024 * 1024;
pub(super) async fn read_file(
path: AbsolutePathBuf,
options: ReadFileOptions,
) -> io::Result<Vec<u8>> {
let cancelled = CancellationToken::new();
let _cancel_on_drop = cancelled.clone().drop_guard();
tokio::task::spawn_blocking(move || {
if cancelled.is_cancelled() {
return Err(io::Error::other("file read cancelled"));
}
let file = if options.follow_symlinks {
regular_file::open_sync(path.as_path(), FsOpenMode::Read)?
} else {
no_follow::open_file(path.as_path())?
};
let metadata = file.metadata()?;
if metadata.len() > MAX_READ_FILE_BYTES {
return Err(file_too_large_error());
}
let mut bytes = Vec::with_capacity(metadata.len() as usize);
CancellableReader {
reader: file.take(MAX_READ_FILE_BYTES + 1),
cancelled,
}
.read_to_end(&mut bytes)?;
if bytes.len() as u64 > MAX_READ_FILE_BYTES {
return Err(file_too_large_error());
}
Ok(bytes)
})
.await
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
}
struct CancellableReader<R> {
reader: R,
cancelled: CancellationToken,
}
impl<R: Read> Read for CancellableReader<R> {
fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
if self.cancelled.is_cancelled() {
// read_to_end retries Interrupted errors, so cancellation must use another kind.
return Err(io::Error::other("file read cancelled"));
}
let count = bytes.len().min(FILE_READ_CHUNK_SIZE);
self.reader.read(&mut bytes[..count])
}
}
fn file_too_large_error() -> io::Error {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("file is too large to read: limit is {MAX_READ_FILE_BYTES} bytes"),
)
}
#[cfg(test)]
#[path = "local_file_system_read_tests.rs"]
mod tests;

View File

@@ -0,0 +1,91 @@
//! Regression coverage for bounded, cancellable reads and regular-file validation.
#[cfg(unix)]
use super::CancellableReader;
use super::MAX_READ_FILE_BYTES;
use crate::ReadFileOptions;
use crate::local_file_system::LOCAL_FS;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use test_case::test_case;
#[test_case(true ; "follow")]
#[test_case(false ; "no_follow")]
#[tokio::test]
async fn reads_file_larger_than_tokio_buffer(follow_symlinks: bool) -> anyhow::Result<()> {
let directory = TempDir::new()?;
let path = directory.path().canonicalize()?.join("large.bin");
let contents = vec![0x5a; 4 * 1024 * 1024];
std::fs::write(&path, &contents)?;
assert_eq!(
LOCAL_FS
.read_file(
&PathUri::from_host_native_path(&path)?,
ReadFileOptions { follow_symlinks },
/*sandbox*/ None,
)
.await?,
contents,
);
Ok(())
}
#[test_case(true ; "follow")]
#[test_case(false ; "no_follow")]
#[tokio::test]
async fn rejects_oversized_file(follow_symlinks: bool) -> anyhow::Result<()> {
let directory = TempDir::new()?;
let path = directory.path().canonicalize()?.join("oversized.bin");
std::fs::File::create(&path)?.set_len(MAX_READ_FILE_BYTES + 1)?;
let error = LOCAL_FS
.read_file(
&PathUri::from_host_native_path(&path)?,
ReadFileOptions { follow_symlinks },
/*sandbox*/ None,
)
.await
.expect_err("oversized file must be rejected before allocation");
assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
Ok(())
}
#[cfg(unix)]
#[test]
fn cancellation_stops_a_reader_after_its_first_chunk() -> anyhow::Result<()> {
use std::io::Read;
use std::io::Write;
use std::os::unix::net::UnixStream;
use tokio_util::sync::CancellationToken;
let (socket, mut writer) = UnixStream::pair()?;
let cancelled = CancellationToken::new();
let (reached_tx, reached_rx) = std::sync::mpsc::channel();
let (resume_tx, resume_rx) = std::sync::mpsc::channel::<()>();
let worker = std::thread::spawn({
let cancelled = cancelled.clone();
move || -> std::io::Result<()> {
let mut reader = CancellableReader {
reader: socket,
cancelled,
};
let mut first = [0];
reader.read_exact(&mut first)?;
let _ = reached_tx.send(first);
let _ = resume_rx.recv();
reader.read_to_end(&mut Vec::new()).map(|_| ())
}
});
writer.write_all(b"x")?;
let first = reached_rx.recv()?;
cancelled.cancel();
// Closing the peer also makes a missing cancellation check fail without hanging the test.
drop(writer);
drop(resume_tx);
let error = worker
.join()
.unwrap()
.expect_err("cancelled read must stop");
assert_eq!((first, error.kind()), (*b"x", std::io::ErrorKind::Other));
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,97 @@
use std::sync::Arc;
use std::sync::RwLock;
use std::time::Duration;
use codex_network_proxy::NetworkDecision;
use codex_network_proxy::NetworkPolicyDecider;
use codex_network_proxy::NetworkPolicyRequest;
use codex_network_proxy::NetworkProtocol;
use tokio_util::sync::CancellationToken;
use crate::ProcessId;
use crate::protocol::ExecServerNetworkPolicyDecision;
use crate::protocol::ExecServerNetworkPolicyRequest;
use crate::protocol::ExecServerNetworkProtocol;
use crate::protocol::MAX_NETWORK_POLICY_HOST_BYTES;
use crate::protocol::MAX_NETWORK_POLICY_REASON_BYTES;
use crate::protocol::NETWORK_POLICY_REQUEST_METHOD;
use crate::protocol::NetworkPolicyRequestParams;
use crate::protocol::NetworkPolicyRequestResponse;
use crate::rpc_server_requests::RpcServerRequestSender;
const NETWORK_POLICY_TRANSPORT_TIMEOUT_MARGIN: Duration = Duration::from_secs(5);
pub(crate) fn network_policy_decider(
process_id: ProcessId,
requests: Arc<RwLock<Option<RpcServerRequestSender>>>,
controller_timeout: Duration,
process_shutdown: CancellationToken,
) -> Arc<dyn NetworkPolicyDecider> {
let request_timeout =
controller_timeout.saturating_add(NETWORK_POLICY_TRANSPORT_TIMEOUT_MARGIN);
Arc::new(move |request: NetworkPolicyRequest| {
let process_id = process_id.clone();
let requests = Arc::clone(&requests);
let process_shutdown = process_shutdown.clone();
async move {
let host = request.host.as_str();
if host.is_empty()
|| host.len() > MAX_NETWORK_POLICY_HOST_BYTES
|| host.chars().any(char::is_control)
|| host.chars().any(char::is_whitespace)
{
return NetworkDecision::deny("not_allowed");
}
let requests = requests
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone();
let Some(requests) = requests else {
return NetworkDecision::deny("not_allowed");
};
let params = NetworkPolicyRequestParams {
process_id,
request: ExecServerNetworkPolicyRequest {
protocol: match request.protocol {
NetworkProtocol::Http => ExecServerNetworkProtocol::Http,
NetworkProtocol::HttpsConnect => ExecServerNetworkProtocol::HttpsConnect,
NetworkProtocol::Socks5Tcp => ExecServerNetworkProtocol::Socks5Tcp,
NetworkProtocol::Socks5Udp => ExecServerNetworkProtocol::Socks5Udp,
},
host: request.host,
port: request.port,
},
};
tokio::select! {
biased;
_ = process_shutdown.cancelled() => NetworkDecision::deny("not_allowed"),
response = requests.call_with_timeout::<_, NetworkPolicyRequestResponse>(
NETWORK_POLICY_REQUEST_METHOD,
&params,
request_timeout,
) => response
.map(|response| match response.decision {
ExecServerNetworkPolicyDecision::Allow => NetworkDecision::Allow,
ExecServerNetworkPolicyDecision::Deny { reason }
| ExecServerNetworkPolicyDecision::Ask { reason }
if reason.len() > MAX_NETWORK_POLICY_REASON_BYTES
|| reason.chars().any(char::is_control) =>
{
NetworkDecision::deny("not_allowed")
}
ExecServerNetworkPolicyDecision::Deny { reason } => {
NetworkDecision::deny(reason)
}
ExecServerNetworkPolicyDecision::Ask { reason } => {
NetworkDecision::ask(reason)
}
})
.unwrap_or_else(|_| NetworkDecision::deny("not_allowed")),
}
}
})
}
#[cfg(test)]
#[path = "network_policy_decisions_tests.rs"]
mod tests;

View File

@@ -0,0 +1,225 @@
use std::sync::Arc;
use std::sync::RwLock;
use std::time::Duration;
use codex_network_proxy::NetworkDecision;
use codex_network_proxy::NetworkPolicyRequest;
use codex_network_proxy::NetworkPolicyRequestArgs;
use codex_network_proxy::NetworkProtocol;
use pretty_assertions::assert_eq;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tokio::time::timeout;
use super::*;
use crate::protocol::ExecServerNetworkPolicyDecision;
use crate::protocol::NetworkPolicyRequestParams;
use crate::protocol::NetworkPolicyRequestResponse;
use crate::rpc::RpcServerOutboundMessage;
struct DeciderHarness {
requests: RpcServerRequestSender,
outgoing: mpsc::Receiver<RpcServerOutboundMessage>,
controller_timeout: Duration,
process_shutdown: CancellationToken,
}
impl DeciderHarness {
fn new() -> Self {
let (outgoing_tx, outgoing) = mpsc::channel(/*buffer*/ 8);
Self {
requests: RpcServerRequestSender::new(outgoing_tx),
outgoing,
controller_timeout: Duration::from_secs(60),
process_shutdown: CancellationToken::new(),
}
}
fn request(&self, host: &str) -> JoinHandle<NetworkDecision> {
let decider = network_policy_decider(
ProcessId::from("process"),
Arc::new(RwLock::new(Some(self.requests.clone()))),
self.controller_timeout,
self.process_shutdown.clone(),
);
let request = NetworkPolicyRequest::new(NetworkPolicyRequestArgs {
protocol: NetworkProtocol::HttpsConnect,
host: host.to_string(),
port: 443,
environment_id: None,
client_addr: None,
method: None,
command: None,
exec_policy_hint: None,
});
tokio::spawn(async move { decider.decide(request).await })
}
async fn next_request(
&mut self,
) -> (
codex_exec_server_protocol::RequestId,
NetworkPolicyRequestParams,
) {
let outbound = timeout(Duration::from_secs(1), self.outgoing.recv())
.await
.expect("policy request should arrive")
.expect("policy request");
let RpcServerOutboundMessage::Request(request) = outbound else {
panic!("expected policy request");
};
assert_eq!(request.method, NETWORK_POLICY_REQUEST_METHOD);
let params = serde_json::from_value(request.params.expect("request params"))
.expect("deserialize policy request");
(request.id, params)
}
}
async fn await_decision(decision: JoinHandle<NetworkDecision>) -> NetworkDecision {
timeout(Duration::from_secs(1), decision)
.await
.expect("network policy decision should resolve")
.expect("network policy decision task")
}
#[tokio::test]
async fn returns_client_policy_decision() {
let mut harness = DeciderHarness::new();
let decision = harness.request("example.com");
let (request_id, params) = harness.next_request().await;
assert_eq!(params.process_id, ProcessId::from("process"));
assert_eq!(params.request.host, "example.com");
harness.requests.complete(
request_id,
Ok(serde_json::to_value(NetworkPolicyRequestResponse {
decision: ExecServerNetworkPolicyDecision::Allow,
})
.expect("serialize policy response")),
);
assert_eq!(await_decision(decision).await, NetworkDecision::Allow);
}
#[tokio::test]
async fn policy_response_reasons_are_bounded_and_fail_closed() {
let mut harness = DeciderHarness::new();
let boundary_reason = "d".repeat(MAX_NETWORK_POLICY_REASON_BYTES);
let cases = [
(
ExecServerNetworkPolicyDecision::Deny {
reason: boundary_reason.clone(),
},
NetworkDecision::deny(boundary_reason),
),
(
ExecServerNetworkPolicyDecision::Deny {
reason: "d".repeat(MAX_NETWORK_POLICY_REASON_BYTES + 1),
},
NetworkDecision::deny("not_allowed"),
),
(
ExecServerNetworkPolicyDecision::Ask {
reason: "ask permission".to_string(),
},
NetworkDecision::ask("ask permission"),
),
(
ExecServerNetworkPolicyDecision::Ask {
reason: "ask\npermission".to_string(),
},
NetworkDecision::deny("not_allowed"),
),
];
for (response, expected) in cases {
let decision = harness.request("example.com");
let (request_id, _) = harness.next_request().await;
harness.requests.complete(
request_id,
Ok(
serde_json::to_value(NetworkPolicyRequestResponse { decision: response })
.expect("serialize policy response"),
),
);
assert_eq!(await_decision(decision).await, expected);
}
}
#[tokio::test]
async fn boundary_host_is_relayed() {
let mut harness = DeciderHarness::new();
let host = "h".repeat(MAX_NETWORK_POLICY_HOST_BYTES);
let decision = harness.request(&host);
let (request_id, params) = harness.next_request().await;
assert_eq!(params.request.host, host);
harness.requests.complete(
request_id,
Ok(serde_json::to_value(NetworkPolicyRequestResponse {
decision: ExecServerNetworkPolicyDecision::Allow,
})
.expect("serialize policy response")),
);
assert_eq!(await_decision(decision).await, NetworkDecision::Allow);
}
#[tokio::test]
async fn invalid_hosts_fail_closed_before_reverse_rpc() {
let mut harness = DeciderHarness::new();
let invalid_hosts = [
String::new(),
"host name".to_string(),
"host\u{0000}name".to_string(),
"h".repeat(MAX_NETWORK_POLICY_HOST_BYTES + 1),
];
for host in invalid_hosts {
assert_eq!(
await_decision(harness.request(&host)).await,
NetworkDecision::deny("not_allowed")
);
assert!(harness.outgoing.try_recv().is_err());
assert_eq!(harness.requests.pending_request_count(), 0);
}
}
#[tokio::test]
async fn process_exit_and_disconnect_fail_closed() {
let mut process_exit = DeciderHarness::new();
let process_decision = process_exit.request("process-exit.example.com");
process_exit.next_request().await;
process_exit.process_shutdown.cancel();
assert_eq!(
await_decision(process_decision).await,
NetworkDecision::deny("not_allowed")
);
assert_eq!(process_exit.requests.pending_request_count(), 0);
let mut disconnect = DeciderHarness::new();
let disconnect_decision = disconnect.request("disconnect.example.com");
disconnect.next_request().await;
disconnect.requests.close();
assert_eq!(
await_decision(disconnect_decision).await,
NetworkDecision::deny("not_allowed")
);
assert_eq!(disconnect.requests.pending_request_count(), 0);
}
#[tokio::test(start_paused = true)]
async fn configured_decision_timeout_fails_closed() {
let mut harness = DeciderHarness::new();
harness.controller_timeout = Duration::from_secs(17);
let decision = harness.request("timeout.example.com");
harness.next_request().await;
tokio::time::advance(Duration::from_secs(21)).await;
assert!(!decision.is_finished());
tokio::time::advance(Duration::from_secs(1)).await;
assert_eq!(
await_decision(decision).await,
NetworkDecision::deny("not_allowed")
);
assert_eq!(harness.requests.pending_request_count(), 0);
}

View File

@@ -0,0 +1,367 @@
use crate::FileMetadata;
use std::io;
use std::path::Path;
#[cfg(windows)]
use std::time::SystemTime;
#[cfg(windows)]
use std::time::UNIX_EPOCH;
#[cfg(unix)]
mod unix;
#[cfg(windows)]
mod windows;
#[cfg(unix)]
use unix as imp;
#[cfg(windows)]
use windows as imp;
fn invalid_output(reason: &'static str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidInput, reason)
}
/// A destination bound before sandboxed tools run. Only ordinary path-based files are truncated.
pub struct BoundOutput {
file: std::fs::File,
destination: Destination,
}
enum Destination {
Path(std::path::PathBuf),
Stream { is_stdout: bool },
}
impl BoundOutput {
pub fn open(path: &Path) -> io::Result<Self> {
// Check raw syntax before absolute() or components() discards directory markers.
let bytes = path.as_os_str().as_encoded_bytes();
let leaf = bytes
.rsplit(|b| *b == b'/' || (cfg!(windows) && *b == b'\\'))
.next();
if matches!(leaf, None | Some(b"" | b"." | b"..")) {
return Err(invalid_output("output must name a file"));
}
#[cfg(windows)]
if bytes.eq_ignore_ascii_case(b"NUL") || bytes.eq_ignore_ascii_case(br"\\.\NUL") {
return Ok(Self {
file: windows::open_null_output()?,
destination: Destination::Stream { is_stdout: false },
});
}
#[cfg(unix)]
if let Some(output) = unix::inherited_output(path)? {
return Ok(output);
}
#[cfg(unix)]
let path = unix::output_path(path)?;
#[cfg(windows)]
let path = std::path::absolute(path)?;
let file = imp::open_output(&path)?;
if file.metadata()?.is_file() {
imp::reject_multiple_links(&file)?;
}
Ok(Self {
file,
destination: Destination::Path(path),
})
}
/// Whether the caller explicitly selected the inherited standard output stream.
pub fn is_stdout(&self) -> bool {
matches!(self.destination, Destination::Stream { is_stdout: true })
}
pub fn write(mut self, contents: &[u8]) -> io::Result<()> {
use std::io::Write;
if let Destination::Path(path) = &self.destination {
imp::verify_output_path(&self.file, path)?;
if self.file.metadata()?.is_file() {
imp::reject_multiple_links(&self.file)?;
self.file.set_len(0)?;
}
}
self.file.write_all(contents)?;
// A caller may reopen the pathname after a successful exit. Detect a visible swap.
if let Destination::Path(path) = &self.destination {
imp::verify_output_path(&self.file, path)?;
}
Ok(())
}
}
pub(crate) fn open_file(path: &Path) -> io::Result<std::fs::File> {
imp::open_file_sync(path)
}
pub(crate) async fn write_file(path: &Path, contents: Vec<u8>) -> io::Result<()> {
imp::write_file(path.to_path_buf(), contents).await
}
#[cfg(unix)]
pub(crate) async fn metadata(path: &Path) -> io::Result<FileMetadata> {
imp::metadata(path.to_path_buf()).await
}
#[cfg(windows)]
pub(crate) async fn metadata(path: &Path) -> io::Result<FileMetadata> {
imp::metadata(path.to_path_buf())
.await
.map(|metadata| FileMetadata {
is_directory: metadata.is_dir(),
is_file: metadata.is_file(),
is_symlink: false,
size: metadata.len(),
created_at_ms: metadata.created().ok().map_or(0, system_time_to_unix_ms),
modified_at_ms: metadata.modified().ok().map_or(0, system_time_to_unix_ms),
})
}
#[cfg(windows)]
fn system_time_to_unix_ms(time: SystemTime) -> i64 {
time.duration_since(UNIX_EPOCH)
.ok()
.and_then(|duration| i64::try_from(duration.as_millis()).ok())
.unwrap_or(0)
}
pub(crate) async fn create_directory(path: &Path, recursive: bool) -> io::Result<()> {
imp::create_directory(path.to_path_buf(), recursive).await
}
pub(crate) async fn remove(path: &Path, recursive: bool, force: bool) -> io::Result<()> {
imp::remove(path.to_path_buf(), recursive, force).await
}
#[cfg(test)]
mod output_tests {
//! Exercise the destination as a caller of the final-message writer.
use super::BoundOutput;
use pretty_assertions::assert_eq;
use std::fs;
#[test]
fn regular_output_is_truncated_only_when_written() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("message");
fs::write(&path, "old message")?;
let output = BoundOutput::open(&path)?;
assert_eq!(fs::read_to_string(&path)?, "old message");
output.write(b"new")?;
assert_eq!(fs::read_to_string(&path)?, "new");
Ok(())
}
#[cfg(unix)]
#[test]
fn rejects_added_links_and_replaced_paths_before_writing() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("message");
fs::write(&path, "new")?;
let output = BoundOutput::open(&path)?;
let alias = dir.path().join("alias");
fs::hard_link(&path, &alias)?;
assert!(BoundOutput::open(&alias).is_err());
assert!(output.write(b"overwritten").is_err());
assert_eq!(fs::read(&alias)?, b"new");
fs::remove_file(&alias)?;
let output = BoundOutput::open(&path)?;
fs::rename(&path, &alias)?;
fs::write(&path, "replacement")?;
assert!(output.write(b"overwritten").is_err());
assert_eq!(fs::read(&path)?, b"replacement");
assert_eq!(fs::read(&alias)?, b"new");
Ok(())
}
#[cfg(windows)]
#[test]
fn windows_output_binds_the_chosen_stream_until_write() -> std::io::Result<()> {
use std::os::windows::fs::OpenOptionsExt;
use windows_sys::Win32::Foundation::ERROR_SHARING_VIOLATION;
use windows_sys::Win32::Storage::FileSystem::DELETE;
let dir = tempfile::tempdir()?;
let base = dir.path().join("message");
fs::write(&base, "base")?;
let fs_name = super::windows::filesystem_name(&fs::File::open(&base)?)?;
let ntfs = fs_name.eq_ignore_ascii_case("NTFS");
let sibling = dir.path().join("message:sibling");
if ntfs {
fs::write(&sibling, "keep")?;
let alias = dir.path().join("alias");
fs::hard_link(&base, &alias)?;
assert!(BoundOutput::open(&base).is_err());
fs::remove_file(alias)?;
}
let names: &[&str] = if ntfs {
&[
"message",
"message::$DATA",
"message:answer",
"message:answer:$DATA",
]
} else {
&["message"]
};
for name in names {
let path = dir.path().join(name);
fs::write(&base, "base")?;
fs::write(&path, "previous contents")?;
let open_for_rename = || fs::OpenOptions::new().access_mode(DELETE).open(&path);
let rename_handle = open_for_rename()?;
assert!(
matches!(BoundOutput::open(&path), Err(e) if e.raw_os_error() == Some(ERROR_SHARING_VIOLATION as i32))
);
drop(rename_handle);
let output = BoundOutput::open(&path)?;
assert!(
matches!(open_for_rename(), Err(e) if e.raw_os_error() == Some(ERROR_SHARING_VIOLATION as i32))
);
output.write(b"done")?;
assert_eq!(fs::read(&path)?, b"done");
drop(open_for_rename()?);
if name.starts_with("message:answer") {
assert_eq!(fs::read(&base)?, b"base");
}
if ntfs {
assert_eq!(fs::read(&sibling)?, b"keep");
}
}
Ok(())
}
#[cfg(windows)]
#[test]
fn nul_discards_output_without_accepting_other_devices() -> std::io::Result<()> {
for name in ["NUL", "nul", r"\\.\NUL"] {
BoundOutput::open(name.as_ref())?.write(b"discarded")?;
}
assert!(BoundOutput::open(r"\\.\CON".as_ref()).is_err());
Ok(())
}
#[cfg(windows)]
#[test]
fn unavailable_full_ids_use_directory_entries_only_on_fat_volumes() -> std::io::Result<()> {
use windows_sys::Win32::Foundation::ERROR_INVALID_PARAMETER;
let dir = tempfile::tempdir()?;
let path = dir.path().join("message");
let output = BoundOutput::open(&path)?;
let other = dir.path().join("other");
fs::write(&other, "other")?;
// Legacy IDs on a ReFS temp volume are not a valid stand-in for FAT directory entries.
let host = super::windows::filesystem_name(&output.file)?;
let legacy_fixture = ["NTFS", "FAT", "FAT32", "exFAT"]
.iter()
.any(|name| host.eq_ignore_ascii_case(name));
let verify = |candidate: &std::path::Path, volume: &str, named: Option<&str>| {
super::windows::verify_output_path_with(
&output.file,
candidate,
|_| {
Err(std::io::Error::from_raw_os_error(
ERROR_INVALID_PARAMETER as i32,
))
},
|file| {
if std::ptr::eq(file, &output.file) {
return Ok(volume.to_owned());
}
named
.map(str::to_owned)
.ok_or(std::io::ErrorKind::Unsupported.into())
},
)
};
for volume in ["FAT", "FAT32", "exFAT"] {
// Reaching the second volume query proves the first one selected the fallback.
assert!(
matches!(verify(&path, volume, None), Err(e) if e.kind() == std::io::ErrorKind::Unsupported)
);
if legacy_fixture {
verify(&path, volume, Some(volume))?;
assert!(verify(&other, volume, Some(volume)).is_err());
}
}
for (bound, named) in [("ReFS", "exFAT"), ("exFAT", "ReFS")] {
assert!(
matches!(verify(&path, bound, Some(named)), Err(e) if e.raw_os_error() == Some(ERROR_INVALID_PARAMETER as i32))
);
}
Ok(())
}
#[cfg(windows)]
#[test]
#[ignore = "requires CODEX_TEST_EXFAT_DIR on a writable exFAT volume"]
fn writes_on_exfat() -> anyhow::Result<()> {
let dir = tempfile::tempdir_in(std::env::var("CODEX_TEST_EXFAT_DIR")?)?;
let path = dir.path().join("message");
fs::write(&path, "previous message")?;
assert!(
super::windows::filesystem_name(&fs::File::open(&path)?)?.eq_ignore_ascii_case("exFAT")
);
BoundOutput::open(&path)?.write(b"done")?;
assert_eq!(fs::read(&path)?, b"done");
Ok(())
}
#[cfg(unix)]
#[test]
fn output_only_accepts_leading_parent_components() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
fs::create_dir_all(dir.path().join("a/b"))?;
let path = dir.path().join("a/b/../../message");
assert!(
matches!(BoundOutput::open(&path), Err(e) if e.kind() == std::io::ErrorKind::InvalidInput)
);
assert!(!dir.path().join("message").exists());
let mut expected = std::env::current_dir()?;
expected.pop();
assert_eq!(
super::unix::output_path("./../message".as_ref())?,
expected.join("message")
);
Ok(())
}
#[cfg(unix)]
#[test]
fn writes_fifo_device_and_inherited_pipe() -> anyhow::Result<()> {
use std::io::Read;
use std::os::fd::AsRawFd;
use std::os::unix::fs::OpenOptionsExt;
let dir = tempfile::tempdir()?;
let fifo = dir.path().join("pipe");
assert!(
std::process::Command::new("mkfifo")
.arg(&fifo)
.status()?
.success()
);
let mut reader = fs::OpenOptions::new()
.read(true)
.custom_flags(libc::O_NONBLOCK)
.open(&fifo)?;
BoundOutput::open(&fifo)?.write(b"fifo")?;
let mut buf = [0; 4];
reader.read_exact(&mut buf)?;
assert_eq!(buf, *b"fifo");
BoundOutput::open(std::path::Path::new("/dev/null"))?.write(b"device")?;
let stdout = BoundOutput::open(std::path::Path::new("/dev/stdout"))?;
assert!(stdout.is_stdout());
let read_only = rustix::io::dup(&reader)?;
let alias = format!("/dev/fd/{}", read_only.as_raw_fd());
assert!(
matches!(BoundOutput::open(alias.as_ref()), Err(e) if e.kind() == std::io::ErrorKind::InvalidInput)
);
let writer = fs::OpenOptions::new().write(true).open(&fifo)?;
// Match the inheritable pipe descriptor passed by shell process substitution.
let inherited = rustix::io::dup(&writer)?;
let alias = format!("/dev/fd/{}", inherited.as_raw_fd());
BoundOutput::open(alias.as_ref())?.write(b"pipe")?;
reader.read_exact(&mut buf)?;
assert_eq!(buf, *b"pipe");
Ok(())
}
}

View File

@@ -0,0 +1,432 @@
use crate::FileMetadata;
use rustix::fs::AtFlags;
use rustix::fs::Mode;
use rustix::fs::OFlags;
use rustix::fs::Stat;
#[cfg(target_os = "linux")]
use rustix::fs::Statx;
#[cfg(target_os = "linux")]
use rustix::fs::StatxFlags;
use rustix::fs::fstat;
use rustix::fs::mkdirat;
use rustix::fs::open;
use rustix::fs::openat;
use rustix::fs::statat;
#[cfg(target_os = "linux")]
use rustix::fs::statx;
use rustix::fs::unlinkat;
use std::ffi::OsString;
use std::io;
use std::io::Write;
use std::os::fd::OwnedFd;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
#[cfg(any(target_os = "linux", target_os = "android"))]
fn directory_access_flags() -> OFlags {
OFlags::PATH
}
#[cfg(target_vendor = "apple")]
fn directory_access_flags() -> OFlags {
OFlags::from_bits_retain(libc::O_SEARCH as u32)
}
#[cfg(not(any(target_os = "linux", target_os = "android", target_vendor = "apple")))]
fn directory_access_flags() -> OFlags {
OFlags::RDONLY
}
fn components(path: &Path) -> io::Result<Vec<OsString>> {
if !path.is_absolute() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"no-follow filesystem operations require an absolute path",
));
}
path.components()
.filter_map(|component| match component {
Component::RootDir => None,
Component::Normal(component) => Some(Ok(component.to_os_string())),
Component::CurDir | Component::ParentDir | Component::Prefix(_) => {
Some(Err(io::Error::new(
io::ErrorKind::InvalidInput,
"no-follow filesystem operations require a normalized path",
)))
}
})
.collect()
}
fn root() -> io::Result<OwnedFd> {
open(
"/",
directory_access_flags() | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)
.map_err(io::Error::from)
}
fn open_directory(parent: &OwnedFd, name: &std::ffi::OsStr) -> io::Result<OwnedFd> {
openat(
parent,
name,
directory_access_flags() | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
)
.map_err(io::Error::from)
}
fn parent(path: &Path) -> io::Result<(OwnedFd, OsString)> {
let mut components = components(path)?;
let leaf = components
.pop()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path must name an entry"))?;
let mut directory = root()?;
for component in components {
directory = open_directory(&directory, &component)?;
}
Ok((directory, leaf))
}
pub(super) fn inherited_output(path: &Path) -> io::Result<Option<super::BoundOutput>> {
use std::os::fd::FromRawFd;
let name = path.to_str().unwrap_or_default();
let fd = match name {
"/dev/stdout" => libc::STDOUT_FILENO,
"/dev/stderr" => libc::STDERR_FILENO,
_ => {
let number = name
.strip_prefix("/dev/fd/")
.or_else(|| name.strip_prefix("/proc/self/fd/"));
let Some(fd) = number
.filter(|s| s.bytes().all(|b| b.is_ascii_digit()))
.and_then(|s| s.parse().ok())
else {
return Ok(None);
};
fd
}
};
// Only caller-supplied descriptors may be selected, including shell process substitution.
// SAFETY: fcntl validates the integer descriptor; F_DUPFD_CLOEXEC returns a new owned fd.
let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
if flags < 0 {
return Err(io::Error::last_os_error());
}
if flags & libc::FD_CLOEXEC != 0 {
return Err(super::invalid_output("output descriptor is not inherited"));
}
let copy = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 3) };
if copy < 0 {
return Err(io::Error::last_os_error());
}
let file = unsafe { std::fs::File::from_raw_fd(copy) };
let access = rustix::fs::fcntl_getfl(&file)? & OFlags::ACCMODE;
if !matches!(access, OFlags::WRONLY | OFlags::RDWR) {
return Err(super::invalid_output("output descriptor is not writable"));
}
Ok(Some(super::BoundOutput {
file,
destination: super::Destination::Stream {
is_stdout: fd == libc::STDOUT_FILENO,
},
}))
}
pub(super) fn reject_multiple_links(file: &std::fs::File) -> io::Result<()> {
use std::os::unix::fs::MetadataExt;
if file.metadata()?.nlink() > 1 {
return Err(super::invalid_output("output has multiple hard links"));
}
Ok(())
}
pub(super) fn output_path(path: &Path) -> io::Result<PathBuf> {
// Resolve leading ".." against the caller's cwd, never against a movable directory fd.
let mut suffix = path.strip_prefix(".").unwrap_or(path);
let mut base = if suffix.is_absolute() {
PathBuf::new()
} else {
std::env::current_dir()?
};
while let Ok(rest) = suffix.strip_prefix("..") {
base.pop();
suffix = rest;
}
let path = base.join(suffix);
#[cfg(target_os = "macos")]
{
// Expand one known root link only. Never canonicalize its target or the caller's suffix.
if let Some(physical) = ["tmp", "var", "etc"].into_iter().find_map(|name| {
let root = Path::new("/").join(name);
let suffix = path.strip_prefix(&root).ok()?;
let expected = Path::new("private").join(name);
(std::fs::read_link(root).ok()? == expected)
.then(|| Path::new("/").join(expected).join(suffix))
}) {
return Ok(physical);
}
}
Ok(path)
}
pub(super) fn verify_output_path(file: &std::fs::File, path: &Path) -> io::Result<()> {
let (dir, leaf) = parent(path)?;
let named = statat(dir, leaf, AtFlags::SYMLINK_NOFOLLOW)?;
let bound = fstat(file)?;
if (named.st_dev, named.st_ino) != (bound.st_dev, bound.st_ino) {
return Err(super::invalid_output("output path was replaced"));
}
Ok(())
}
pub(super) fn open_output(path: &Path) -> io::Result<std::fs::File> {
let (directory, leaf) = parent(path)?;
let file = open_writable(&directory, &leaf)?;
if !file.metadata()?.is_file() {
let flags = rustix::fs::fcntl_getfl(&file)?;
rustix::fs::fcntl_setfl(&file, flags & !OFlags::NONBLOCK)?;
}
Ok(file)
}
// Opening the leaf must not truncate it or hang on a FIFO without a reader.
fn open_writable(directory: &OwnedFd, leaf: &std::ffi::OsStr) -> io::Result<std::fs::File> {
let file = openat(
directory,
leaf,
OFlags::WRONLY
| OFlags::CREATE
| OFlags::NOFOLLOW
| OFlags::CLOEXEC
| OFlags::NOCTTY
| OFlags::NONBLOCK,
Mode::from_raw_mode(0o666),
)?;
Ok(std::fs::File::from(file))
}
fn open_entry_sync(path: &Path) -> io::Result<std::fs::File> {
let (parent, leaf) = parent(path)?;
let file = openat(
&parent,
leaf,
OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
Mode::empty(),
)
.map_err(io::Error::from)?;
Ok(std::fs::File::from(file))
}
pub(super) fn open_file_sync(path: &Path) -> io::Result<std::fs::File> {
let file = open_entry_sync(path)?;
if !file.metadata()?.is_file() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"path is not a regular file",
));
}
Ok(file)
}
pub(super) async fn write_file(path: PathBuf, contents: Vec<u8>) -> io::Result<()> {
tokio::task::spawn_blocking(move || {
let (directory, leaf) = parent(&path)?;
let mut file = open_writable(&directory, &leaf)?;
if !file.metadata()?.is_file() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"path is not a regular file",
));
}
file.set_len(0)?;
file.write_all(&contents)
})
.await
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
}
fn metadata_sync(path: &Path) -> io::Result<FileMetadata> {
let components = components(path)?;
#[cfg(target_os = "linux")]
{
let (parent, leaf, flags) = if components.is_empty() {
(root()?, OsString::new(), AtFlags::EMPTY_PATH)
} else {
let (parent, leaf) = parent(path)?;
(parent, leaf, AtFlags::SYMLINK_NOFOLLOW)
};
let metadata = statx(
&parent,
&leaf,
flags,
StatxFlags::BASIC_STATS | StatxFlags::BTIME,
);
match metadata {
Ok(metadata) => file_metadata_linux(metadata),
Err(error) if error == rustix::io::Errno::NOSYS || error == rustix::io::Errno::PERM => {
let metadata = if components.is_empty() {
fstat(&parent)
} else {
statat(&parent, &leaf, AtFlags::SYMLINK_NOFOLLOW)
}
.map_err(io::Error::from)?;
file_metadata(metadata, /*created_at_ms*/ 0)
}
Err(error) => Err(io::Error::from(error)),
}
}
#[cfg(not(target_os = "linux"))]
if components.is_empty() {
let root = root()?;
let metadata = fstat(&root).map_err(io::Error::from)?;
let created_at_ms = created_at_ms(&metadata);
file_metadata(metadata, created_at_ms)
} else {
let (parent, leaf) = parent(path)?;
let metadata =
statat(&parent, &leaf, AtFlags::SYMLINK_NOFOLLOW).map_err(io::Error::from)?;
let created_at_ms = created_at_ms(&metadata);
file_metadata(metadata, created_at_ms)
}
}
#[cfg(target_os = "linux")]
fn file_metadata_linux(metadata: Statx) -> io::Result<FileMetadata> {
let kind = u32::from(metadata.stx_mode) & libc::S_IFMT;
if kind == libc::S_IFLNK {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"path contains a symbolic link",
));
}
let created_at_ms = if metadata.stx_mask & StatxFlags::BTIME.bits() == 0 {
0
} else {
unix_time_ms(metadata.stx_btime.tv_sec, metadata.stx_btime.tv_nsec)
};
Ok(FileMetadata {
is_directory: kind == libc::S_IFDIR,
is_file: kind == libc::S_IFREG,
is_symlink: false,
size: metadata.stx_size,
created_at_ms,
modified_at_ms: unix_time_ms(metadata.stx_mtime.tv_sec, metadata.stx_mtime.tv_nsec),
})
}
fn file_metadata(metadata: Stat, created_at_ms: i64) -> io::Result<FileMetadata> {
let kind = metadata.st_mode & libc::S_IFMT;
if kind == libc::S_IFLNK {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"path contains a symbolic link",
));
}
Ok(FileMetadata {
is_directory: kind == libc::S_IFDIR,
is_file: kind == libc::S_IFREG,
is_symlink: false,
size: u64::try_from(metadata.st_size).unwrap_or(0),
created_at_ms,
modified_at_ms: unix_time_ms(metadata.st_mtime, metadata.st_mtime_nsec),
})
}
#[cfg(target_vendor = "apple")]
fn created_at_ms(metadata: &Stat) -> i64 {
unix_time_ms(metadata.st_birthtime, metadata.st_birthtime_nsec)
}
#[cfg(not(any(target_vendor = "apple", target_os = "linux")))]
fn created_at_ms(_metadata: &Stat) -> i64 {
0
}
fn unix_time_ms(seconds: i64, nanoseconds: impl TryInto<i64>) -> i64 {
let nanoseconds = nanoseconds.try_into().unwrap_or_default();
seconds
.saturating_mul(1_000)
.saturating_add(nanoseconds / 1_000_000)
}
pub(super) async fn metadata(path: PathBuf) -> io::Result<FileMetadata> {
tokio::task::spawn_blocking(move || metadata_sync(&path))
.await
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
}
pub(super) async fn create_directory(path: PathBuf, recursive: bool) -> io::Result<()> {
tokio::task::spawn_blocking(move || {
let components = components(&path)?;
if components.is_empty() && !recursive {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"directory already exists",
));
}
let mut directory = root()?;
for (index, component) in components.iter().enumerate() {
let is_leaf = index + 1 == components.len();
if !recursive && is_leaf {
mkdirat(&directory, component, Mode::from_raw_mode(0o777))
.map_err(io::Error::from)?;
return Ok(());
}
match open_directory(&directory, component) {
Ok(next) => directory = next,
Err(error) if recursive && error.kind() == io::ErrorKind::NotFound => {
match mkdirat(&directory, component, Mode::from_raw_mode(0o777)) {
Ok(()) | Err(rustix::io::Errno::EXIST) => {}
Err(error) => return Err(io::Error::from(error)),
}
directory = open_directory(&directory, component)?;
}
Err(error) => return Err(error),
}
}
Ok(())
})
.await
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
}
pub(super) async fn remove(path: PathBuf, recursive: bool, force: bool) -> io::Result<()> {
tokio::task::spawn_blocking(move || {
if recursive {
return Err(io::Error::new(
io::ErrorKind::Unsupported,
"recursive no-follow removal is unsupported",
));
}
let (parent, leaf) = match parent(&path) {
Ok(value) => value,
Err(error) if force && error.kind() == io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error),
};
let metadata = match statat(&parent, &leaf, AtFlags::SYMLINK_NOFOLLOW) {
Ok(metadata) => metadata,
Err(error) if force && error == rustix::io::Errno::NOENT => return Ok(()),
Err(error) => return Err(io::Error::from(error)),
};
let kind = metadata.st_mode & libc::S_IFMT;
if kind == libc::S_IFLNK {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"path contains a symbolic link",
));
}
let flags = if kind == libc::S_IFDIR {
AtFlags::REMOVEDIR
} else {
AtFlags::empty()
};
unlinkat(&parent, leaf, flags).map_err(io::Error::from)
})
.await
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
}

View File

@@ -0,0 +1,535 @@
use crate::regular_file;
use std::ffi::OsStr;
use std::ffi::c_void;
use std::io;
use std::io::Write;
use std::mem::size_of;
use std::mem::size_of_val;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use std::path::Prefix;
use std::ptr;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
use windows_sys::Win32::Foundation::NTSTATUS;
use windows_sys::Win32::Foundation::OBJ_CASE_INSENSITIVE;
use windows_sys::Win32::Foundation::OBJ_DONT_REPARSE;
use windows_sys::Win32::Foundation::RtlNtStatusToDosError;
use windows_sys::Win32::Foundation::UNICODE_STRING;
use windows_sys::Win32::Security::SECURITY_QUALITY_OF_SERVICE;
use windows_sys::Win32::Security::SecurityIdentification;
use windows_sys::Win32::Storage::FileSystem::BY_HANDLE_FILE_INFORMATION;
use windows_sys::Win32::Storage::FileSystem::DELETE;
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_NORMAL;
use windows_sys::Win32::Storage::FileSystem::FILE_DISPOSITION_INFO;
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_READ;
use windows_sys::Win32::Storage::FileSystem::FILE_ID_INFO;
use windows_sys::Win32::Storage::FileSystem::FILE_READ_ATTRIBUTES;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_DELETE;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
use windows_sys::Win32::Storage::FileSystem::FILE_WRITE_DATA;
use windows_sys::Win32::Storage::FileSystem::FileDispositionInfo;
use windows_sys::Win32::Storage::FileSystem::FileIdInfo;
use windows_sys::Win32::Storage::FileSystem::GetFileInformationByHandle;
use windows_sys::Win32::Storage::FileSystem::GetFileInformationByHandleEx;
use windows_sys::Win32::Storage::FileSystem::GetVolumeInformationByHandleW;
use windows_sys::Win32::Storage::FileSystem::SetFileInformationByHandle;
use windows_sys::Win32::System::IO::IO_STATUS_BLOCK;
use windows_sys::Win32::System::IO::IO_STATUS_BLOCK_0;
#[path = "windows_volume_fallback.rs"]
mod volume_fallback;
const SHARE_ALL: u32 = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
const FILE_DIRECTORY_FILE: u32 = 0x0000_0001;
const FILE_SYNCHRONOUS_IO_NONALERT: u32 = 0x0000_0020;
const FILE_NON_DIRECTORY_FILE: u32 = 0x0000_0040;
const FILE_OPEN: u32 = 1;
const FILE_CREATE: u32 = 2;
const FILE_OPEN_IF: u32 = 3;
const SYNCHRONIZE_ACCESS: u32 = 0x0010_0000;
const STATUS_REPARSE_POINT_ENCOUNTERED: NTSTATUS = 0xC000_050B_u32 as i32;
const SECURITY_STATIC_TRACKING: u8 = 0;
#[repr(C)]
struct ObjectAttributes {
length: u32,
root_directory: HANDLE,
object_name: *const UNICODE_STRING,
attributes: u32,
security_descriptor: *const c_void,
security_quality_of_service: *const c_void,
}
#[link(name = "ntdll")]
unsafe extern "system" {
fn NtCreateFile(
file_handle: *mut HANDLE,
desired_access: u32,
object_attributes: *const ObjectAttributes,
io_status_block: *mut IO_STATUS_BLOCK,
allocation_size: *const i64,
file_attributes: u32,
share_access: u32,
create_disposition: u32,
create_options: u32,
ea_buffer: *const c_void,
ea_length: u32,
) -> NTSTATUS;
}
fn nt_path(path: &Path) -> io::Result<Vec<u16>> {
if !path.is_absolute() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"no-follow filesystem operations require an absolute path",
));
}
let (prefix, source_offset) = match path.components().next() {
Some(Component::Prefix(prefix)) => match prefix.kind() {
Prefix::Disk(_) => ("\\??\\", 0),
Prefix::VerbatimDisk(_) => ("\\??\\", 4),
Prefix::UNC(_, _) => ("\\??\\UNC\\", 2),
Prefix::VerbatimUNC(_, _) => ("\\??\\UNC\\", 8),
_ => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"no-follow filesystem operations require a local disk or UNC path",
));
}
},
_ => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"no-follow filesystem operations require an absolute Windows path",
));
}
};
let mut result: Vec<u16> = OsStr::new(prefix).encode_wide().collect();
result.extend(
path.as_os_str()
.encode_wide()
.skip(source_offset)
.map(|unit| {
if unit == b'/' as u16 {
b'\\' as u16
} else {
unit
}
}),
);
result.push(0);
Ok(result)
}
fn open_handle(
path: &Path,
desired_access: u32,
create_disposition: u32,
create_options: u32,
) -> io::Result<OwnedHandle> {
open_handle_with_sharing(
path,
desired_access,
create_disposition,
create_options,
SHARE_ALL,
)
}
fn open_handle_with_sharing(
path: &Path,
desired_access: u32,
create_disposition: u32,
create_options: u32,
share_access: u32,
) -> io::Result<OwnedHandle> {
let mut name = nt_path(path)?;
if let Some(handle) = open_nt_handle(
&mut name,
/*root_directory*/ None,
desired_access,
create_disposition,
create_options,
OBJ_DONT_REPARSE,
share_access,
)? {
return Ok(handle);
}
// Windows 10 also rejects the DOS drive alias itself. Only for drive-letter
// paths, open its verified volume root and keep strict checks below it.
if matches!(path.components().next(), Some(Component::Prefix(prefix))
if matches!(prefix.kind(), Prefix::Disk(_) | Prefix::VerbatimDisk(_)))
{
return volume_fallback::open_relative_to_volume(
&mut name,
desired_access,
create_disposition,
create_options,
share_access,
);
}
Err(reparse_error())
}
fn reparse_error() -> io::Error {
io::Error::new(io::ErrorKind::InvalidInput, "path contains a reparse point")
}
/// Returns `None` only for the native reparse status; other errors propagate.
fn open_nt_handle(
path: &mut [u16],
root_directory: Option<&OwnedHandle>,
desired_access: u32,
create_disposition: u32,
create_options: u32,
attributes: u32,
share_access: u32,
) -> io::Result<Option<OwnedHandle>> {
let maximum_length = u16::try_from(size_of_val(path))
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "filesystem path is too long"))?;
let object_name = UNICODE_STRING {
Length: maximum_length - size_of::<u16>() as u16,
MaximumLength: maximum_length,
Buffer: path.as_mut_ptr(),
};
let security_quality_of_service = SECURITY_QUALITY_OF_SERVICE {
Length: size_of::<SECURITY_QUALITY_OF_SERVICE>() as u32,
ImpersonationLevel: SecurityIdentification,
ContextTrackingMode: SECURITY_STATIC_TRACKING,
EffectiveOnly: true,
};
let object_attributes = ObjectAttributes {
length: size_of::<ObjectAttributes>() as u32,
root_directory: root_directory.map_or(ptr::null_mut(), AsRawHandle::as_raw_handle),
object_name: &object_name,
attributes: OBJ_CASE_INSENSITIVE | attributes,
security_descriptor: ptr::null(),
security_quality_of_service: (&raw const security_quality_of_service).cast(),
};
let mut io_status_block = IO_STATUS_BLOCK {
Anonymous: IO_STATUS_BLOCK_0 { Status: 0 },
Information: 0,
};
let mut handle = ptr::null_mut();
let status = unsafe {
NtCreateFile(
&mut handle,
desired_access | SYNCHRONIZE_ACCESS,
&object_attributes,
&mut io_status_block,
ptr::null(),
FILE_ATTRIBUTE_NORMAL,
share_access,
create_disposition,
create_options | FILE_SYNCHRONOUS_IO_NONALERT,
ptr::null(),
/*ea_length*/ 0,
)
};
if status == STATUS_REPARSE_POINT_ENCOUNTERED {
return Ok(None);
}
if status < 0 {
let code = unsafe { RtlNtStatusToDosError(status) };
return Err(io::Error::from_raw_os_error(code as i32));
}
if handle.is_null() || handle == INVALID_HANDLE_VALUE {
return Err(io::Error::other(
"NtCreateFile returned an invalid filesystem handle",
));
}
Ok(Some(unsafe { OwnedHandle::from_raw_handle(handle) }))
}
fn open_entry(path: &Path) -> io::Result<std::fs::File> {
let handle = open_handle(
path,
FILE_READ_ATTRIBUTES,
FILE_OPEN,
/*create_options*/ 0,
)?;
Ok(std::fs::File::from(handle))
}
pub(super) fn open_file_sync(path: &Path) -> io::Result<std::fs::File> {
let handle = open_handle(path, FILE_GENERIC_READ, FILE_OPEN, FILE_NON_DIRECTORY_FILE)?;
let file = std::fs::File::from(handle);
validate_regular_file(&file, path)?;
Ok(file)
}
fn validate_regular_file(file: &std::fs::File, path: &Path) -> io::Result<()> {
if !regular_file::is_disk_file(file) || !file.metadata()?.is_file() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("path `{}` is not a file", path.display()),
));
}
Ok(())
}
fn file_information(file: &std::fs::File) -> io::Result<BY_HANDLE_FILE_INFORMATION> {
let mut info = std::mem::MaybeUninit::uninit();
// SAFETY: the file owns the handle and a successful call initializes info.
if unsafe { GetFileInformationByHandle(file.as_raw_handle(), info.as_mut_ptr()) } == 0 {
return Err(io::Error::last_os_error());
}
Ok(unsafe { info.assume_init() })
}
pub(super) fn reject_multiple_links(file: &std::fs::File) -> io::Result<()> {
if file_information(file)?.nNumberOfLinks > 1 {
return Err(super::invalid_output("output has multiple hard links"));
}
Ok(())
}
fn file_identity(file: &std::fs::File) -> io::Result<(u64, [u8; 16])> {
// ReFS requires the full 128-bit identifier to distinguish files on the same volume.
let mut info = std::mem::MaybeUninit::<FILE_ID_INFO>::uninit();
// SAFETY: the open handle is valid and FileIdInfo fills this exact structure on success.
if unsafe {
GetFileInformationByHandleEx(
file.as_raw_handle(),
FileIdInfo,
info.as_mut_ptr().cast(),
size_of::<FILE_ID_INFO>() as u32,
)
} == 0
{
return Err(io::Error::last_os_error());
}
let info = unsafe { info.assume_init() };
// A filesystem may report success with an all-zero ID when it cannot identify the file.
if info.FileId.Identifier == [0; 16] {
return Err(super::invalid_output(
"filesystem did not provide an output file ID",
));
}
Ok((info.VolumeSerialNumber, info.FileId.Identifier))
}
pub(super) fn verify_output_path(file: &std::fs::File, path: &Path) -> io::Result<()> {
verify_output_path_with(file, path, file_identity, filesystem_name)
}
pub(super) fn verify_output_path_with(
file: &std::fs::File,
path: &Path,
file_id: impl Fn(&std::fs::File) -> io::Result<(u64, [u8; 16])>,
volume_name: impl Fn(&std::fs::File) -> io::Result<String>,
) -> io::Result<()> {
let current = open_entry(path)?;
let same = match file_id(file) {
Ok(id) => id == file_id(&current)?,
Err(error) => {
let is_fat = |name: String| {
["FAT", "FAT32", "exFAT"]
.iter()
.any(|fs| name.eq_ignore_ascii_case(fs))
};
if !is_fat(volume_name(file)?) || !is_fat(volume_name(&current)?) {
return Err(error);
}
same_fat_file(file, &current)?
}
};
if !same {
return Err(super::invalid_output("output path was replaced"));
}
Ok(())
}
pub(super) fn filesystem_name(file: &std::fs::File) -> io::Result<String> {
let mut name = [0u16; 32];
// SAFETY: only the filesystem name is requested, in the supplied writable buffer.
if unsafe {
GetVolumeInformationByHandleW(
file.as_raw_handle(),
ptr::null_mut(),
/*nvolumenamesize*/ 0,
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
name.as_mut_ptr(),
name.len() as u32,
)
} == 0
{
return Err(io::Error::last_os_error());
}
let name = name.split(|unit| *unit == 0).next().unwrap_or_default();
Ok(String::from_utf16_lossy(name))
}
fn same_fat_file(file: &std::fs::File, current: &std::fs::File) -> io::Result<bool> {
// The bound output denies delete sharing, so its FAT directory slot cannot be recycled.
let id = |file| -> io::Result<_> {
let info = file_information(file)?;
if info.nFileIndexHigh == 0 && info.nFileIndexLow == 0 {
return Err(super::invalid_output(
"filesystem did not provide an output file ID",
));
}
Ok((
info.dwVolumeSerialNumber,
info.nFileIndexHigh,
info.nFileIndexLow,
))
};
Ok(id(file)? == id(current)?)
}
pub(super) fn open_null_output() -> io::Result<std::fs::File> {
// Use the kernel null device directly so no user-controlled DOS alias is followed.
let mut name: Vec<_> = r"\Device\Null".encode_utf16().chain([0]).collect();
let handle = open_nt_handle(
&mut name,
/*root_directory*/ None,
FILE_WRITE_DATA,
FILE_OPEN,
/*create_options*/ 0,
OBJ_DONT_REPARSE,
SHARE_ALL,
)?
.ok_or_else(reparse_error)?;
Ok(handle.into())
}
fn open_writable_regular_file(path: &Path, share_access: u32) -> io::Result<std::fs::File> {
let handle = open_handle_with_sharing(
path,
FILE_READ_ATTRIBUTES | FILE_WRITE_DATA,
FILE_OPEN_IF,
FILE_NON_DIRECTORY_FILE,
share_access,
)?;
let file = std::fs::File::from(handle);
validate_regular_file(&file, path)?;
Ok(file)
}
pub(super) fn open_output(path: &Path) -> io::Result<std::fs::File> {
if matches!(path.components().next(), Some(Component::Prefix(p)) if p.kind().is_verbatim())
&& path.as_os_str().as_encoded_bytes().contains(&b'/')
{
return Err(super::invalid_output("invalid verbatim output path"));
}
// Full file IDs identify the base file, not a particular data stream. Keep the
// selected stream bound from the first open, including the unnamed default stream.
let file = open_writable_regular_file(path, FILE_SHARE_READ | FILE_SHARE_WRITE)?;
// Fail before starting a turn if this filesystem cannot verify the output.
verify_output_path(&file, path)?;
Ok(file)
}
pub(super) async fn write_file(path: PathBuf, contents: Vec<u8>) -> io::Result<()> {
tokio::task::spawn_blocking(move || {
let mut file = open_writable_regular_file(&path, SHARE_ALL)?;
file.set_len(0)?;
file.write_all(&contents)
})
.await
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
}
pub(super) async fn metadata(path: PathBuf) -> io::Result<std::fs::Metadata> {
tokio::task::spawn_blocking(move || open_entry(&path)?.metadata())
.await
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
}
fn create_directory_sync(path: &Path, recursive: bool) -> io::Result<()> {
if !recursive {
open_handle(path, FILE_READ_ATTRIBUTES, FILE_CREATE, FILE_DIRECTORY_FILE)?;
return Ok(());
}
let mut current = PathBuf::new();
for component in path.components() {
current.push(component.as_os_str());
if matches!(component, Component::Normal(_)) {
open_or_create_directory(&current)?;
}
}
Ok(())
}
fn open_or_create_directory(path: &Path) -> io::Result<()> {
match open_handle(path, FILE_READ_ATTRIBUTES, FILE_OPEN, FILE_DIRECTORY_FILE) {
Ok(_) => Ok(()),
Err(error) if error.kind() == io::ErrorKind::NotFound => {
match open_handle(path, FILE_READ_ATTRIBUTES, FILE_CREATE, FILE_DIRECTORY_FILE) {
Ok(_) => Ok(()),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
open_handle(path, FILE_READ_ATTRIBUTES, FILE_OPEN, FILE_DIRECTORY_FILE)?;
Ok(())
}
Err(error) => Err(error),
}
}
Err(error) => Err(error),
}
}
pub(super) async fn create_directory(path: PathBuf, recursive: bool) -> io::Result<()> {
tokio::task::spawn_blocking(move || create_directory_sync(&path, recursive))
.await
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
}
fn remove_sync(path: &Path, recursive: bool, force: bool) -> io::Result<()> {
if recursive {
return Err(io::Error::new(
io::ErrorKind::Unsupported,
"recursive no-follow removal is unsupported",
));
}
let metadata = match open_entry(path).and_then(|file| file.metadata()) {
Ok(metadata) => metadata,
Err(error) if force && error.kind() == io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error),
};
let create_options = if metadata.is_dir() {
FILE_DIRECTORY_FILE
} else {
FILE_NON_DIRECTORY_FILE
};
let handle = open_handle(path, DELETE, FILE_OPEN, create_options)?;
let disposition = FILE_DISPOSITION_INFO { DeleteFile: true };
let result = unsafe {
SetFileInformationByHandle(
handle.as_raw_handle(),
FileDispositionInfo,
(&raw const disposition).cast(),
size_of::<FILE_DISPOSITION_INFO>() as u32,
)
};
if result == 0 {
return Err(io::Error::last_os_error());
}
drop(handle);
Ok(())
}
pub(super) async fn remove(path: PathBuf, recursive: bool, force: bool) -> io::Result<()> {
tokio::task::spawn_blocking(move || remove_sync(&path, recursive, force))
.await
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
}
#[cfg(test)]
#[path = "windows_tests.rs"]
mod tests;

View File

@@ -0,0 +1,146 @@
use super::*;
use pretty_assertions::assert_eq;
use windows_sys::Win32::Foundation::ERROR_PIPE_LISTENING;
use windows_sys::Win32::Foundation::GetLastError;
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_WRITE;
use windows_sys::Win32::Storage::FileSystem::PIPE_ACCESS_DUPLEX;
use windows_sys::Win32::System::Pipes::ConnectNamedPipe;
use windows_sys::Win32::System::Pipes::CreateNamedPipeW;
use windows_sys::Win32::System::Pipes::PIPE_NOWAIT;
use windows_sys::Win32::System::Pipes::PIPE_READMODE_BYTE;
use windows_sys::Win32::System::Pipes::PIPE_TYPE_BYTE;
#[test]
fn relative_volume_opens_files_and_rejects_junctions() -> io::Result<()> {
let temp = tempfile::tempdir()?;
let real = std::fs::canonicalize(temp.path())?;
let open = |path: &Path, access, disposition, options| {
volume_fallback::open_relative_to_volume(
&mut nt_path(path)?,
access,
disposition,
options,
SHARE_ALL,
)
};
let existing = real.join("existing.txt");
std::fs::File::from(open(
&existing,
FILE_WRITE_DATA,
FILE_CREATE,
FILE_NON_DIRECTORY_FILE,
)?)
.write_all(b"updated")?;
let file = std::fs::File::from(open(
&existing,
FILE_GENERIC_READ,
FILE_OPEN,
FILE_NON_DIRECTORY_FILE,
)?);
assert_eq!(file.metadata()?.len(), 7);
let drive_root = existing.ancestors().last().expect("absolute path root");
let root = std::fs::File::from(open(
drive_root,
FILE_READ_ATTRIBUTES,
FILE_OPEN,
FILE_DIRECTORY_FILE,
)?);
assert!(root.metadata()?.is_dir());
let junction_parent = tempfile::tempdir()?;
let junction = junction_parent.path().join("junction");
let result = std::process::Command::new("cmd")
.args(["/C", "mklink", "/J"])
.arg(&junction)
.arg(&real)
.output()?;
assert!(
result.status.success(),
"{}",
String::from_utf8_lossy(&result.stderr)
);
for (path, disposition, options) in [
(junction.clone(), FILE_OPEN, FILE_DIRECTORY_FILE),
(
junction.join("existing.txt"),
FILE_OPEN,
FILE_NON_DIRECTORY_FILE,
),
(
junction.join("blocked.txt"),
FILE_CREATE,
FILE_NON_DIRECTORY_FILE,
),
] {
let error = open(&path, FILE_READ_ATTRIBUTES, disposition, options)
.expect_err("a junction must never be traversed");
assert_eq!(error.to_string(), "path contains a reparse point");
}
assert!(!real.join("blocked.txt").exists());
Ok(())
}
#[test]
fn volume_root_validation_rejects_devices_and_subdirectories() {
for (path, expected) in [
(r"\Device\HarddiskVolume1\", true),
(r"\Device\HarddiskVolume123\", true),
(r"\Device\HarddiskVolume\", false),
(r"\Device\HarddiskVolume1", false),
(r"\Device\HarddiskVolume1\workspace\", false),
(r"\Device\HarddiskVolume1x\", false),
(r"\Device\NamedPipe\", false),
(r"\Device\Mup\", false),
(r"\Device\CdRom0\", false),
] {
let path = OsStr::new(path).encode_wide().collect::<Vec<_>>();
assert_eq!(volume_fallback::is_local_volume_root(&path), expected);
}
}
#[test]
fn native_open_rejects_named_pipes_before_connecting() {
let pipe_name = format!("codex-no-follow-{}", uuid::Uuid::new_v4());
let server_path = PathBuf::from(format!(r"\\.\pipe\{pipe_name}"));
let client_path = PathBuf::from(format!(r"\\localhost\pipe\{pipe_name}"));
let wide_path = server_path
.as_os_str()
.encode_wide()
.chain(std::iter::once(0))
.collect::<Vec<_>>();
let pipe = unsafe {
CreateNamedPipeW(
wide_path.as_ptr(),
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_NOWAIT,
/*nmaxinstances*/ 1,
/*noutbuffersize*/ 1,
/*ninbuffersize*/ 1,
/*ndefaulttimeout*/ 1_000,
ptr::null(),
)
};
assert_ne!(pipe, INVALID_HANDLE_VALUE);
let _pipe = unsafe { OwnedHandle::from_raw_handle(pipe) };
// A DOS drive alias could target a pipe; the root open must reject a pipe
// before obtaining a client connection, even before final-path validation.
let mut pipe_root: Vec<_> = format!(r"\Device\NamedPipe\{pipe_name}\")
.encode_utf16()
.chain(std::iter::once(0))
.collect();
assert!(volume_fallback::open_volume_root(&mut pipe_root).is_err());
let error = open_handle(
&client_path,
FILE_GENERIC_READ | FILE_GENERIC_WRITE,
FILE_OPEN,
FILE_NON_DIRECTORY_FILE,
)
.expect_err("strict native open should reject named pipes");
assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
assert_eq!(error.to_string(), "path contains a reparse point");
assert_eq!(unsafe { ConnectNamedPipe(pipe, ptr::null_mut()) }, 0);
assert_eq!(unsafe { GetLastError() }, ERROR_PIPE_LISTENING);
}

View File

@@ -0,0 +1,77 @@
//! Retry drive-letter opens from a verified physical volume root when strict NT opens reject
//! the DOS alias. The root must be a local directory; all path components below it stay no-follow.
use super::*;
use std::os::windows::fs::MetadataExt;
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT;
use windows_sys::Win32::Storage::FileSystem::FILE_TRAVERSE;
use windows_sys::Win32::Storage::FileSystem::GetFinalPathNameByHandleW;
use windows_sys::Win32::Storage::FileSystem::VOLUME_NAME_NT;
const FILE_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
const DOS_DRIVE_ROOT_LEN: usize = r"\??\C:\".len();
pub(super) fn open_relative_to_volume(
name: &mut [u16],
desired_access: u32,
create_disposition: u32,
create_options: u32,
share_access: u32,
) -> io::Result<OwnedHandle> {
let mut root_name = name[..DOS_DRIVE_ROOT_LEN].to_vec();
root_name.push(0);
let root = open_volume_root(&mut root_name)?;
open_nt_handle(
&mut name[DOS_DRIVE_ROOT_LEN..],
Some(&root),
desired_access,
create_disposition,
create_options,
OBJ_DONT_REPARSE,
share_access,
)?
.ok_or_else(reparse_error)
}
pub(super) fn open_volume_root(name: &mut [u16]) -> io::Result<OwnedHandle> {
let handle = open_nt_handle(
name,
/*root_directory*/ None,
FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
FILE_OPEN,
FILE_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT,
/*attributes*/ 0,
SHARE_ALL,
)?
.ok_or_else(reparse_error)?;
let root = std::fs::File::from(handle);
let metadata = root.metadata()?;
if !metadata.is_dir() || metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
return Err(reparse_error());
}
let mut name = [0u16; 128];
let length = unsafe {
GetFinalPathNameByHandleW(
root.as_raw_handle(),
name.as_mut_ptr(),
name.len() as u32,
VOLUME_NAME_NT,
)
} as usize;
if length == 0 {
return Err(io::Error::last_os_error());
}
if length >= name.len() || !is_local_volume_root(&name[..length]) {
return Err(reparse_error());
}
Ok(root.into())
}
pub(super) fn is_local_volume_root(name: &[u16]) -> bool {
String::from_utf16(name).is_ok_and(|name| {
name.strip_prefix(r"\Device\HarddiskVolume")
.and_then(|suffix| suffix.strip_suffix('\\'))
.is_some_and(|number| !number.is_empty() && number.bytes().all(|b| b.is_ascii_digit()))
})
}

View File

@@ -0,0 +1,343 @@
//! Noise channel used by the remote exec-server relay.
//!
//! The harness initiates hybrid IK and pins the exec-server static key returned
//! by the registry. The first handshake message lets the exec-server authenticate
//! the harness static key; the exec-server then asks the registry whether that
//! key is authorized before opening a transport. A denied request can receive an
//! authenticated rejection without creating a transport on either peer.
//!
//! "Hybrid" means the session keys include both X25519 and ML-KEM-768 key
//! agreement. Once the two-message handshake finishes, AES-GCM protects the
//! ordered transport records carrying JSON-RPC.
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use clatter::HybridHandshake;
use clatter::HybridHandshakeParams;
use clatter::KeyPair;
use clatter::bytearray::ByteArray;
use clatter::constants::MAX_MESSAGE_LEN;
use clatter::crypto::cipher::AesGcm;
use clatter::crypto::dh::X25519;
use clatter::crypto::hash::Sha256;
use clatter::crypto::kem::rust_crypto_ml_kem::MlKem768;
use clatter::handshakepattern::noise_hybrid_ik;
use clatter::traits::Cipher;
use clatter::traits::Dh;
use clatter::traits::Handshaker;
use clatter::traits::Kem;
use clatter::transportstate::TransportState;
use serde::Deserialize;
use serde::Serialize;
/// Identifies the handshake pattern and algorithms used by this channel.
pub(crate) const NOISE_CHANNEL_SUITE: &str = "Noise_hybridIK_X25519+MLKEM768_AESGCM_SHA256";
const PROLOGUE_DOMAIN: &[u8] = b"codex-exec-server-relay-noise/v1";
const REGISTRY_AUTH_REJECTED: &[u8] = b"codex-registry-authentication-rejected/v1";
type Handshake = HybridHandshake<X25519, MlKem768, MlKem768, AesGcm, Sha256>;
type Transport = TransportState<AesGcm, Sha256>;
type DhKeyPair = KeyPair<<X25519 as Dh>::PubKey, <X25519 as Dh>::PrivateKey>;
type MlKem768PublicKey = <MlKem768 as Kem>::PubKey;
type KemKeyPair = KeyPair<<MlKem768 as Kem>::PubKey, <MlKem768 as Kem>::SecretKey>;
/// Public key material for the exec-server Noise suite.
/// The suite tag prevents keys for another protocol from being accepted just
/// because their components have the expected lengths.
#[derive(Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NoiseChannelPublicKey {
suite: String,
x25519_public_key: String,
mlkem768_public_key: String,
}
impl std::fmt::Debug for NoiseChannelPublicKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("NoiseChannelPublicKey")
.field("suite", &self.suite)
.field("x25519_public_key", &"<redacted>")
.field("mlkem768_public_key", &"<redacted>")
.finish()
}
}
impl NoiseChannelPublicKey {
/// Decode registry-provided key material before passing it to Clatter.
fn decode(&self) -> Result<(<X25519 as Dh>::PubKey, MlKem768PublicKey), NoiseChannelError> {
if self.suite != NOISE_CHANNEL_SUITE {
return Err(NoiseChannelError::InvalidPublicKey(
"unsupported Noise channel suite",
));
}
let dh = STANDARD
.decode(&self.x25519_public_key)
.map_err(|_| NoiseChannelError::InvalidPublicKey("invalid X25519 public key"))?;
let dh: <X25519 as Dh>::PubKey = dh
.try_into()
.map_err(|_| NoiseChannelError::InvalidPublicKey("invalid X25519 public key length"))?;
let kem = STANDARD
.decode(&self.mlkem768_public_key)
.map_err(|_| NoiseChannelError::InvalidPublicKey("invalid ML-KEM-768 public key"))?;
if kem.len() != MlKem768PublicKey::LENGTH {
return Err(NoiseChannelError::InvalidPublicKey(
"invalid ML-KEM-768 public key length",
));
}
Ok((dh, MlKem768PublicKey::from_slice(kem.as_slice())))
}
}
/// Static Noise identity kept for the lifetime of an executor or harness process.
#[derive(Clone)]
pub struct NoiseChannelIdentity {
dh: DhKeyPair,
kem: KemKeyPair,
}
impl NoiseChannelIdentity {
pub fn generate() -> Result<Self, NoiseChannelError> {
let dh = X25519::genkey()
.map_err(|error| NoiseChannelError::KeyGeneration(error.to_string()))?;
let kem = MlKem768::genkey()
.map_err(|error| NoiseChannelError::KeyGeneration(error.to_string()))?;
Ok(Self { dh, kem })
}
pub fn public_key(&self) -> NoiseChannelPublicKey {
NoiseChannelPublicKey {
suite: NOISE_CHANNEL_SUITE.to_string(),
x25519_public_key: STANDARD.encode(self.dh.public),
mlkem768_public_key: STANDARD.encode(self.kem.public.as_slice()),
}
}
}
/// Harness-side state between the two hybrid-IK messages.
/// Consuming it in [`Self::finish`] keeps a handshake tied to one relay stream.
pub(crate) struct InitiatorHandshake {
handshake: Handshake,
}
impl InitiatorHandshake {
/// Start hybrid IK and pin the expected executor key.
/// `payload` carries the short-lived registry authorization inside the first
/// encrypted handshake message.
pub(crate) fn start(
identity: &NoiseChannelIdentity,
responder_public_key: &NoiseChannelPublicKey,
prologue: &[u8],
payload: &[u8],
) -> Result<(Self, Vec<u8>), NoiseChannelError> {
let (responder_dh, responder_kem) = responder_public_key.decode()?;
// Both executor key components are pinned before any JSON-RPC is sent.
let params = HybridHandshakeParams::new(noise_hybrid_ik(), true)
.with_prologue(prologue)
.with_s(identity.dh.clone())
.with_s_kem(identity.kem.clone())
.with_rs(responder_dh)
.with_rs_kem(responder_kem);
let mut handshake = Handshake::new(params)?;
let overhead = handshake.get_next_message_overhead()?;
if payload.len() > MAX_MESSAGE_LEN - overhead {
return Err(NoiseChannelError::InvalidMessage(
"handshake payload is too large",
));
}
let mut output = vec![0u8; payload.len() + overhead];
let output_len = handshake.write_message(payload, &mut output)?;
output.truncate(output_len);
Ok((Self { handshake }, output))
}
/// Consume the executor response and enter transport mode.
/// Successful responses have no payload. A fixed authenticated rejection
/// fails this request without opening an application transport.
pub(crate) fn finish(mut self, response: &[u8]) -> Result<NoiseTransport, NoiseChannelError> {
ensure_noise_frame_len(response.len(), "handshake response is too large")?;
let overhead = self.handshake.get_next_message_overhead()?;
let mut payload = vec![0u8; response.len().saturating_sub(overhead)];
let payload_len = self.handshake.read_message(response, &mut payload)?;
if &payload[..payload_len] == REGISTRY_AUTH_REJECTED {
return Err(NoiseChannelError::RegistryAuthenticationRejected);
}
if payload_len != 0 {
return Err(NoiseChannelError::InvalidMessage(
"handshake response payload must be empty",
));
}
Ok(NoiseTransport {
transport: self.handshake.finalize()?,
})
}
}
/// Executor-side handshake state while harness authorization is pending.
/// This is not a usable transport until the registry accepts the authenticated
/// harness key.
pub(crate) struct PendingResponderHandshake {
handshake: Handshake,
pub(crate) initiator_public_key: NoiseChannelPublicKey,
pub(crate) payload: Vec<u8>,
}
impl PendingResponderHandshake {
/// Parse the first IK message and recover the authenticated harness key.
/// Callers must authorize that key before calling [`Self::complete`].
pub(crate) fn read_request(
identity: &NoiseChannelIdentity,
prologue: &[u8],
request: &[u8],
) -> Result<Self, NoiseChannelError> {
ensure_noise_frame_len(request.len(), "handshake request is too large")?;
let params = HybridHandshakeParams::new(noise_hybrid_ik(), false)
.with_prologue(prologue)
.with_s(identity.dh.clone())
.with_s_kem(identity.kem.clone());
let mut handshake = Handshake::new(params)?;
let overhead = handshake.get_next_message_overhead()?;
let mut payload = vec![0u8; request.len().saturating_sub(overhead)];
let payload_len = handshake.read_message(request, &mut payload)?;
// Clatter exposes this key only after the first IK message authenticates.
let remote = handshake
.get_remote_static()
.ok_or(NoiseChannelError::InvalidMessage(
"handshake request is missing initiator static key",
))?;
let initiator_public_key = NoiseChannelPublicKey {
suite: NOISE_CHANNEL_SUITE.to_string(),
x25519_public_key: STANDARD.encode(remote.dh()),
mlkem768_public_key: STANDARD.encode(remote.kem().as_slice()),
};
payload.truncate(payload_len);
Ok(Self {
handshake,
initiator_public_key,
payload,
})
}
/// Finish the handshake after the registry authorizes the harness key.
pub(crate) fn complete(mut self) -> Result<(NoiseTransport, Vec<u8>), NoiseChannelError> {
let overhead = self.handshake.get_next_message_overhead()?;
let mut response = vec![0u8; overhead];
let response_len = self.handshake.write_message(&[], &mut response)?;
response.truncate(response_len);
Ok((
NoiseTransport {
transport: self.handshake.finalize()?,
},
response,
))
}
/// Authenticate a terminal registry 401 to the harness without authorizing
/// its key or constructing a transport. Older peers reject nonempty payloads.
pub(crate) fn reject_registry_authentication(mut self) -> Result<Vec<u8>, NoiseChannelError> {
let overhead = self.handshake.get_next_message_overhead()?;
let mut response = vec![0u8; overhead + REGISTRY_AUTH_REJECTED.len()];
let response_len = self
.handshake
.write_message(REGISTRY_AUTH_REJECTED, &mut response)?;
response.truncate(response_len);
Ok(response)
}
}
/// Established channel with independent implicit send and receive nonces.
/// Relay records must be ordered before decryption, and a logical record must
/// not be encrypted again for retry.
pub(crate) struct NoiseTransport {
transport: Transport,
}
impl NoiseTransport {
/// Encrypt the next transport record.
pub(crate) fn encrypt(&mut self, plaintext: &[u8]) -> Result<Vec<u8>, NoiseChannelError> {
let frame_len = plaintext.len().checked_add(AesGcm::tag_len()).ok_or(
NoiseChannelError::InvalidMessage("transport plaintext is too large"),
)?;
ensure_noise_frame_len(frame_len, "transport plaintext is too large")?;
Ok(self.transport.send_vec(plaintext)?)
}
/// Decrypt the next ordered transport record.
pub(crate) fn decrypt(&mut self, ciphertext: &[u8]) -> Result<Vec<u8>, NoiseChannelError> {
if ciphertext.len() < AesGcm::tag_len() {
return Err(NoiseChannelError::InvalidMessage(
"transport ciphertext is too short",
));
}
ensure_noise_frame_len(ciphertext.len(), "transport ciphertext is too large")?;
Ok(self.transport.receive_vec(ciphertext)?)
}
}
/// Bind the handshake to one environment registration and relay stream.
/// Both peers include these values in the Noise transcript before processing
/// the first handshake message.
pub(crate) fn noise_channel_prologue(
environment_id: &str,
executor_registration_id: &str,
stream_id: &str,
) -> Vec<u8> {
let mut prologue = Vec::new();
append_prologue_part(&mut prologue, PROLOGUE_DOMAIN);
append_prologue_part(&mut prologue, environment_id.as_bytes());
append_prologue_part(&mut prologue, executor_registration_id.as_bytes());
append_prologue_part(&mut prologue, stream_id.as_bytes());
prologue
}
fn append_prologue_part(prologue: &mut Vec<u8>, part: &[u8]) {
// Length prefixes make component boundaries unambiguous. Raw concatenation
// would allow different identifier tuples to produce the same prologue.
let len = part.len() as u64;
prologue.extend_from_slice(&len.to_be_bytes());
prologue.extend_from_slice(part);
}
fn ensure_noise_frame_len(
frame_len: usize,
message: &'static str,
) -> Result<(), NoiseChannelError> {
if frame_len > MAX_MESSAGE_LEN {
return Err(NoiseChannelError::InvalidMessage(message));
}
Ok(())
}
#[derive(Debug, thiserror::Error)]
pub enum NoiseChannelError {
#[error("environment registry authentication rejected")]
RegistryAuthenticationRejected,
#[error("Noise channel key generation failed: {0}")]
KeyGeneration(String),
#[error("invalid Noise channel public key: {0}")]
InvalidPublicKey(&'static str),
#[error("invalid Noise channel message: {0}")]
InvalidMessage(&'static str),
#[error("Noise channel handshake failed: {0}")]
Handshake(String),
#[error("Noise channel transport failed: {0}")]
Transport(String),
}
impl From<clatter::error::HandshakeError> for NoiseChannelError {
fn from(error: clatter::error::HandshakeError) -> Self {
Self::Handshake(error.to_string())
}
}
impl From<clatter::error::TransportError> for NoiseChannelError {
fn from(error: clatter::error::TransportError) -> Self {
Self::Transport(error.to_string())
}
}
#[cfg(test)]
#[path = "noise_channel_tests.rs"]
mod tests;

View File

@@ -0,0 +1,260 @@
use pretty_assertions::assert_eq;
use super::InitiatorHandshake;
use super::MAX_MESSAGE_LEN;
use super::NOISE_CHANNEL_SUITE;
use super::NoiseChannelError;
use super::NoiseChannelIdentity;
use super::NoiseChannelPublicKey;
use super::PendingResponderHandshake;
use super::noise_channel_prologue;
#[test]
fn hybrid_ik_roundtrip_authenticates_both_endpoints() {
let initiator = NoiseChannelIdentity::generate().expect("generate initiator identity");
let responder = NoiseChannelIdentity::generate().expect("generate responder identity");
let prologue = noise_channel_prologue("env-1", "registration-1", "stream-1");
let authorization = b"harness-key-authorization";
let (initiator_handshake, request) = InitiatorHandshake::start(
&initiator,
&responder.public_key(),
&prologue,
authorization,
)
.expect("start initiator handshake");
let responder_handshake =
PendingResponderHandshake::read_request(&responder, &prologue, &request)
.expect("read responder handshake");
assert_eq!(
&responder_handshake.initiator_public_key,
&initiator.public_key()
);
assert_eq!(responder_handshake.payload.as_slice(), authorization);
let (mut responder_transport, response) = responder_handshake
.complete()
.expect("complete responder handshake");
let mut initiator_transport = initiator_handshake
.finish(&response)
.expect("complete initiator handshake");
let request_ciphertext = initiator_transport
.encrypt(b"request")
.expect("encrypt request");
assert_ne!(request_ciphertext, b"request");
assert_eq!(
responder_transport
.decrypt(&request_ciphertext)
.expect("decrypt request"),
b"request"
);
let response_ciphertext = responder_transport
.encrypt(b"response")
.expect("encrypt response");
assert_ne!(response_ciphertext, b"response");
assert_eq!(
initiator_transport
.decrypt(&response_ciphertext)
.expect("decrypt response"),
b"response"
);
}
#[test]
fn initiator_rejects_wrong_responder_key() {
let initiator = NoiseChannelIdentity::generate().expect("generate initiator identity");
let expected_responder = NoiseChannelIdentity::generate().expect("generate expected identity");
let actual_responder = NoiseChannelIdentity::generate().expect("generate actual identity");
let prologue = noise_channel_prologue("env-1", "registration-1", "stream-1");
let (_initiator_handshake, request) = InitiatorHandshake::start(
&initiator,
&expected_responder.public_key(),
&prologue,
b"authorization",
)
.expect("start initiator handshake");
assert!(
PendingResponderHandshake::read_request(&actual_responder, &prologue, &request).is_err()
);
}
#[test]
fn registry_rejection_must_be_authenticated() {
for tamper in [false, true] {
let initiator = NoiseChannelIdentity::generate().expect("initiator");
let responder = NoiseChannelIdentity::generate().expect("responder");
let prologue = noise_channel_prologue("env-1", "registration-1", "stream-1");
let (handshake, request) = InitiatorHandshake::start(
&initiator,
&responder.public_key(),
&prologue,
b"authorization",
)
.expect("request");
let pending = PendingResponderHandshake::read_request(&responder, &prologue, &request)
.expect("read request");
let mut response = pending.reject_registry_authentication().expect("rejection");
if tamper {
*response.last_mut().expect("encrypted payload") ^= 1;
}
let error = handshake
.finish(&response)
.err()
.expect("must not open transport");
if tamper {
assert!(matches!(error, NoiseChannelError::Handshake(_)));
} else {
assert!(matches!(
error,
NoiseChannelError::RegistryAuthenticationRejected
));
}
}
}
#[test]
fn responder_rejects_mismatched_prologue() {
let initiator = NoiseChannelIdentity::generate().expect("generate initiator identity");
let responder = NoiseChannelIdentity::generate().expect("generate responder identity");
let initiator_prologue = noise_channel_prologue("env-1", "registration-1", "stream-1");
let responder_prologue = noise_channel_prologue("env-1", "registration-1", "stream-2");
let (_initiator_handshake, request) = InitiatorHandshake::start(
&initiator,
&responder.public_key(),
&initiator_prologue,
b"authorization",
)
.expect("start initiator handshake");
assert!(
PendingResponderHandshake::read_request(&responder, &responder_prologue, &request).is_err()
);
}
#[test]
fn prologue_encoding_is_stable_and_unambiguous() {
let prologue = noise_channel_prologue("env-1", "registration-1", "stream-1");
assert_eq!(
prologue,
b"\x00\x00\x00\x00\x00\x00\x00\x20codex-exec-server-relay-noise/v1\
\x00\x00\x00\x00\x00\x00\x00\x05env-1\
\x00\x00\x00\x00\x00\x00\x00\x0eregistration-1\
\x00\x00\x00\x00\x00\x00\x00\x08stream-1"
.to_vec()
);
}
#[test]
fn transport_rejects_tampered_ciphertext() {
let initiator = NoiseChannelIdentity::generate().expect("generate initiator identity");
let responder = NoiseChannelIdentity::generate().expect("generate responder identity");
let prologue = noise_channel_prologue("env-1", "registration-1", "stream-1");
let (initiator_handshake, request) = InitiatorHandshake::start(
&initiator,
&responder.public_key(),
&prologue,
b"authorization",
)
.expect("start initiator handshake");
let responder_handshake =
PendingResponderHandshake::read_request(&responder, &prologue, &request)
.expect("read responder handshake");
let (mut responder_transport, response) = responder_handshake
.complete()
.expect("complete responder handshake");
let mut initiator_transport = initiator_handshake
.finish(&response)
.expect("complete initiator handshake");
let mut ciphertext = initiator_transport
.encrypt(b"request")
.expect("encrypt request");
ciphertext[0] ^= 1;
assert!(responder_transport.decrypt(&ciphertext).is_err());
}
#[test]
fn transport_rejects_replayed_ciphertext() {
let initiator = NoiseChannelIdentity::generate().expect("generate initiator identity");
let responder = NoiseChannelIdentity::generate().expect("generate responder identity");
let prologue = noise_channel_prologue("env-1", "registration-1", "stream-1");
let (initiator_handshake, request) = InitiatorHandshake::start(
&initiator,
&responder.public_key(),
&prologue,
b"authorization",
)
.expect("start initiator handshake");
let responder_handshake =
PendingResponderHandshake::read_request(&responder, &prologue, &request)
.expect("read responder handshake");
let (mut responder_transport, response) = responder_handshake
.complete()
.expect("complete responder handshake");
let mut initiator_transport = initiator_handshake
.finish(&response)
.expect("complete initiator handshake");
let ciphertext = initiator_transport
.encrypt(b"request")
.expect("encrypt request");
assert_eq!(
responder_transport
.decrypt(&ciphertext)
.expect("decrypt request"),
b"request"
);
assert!(matches!(
responder_transport.decrypt(&ciphertext),
Err(NoiseChannelError::Transport(_))
));
}
#[test]
fn public_key_validation_rejects_unknown_suite() {
let key = NoiseChannelIdentity::generate()
.expect("generate identity")
.public_key();
let json = serde_json::to_value(key).expect("serialize key");
let mut object = json.as_object().expect("key object").clone();
object.insert("suite".to_string(), serde_json::json!("unknown"));
let key: NoiseChannelPublicKey =
serde_json::from_value(serde_json::Value::Object(object)).expect("deserialize key");
let initiator = NoiseChannelIdentity::generate().expect("generate initiator identity");
assert!(InitiatorHandshake::start(&initiator, &key, b"prologue", b"").is_err());
}
#[test]
fn public_key_serializes_with_expected_suite() {
let key = NoiseChannelIdentity::generate()
.expect("generate identity")
.public_key();
let json = serde_json::to_value(key).expect("serialize key");
assert_eq!(json["suite"], NOISE_CHANNEL_SUITE);
}
#[test]
fn initiator_rejects_oversized_handshake_payload() {
let initiator = NoiseChannelIdentity::generate().expect("generate initiator identity");
let responder = NoiseChannelIdentity::generate().expect("generate responder identity");
let payload = vec![0; MAX_MESSAGE_LEN];
let result =
InitiatorHandshake::start(&initiator, &responder.public_key(), b"prologue", &payload);
assert!(matches!(
result,
Err(NoiseChannelError::InvalidMessage(
"handshake payload is too large"
))
));
}

View File

@@ -0,0 +1,195 @@
//! One executor-side virtual stream after the Noise handshake.
//!
//! The environment loop owns reads and a per-stream task owns writes. They share
//! `NoiseTransport` because its send and receive nonces live in the same value;
//! the mutex is never held across `.await`.
use std::sync::Arc;
use std::sync::Mutex;
use tokio::sync::mpsc;
use tokio::sync::watch;
use tracing::warn;
use crate::ExecServerError;
use crate::connection::CHANNEL_CAPACITY;
use crate::noise_channel::NoiseTransport;
use crate::noise_relay::message_framing::MessageDecoder;
use crate::noise_relay::message_framing::NOISE_RECORD_PLAINTEXT_LEN;
use crate::noise_relay::ordered_ciphertext::OrderedCiphertextFrames;
use crate::noise_relay::stream_handler::NoiseStreamConnection;
use crate::noise_relay::stream_handler::NoiseStreamHandler;
use crate::noise_relay::take_next_sequence;
use crate::relay::encode_relay_message_frame;
use crate::relay_proto::RelayData;
use crate::relay_proto::RelayMessageFrame;
use crate::telemetry::ExecutorRegistration;
/// Identifies one completed virtual-stream instance.
///
/// Stream IDs are supplied by the untrusted relay peer and may be reused. The
/// instance ID prevents a delayed writer notification from removing a newer
/// stream that happens to use the same routing ID.
pub(crate) struct ClosedNoiseVirtualStream {
pub(crate) stream_id: String,
pub(crate) instance_id: u64,
}
/// One authenticated application stream carried by the executor's physical relay.
///
/// Inbound delivery is intentionally nonblocking. An overloaded or abandoned
/// stream fails independently instead of stalling every stream multiplexed over
/// the same physical websocket.
pub(crate) struct NoiseVirtualStream<H: NoiseStreamHandler> {
incoming_tx: mpsc::Sender<H::Incoming>,
disconnected_tx: watch::Sender<bool>,
transport: Arc<Mutex<NoiseTransport>>,
inbound_ciphertexts: OrderedCiphertextFrames,
inbound_decoder: MessageDecoder,
pub(crate) instance_id: u64,
}
impl<H: NoiseStreamHandler> NoiseVirtualStream<H> {
pub(crate) fn disconnect(self) {
let _ = self.disconnected_tx.send(true);
}
/// Reorder and decrypt one record, then deliver complete payloads to the handler.
/// This must stay nonblocking because all virtual streams share the read loop.
pub(crate) fn receive_data(&mut self, data: RelayData) -> Result<(), ExecServerError> {
for ciphertext in self.inbound_ciphertexts.push(data.seq, data.payload)? {
let plaintext = {
let mut transport = self
.transport
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
transport.decrypt(&ciphertext).map_err(|error| {
ExecServerError::Protocol(format!("Noise relay decryption failed: {error}"))
})?
};
for message in self.inbound_decoder.push(&plaintext)? {
self.incoming_tx
.try_send(H::decode(message)?)
.map_err(|_| {
ExecServerError::Protocol(
"Noise virtual stream inbound queue is full or closed".to_string(),
)
})?;
}
}
Ok(())
}
}
/// Hand a completed handshake to its execution or forwarding owner.
///
/// The returned value is the read half; the spawned task owns outbound framing
/// and reports its instance ID on exit so stream-ID reuse is safe.
pub(crate) fn spawn_noise_virtual_stream<H: NoiseStreamHandler>(
stream_id: String,
instance_id: u64,
handler: H,
physical_outgoing_tx: mpsc::Sender<Vec<u8>>,
closed_stream_tx: mpsc::Sender<ClosedNoiseVirtualStream>,
transport: NoiseTransport,
executor_registration: Option<Arc<ExecutorRegistration>>,
) -> NoiseVirtualStream<H> {
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(CHANNEL_CAPACITY);
let (incoming_tx, incoming_rx) = mpsc::channel(CHANNEL_CAPACITY);
let (disconnected_tx, disconnected_rx) = watch::channel(false);
let transport = Arc::new(Mutex::new(transport));
let writer_transport = Arc::clone(&transport);
let owner_stream_id = stream_id.clone();
let owner_closed_stream_tx = closed_stream_tx.clone();
let writer_stream_id = stream_id;
let writer_task = tokio::spawn(async move {
let mut next_seq = 0u32;
'writer: while let Some(message) = outgoing_rx.recv().await {
let message = match H::encode(message) {
Ok(message) => message,
Err(error) => {
warn!("failed to encode Noise virtual stream payload: {error}");
break;
}
};
// Each chunk becomes one Noise record and consumes one nonce.
let mut trace = message.trace;
for plaintext_record in message.framed.chunks(NOISE_RECORD_PLAINTEXT_LEN) {
let seq = match take_next_sequence(&mut next_seq) {
Ok(seq) => seq,
Err(error) => {
warn!("Noise virtual stream sequence exhausted: {error}");
break 'writer;
}
};
let ciphertext = {
let mut transport = writer_transport
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
transport.encrypt(plaintext_record)
};
let ciphertext = match ciphertext {
Ok(ciphertext) => ciphertext,
Err(error) => {
warn!("failed to encrypt Noise virtual stream payload: {error}");
break 'writer;
}
};
let frame = RelayMessageFrame::data(
writer_stream_id.clone(),
seq,
ciphertext,
trace.take(),
);
if physical_outgoing_tx
.send(encode_relay_message_frame(&frame))
.await
.is_err()
{
break 'writer;
}
}
}
// The physical relay owns reset delivery and rejects stale instance IDs.
let closed_stream = ClosedNoiseVirtualStream {
stream_id: writer_stream_id,
instance_id,
};
let _ = closed_stream_tx.send(closed_stream).await;
});
let connection = NoiseStreamConnection {
outgoing_tx,
incoming_rx,
disconnected_rx,
writer_task,
executor_registration,
};
tokio::spawn(async move {
handler.run_connection(connection).await;
let _ = owner_closed_stream_tx
.send(ClosedNoiseVirtualStream {
stream_id: owner_stream_id,
instance_id,
})
.await;
});
NoiseVirtualStream {
incoming_tx,
disconnected_tx,
transport,
inbound_ciphertexts: OrderedCiphertextFrames::default(),
inbound_decoder: MessageDecoder::default(),
instance_id,
}
}
#[cfg(test)]
#[path = "executor_stream_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "forward_stream_tests.rs"]
mod forward_tests;

View File

@@ -0,0 +1,125 @@
use std::time::Duration;
use anyhow::Result;
use codex_exec_server_protocol::JSONRPCMessage;
use codex_exec_server_protocol::JSONRPCRequest;
use codex_exec_server_protocol::JSONRPCResponse;
use codex_exec_server_protocol::RequestId;
use codex_protocol::protocol::W3cTraceContext;
use tokio::sync::mpsc;
use tokio::time::timeout;
use super::ClosedNoiseVirtualStream;
use super::spawn_noise_virtual_stream;
use crate::ExecServerRuntimeOptions;
use crate::connection::CHANNEL_CAPACITY;
use crate::noise_channel::InitiatorHandshake;
use crate::noise_channel::NoiseChannelIdentity;
use crate::noise_channel::PendingResponderHandshake;
use crate::noise_relay::message_framing::frame_jsonrpc_message;
use crate::relay_proto::RelayData;
use crate::relay_proto::RelayMessageFrame;
use crate::server::ConnectionProcessor;
#[test]
fn executor_requests_attach_trace_context_only_to_the_first_noise_record() {
let traceparent = "00-00000000000000000000000000000001-0000000000000002-01";
let tracestate = "dd=s:1";
let owned_traceparent = traceparent.to_string();
let owned_tracestate = tracestate.to_string();
let traceparent_ptr = owned_traceparent.as_ptr();
let tracestate_ptr = owned_tracestate.as_ptr();
let mut request = JSONRPCRequest {
id: RequestId::Integer(1),
method: "approval/request".to_string(),
params: None,
trace: Some(W3cTraceContext {
traceparent: Some(owned_traceparent),
tracestate: Some(owned_tracestate),
}),
};
let first = RelayMessageFrame::data(
"stream-1".to_string(),
/*seq*/ 0,
vec![1],
request.trace.take(),
);
assert_eq!(first.traceparent.as_deref(), Some(traceparent));
assert_eq!(first.tracestate.as_deref(), Some(tracestate));
assert_eq!(
first.traceparent.as_ref().unwrap().as_ptr(),
traceparent_ptr
);
assert_eq!(first.tracestate.as_ref().unwrap().as_ptr(), tracestate_ptr);
let second = RelayMessageFrame::data(
"stream-1".to_string(),
/*seq*/ 1,
vec![2],
request.trace.take(),
);
assert!(second.traceparent.is_none());
assert!(second.tracestate.is_none());
let response = RelayMessageFrame::data(
"stream-1".to_string(),
/*seq*/ 2,
vec![3],
/*trace*/ None,
);
assert!(response.traceparent.is_none());
assert!(response.tracestate.is_none());
}
#[tokio::test]
async fn processor_exit_reports_closed_virtual_stream() -> Result<()> {
let executor_identity = NoiseChannelIdentity::generate()?;
let harness_identity = NoiseChannelIdentity::generate()?;
let prologue = b"test-prologue";
let (initiator, request) = InitiatorHandshake::start(
&harness_identity,
&executor_identity.public_key(),
prologue,
b"authorization",
)?;
let pending = PendingResponderHandshake::read_request(&executor_identity, prologue, &request)?;
let (executor_transport, response) = pending.complete()?;
let mut harness_transport = initiator.finish(&response)?;
let (physical_outgoing_tx, _physical_outgoing_rx) = mpsc::channel(CHANNEL_CAPACITY);
let (closed_stream_tx, mut closed_stream_rx) = mpsc::channel(1);
let mut stream = spawn_noise_virtual_stream(
"stream-1".to_string(),
/*instance_id*/ 7,
ConnectionProcessor::new(ExecServerRuntimeOptions::new(
std::env::current_exe()?,
/*codex_linux_sandbox_exe*/ None,
)?),
physical_outgoing_tx,
closed_stream_tx,
executor_transport,
/*executor_registration*/ None,
);
let message = JSONRPCMessage::Response(JSONRPCResponse {
id: RequestId::Integer(1),
result: serde_json::Value::Null,
});
let ciphertext = harness_transport.encrypt(&frame_jsonrpc_message(&message)?)?;
stream.receive_data(RelayData {
seq: 0,
segment_index: 0,
segment_count: 1,
payload: ciphertext,
})?;
assert!(matches!(
timeout(Duration::from_secs(1), closed_stream_rx.recv()).await?,
Some(ClosedNoiseVirtualStream {
stream_id,
instance_id: 7,
}) if stream_id == "stream-1"
));
Ok(())
}

View File

@@ -0,0 +1,112 @@
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use bytes::Bytes;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use futures::SinkExt;
use futures::StreamExt;
use pretty_assertions::assert_eq;
use tokio::net::TcpListener;
use tokio::sync::mpsc;
use tokio::time::timeout;
use tokio_tungstenite::accept_async;
use tokio_tungstenite::tungstenite::Message;
use super::ClosedNoiseVirtualStream;
use super::spawn_noise_virtual_stream;
use crate::ExecServerTelemetry;
use crate::forward::Forwarder;
use crate::noise_channel::InitiatorHandshake;
use crate::noise_channel::NoiseChannelIdentity;
use crate::noise_channel::PendingResponderHandshake;
use crate::noise_relay::message_framing::MessageDecoder;
use crate::noise_relay::message_framing::frame_message;
use crate::relay::decode_relay_message_frame;
use crate::relay_proto::RelayData;
const TEST_TIMEOUT: Duration = Duration::from_secs(5);
#[tokio::test]
async fn forwards_opaque_noise_payloads_and_drains_before_closing() -> Result<()> {
let executor_identity = NoiseChannelIdentity::generate()?;
let harness_identity = NoiseChannelIdentity::generate()?;
let prologue = b"forwarding-test";
let (initiator, request) = InitiatorHandshake::start(
&harness_identity,
&executor_identity.public_key(),
prologue,
b"authorization",
)?;
let pending = PendingResponderHandshake::read_request(&executor_identity, prologue, &request)?;
let (executor_transport, response) = pending.complete()?;
let mut harness_transport = initiator.finish(&response)?;
let destination = TcpListener::bind("127.0.0.1:0").await?;
let forwarder = Forwarder::new(
format!("ws://{}", destination.local_addr()?),
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
ExecServerTelemetry::default(),
)?;
// A single queued record makes the final response exercise writer draining.
let (physical_outgoing_tx, mut physical_outgoing_rx) = mpsc::channel(1);
let (closed_stream_tx, mut closed_stream_rx) = mpsc::channel(2);
let mut stream = spawn_noise_virtual_stream(
"stream-1".to_string(),
/*instance_id*/ 7,
forwarder,
physical_outgoing_tx,
closed_stream_tx,
executor_transport,
/*executor_registration*/ None,
);
let (socket, _) = timeout(TEST_TIMEOUT, destination.accept()).await??;
let mut socket = timeout(TEST_TIMEOUT, accept_async(socket)).await??;
let request = Bytes::from_static(b"not JSON\x00\xff");
stream.receive_data(RelayData {
seq: 0,
segment_index: 0,
segment_count: 1,
payload: harness_transport.encrypt(&frame_message(&request)?)?,
})?;
let forwarded = timeout(TEST_TIMEOUT, socket.next())
.await?
.context("forwarded request")??;
assert_eq!(forwarded.into_data(), request);
let response = Bytes::from(vec![0xff; 128 * 1024]);
socket.send(Message::Binary(response.clone())).await?;
socket.close(None).await?;
let mut decoder = MessageDecoder::default();
let mut messages = Vec::new();
let mut next_seq = 0;
let closed = timeout(TEST_TIMEOUT, async {
loop {
tokio::select! {
biased;
Some(encoded) = physical_outgoing_rx.recv() => {
let frame = decode_relay_message_frame(&encoded)?;
assert_eq!(frame.stream_id, "stream-1");
let data = frame.into_data()?;
assert_eq!(data.seq, next_seq);
next_seq += 1;
messages.extend(decoder.push(&harness_transport.decrypt(&data.payload)?)?);
}
closed = closed_stream_rx.recv() => {
break closed.context("stream close notification");
}
}
}
})
.await??;
assert!(next_seq > 1);
assert_eq!(messages, vec![response]);
assert!(matches!(
closed,
ClosedNoiseVirtualStream { stream_id, instance_id: 7 } if stream_id == "stream-1"
));
Ok(())
}

View File

@@ -0,0 +1,843 @@
//! Harness side of the Noise relay.
//!
//! The rendezvous service routes frames by `stream_id`, but does not authenticate
//! the executor or see JSON-RPC plaintext. We claim a stream, complete hybrid IK
//! against the registry-provided executor key, and then expose the result as a
//! normal `JsonRpcConnection`. Outbound JSON-RPC is framed and split into Noise
//! records; inbound records are reordered before decryption and reassembly.
use futures::FutureExt;
use futures::Sink;
use futures::SinkExt;
use futures::Stream;
use futures::StreamExt;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::sync::watch;
use tokio::time::Instant;
use tokio_tungstenite::tungstenite::Error as WebSocketError;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::error::ProtocolError;
use tracing::Instrument;
use tracing::debug;
use tracing::info;
use tracing::warn;
use uuid::Uuid;
use crate::ExecServerError;
use crate::connection::CHANNEL_CAPACITY;
use crate::connection::JsonRpcConnection;
use crate::connection::JsonRpcConnectionEvent;
use crate::connection::JsonRpcTransport;
use crate::connection::WEBSOCKET_KEEPALIVE_INTERVAL;
use crate::noise_channel::InitiatorHandshake;
use crate::noise_channel::NoiseChannelError;
use crate::noise_channel::NoiseChannelIdentity;
use crate::noise_channel::NoiseChannelPublicKey;
use crate::noise_channel::NoiseTransport;
use crate::noise_channel::noise_channel_prologue;
use crate::noise_relay::message_framing::ClientJsonRpcMessageDecoder;
use crate::noise_relay::message_framing::JsonRpcMessageDecoder;
use crate::noise_relay::message_framing::NOISE_RECORD_PLAINTEXT_LEN;
use crate::noise_relay::message_framing::frame_jsonrpc_message;
use crate::noise_relay::ordered_ciphertext::OrderedCiphertextFrames;
use crate::noise_relay::take_next_sequence;
use crate::relay::RelayFrameBodyKind;
use crate::relay::decode_relay_message_frame;
use crate::relay::encode_relay_message_frame;
use crate::relay_proto::RelayData;
use crate::relay_proto::RelayMessageFrame;
use crate::websocket_pong_watchdog::WEBSOCKET_PONG_TIMEOUT;
use crate::websocket_pong_watchdog::WEBSOCKET_PONG_TIMEOUT_REASON;
use crate::websocket_pong_watchdog::WebSocketPongWatchdog;
#[path = "harness_diagnostics.rs"]
mod diagnostics;
use diagnostics::TransportExitReason;
use diagnostics::WebsocketWriteError;
/// Values that bind one harness websocket to the intended executor registration.
///
/// These fields all come from the same registry response. Keeping them together
/// makes that relationship visible at the call site and avoids mixing up the
/// several string and key arguments used to start the handshake.
pub(crate) struct NoiseHarnessConnectionArgs {
pub(crate) connection_label: String,
pub(crate) environment_id: String,
pub(crate) executor_registration_id: String,
pub(crate) identity: NoiseChannelIdentity,
pub(crate) responder_public_key: NoiseChannelPublicKey,
pub(crate) harness_key_authorization: String,
}
/// One Noise-backed JSON-RPC connection plus a signal that its authenticated
/// transport is ready for application messages.
pub(crate) struct NoiseHarnessConnection {
pub(crate) connection: JsonRpcConnection,
pub(crate) handshake_ready: oneshot::Receiver<Result<(), ExecServerError>>,
pub(crate) stream_id: String,
pub(crate) handshake_started: Instant,
}
// Reset frames are cleartext relay control and are not authenticated by Noise.
// Preserve the availability signal while replacing attacker-controlled reason
// text before it reaches disconnect diagnostics.
const NOISE_RELAY_RESET_DISCONNECT_REASON: &str = "Noise relay stream reset";
// Give a Pong already queued behind data a bounded chance to reach the reader.
const MAX_FRAMES_DRAINED_AFTER_PONG_DEADLINE: usize = 32;
/// Adapt one harness rendezvous websocket and expose when hybrid IK completes.
///
/// Callers that send application messages immediately after opening the
/// websocket must await handshake_ready first. Dropping that receiver keeps
/// the legacy fire-and-forget behavior for existing connection owners.
pub(crate) fn noise_harness_connection_from_websocket_with_readiness<T>(
stream: T,
args: NoiseHarnessConnectionArgs,
) -> NoiseHarnessConnection
where
T: Sink<Message, Error = WebSocketError>
+ Stream<Item = Result<Message, WebSocketError>>
+ Unpin
+ Send
+ 'static,
{
let NoiseHarnessConnectionArgs {
connection_label,
environment_id,
executor_registration_id,
identity,
responder_public_key,
harness_key_authorization,
} = args;
let stream_id = Uuid::new_v4().to_string();
let connection_stream_id = stream_id.clone();
let handshake_started = Instant::now();
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(CHANNEL_CAPACITY);
let (incoming_tx, incoming_rx) = mpsc::channel(CHANNEL_CAPACITY);
let (disconnected_tx, disconnected_rx) = watch::channel(false);
let (handshake_ready_tx, handshake_ready_rx) = oneshot::channel();
let stream_span = tracing::debug_span!("noise_relay.stream", noise_side = "harness", stream_id);
debug!(
environment_id,
executor_registration_id, stream_id, "Noise harness relay details"
);
let websocket_task = tokio::spawn(async move {
let mut handshake_ready_tx = Some(handshake_ready_tx);
let mut websocket = stream;
// Readiness only carries success; record failures before that signal is dropped.
let record_handshake_failure = |reason: &'static str| {
tracing::event!(
name: "codex.exec_server.noise_handshake_failed",
target: "codex_otel.trace_safe",
tracing::Level::WARN,
event.name = "codex.exec_server.noise_handshake_failed",
noise_event = "handshake",
noise_outcome = "failed",
noise_side = "harness",
noise_reason = reason,
elapsed_ms = handshake_started.elapsed().as_millis() as u64,
environment_id,
executor_registration_id,
stream_id,
);
};
// Bind the Noise transcript to the exact environment registration and
// virtual relay stream before emitting any handshake bytes. A captured
// handshake cannot be spliced onto a different routed connection.
let prologue =
noise_channel_prologue(&environment_id, &executor_registration_id, &stream_id);
let (initiator_handshake, request) = match InitiatorHandshake::start(
&identity,
&responder_public_key,
&prologue,
harness_key_authorization.as_bytes(),
) {
Ok(handshake) => handshake,
Err(error) => {
record_handshake_failure("handshake_start");
send_disconnected(
&incoming_tx,
&disconnected_tx,
format!("failed to start Noise relay handshake: {error}"),
);
return;
}
};
// Resume claims the stream ID at rendezvous; Handshake carries the
// opaque first IK message. No JSON-RPC data is sent before the
// responder proves possession of the pinned static key.
let resume = RelayMessageFrame::resume(stream_id.clone());
let handshake = RelayMessageFrame::handshake(stream_id.clone(), request);
if websocket
.send(Message::Binary(encode_relay_message_frame(&resume).into()))
.await
.is_err()
|| websocket
.send(Message::Binary(
encode_relay_message_frame(&handshake).into(),
))
.await
.is_err()
{
record_handshake_failure("websocket_write");
let _ = disconnected_tx.send(true);
return;
}
// During the handshake, ignore unrelated routed streams and control
// frames, but reject data on our stream. Accepting early data would
// create a plaintext or unauthenticated application path.
let mut transport = loop {
let Some(incoming_message) = websocket.next().await else {
record_handshake_failure("websocket_ended");
send_disconnected(
&incoming_tx,
&disconnected_tx,
"Noise relay websocket ended during handshake".to_string(),
);
return;
};
let message = match incoming_message {
Ok(Message::Binary(payload)) => payload,
Ok(Message::Close(_)) => {
record_handshake_failure("websocket_close");
send_disconnected(
&incoming_tx,
&disconnected_tx,
"Noise relay websocket received close frame during handshake".to_string(),
);
return;
}
Ok(Message::Ping(_) | Message::Pong(_) | Message::Frame(_)) => continue,
Ok(Message::Text(_)) => {
record_handshake_failure("unexpected_text");
send_disconnected(
&incoming_tx,
&disconnected_tx,
"Noise relay transport expects binary protobuf frames".to_string(),
);
return;
}
Err(error) => {
record_handshake_failure(websocket_read_error_reason(&error));
send_disconnected(
&incoming_tx,
&disconnected_tx,
format!(
"failed to read Noise relay websocket from {connection_label}: {error}"
),
);
return;
}
};
let frame = match decode_relay_message_frame(message.as_ref()) {
Ok(frame) => frame,
Err(error) => {
record_handshake_failure("invalid_frame");
send_disconnected(
&incoming_tx,
&disconnected_tx,
format!("failed to parse Noise relay frame: {error}"),
);
return;
}
};
if frame.stream_id != stream_id {
debug!("Noise relay ignored frame for unrelated stream during handshake");
continue;
}
match frame.validate() {
Ok(RelayFrameBodyKind::Handshake) => {
let response = match frame.into_handshake_payload() {
Ok(response) => response,
Err(error) => {
record_handshake_failure("invalid_response");
send_disconnected(
&incoming_tx,
&disconnected_tx,
format!("invalid Noise relay handshake response: {error}"),
);
return;
}
};
match initiator_handshake.finish(&response) {
Ok(transport) => {
info!(
target: "codex_otel.trace_safe",
noise_event = "handshake",
noise_outcome = "ok",
noise_side = "harness",
elapsed_ms = handshake_started.elapsed().as_millis() as u64,
environment_id,
executor_registration_id,
stream_id,
"Noise harness handshake completed"
);
if let Some(handshake_ready_tx) = handshake_ready_tx.take() {
let _ = handshake_ready_tx.send(Ok(()));
}
break transport;
}
Err(NoiseChannelError::RegistryAuthenticationRejected) => {
record_handshake_failure("registry_authentication_rejected");
if let Some(handshake_ready_tx) = handshake_ready_tx.take() {
let _ = handshake_ready_tx.send(Err(ExecServerError::EnvironmentRegistryAuth(
"executor credentials rejected".to_string(),
)));
}
send_disconnected(&incoming_tx, &disconnected_tx,
"environment registry rejected executor credentials".to_string());
return;
}
Err(error) => {
record_handshake_failure("handshake_finish");
send_disconnected(
&incoming_tx,
&disconnected_tx,
format!("Noise relay handshake failed: {error}"),
);
return;
}
}
}
Ok(RelayFrameBodyKind::Reset) => {
record_handshake_failure("relay_reset");
send_disconnected(
&incoming_tx,
&disconnected_tx,
NOISE_RELAY_RESET_DISCONNECT_REASON.to_string(),
);
return;
}
Ok(
RelayFrameBodyKind::Ack
| RelayFrameBodyKind::Resume
| RelayFrameBodyKind::Heartbeat,
) => {}
Ok(RelayFrameBodyKind::Data) | Err(_) => {
record_handshake_failure("unexpected_frame");
send_disconnected(
&incoming_tx,
&disconnected_tx,
"Noise relay received data before handshake completion".to_string(),
);
return;
}
}
};
// After the handshake, each relay sequence maps to exactly one Noise
// transport record. Outbound records are encrypted once; inbound
// records are reordered and deduplicated before decryption.
let mut websocket = websocket.peekable();
let mut next_outbound_seq = 0u32;
let mut inbound_ciphertexts = OrderedCiphertextFrames::default();
let mut inbound_decoder = JsonRpcMessageDecoder::client();
let mut keepalive = tokio::time::interval_at(
tokio::time::Instant::now() + WEBSOCKET_KEEPALIVE_INTERVAL,
WEBSOCKET_KEEPALIVE_INTERVAL,
);
keepalive.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut pong_watchdog = WebSocketPongWatchdog::new(WEBSOCKET_PONG_TIMEOUT);
let pong_deadline = tokio::time::sleep(WEBSOCKET_PONG_TIMEOUT);
tokio::pin!(pong_deadline);
// Keep one framed message as a cursor. Sending one Noise record per loop
// creates a scheduling point for keepalive and inbound control frames
// without splitting the WebSocket reader and writer.
let mut pending_outbound = None;
let mut force_incoming = false;
let mut frames_drained_after_pong_deadline = 0usize;
let connected_at = Instant::now();
let mut last_read_at = connected_at;
let mut last_write_at = connected_at;
let mut write_started_at = None;
let mut write_kind = "none";
let mut records_written = 0_u64;
let mut frames_read = 0_u64;
let mut read_reason = "none";
let mut messages_dequeued = 0_u64;
let mut messages_written = 0_u64;
let mut pending_request: Option<(tracing::Span, Instant)> = None;
let mut heartbeat = diagnostics::HeartbeatDiagnostics::default();
let exit_reason = 'relay: loop {
// Consume a due tick before the always-ready record arm below can win
// another select iteration and postpone the keepalive.
if pong_watchdog.deadline().is_none()
&& keepalive.tick().now_or_never().is_some()
{
write_started_at = Some(Instant::now());
write_kind = "keepalive";
if let Err(error) = send_keepalive_ping(
&mut websocket,
&mut pong_watchdog,
pong_deadline.as_mut(),
)
.await
{
warn!("failed to write Noise relay keepalive ping: {error}");
break error.exit_reason();
}
last_write_at = Instant::now();
write_started_at = None;
heartbeat.record(diagnostics::HeartbeatProgress::PingWritten, &stream_id);
frames_drained_after_pong_deadline = 0;
continue;
}
let pong_deadline_expired = pong_watchdog
.deadline()
.is_some_and(|deadline| tokio::time::Instant::now() >= deadline);
// After expiry, inspect only frames already queued. Forcing the peeked
// item through next() makes the 32-frame grace deterministic.
if pong_deadline_expired && !force_incoming {
if frames_drained_after_pong_deadline
< MAX_FRAMES_DRAINED_AFTER_PONG_DEADLINE
&& std::pin::Pin::new(&mut websocket)
.peek()
.now_or_never()
.is_some()
{
force_incoming = true;
} else {
let _ = incoming_tx.try_send(JsonRpcConnectionEvent::Disconnected {
reason: Some(WEBSOCKET_PONG_TIMEOUT_REASON.to_string()),
});
break TransportExitReason::PongTimeout;
}
}
// While a Pong is outstanding, drain already-queued inbound traffic
// before the next fragment so a queued Pong cannot sit behind writes.
if !force_incoming
&& pong_watchdog.deadline().is_some()
&& pending_outbound.is_some()
&& std::pin::Pin::new(&mut websocket)
.peek()
.now_or_never()
.is_some()
{
force_incoming = true;
}
tokio::select! {
maybe_message = outgoing_rx.recv(), if pending_outbound.is_none() && !force_incoming && !pong_deadline_expired => {
let Some(message) = maybe_message else {
break TransportExitReason::OutgoingClosed;
};
messages_dequeued += 1;
if let codex_exec_server_protocol::JSONRPCMessage::Request(request) = &message {
// Link transport progress to the existing RPC trace without copying
// its method, ID, payload or unvalidated trace carrier into fields.
let span = tracing::info_span!("codex.exec_server.noise_request_write", stream_id);
if let Some(trace) = &request.trace {
codex_otel::set_parent_from_w3c_trace_context(&span, trace);
}
// Live JSON correlation reads OtelData before this span closes.
// Setting a remote parent alone leaves its trace ID lazy.
let _ = codex_otel::span_w3c_trace_context(&span);
tracing::event!(
name: "codex.exec_server.request_dequeued",
target: "codex_otel.trace_safe",
parent: &span,
tracing::Level::INFO,
event.name = "codex.exec_server.request_dequeued",
stream_id,
message_sequence = messages_dequeued,
outgoing_queue_depth = outgoing_rx.len(),
);
pending_request = Some((span, Instant::now()));
}
let framed = match frame_jsonrpc_message(&message) {
Ok(framed) => framed,
Err(error) => {
warn!("failed to frame JSON-RPC payload for Noise relay: {error}");
break TransportExitReason::Framing;
}
};
let request_trace = match message {
codex_exec_server_protocol::JSONRPCMessage::Request(request) => request.trace,
codex_exec_server_protocol::JSONRPCMessage::Notification(_)
| codex_exec_server_protocol::JSONRPCMessage::Response(_)
| codex_exec_server_protocol::JSONRPCMessage::Error(_) => None,
};
pending_outbound = Some((framed, 0, request_trace));
}
_ = std::future::ready(()), if pending_outbound.is_some() && !force_incoming && !pong_deadline_expired => {
let seq = match take_next_sequence(&mut next_outbound_seq) {
Ok(seq) => seq,
Err(error) => {
warn!("Noise relay sequence exhausted: {error}");
break 'relay TransportExitReason::SequenceExhausted;
}
};
let (ciphertext, next_offset, message_complete, request_trace) = {
let Some((framed, offset, request_trace)) = pending_outbound.as_mut() else {
continue;
};
let next_offset = (*offset + NOISE_RECORD_PLAINTEXT_LEN).min(framed.len());
let ciphertext = match transport.encrypt(&framed[*offset..next_offset]) {
Ok(ciphertext) => ciphertext,
Err(error) => {
warn!("failed to encrypt JSON-RPC payload for Noise relay: {error}");
break 'relay TransportExitReason::Encryption;
}
};
(
ciphertext,
next_offset,
next_offset == framed.len(),
request_trace.take(),
)
};
let frame =
RelayMessageFrame::data(stream_id.clone(), seq, ciphertext, request_trace);
// A Pong can arrive after the readiness check while this write owns the
// combined sink and stream. A single bounded record can therefore hit the
// deadline and disconnect with that Pong queued. Treat that as write
// backpressure; this loop yields only between records.
write_started_at = Some(Instant::now());
write_kind = "data";
if let Err(error) = send_websocket_message(
&mut websocket,
Message::Binary(encode_relay_message_frame(&frame).into()),
pong_watchdog.write_deadline(tokio::time::Instant::now()),
)
.await
{
warn!("failed to write Noise relay websocket: {error}");
break 'relay error.exit_reason();
}
last_write_at = Instant::now();
write_started_at = None;
records_written += 1;
if message_complete {
messages_written += 1;
if let Some((span, started_at)) = pending_request.take() {
tracing::event!(
name: "codex.exec_server.request_written",
target: "codex_otel.trace_safe",
parent: &span,
tracing::Level::INFO,
event.name = "codex.exec_server.request_written",
stream_id,
message_sequence = messages_dequeued,
write_elapsed_ms = started_at.elapsed().as_millis() as u64,
);
}
pending_outbound = None;
} else if let Some((_framed, offset, _request_trace)) = pending_outbound.as_mut() {
*offset = next_offset;
}
}
_ = &mut pong_deadline, if pong_watchdog.deadline().is_some() && !force_incoming => {
continue;
}
_ = keepalive.tick(), if pong_watchdog.deadline().is_none() => {
write_started_at = Some(Instant::now());
write_kind = "keepalive";
if let Err(error) = send_keepalive_ping(
&mut websocket,
&mut pong_watchdog,
pong_deadline.as_mut(),
)
.await
{
warn!("failed to write Noise relay keepalive ping: {error}");
break error.exit_reason();
}
last_write_at = Instant::now();
write_started_at = None;
heartbeat.record(diagnostics::HeartbeatProgress::PingWritten, &stream_id);
frames_drained_after_pong_deadline = 0;
}
incoming_message = websocket.next() => {
force_incoming = false;
let Some(incoming_message) = incoming_message else {
break TransportExitReason::WebsocketEnded;
};
if incoming_message.is_ok() {
last_read_at = Instant::now();
frames_read += 1;
}
// Count each completed read after expiry. If only the deadline arm
// advanced this counter, reads won by a simultaneously ready incoming
// arm would not count toward the 32-frame cap.
if pong_watchdog
.deadline()
.is_some_and(|deadline| tokio::time::Instant::now() >= deadline)
{
frames_drained_after_pong_deadline += 1;
}
match incoming_message {
Ok(Message::Binary(payload)) => {
let frame = match decode_relay_message_frame(payload.as_ref()) {
Ok(frame) => frame,
Err(error) => {
send_malformed(&incoming_tx, error.to_string());
break TransportExitReason::InvalidFrame;
}
};
if frame.stream_id != stream_id {
continue;
}
match frame.validate() {
Ok(RelayFrameBodyKind::Data) => {
let data = match frame.into_data() {
Ok(data) => data,
Err(error) => {
send_malformed(&incoming_tx, error.to_string());
break TransportExitReason::InvalidFrame;
}
};
if let Err(error) = receive_data(
&mut inbound_ciphertexts,
&mut transport,
&mut inbound_decoder,
data,
pong_watchdog.write_deadline(tokio::time::Instant::now()),
&incoming_tx,
)
.await
{
if matches!(error, ExecServerError::Closed) {
break TransportExitReason::ApplicationDelivery;
}
send_malformed(&incoming_tx, error.to_string());
break TransportExitReason::InvalidData;
}
}
Ok(RelayFrameBodyKind::Reset) => {
let _ = incoming_tx.try_send(
JsonRpcConnectionEvent::Disconnected {
reason: Some(
NOISE_RELAY_RESET_DISCONNECT_REASON.to_string(),
),
},
);
break TransportExitReason::RelayReset;
}
Ok(
RelayFrameBodyKind::Ack
| RelayFrameBodyKind::Resume
| RelayFrameBodyKind::Heartbeat,
) => {}
Ok(RelayFrameBodyKind::Handshake) | Err(_) => {
send_malformed(
&incoming_tx,
"Noise relay received invalid post-handshake frame".to_string(),
);
break TransportExitReason::InvalidFrame;
}
}
}
Ok(Message::Close(_)) => break TransportExitReason::WebsocketClose,
Ok(Message::Pong(_)) => {
heartbeat.record(diagnostics::HeartbeatProgress::PongReceived, &stream_id);
pong_watchdog.received_pong();
frames_drained_after_pong_deadline = 0;
}
Ok(Message::Ping(_) | Message::Frame(_)) => {}
Ok(Message::Text(_)) => {
send_malformed(
&incoming_tx,
"Noise relay transport expects binary protobuf frames".to_string(),
);
break TransportExitReason::UnexpectedText;
}
Err(error) => {
debug!("Noise relay websocket read failed: {error}");
read_reason = websocket_read_error_reason(&error);
break TransportExitReason::WebsocketRead;
}
}
}
}
};
// Fixed reasons and local counters only. Raw errors, frames and peer-provided
// close/reset text must remain outside the trace-safe target.
tracing::event!(
name: "codex.exec_server.noise_transport_closed",
target: "codex_otel.trace_safe",
tracing::Level::INFO,
event.name = "codex.exec_server.noise_transport_closed",
noise_side = "harness",
noise_reason = exit_reason.as_str(),
read_reason,
stream_id,
messages_dequeued,
messages_written,
pings_written = heartbeat.pings_written,
pongs_received = heartbeat.pongs_received,
connection_age_ms = connected_at.elapsed().as_millis() as u64,
last_read_age_ms = last_read_at.elapsed().as_millis() as u64,
last_write_age_ms = last_write_at.elapsed().as_millis() as u64,
write_pending = write_started_at.is_some(),
write_kind = if write_started_at.is_some() { write_kind } else { "none" },
write_wait_ms = write_started_at.map(|at| at.elapsed().as_millis() as u64).unwrap_or(0),
pong_pending = pong_watchdog.deadline().is_some(),
pong_deadline_overdue_ms = pong_watchdog.deadline()
.map(|at| Instant::now().saturating_duration_since(at).as_millis() as u64).unwrap_or(0),
frames_read,
records_written,
outgoing_queue_depth = outgoing_rx.len(),
incoming_queue_depth = incoming_tx.max_capacity() - incoming_tx.capacity(),
);
let _ = disconnected_tx.send(true);
}
.instrument(stream_span));
NoiseHarnessConnection {
connection: JsonRpcConnection {
outgoing_tx,
incoming_rx,
disconnected_rx,
task_handles: vec![websocket_task],
transport: JsonRpcTransport::Plain,
},
handshake_ready: handshake_ready_rx,
stream_id: connection_stream_id,
handshake_started,
}
}
// Classify locally typed errors only; their text can contain untrusted wire data.
fn websocket_read_error_reason(error: &WebSocketError) -> &'static str {
match error {
WebSocketError::Io(error) => match error.kind() {
std::io::ErrorKind::ConnectionReset => "websocket_read_connection_reset",
std::io::ErrorKind::ConnectionAborted => "websocket_read_connection_aborted",
std::io::ErrorKind::UnexpectedEof => "websocket_read_unexpected_eof",
std::io::ErrorKind::TimedOut => "websocket_read_timed_out",
_ => "websocket_read_io_other",
},
WebSocketError::Protocol(ProtocolError::ResetWithoutClosingHandshake) => {
"websocket_read_reset_without_close"
}
WebSocketError::Protocol(_) => "websocket_read_protocol",
WebSocketError::ConnectionClosed | WebSocketError::AlreadyClosed => "websocket_read_closed",
WebSocketError::Tls(_) => "websocket_read_tls",
_ => "websocket_read_other",
}
}
async fn send_websocket_message<T, E>(
websocket: &mut T,
message: Message,
deadline: tokio::time::Instant,
) -> Result<(), WebsocketWriteError>
where
T: Sink<Message, Error = E> + Unpin,
E: std::fmt::Display,
{
match tokio::time::timeout_at(deadline, websocket.send(message)).await {
Ok(Ok(())) => Ok(()),
Ok(Err(error)) => Err(WebsocketWriteError::Transport(error.to_string())),
Err(_) => Err(WebsocketWriteError::Timeout),
}
}
async fn send_keepalive_ping<T, E>(
websocket: &mut T,
pong_watchdog: &mut WebSocketPongWatchdog,
pong_deadline: std::pin::Pin<&mut tokio::time::Sleep>,
) -> Result<(), WebsocketWriteError>
where
T: Sink<Message, Error = E> + Unpin,
E: std::fmt::Display,
{
send_websocket_message(
websocket,
Message::Ping(Vec::new().into()),
pong_watchdog.write_deadline(tokio::time::Instant::now()),
)
.await?;
// Start the response clock after the Ping flushes; waiting for sink capacity
// is governed by the write deadline above.
pong_watchdog.ping_sent(tokio::time::Instant::now());
if let Some(deadline) = pong_watchdog.deadline() {
pong_deadline.reset(deadline);
}
Ok(())
}
/// Order and decrypt one relay frame, then emit any complete JSON-RPC messages.
/// Relay records and JSON-RPC messages do not share boundaries, so reassembly
/// happens after decryption.
async fn receive_data(
inbound_ciphertexts: &mut OrderedCiphertextFrames,
transport: &mut NoiseTransport,
decoder: &mut ClientJsonRpcMessageDecoder,
data: RelayData,
delivery_deadline: tokio::time::Instant,
incoming_tx: &mpsc::Sender<JsonRpcConnectionEvent>,
) -> Result<(), ExecServerError> {
// Ordering must happen before decryption because Noise transport nonces are
// implicit. A future or duplicate ciphertext passed directly to Clatter
// would desynchronize the channel.
for ciphertext in inbound_ciphertexts.push(data.seq, data.payload)? {
let plaintext = transport.decrypt(&ciphertext).map_err(|error| {
ExecServerError::Protocol(format!("Noise relay decryption failed: {error}"))
})?;
// The authenticated byte stream can carry partial or multiple JSON-RPC
// messages; emit only complete, successfully parsed messages.
for message in decoder.push(&plaintext)? {
send_incoming_event(
incoming_tx,
JsonRpcConnectionEvent::message(message),
delivery_deadline,
)
.await?;
}
}
Ok(())
}
async fn send_incoming_event(
incoming_tx: &mpsc::Sender<JsonRpcConnectionEvent>,
event: JsonRpcConnectionEvent,
deadline: tokio::time::Instant,
) -> Result<(), ExecServerError> {
let delivery_started = Instant::now();
match tokio::time::timeout_at(deadline, incoming_tx.send(event)).await {
Ok(Ok(())) => Ok(()),
Ok(Err(_)) => Err(ExecServerError::Closed),
Err(_) => {
tracing::event!(
name: "codex.exec_server.noise_application_backpressure",
target: "codex_otel.trace_safe",
tracing::Level::WARN,
event.name = "codex.exec_server.noise_application_backpressure",
noise_side = "harness",
noise_reason = "application_backpressure",
delivery_wait_ms = delivery_started.elapsed().as_millis() as u64,
incoming_queue_depth = incoming_tx.max_capacity() - incoming_tx.capacity(),
incoming_queue_capacity = incoming_tx.max_capacity(),
);
Err(ExecServerError::Closed)
}
}
}
fn send_malformed(incoming_tx: &mpsc::Sender<JsonRpcConnectionEvent>, reason: String) {
let _ = incoming_tx.try_send(JsonRpcConnectionEvent::MalformedMessage { reason });
}
fn send_disconnected(
incoming_tx: &mpsc::Sender<JsonRpcConnectionEvent>,
disconnected_tx: &watch::Sender<bool>,
reason: String,
) {
let _ = disconnected_tx.send(true);
let _ = incoming_tx.try_send(JsonRpcConnectionEvent::Disconnected {
reason: Some(reason),
});
}
#[cfg(test)]
#[path = "harness_tests.rs"]
mod tests;

View File

@@ -0,0 +1,109 @@
//! Fixed transport exit categories and bounded heartbeat progress telemetry.
//!
//! Keep wire values and error text out of these categories: CCA retains this
//! telemetry even when ordinary exec-server diagnostics are filtered out.
pub(super) enum TransportExitReason {
PongTimeout,
OutgoingClosed,
Framing,
SequenceExhausted,
Encryption,
WebsocketWriteTimeout,
WebsocketWrite,
WebsocketEnded,
InvalidFrame,
ApplicationDelivery,
InvalidData,
RelayReset,
WebsocketClose,
UnexpectedText,
WebsocketRead,
}
impl TransportExitReason {
pub(super) fn as_str(&self) -> &'static str {
match self {
Self::PongTimeout => "pong_timeout",
Self::OutgoingClosed => "outgoing_closed",
Self::Framing => "framing",
Self::SequenceExhausted => "sequence_exhausted",
Self::Encryption => "encryption",
Self::WebsocketWriteTimeout => "websocket_write_timeout",
Self::WebsocketWrite => "websocket_write",
Self::WebsocketEnded => "websocket_ended",
Self::InvalidFrame => "invalid_frame",
Self::ApplicationDelivery => "application_delivery",
Self::InvalidData => "invalid_data",
Self::RelayReset => "relay_reset",
Self::WebsocketClose => "websocket_close",
Self::UnexpectedText => "unexpected_text",
Self::WebsocketRead => "websocket_read",
}
}
}
#[derive(Debug, thiserror::Error)]
pub(super) enum WebsocketWriteError {
#[error("websocket write timed out")]
Timeout,
#[error("{0}")]
Transport(String),
}
impl WebsocketWriteError {
pub(super) fn exit_reason(&self) -> TransportExitReason {
match self {
Self::Timeout => TransportExitReason::WebsocketWriteTimeout,
Self::Transport(_) => TransportExitReason::WebsocketWrite,
}
}
}
/// WebSocket heartbeat progress only proves reachability of the relay peer, not
/// delivery to the executor behind it. Emit at most once per local Ping or Pong.
pub(super) enum HeartbeatProgress {
PingWritten,
PongReceived,
}
#[derive(Default)]
pub(super) struct HeartbeatDiagnostics {
pub(super) pings_written: u64,
pub(super) pongs_received: u64,
last_ping_at: Option<tokio::time::Instant>,
}
impl HeartbeatDiagnostics {
pub(super) fn record(&mut self, progress: HeartbeatProgress, stream_id: &str) {
let phase = match progress {
HeartbeatProgress::PingWritten => {
self.pings_written += 1;
self.last_ping_at = Some(tokio::time::Instant::now());
"ping_written"
}
HeartbeatProgress::PongReceived => {
// Unsolicited Pongs must not create unbounded telemetry volume.
if self.last_ping_at.is_none() {
return;
}
self.pongs_received += 1;
"pong_received"
}
};
tracing::event!(
name: "codex.exec_server.noise_heartbeat",
target: "codex_otel.trace_safe",
tracing::Level::INFO,
event.name = "codex.exec_server.noise_heartbeat",
stream_id,
phase,
pings_written = self.pings_written,
pongs_received = self.pongs_received,
ping_elapsed_ms = self.last_ping_at.map(|at| at.elapsed().as_millis() as u64).unwrap_or(0),
);
if matches!(progress, HeartbeatProgress::PongReceived) {
self.last_ping_at = None;
}
}
}

View File

@@ -0,0 +1,958 @@
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::task::Context as TaskContext;
use std::task::Poll;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use codex_exec_server_protocol::JSONRPCMessage;
use codex_exec_server_protocol::JSONRPCRequest;
use codex_exec_server_protocol::RequestId;
use codex_protocol::protocol::W3cTraceContext;
use futures::Sink;
use futures::SinkExt;
use futures::StreamExt;
use futures::channel::mpsc as futures_mpsc;
use pretty_assertions::assert_eq;
use tokio::net::TcpListener;
use tokio::sync::mpsc;
use tokio::time::Instant;
use tokio::time::timeout;
use tokio_tungstenite::accept_async;
use tokio_tungstenite::connect_async;
use tokio_tungstenite::tungstenite::Message;
use super::*;
use crate::connection::JsonRpcConnectionEvent;
use crate::noise_channel::PendingResponderHandshake;
fn noise_harness_connection_from_websocket<T>(
stream: T,
args: NoiseHarnessConnectionArgs,
) -> JsonRpcConnection
where
T: Sink<Message, Error = WebSocketError>
+ Stream<Item = Result<Message, WebSocketError>>
+ Unpin
+ Send
+ 'static,
{
noise_harness_connection_from_websocket_with_readiness(stream, args).connection
}
const ENVIRONMENT_ID: &str = "environment-1";
const EXECUTOR_REGISTRATION_ID: &str = "registration-1";
#[test]
fn websocket_read_diagnostics_use_typed_errors_only() {
let reset = std::io::Error::new(std::io::ErrorKind::ConnectionReset, "private data");
for (error, expected) in [
(WebSocketError::Io(reset), "websocket_read_connection_reset"),
(
WebSocketError::Protocol(ProtocolError::ResetWithoutClosingHandshake),
"websocket_read_reset_without_close",
),
(
WebSocketError::Protocol(ProtocolError::InvalidOpcode(255)),
"websocket_read_protocol",
),
] {
assert_eq!(websocket_read_error_reason(&error), expected);
}
}
#[tokio::test(start_paused = true)]
async fn first_encrypted_request_frame_exposes_only_its_trace_context() -> Result<()> {
use opentelemetry::trace::TracerProvider as _;
use opentelemetry_sdk::trace::InMemorySpanExporter;
use opentelemetry_sdk::trace::SdkTracerProvider;
use tracing_subscriber::prelude::*;
let exporter = InMemorySpanExporter::default();
let provider = SdkTracerProvider::builder()
.with_simple_exporter(exporter.clone())
.build();
let events = SafeEvents::default();
let _subscriber = tracing::subscriber::set_default(
tracing_subscriber::registry()
.with(
events
.clone()
.with_filter(tracing_subscriber::filter::LevelFilter::INFO),
)
.with(
tracing_opentelemetry::layer()
.with_tracer(provider.tracer("harness-test"))
.with_filter(tracing_subscriber::filter::LevelFilter::INFO),
),
);
let (connection, mut control, mut outbound_rx) = connected_controlled_harness().await?;
let traceparent = "00-00000000000000000000000000000001-0000000000000002-01";
let tracestate = "dd=s:1";
connection
.outgoing_tx
.send(JSONRPCMessage::Request(JSONRPCRequest {
id: RequestId::Integer(1),
method: "fs/getMetadata".to_string(),
params: Some(serde_json::json!({
"payload": "x".repeat(NOISE_RECORD_PLAINTEXT_LEN * 2),
})),
trace: Some(W3cTraceContext {
traceparent: Some(traceparent.to_string()),
tracestate: Some(tracestate.to_string()),
}),
}))
.await?;
control.wait_for_blocked_write(/*expected*/ 1).await?;
{
let captured = events.0.lock().unwrap();
let dequeue = captured
.iter()
.find(|event| {
event
.get("event.name")
.is_some_and(|name| name.contains("request_dequeued"))
})
.context("live dequeue")?;
assert_eq!(
dequeue.get("trace_id").map(String::as_str),
Some("00000000000000000000000000000001")
);
assert!(
exporter
.get_finished_spans()?
.iter()
.all(|span| span.name != "codex.exec_server.noise_request_write")
);
}
control.grant_writes(/*count*/ 1);
let first = read_outbound_frame(&mut outbound_rx).await?;
assert_eq!(
(first.traceparent.as_deref(), first.tracestate.as_deref()),
(Some(traceparent), Some(tracestate))
);
let stream_id = first.stream_id.clone();
let first_payload = first.into_data()?.payload;
assert!(
!first_payload
.windows("fs/getMetadata".len())
.any(|window| window == b"fs/getMetadata")
);
control.wait_for_blocked_write(/*expected*/ 2).await?;
control.grant_writes(/*count*/ 1);
let second = read_outbound_frame(&mut outbound_rx).await?;
assert_eq!((second.traceparent, second.tracestate), (None, None));
assert!(!format!("{:?}", events.0.lock().unwrap()).contains("request_written"));
control.wait_for_blocked_write(/*expected*/ 3).await?;
control.grant_writes(/*count*/ 1);
read_outbound_frame(&mut outbound_rx).await?;
let spans = exporter.get_finished_spans()?;
let write_span = spans
.iter()
.find(|span| span.name == "codex.exec_server.noise_request_write")
.context("expected finished request write span")?;
assert_eq!(
write_span.span_context.trace_id().to_string(),
"00000000000000000000000000000001"
);
assert_eq!(write_span.parent_span_id.to_string(), "0000000000000002");
let captured = events.0.lock().unwrap();
let progress: Vec<_> = captured
.iter()
.filter(|e| {
e.get("event.name").is_some_and(|name| {
name.contains("request_dequeued") || name.contains("request_written")
})
})
.collect();
assert_eq!(progress.len(), 2);
for event in &progress {
assert_eq!(
event.get("trace_id").map(String::as_str),
Some("00000000000000000000000000000001")
);
}
assert_eq!(progress[0]["stream_id"], format!("{stream_id:?}"));
assert_eq!(progress[0]["stream_id"], progress[1]["stream_id"]);
assert_eq!(
progress[0]["message_sequence"],
progress[1]["message_sequence"]
);
drop(captured);
for task in &connection.task_handles {
task.abort();
}
Ok(())
}
#[tokio::test(start_paused = true)]
async fn fragmented_writes_yield_to_keepalive_and_queued_pong() -> Result<()> {
let (connection, mut control, mut outbound_rx) = connected_controlled_harness().await?;
connection
.outgoing_tx
.send(JSONRPCMessage::Request(JSONRPCRequest {
id: RequestId::Integer(1),
method: "large".to_string(),
params: Some(serde_json::json!({
"payload": "x".repeat(NOISE_RECORD_PLAINTEXT_LEN * 3),
})),
trace: None,
}))
.await?;
control.wait_for_blocked_write(/*expected*/ 1).await?;
tokio::time::advance(WEBSOCKET_KEEPALIVE_INTERVAL + Duration::from_millis(10)).await;
control.grant_writes(/*count*/ 1);
let first_data = read_outbound_data(&mut outbound_rx).await?;
assert_eq!(first_data.seq, 0);
control.wait_for_blocked_write(/*expected*/ 2).await?;
control.grant_writes(/*count*/ 1);
let Message::Ping(ping_payload) = timeout(Duration::from_secs(1), outbound_rx.next())
.await?
.context("harness closed before sending keepalive")?
else {
anyhow::bail!("expected keepalive between fragmented writes");
};
control.wait_for_blocked_write(/*expected*/ 3).await?;
control.send_inbound(Message::Pong(ping_payload))?;
tokio::time::advance(WEBSOCKET_KEEPALIVE_INTERVAL + Duration::from_millis(10)).await;
control.grant_writes(/*count*/ 1);
let second_data = read_outbound_data(&mut outbound_rx).await?;
assert_eq!(second_data.seq, 1);
control.wait_for_blocked_write(/*expected*/ 4).await?;
control.grant_writes(/*count*/ 1);
let next_message = timeout(Duration::from_secs(1), outbound_rx.next())
.await?
.context("harness closed after receiving queued Pong")?;
assert!(matches!(next_message, Message::Ping(_)));
for task in &connection.task_handles {
task.abort();
}
Ok(())
}
#[tokio::test(flavor = "current_thread")]
async fn post_deadline_drain_stops_before_frame_33() -> Result<()> {
let (mut connection, mut control, mut outbound_rx) = connected_controlled_harness().await?;
control.wait_for_blocked_write(/*expected*/ 1).await?;
control.grant_writes(/*count*/ 1);
let Message::Ping(ping_payload) = timeout(Duration::from_secs(1), outbound_rx.next())
.await?
.context("harness closed before sending keepalive")?
else {
anyhow::bail!("expected keepalive ping");
};
let reads_before_deadline = control.inbound_reads();
let unrelated_frame =
encode_relay_message_frame(&RelayMessageFrame::resume("unrelated-stream".to_string()));
for _ in 0..MAX_FRAMES_DRAINED_AFTER_PONG_DEADLINE {
control.send_inbound(Message::Binary(unrelated_frame.clone().into()))?;
}
control.send_inbound(Message::Pong(ping_payload))?;
// Keep the current-thread runtime from consuming the queued frames until the
// Pong deadline and every frame are ready together.
std::thread::sleep(WEBSOCKET_PONG_TIMEOUT + Duration::from_millis(10));
let event = timeout(Duration::from_secs(1), connection.incoming_rx.recv()).await?;
let Some(JsonRpcConnectionEvent::Disconnected { reason }) = event else {
anyhow::bail!("expected Pong timeout, got {event:?}");
};
assert_eq!(reason.as_deref(), Some(WEBSOCKET_PONG_TIMEOUT_REASON));
assert_eq!(
control.inbound_reads() - reads_before_deadline,
MAX_FRAMES_DRAINED_AFTER_PONG_DEADLINE
);
Ok(())
}
#[tokio::test]
async fn pong_keeps_harness_alive_until_peer_stops_responding() -> Result<()> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let websocket_url = format!("ws://{}", listener.local_addr()?);
let harness_connection = tokio::spawn(connect_async(websocket_url));
let (socket, _peer_addr) = listener.accept().await?;
let mut executor_websocket = accept_async(socket).await?;
let (harness_websocket, _response) = harness_connection.await??;
let executor_identity = NoiseChannelIdentity::generate()?;
let mut connection = noise_harness_connection_from_websocket(
harness_websocket,
NoiseHarnessConnectionArgs {
connection_label: "test rendezvous".to_string(),
environment_id: ENVIRONMENT_ID.to_string(),
executor_registration_id: EXECUTOR_REGISTRATION_ID.to_string(),
identity: NoiseChannelIdentity::generate()?,
responder_public_key: executor_identity.public_key(),
harness_key_authorization: "authorization".to_string(),
},
);
let resume_message = timeout(Duration::from_secs(1), executor_websocket.next())
.await?
.context("harness closed before sending resume")??;
let Message::Binary(resume_payload) = resume_message else {
anyhow::bail!("expected resume frame, got {resume_message:?}");
};
let resume = decode_relay_message_frame(resume_payload.as_ref())?;
assert_eq!(resume.validate()?, RelayFrameBodyKind::Resume);
let handshake_message = timeout(Duration::from_secs(1), executor_websocket.next())
.await?
.context("harness closed before sending handshake")??;
let Message::Binary(handshake_payload) = handshake_message else {
anyhow::bail!("expected handshake frame, got {handshake_message:?}");
};
let handshake = decode_relay_message_frame(handshake_payload.as_ref())?;
assert_eq!(handshake.stream_id, resume.stream_id);
let stream_id = handshake.stream_id.clone();
let prologue =
noise_channel_prologue(ENVIRONMENT_ID, EXECUTOR_REGISTRATION_ID, stream_id.as_str());
let pending = PendingResponderHandshake::read_request(
&executor_identity,
&prologue,
&handshake.into_handshake_payload()?,
)?;
let (_transport, response) = pending.complete()?;
let response = RelayMessageFrame::handshake(stream_id, response);
executor_websocket
.send(Message::Binary(
encode_relay_message_frame(&response).into(),
))
.await?;
let mut pings = 0;
while pings < 6 {
let message = timeout(Duration::from_secs(1), executor_websocket.next())
.await?
.context("harness disconnected before six keepalive pings")??;
match message {
Message::Ping(payload) => {
executor_websocket.send(Message::Pong(payload)).await?;
pings += 1;
}
Message::Pong(_) | Message::Frame(_) => {}
message => anyhow::bail!("expected keepalive ping, got {message:?}"),
}
}
// Keep non-Pong traffic flowing after responses stop. It must not defeat
// the bounded grace for a Pong already queued behind data.
let unrelated_frame =
encode_relay_message_frame(&RelayMessageFrame::resume("unrelated-stream".to_string()));
let traffic_task = tokio::spawn(async move {
loop {
if executor_websocket
.send(Message::Binary(unrelated_frame.clone().into()))
.await
.is_err()
{
break;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
});
let event = timeout(Duration::from_secs(1), connection.incoming_rx.recv()).await?;
traffic_task.abort();
let _ = traffic_task.await;
let Some(JsonRpcConnectionEvent::Disconnected { reason }) = event else {
anyhow::bail!("expected pong timeout, got {event:?}");
};
assert_eq!(reason.as_deref(), Some(WEBSOCKET_PONG_TIMEOUT_REASON));
Ok(())
}
/// A full consumer queue times out with occupancy and wait duration, without logging its data.
#[tokio::test(start_paused = true)]
async fn application_event_delivery_is_bounded() -> Result<()> {
use tracing_subscriber::prelude::*;
let events = SafeEvents::default();
let _subscriber =
tracing::subscriber::set_default(tracing_subscriber::registry().with(events.clone()));
let (incoming_tx, _incoming_rx) = mpsc::channel(1);
incoming_tx
.send(JsonRpcConnectionEvent::MalformedMessage {
reason: "fill queue".to_string(),
})
.await?;
let result = send_incoming_event(
&incoming_tx,
JsonRpcConnectionEvent::MalformedMessage {
reason: "blocked event".to_string(),
},
Instant::now() + Duration::from_millis(10),
)
.await;
assert!(matches!(result, Err(ExecServerError::Closed)));
let events = events.0.lock().unwrap();
assert_eq!(events.len(), 1);
let event = &events[0];
assert_eq!(event["noise_reason"], "\"application_backpressure\"");
assert_eq!(event["incoming_queue_depth"], "1");
assert_eq!(event["incoming_queue_capacity"], "1");
assert!(event["delivery_wait_ms"].parse::<u64>()? >= 10);
assert!(!format!("{events:?}").contains("blocked event"));
Ok(())
}
async fn read_outbound_data(
outbound_rx: &mut futures_mpsc::UnboundedReceiver<Message>,
) -> Result<RelayData> {
read_outbound_frame(outbound_rx)
.await?
.into_data()
.map_err(anyhow::Error::from)
}
async fn read_outbound_frame(
outbound_rx: &mut futures_mpsc::UnboundedReceiver<Message>,
) -> Result<RelayMessageFrame> {
let Message::Binary(payload) = timeout(Duration::from_secs(1), outbound_rx.next())
.await?
.context("harness closed before sending data")?
else {
anyhow::bail!("expected relay data frame");
};
let frame = decode_relay_message_frame(payload.as_ref())?;
assert_eq!(frame.validate()?, RelayFrameBodyKind::Data);
Ok(frame)
}
async fn connected_controlled_harness() -> Result<(
JsonRpcConnection,
ControlledWebSocketHandle,
futures_mpsc::UnboundedReceiver<Message>,
)> {
let (connection, control, outbound_rx, _transport, _stream_id) =
connected_controlled_harness_with_transport().await?;
Ok((connection, control, outbound_rx))
}
async fn connected_controlled_harness_with_transport() -> Result<(
JsonRpcConnection,
ControlledWebSocketHandle,
futures_mpsc::UnboundedReceiver<Message>,
NoiseTransport,
String,
)> {
let (websocket, control, mut outbound_rx) = ControlledWebSocket::new(/*write_permits*/ 2);
let executor_identity = NoiseChannelIdentity::generate()?;
let connection = noise_harness_connection_from_websocket(
websocket,
NoiseHarnessConnectionArgs {
connection_label: "test rendezvous".to_string(),
environment_id: ENVIRONMENT_ID.to_string(),
executor_registration_id: EXECUTOR_REGISTRATION_ID.to_string(),
identity: NoiseChannelIdentity::generate()?,
responder_public_key: executor_identity.public_key(),
harness_key_authorization: "authorization".to_string(),
},
);
let Message::Binary(resume_payload) = timeout(Duration::from_secs(1), outbound_rx.next())
.await?
.context("harness closed before sending resume")?
else {
anyhow::bail!("expected resume frame");
};
let resume = decode_relay_message_frame(resume_payload.as_ref())?;
let Message::Binary(handshake_payload) = timeout(Duration::from_secs(1), outbound_rx.next())
.await?
.context("harness closed before sending handshake")?
else {
anyhow::bail!("expected handshake frame");
};
let handshake = decode_relay_message_frame(handshake_payload.as_ref())?;
let stream_id = handshake.stream_id.clone();
assert_eq!(stream_id, resume.stream_id);
let prologue =
noise_channel_prologue(ENVIRONMENT_ID, EXECUTOR_REGISTRATION_ID, stream_id.as_str());
let pending = PendingResponderHandshake::read_request(
&executor_identity,
&prologue,
&handshake.into_handshake_payload()?,
)?;
let (transport, response) = pending.complete()?;
control.send_inbound(Message::Binary(
encode_relay_message_frame(&RelayMessageFrame::handshake(stream_id.clone(), response))
.into(),
))?;
Ok((connection, control, outbound_rx, transport, stream_id))
}
struct ControlledWebSocket {
inbound_rx: futures_mpsc::UnboundedReceiver<Result<Message, WebSocketError>>,
outbound_tx: futures_mpsc::UnboundedSender<Message>,
write_permit_rx: futures_mpsc::UnboundedReceiver<()>,
blocked_write_tx: futures_mpsc::UnboundedSender<usize>,
write_waiting: bool,
blocked_writes: usize,
inbound_reads: Arc<AtomicUsize>,
}
struct ControlledWebSocketHandle {
inbound_tx: futures_mpsc::UnboundedSender<Result<Message, WebSocketError>>,
write_permit_tx: futures_mpsc::UnboundedSender<()>,
blocked_write_rx: futures_mpsc::UnboundedReceiver<usize>,
inbound_reads: Arc<AtomicUsize>,
}
impl ControlledWebSocket {
fn new(
write_permits: usize,
) -> (
Self,
ControlledWebSocketHandle,
futures_mpsc::UnboundedReceiver<Message>,
) {
let (inbound_tx, inbound_rx) = futures_mpsc::unbounded();
let (outbound_tx, outbound_rx) = futures_mpsc::unbounded();
let (write_permit_tx, write_permit_rx) = futures_mpsc::unbounded();
let (blocked_write_tx, blocked_write_rx) = futures_mpsc::unbounded();
for _ in 0..write_permits {
write_permit_tx
.unbounded_send(())
.expect("test write permit receiver should stay open");
}
let inbound_reads = Arc::new(AtomicUsize::new(0));
(
Self {
inbound_rx,
outbound_tx,
write_permit_rx,
blocked_write_tx,
write_waiting: false,
blocked_writes: 0,
inbound_reads: Arc::clone(&inbound_reads),
},
ControlledWebSocketHandle {
inbound_tx,
write_permit_tx,
blocked_write_rx,
inbound_reads,
},
outbound_rx,
)
}
}
impl ControlledWebSocketHandle {
fn send_inbound(&self, message: Message) -> Result<()> {
self.inbound_tx
.unbounded_send(Ok(message))
.map_err(anyhow::Error::from)
}
fn grant_writes(&self, count: usize) {
for _ in 0..count {
self.write_permit_tx
.unbounded_send(())
.expect("test write permit receiver should stay open");
}
}
fn inbound_reads(&self) -> usize {
self.inbound_reads.load(Ordering::Acquire)
}
async fn wait_for_blocked_write(&mut self, expected: usize) -> Result<()> {
let actual = timeout(Duration::from_secs(1), self.blocked_write_rx.next())
.await?
.context("websocket closed before blocking the expected write")?;
assert_eq!(actual, expected);
Ok(())
}
}
impl Sink<Message> for ControlledWebSocket {
type Error = WebSocketError;
fn poll_ready(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Result<(), Self::Error>> {
let this = self.get_mut();
match Pin::new(&mut this.write_permit_rx).poll_next(cx) {
Poll::Ready(Some(())) => {
this.write_waiting = false;
Poll::Ready(Ok(()))
}
Poll::Ready(None) | Poll::Pending => {
if !this.write_waiting {
this.write_waiting = true;
this.blocked_writes += 1;
this.blocked_write_tx
.unbounded_send(this.blocked_writes)
.expect("test blocked-write receiver should stay open");
}
Poll::Pending
}
}
}
fn start_send(self: Pin<&mut Self>, item: Message) -> Result<(), Self::Error> {
self.outbound_tx
.unbounded_send(item)
.expect("test outbound receiver should stay open");
Ok(())
}
fn poll_flush(
self: Pin<&mut Self>,
_cx: &mut TaskContext<'_>,
) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn poll_close(
self: Pin<&mut Self>,
_cx: &mut TaskContext<'_>,
) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
}
impl futures::Stream for ControlledWebSocket {
type Item = Result<Message, WebSocketError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Option<Self::Item>> {
let result = Pin::new(&mut self.inbound_rx).poll_next(cx);
if matches!(result, Poll::Ready(Some(_))) {
self.inbound_reads.fetch_add(1, Ordering::Release);
}
result
}
}
#[derive(Clone, Default)]
struct SafeEvents(Arc<std::sync::Mutex<Vec<std::collections::BTreeMap<String, String>>>>);
impl<S> tracing_subscriber::Layer<S> for SafeEvents
where
S: tracing::Subscriber + for<'lookup> tracing_subscriber::registry::LookupSpan<'lookup>,
{
fn on_event(
&self,
event: &tracing::Event<'_>,
context: tracing_subscriber::layer::Context<'_, S>,
) {
if event.metadata().target() != "codex_otel.trace_safe" {
return;
}
#[derive(Default)]
struct Fields(std::collections::BTreeMap<String, String>);
impl tracing::field::Visit for Fields {
fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
self.0.insert(field.name().to_owned(), format!("{value:?}"));
}
}
let mut fields = Fields::default();
event.record(&mut fields);
// Match CCA's live JSON lookup: inspecting OtelData must not materialize
// the context and accidentally hide a missing producer initialization.
if let Some(trace_id) = context.event_scope(event).and_then(|mut scope| {
scope.find_map(|span| {
span.extensions()
.get::<tracing_opentelemetry::OtelData>()?
.trace_id()
})
}) {
fields.0.insert("trace_id".to_owned(), trace_id.to_string());
}
self.0.lock().unwrap().push(fields.0);
}
}
/// A blocked write can time out with a Pong queued; its diagnostic must distinguish this
/// local write stall from the read loop's missing-Pong watchdog.
#[tokio::test(start_paused = true)]
async fn blocked_write_reports_timeout_with_pong_still_queued() -> Result<()> {
use tracing_subscriber::prelude::*;
let events = SafeEvents::default();
let _subscriber =
tracing::subscriber::set_default(tracing_subscriber::registry().with(events.clone()));
let (mut connection, mut control, mut outbound_rx) = connected_controlled_harness().await?;
control.wait_for_blocked_write(/*expected*/ 1).await?;
control.grant_writes(/*count*/ 1);
let Message::Ping(payload) = outbound_rx.next().await.context("expected Ping")? else {
anyhow::bail!("expected Ping before blocked write");
};
connection
.outgoing_tx
.send(JSONRPCMessage::Request(JSONRPCRequest {
id: RequestId::Integer(1),
method: "SYNTHETIC_PRIVATE_METHOD".to_owned(),
params: Some(serde_json::json!({"secret": "SYNTHETIC_PRIVATE_PAYLOAD"})),
trace: None,
}))
.await?;
control.wait_for_blocked_write(/*expected*/ 2).await?;
connection
.outgoing_tx
.send(JSONRPCMessage::Request(JSONRPCRequest {
id: RequestId::Integer(2),
method: "SYNTHETIC_PRIVATE_QUEUED".to_owned(),
params: None,
trace: None,
}))
.await?;
let reads = control.inbound_reads();
control.send_inbound(Message::Pong(payload))?;
tokio::time::advance(WEBSOCKET_PONG_TIMEOUT + Duration::from_millis(1)).await;
for task in connection.task_handles.drain(..) {
task.await?;
}
assert_eq!(control.inbound_reads(), reads);
assert!(*connection.disconnected_rx.borrow());
let events = events.0.lock().unwrap();
let terminal: Vec<_> = events
.iter()
.filter(|e| {
e.get("event.name")
.is_some_and(|name| name == "\"codex.exec_server.noise_transport_closed\"")
})
.collect();
assert_eq!(terminal.len(), 1);
let event = terminal[0];
assert_eq!(event["noise_reason"], "\"websocket_write_timeout\"");
assert_eq!(event["write_pending"], "true");
assert_eq!(event["write_kind"], "\"data\"");
assert_eq!(event["pong_pending"], "true");
assert_eq!(event["records_written"], "0");
assert_eq!(event["messages_dequeued"], "1");
assert_eq!(event["messages_written"], "0");
assert_eq!(event["outgoing_queue_depth"], "1");
assert_eq!(event["pings_written"], "1");
assert_eq!(event["pongs_received"], "0");
assert!(!format!("{events:?}").contains("request_written"));
assert!(event["write_wait_ms"].parse::<u64>()? >= WEBSOCKET_PONG_TIMEOUT.as_millis() as u64);
assert!(!format!("{events:?}").contains("SYNTHETIC_PRIVATE"));
Ok(())
}
/// Peer-controlled read errors must produce a fixed terminal category without retaining
/// the raw error, even though ordinary debug logs still carry it.
#[tokio::test(start_paused = true)]
async fn read_error_reports_safe_terminal_category() -> Result<()> {
use tracing_subscriber::prelude::*;
let events = SafeEvents::default();
let _subscriber =
tracing::subscriber::set_default(tracing_subscriber::registry().with(events.clone()));
let (mut connection, control, _outbound_rx) = connected_controlled_harness().await?;
control
.inbound_tx
.unbounded_send(Err(WebSocketError::Io(std::io::Error::other(
"SYNTHETIC_PRIVATE_ERROR",
))))?;
for task in connection.task_handles.drain(..) {
task.await?;
}
let events = events.0.lock().unwrap();
let event = events.last().context("expected terminal event")?;
assert_eq!(
event["event.name"],
"\"codex.exec_server.noise_transport_closed\""
);
assert_eq!(event["noise_reason"], "\"websocket_read\"");
assert_eq!(event["read_reason"], "\"websocket_read_io_other\"");
assert!(!format!("{events:?}").contains("SYNTHETIC_PRIVATE_ERROR"));
Ok(())
}
/// A keepalive write stall has no outstanding Pong yet; retain that distinction
/// when a disconnect aligns with the periodic keepalive schedule.
#[tokio::test(start_paused = true)]
async fn blocked_keepalive_reports_write_phase_without_pong_deadline() -> Result<()> {
use tracing_subscriber::prelude::*;
let events = SafeEvents::default();
let _subscriber =
tracing::subscriber::set_default(tracing_subscriber::registry().with(events.clone()));
let (mut connection, mut control, _outbound_rx) = connected_controlled_harness().await?;
control.wait_for_blocked_write(/*expected*/ 1).await?;
tokio::time::advance(WEBSOCKET_PONG_TIMEOUT + Duration::from_millis(1)).await;
for task in connection.task_handles.drain(..) {
task.await?;
}
let events = events.0.lock().unwrap();
let event = events.last().context("expected terminal event")?;
assert_eq!(event["noise_reason"], "\"websocket_write_timeout\"");
assert_eq!(event["write_kind"], "\"keepalive\"");
assert_eq!(event["pong_pending"], "false");
assert_eq!(event["write_pending"], "true");
Ok(())
}
/// Successful local writes with no inbound traffic reproduce a blackholed path,
/// which must report a Pong timeout rather than a blocked write.
#[tokio::test(start_paused = true)]
async fn blackholed_peer_reports_pong_timeout_after_successful_writes() -> Result<()> {
use tracing_subscriber::prelude::*;
let events = SafeEvents::default();
let _subscriber =
tracing::subscriber::set_default(tracing_subscriber::registry().with(events.clone()));
let (mut connection, mut control, mut outbound_rx) = connected_controlled_harness().await?;
control.wait_for_blocked_write(/*expected*/ 1).await?;
control.grant_writes(/*count*/ 1);
assert!(matches!(outbound_rx.next().await, Some(Message::Ping(_))));
connection
.outgoing_tx
.send(JSONRPCMessage::Request(JSONRPCRequest {
id: RequestId::Integer(1),
method: "test".to_owned(),
params: None,
trace: None,
}))
.await?;
control.wait_for_blocked_write(/*expected*/ 2).await?;
control.grant_writes(/*count*/ 1);
read_outbound_data(&mut outbound_rx).await?;
tokio::time::advance(WEBSOCKET_PONG_TIMEOUT / 2).await;
assert!(!*connection.disconnected_rx.borrow());
tokio::time::advance(WEBSOCKET_PONG_TIMEOUT / 2 + Duration::from_millis(1)).await;
for task in connection.task_handles.drain(..) {
task.await?;
}
let events = events.0.lock().unwrap();
let event = events.last().context("expected terminal event")?;
assert_eq!(event["noise_reason"], "\"pong_timeout\"");
assert_eq!(event["write_pending"], "false");
assert_eq!(event["records_written"], "1");
assert_eq!(event["messages_dequeued"], "1");
assert_eq!(event["messages_written"], "1");
assert_eq!(event["pings_written"], "1");
assert_eq!(event["pongs_received"], "0");
assert!(format!("{events:?}").contains("request_written"));
assert_eq!(event["pong_pending"], "true");
Ok(())
}
/// A stalled application consumer can prevent the shared loop from reading an
/// already queued Pong; retain queue saturation separately from network timeout.
#[tokio::test(start_paused = true)]
async fn full_application_queue_reports_backpressure_with_pong_queued() -> Result<()> {
use tracing_subscriber::prelude::*;
let events = SafeEvents::default();
let _subscriber =
tracing::subscriber::set_default(tracing_subscriber::registry().with(events.clone()));
let (mut connection, mut control, mut outbound_rx, mut transport, stream_id) =
connected_controlled_harness_with_transport().await?;
control.wait_for_blocked_write(/*expected*/ 1).await?;
control.grant_writes(/*count*/ 1);
let Some(Message::Ping(payload)) = outbound_rx.next().await else {
anyhow::bail!("expected Ping");
};
let framed = frame_jsonrpc_message(&JSONRPCMessage::Response(
codex_exec_server_protocol::JSONRPCResponse {
id: RequestId::Integer(1),
result: serde_json::json!({"private": "SYNTHETIC_PRIVATE_RESPONSE"}),
},
))?;
let reads = control.inbound_reads();
for seq in 0..=CHANNEL_CAPACITY {
let frame = RelayMessageFrame::data(
stream_id.clone(),
seq as u32,
transport.encrypt(&framed)?,
/*trace*/ None,
);
control.send_inbound(Message::Binary(encode_relay_message_frame(&frame).into()))?;
}
control.send_inbound(Message::Pong(payload))?;
// Awaiting the task lets the paused clock advance only once frame processing
// has filled the application queue and is waiting on its delivery deadline.
for task in connection.task_handles.drain(..) {
task.await?;
}
assert_eq!(control.inbound_reads() - reads, CHANNEL_CAPACITY + 1);
assert_eq!(connection.incoming_rx.len(), CHANNEL_CAPACITY);
let events = events.0.lock().unwrap();
let backpressure = events
.iter()
.find(|event| {
event
.get("noise_reason")
.is_some_and(|value| value == "\"application_backpressure\"")
})
.context("expected application backpressure")?;
assert_eq!(
backpressure["incoming_queue_depth"],
CHANNEL_CAPACITY.to_string()
);
let terminal = events.last().context("expected terminal event")?;
assert_eq!(terminal["noise_reason"], "\"application_delivery\"");
assert_eq!(terminal["pong_pending"], "true");
assert!(!format!("{events:?}").contains("SYNTHETIC_PRIVATE_RESPONSE"));
Ok(())
}
/// A responsive relay can coexist with a missing executor response. Ping/Pong
/// progress must remain distinct from successful application delivery.
#[tokio::test(start_paused = true)]
async fn responsive_relay_without_application_response_reports_progress() -> Result<()> {
use tracing_subscriber::prelude::*;
let events = SafeEvents::default();
let _subscriber =
tracing::subscriber::set_default(tracing_subscriber::registry().with(events.clone()));
let (mut connection, mut control, mut outbound_rx) = connected_controlled_harness().await?;
connection
.outgoing_tx
.send(JSONRPCMessage::Request(JSONRPCRequest {
id: RequestId::Integer(1),
method: "SYNTHETIC_PRIVATE_METHOD".to_owned(),
params: None,
trace: None,
}))
.await?;
control.wait_for_blocked_write(/*expected*/ 1).await?;
control.grant_writes(/*count*/ 1);
read_outbound_data(&mut outbound_rx).await?;
for expected in 2..=3 {
control.wait_for_blocked_write(expected).await?;
control.grant_writes(/*count*/ 1);
let Some(Message::Ping(payload)) = outbound_rx.next().await else {
anyhow::bail!("expected Ping")
};
for _ in 0..3 {
control.send_inbound(Message::Pong(payload.clone()))?;
}
}
// A subsequent Close is ordered behind the last Pong and completes the summary.
control.send_inbound(Message::Close(None))?;
for task in connection.task_handles.drain(..) {
task.await?;
}
assert!(connection.incoming_rx.is_empty());
let captured = events.0.lock().unwrap();
let terminal = captured.last().context("expected terminal")?;
assert_eq!(terminal["noise_reason"], "\"websocket_close\"");
assert_eq!(terminal["messages_written"], "1");
assert_eq!(terminal["pings_written"], "2");
assert_eq!(terminal["pongs_received"], "2");
let heartbeats: Vec<_> = captured
.iter()
.filter_map(|event| event.get("phase"))
.collect();
assert_eq!(
heartbeats,
vec![
"\"ping_written\"",
"\"pong_received\"",
"\"ping_written\"",
"\"pong_received\""
]
);
assert!(!format!("{captured:?}").contains("SYNTHETIC_PRIVATE"));
Ok(())
}

View File

@@ -0,0 +1,159 @@
use bytes::Buf;
use bytes::Bytes;
use bytes::BytesMut;
use codex_exec_server_protocol::JSONRPCMessage;
use crate::ExecServerError;
use crate::client_inbound_request_limit::MAX_CLIENT_INBOUND_REQUEST_LEN;
use crate::client_inbound_request_limit::client_inbound_message_exceeded_limit;
const LENGTH_PREFIX_BYTES: usize = size_of::<u32>();
pub(crate) const MAX_NOISE_JSONRPC_MESSAGE_LEN: usize = 64 * 1024 * 1024;
pub(crate) const NOISE_RECORD_PLAINTEXT_LEN: usize = 60 * 1024;
/// Serialize one JSON-RPC message into the encrypted record byte stream.
///
/// Clatter limits an individual Noise message to 65,535 bytes, while valid
/// exec-server responses can be much larger. A four-byte authenticated length
/// prefix lets the caller split this byte stream into bounded Noise records and
/// lets the receiver reconstruct exact JSON-RPC message boundaries.
pub(crate) fn frame_jsonrpc_message(message: &JSONRPCMessage) -> Result<Vec<u8>, ExecServerError> {
let mut framed = vec![0; LENGTH_PREFIX_BYTES];
serde_json::to_writer(&mut framed, message)?;
let prefix = message_length_prefix(framed.len() - LENGTH_PREFIX_BYTES)?;
framed[..LENGTH_PREFIX_BYTES].copy_from_slice(&prefix);
Ok(framed)
}
pub(crate) fn frame_message(message: &[u8]) -> Result<Vec<u8>, ExecServerError> {
let prefix = message_length_prefix(message.len())?;
let mut framed = Vec::with_capacity(LENGTH_PREFIX_BYTES + message.len());
framed.extend_from_slice(&prefix);
framed.extend_from_slice(message);
Ok(framed)
}
fn message_length_prefix(message_len: usize) -> Result<[u8; LENGTH_PREFIX_BYTES], ExecServerError> {
if message_len == 0 || message_len > MAX_NOISE_JSONRPC_MESSAGE_LEN {
return Err(ExecServerError::Protocol(
"Noise relay JSON-RPC message exceeds maximum length".to_string(),
));
}
Ok((message_len as u32).to_be_bytes())
}
/// Incrementally reconstructs authenticated JSON-RPC messages from Noise records.
///
/// The length prefix is encrypted along with the message. It is still bounded
/// here so a bad authenticated peer cannot grow the reassembly buffer forever.
#[derive(Default)]
pub(crate) struct JsonRpcMessageDecoder {
decoder: MessageDecoder,
}
impl JsonRpcMessageDecoder {
pub(crate) fn push(
&mut self,
plaintext_record: &[u8],
) -> Result<Vec<JSONRPCMessage>, ExecServerError> {
self.decoder
.push(plaintext_record)?
.into_iter()
.map(|message| serde_json::from_slice(&message).map_err(Into::into))
.collect()
}
}
/// Reassembles opaque application payloads without interpreting their schema.
#[derive(Default)]
pub(crate) struct MessageDecoder {
buffered: BytesMut,
}
impl MessageDecoder {
/// Append one decrypted record and return all complete framed messages.
pub(crate) fn push(&mut self, plaintext_record: &[u8]) -> Result<Vec<Bytes>, ExecServerError> {
if plaintext_record.len() > NOISE_RECORD_PLAINTEXT_LEN {
return Err(ExecServerError::Protocol(
"Noise relay plaintext record exceeds maximum length".to_string(),
));
}
self.buffered.extend_from_slice(plaintext_record);
// One record can finish multiple messages, and one message can span
// multiple records. Parse only after the authenticated length prefix
// and the full declared payload are present.
let mut messages = Vec::new();
while let Some(prefix) = self.buffered.get(..LENGTH_PREFIX_BYTES) {
let message_len =
u32::from_be_bytes([prefix[0], prefix[1], prefix[2], prefix[3]]) as usize;
// Reject the authenticated length before waiting for its payload.
if message_len == 0 || message_len > MAX_NOISE_JSONRPC_MESSAGE_LEN {
return Err(ExecServerError::Protocol(
"Noise relay JSON-RPC message has invalid length".to_string(),
));
}
let framed_len = LENGTH_PREFIX_BYTES + message_len;
if self.buffered.len() < framed_len {
break;
}
self.buffered.advance(LENGTH_PREFIX_BYTES);
messages.push(self.buffered.split_to(message_len).freeze());
}
// Even before a message is complete, keep reassembly memory bounded.
if self.buffered.len() > LENGTH_PREFIX_BYTES + MAX_NOISE_JSONRPC_MESSAGE_LEN {
return Err(ExecServerError::Protocol(
"Noise relay JSON-RPC reassembly buffer exceeds maximum length".to_string(),
));
}
Ok(messages)
}
}
#[derive(Default)]
pub(crate) struct ClientJsonRpcMessageDecoder {
decoder: JsonRpcMessageDecoder,
}
impl ClientJsonRpcMessageDecoder {
pub(crate) fn push(
&mut self,
plaintext_record: &[u8],
) -> Result<Vec<JSONRPCMessage>, ExecServerError> {
if self.decoder.decoder.buffered.is_empty()
&& plaintext_record.len() <= MAX_CLIENT_INBOUND_REQUEST_LEN
{
return self.decoder.push(plaintext_record);
}
self.decoder
.decoder
.push(plaintext_record)?
.into_iter()
.map(|encoded| {
let message = serde_json::from_slice(&encoded);
if let Some(max_len) = client_inbound_message_exceeded_limit(
message.as_ref(),
encoded.len(),
MAX_CLIENT_INBOUND_REQUEST_LEN,
) {
return Err(ExecServerError::Protocol(format!(
"Noise relay JSON-RPC message exceeds maximum length of {max_len} bytes"
)));
}
message.map_err(Into::into)
})
.collect()
}
}
impl JsonRpcMessageDecoder {
pub(crate) fn client() -> ClientJsonRpcMessageDecoder {
ClientJsonRpcMessageDecoder::default()
}
}
#[cfg(test)]
#[path = "message_framing_tests.rs"]
mod tests;

View File

@@ -0,0 +1,130 @@
use codex_exec_server_protocol::EXEC_OUTPUT_DELTA_METHOD;
use codex_exec_server_protocol::JSONRPCMessage;
use codex_exec_server_protocol::JSONRPCNotification;
use codex_exec_server_protocol::JSONRPCRequest;
use codex_exec_server_protocol::JSONRPCResponse;
use codex_exec_server_protocol::RequestId;
use pretty_assertions::assert_eq;
use super::JsonRpcMessageDecoder;
use super::MAX_NOISE_JSONRPC_MESSAGE_LEN;
use super::NOISE_RECORD_PLAINTEXT_LEN;
use super::frame_jsonrpc_message;
use crate::ExecServerError;
use crate::client_inbound_request_limit::MAX_CLIENT_INBOUND_REQUEST_LEN;
#[test]
fn fragments_and_reassembles_large_jsonrpc_message() {
let message = JSONRPCMessage::Notification(JSONRPCNotification {
method: EXEC_OUTPUT_DELTA_METHOD.to_string(),
params: Some(serde_json::json!({
"data": "x".repeat(128 * 1024),
})),
});
let framed = frame_jsonrpc_message(&message).unwrap();
assert!(framed.len() > 128 * 1024);
let mut decoder = JsonRpcMessageDecoder::client();
let mut decoded = Vec::new();
for record in framed.chunks(NOISE_RECORD_PLAINTEXT_LEN) {
decoded.extend(decoder.push(record).unwrap());
}
assert_eq!(decoded, vec![message]);
}
#[test]
fn rejects_declared_message_length_above_limit_without_payload() {
let mut decoder = JsonRpcMessageDecoder::default();
let declared_len = (MAX_NOISE_JSONRPC_MESSAGE_LEN as u32 + 1).to_be_bytes();
assert!(matches!(
decoder.push(&declared_len),
Err(ExecServerError::Protocol(message))
if message == "Noise relay JSON-RPC message has invalid length"
));
}
#[test]
fn rejects_oversized_plaintext_record() {
let mut decoder = JsonRpcMessageDecoder::default();
assert!(matches!(
decoder.push(&vec![0; NOISE_RECORD_PLAINTEXT_LEN + 1]),
Err(ExecServerError::Protocol(message))
if message == "Noise relay plaintext record exceeds maximum length"
));
}
#[test]
fn client_decoder_rejects_oversized_request_and_preserves_large_response() {
let request = JSONRPCMessage::Request(JSONRPCRequest {
id: RequestId::Integer(1),
method: "network/policyRequest".to_string(),
params: Some(serde_json::json!({
"padding": "x".repeat(MAX_CLIENT_INBOUND_REQUEST_LEN),
})),
trace: None,
});
let request = frame_jsonrpc_message(&request).unwrap();
let mut client = JsonRpcMessageDecoder::client();
assert!(matches!(
client.push(&request),
Err(ExecServerError::Protocol(message))
if message == format!(
"Noise relay JSON-RPC message exceeds maximum length of {MAX_CLIENT_INBOUND_REQUEST_LEN} bytes"
)
));
let mut client = JsonRpcMessageDecoder::client();
let split = MAX_CLIENT_INBOUND_REQUEST_LEN / 2;
assert!(client.push(&request[..split]).unwrap().is_empty());
assert!(matches!(
client.push(&request[split..]),
Err(ExecServerError::Protocol(message))
if message == format!(
"Noise relay JSON-RPC message exceeds maximum length of {MAX_CLIENT_INBOUND_REQUEST_LEN} bytes"
)
));
let response = JSONRPCMessage::Response(JSONRPCResponse {
id: RequestId::Integer(1),
result: serde_json::json!({
"padding": "x".repeat(MAX_CLIENT_INBOUND_REQUEST_LEN),
}),
});
let framed = frame_jsonrpc_message(&response).unwrap();
let mut client = JsonRpcMessageDecoder::client();
assert_eq!(client.push(&framed).unwrap(), vec![response]);
}
#[test]
fn executor_decoder_preserves_large_request() {
let request = JSONRPCMessage::Request(JSONRPCRequest {
id: RequestId::Integer(1),
method: "process/start".to_string(),
params: Some(serde_json::json!({
"padding": "x".repeat(MAX_CLIENT_INBOUND_REQUEST_LEN),
})),
trace: None,
});
let framed = frame_jsonrpc_message(&request).unwrap();
let mut executor = JsonRpcMessageDecoder::default();
assert_eq!(executor.push(&framed).unwrap(), vec![request]);
}
#[test]
fn reassembles_many_messages_from_one_record() {
let message = JSONRPCMessage::Notification(JSONRPCNotification {
method: "small/test".to_string(),
params: None,
});
let framed = frame_jsonrpc_message(&message).expect("frame message");
let message_count = NOISE_RECORD_PLAINTEXT_LEN / framed.len();
let record = framed.repeat(message_count);
let mut decoder = JsonRpcMessageDecoder::default();
let decoded = decoder.push(&record).expect("decode record");
assert_eq!(decoded, vec![message; message_count]);
}

View File

@@ -0,0 +1,35 @@
pub(crate) mod executor_stream;
mod harness;
pub(crate) mod message_framing;
mod ordered_ciphertext;
pub(crate) mod stream_handler;
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
use crate::ExecServerError;
pub(crate) use harness::NoiseHarnessConnectionArgs;
pub(crate) use harness::noise_harness_connection_from_websocket_with_readiness;
pub(crate) const NOISE_RELAY_RESET_REASON: &str = "noise_relay_protocol_error";
// This bounds allocation in tungstenite before protobuf and Noise record
// validation run. It comfortably fits one maximum Noise record plus metadata.
const MAX_NOISE_RELAY_WEBSOCKET_MESSAGE_SIZE: usize = 256 * 1024;
/// Return the websocket limits required by every Noise relay endpoint.
pub(crate) fn noise_relay_websocket_config() -> WebSocketConfig {
WebSocketConfig::default()
.max_frame_size(Some(MAX_NOISE_RELAY_WEBSOCKET_MESSAGE_SIZE))
.max_message_size(Some(MAX_NOISE_RELAY_WEBSOCKET_MESSAGE_SIZE))
}
fn take_next_sequence(next_seq: &mut u32) -> Result<u32, ExecServerError> {
// Never wrap: relay sequence is the explicit ordering key for an implicit
// Noise nonce. Reusing zero after u32::MAX would be ambiguous and unsafe.
let seq = *next_seq;
*next_seq = next_seq.checked_add(1).ok_or_else(|| {
ExecServerError::Protocol("Noise relay sequence number exhausted".to_string())
})?;
Ok(seq)
}

View File

@@ -0,0 +1,70 @@
use std::collections::BTreeMap;
use crate::ExecServerError;
const MAX_REORDER_DISTANCE: u32 = 64;
const MAX_PENDING_BYTES: usize = 1024 * 1024;
/// Reorders relay records before they reach Noise's implicit receive nonce.
/// The window is bounded, and each sequence number is released at most once.
#[derive(Default)]
pub(crate) struct OrderedCiphertextFrames {
next_seq: u32,
pending: BTreeMap<u32, Vec<u8>>,
pending_bytes: usize,
}
impl OrderedCiphertextFrames {
/// Accept one relay record and return the newly contiguous ciphertext run.
///
/// Returns nothing for duplicates or while a gap remains. Closing a gap also
/// releases any buffered records that now follow it contiguously.
pub(crate) fn push(
&mut self,
seq: u32,
payload: Vec<u8>,
) -> Result<Vec<Vec<u8>>, ExecServerError> {
// Keep the first ciphertext for a sequence. Later copies are duplicates.
if seq < self.next_seq || self.pending.contains_key(&seq) {
return Ok(Vec::new());
}
if seq > self.next_seq {
// Bound both the sequence gap and buffered bytes.
if seq - self.next_seq > MAX_REORDER_DISTANCE {
return Err(ExecServerError::Protocol(
"Noise relay ciphertext exceeds reorder window".to_string(),
));
}
let pending_bytes = self.pending_bytes + payload.len();
if pending_bytes > MAX_PENDING_BYTES {
return Err(ExecServerError::Protocol(
"Noise relay pending ciphertext buffer is full".to_string(),
));
}
self.pending.insert(seq, payload);
self.pending_bytes = pending_bytes;
return Ok(Vec::new());
}
// Release the expected record and anything now contiguous behind it.
let mut ready = vec![payload];
self.advance()?;
while let Some(payload) = self.pending.remove(&self.next_seq) {
self.pending_bytes -= payload.len();
ready.push(payload);
self.advance()?;
}
Ok(ready)
}
fn advance(&mut self) -> Result<(), ExecServerError> {
self.next_seq = self.next_seq.checked_add(1).ok_or_else(|| {
ExecServerError::Protocol("Noise relay sequence number exhausted".to_string())
})?;
Ok(())
}
}
#[cfg(test)]
#[path = "ordered_ciphertext_tests.rs"]
mod tests;

View File

@@ -0,0 +1,52 @@
use pretty_assertions::assert_eq;
use super::MAX_PENDING_BYTES;
use super::OrderedCiphertextFrames;
#[test]
fn releases_ciphertexts_only_in_nonce_order() {
let mut frames = OrderedCiphertextFrames::default();
assert_eq!(
frames.push(/*seq*/ 1, b"second".to_vec()).unwrap(),
Vec::<Vec<u8>>::new()
);
assert_eq!(
frames.push(/*seq*/ 0, b"first".to_vec()).unwrap(),
vec![b"first".to_vec(), b"second".to_vec()]
);
}
#[test]
fn ignores_duplicate_ciphertexts_without_replacing_buffered_record() {
let mut frames = OrderedCiphertextFrames::default();
assert_eq!(
frames.push(/*seq*/ 1, b"first copy".to_vec()).unwrap(),
Vec::<Vec<u8>>::new()
);
assert_eq!(
frames.push(/*seq*/ 1, b"replacement".to_vec()).unwrap(),
Vec::<Vec<u8>>::new()
);
assert_eq!(
frames.push(/*seq*/ 0, b"zero".to_vec()).unwrap(),
vec![b"zero".to_vec(), b"first copy".to_vec()]
);
assert_eq!(
frames.push(/*seq*/ 0, b"duplicate".to_vec()).unwrap(),
Vec::<Vec<u8>>::new()
);
}
#[test]
fn rejects_unbounded_reordering() {
let mut frames = OrderedCiphertextFrames::default();
assert!(frames.push(/*seq*/ 65, Vec::new()).is_err());
assert!(
frames
.push(/*seq*/ 1, vec![0; MAX_PENDING_BYTES + 1])
.is_err()
);
}

View File

@@ -0,0 +1,98 @@
use std::future::Future;
use std::sync::Arc;
use bytes::Bytes;
use codex_exec_server_protocol::JSONRPCMessage;
use codex_protocol::protocol::W3cTraceContext;
use tokio::sync::mpsc;
use tokio::sync::watch;
use tokio::task::JoinHandle;
use crate::ExecServerError;
use crate::connection::JsonRpcConnection;
use crate::connection::JsonRpcConnectionEvent;
use crate::connection::JsonRpcTransport;
use crate::noise_relay::message_framing::frame_jsonrpc_message;
use crate::server::ConnectionProcessor;
use crate::telemetry::ExecutorRegistration;
pub(crate) struct NoiseStreamConnection<I, O> {
pub(crate) outgoing_tx: mpsc::Sender<O>,
pub(crate) incoming_rx: mpsc::Receiver<I>,
pub(crate) disconnected_rx: watch::Receiver<bool>,
pub(crate) writer_task: JoinHandle<()>,
pub(crate) executor_registration: Option<Arc<ExecutorRegistration>>,
}
pub(crate) struct NoiseOutboundMessage {
/// Payload with the authenticated length prefix supplied by message_framing.
pub(crate) framed: Vec<u8>,
pub(crate) trace: Option<W3cTraceContext>,
}
/// Adapts complete Noise payloads to one owner without adding an inbound queue.
/// Decoding is synchronous so execution spans begin before queue admission.
pub(crate) trait NoiseStreamHandler: Clone + Send + 'static {
type Incoming: Send + 'static;
type Outgoing: Send + 'static;
fn decode(payload: Bytes) -> Result<Self::Incoming, ExecServerError>;
fn encode(message: Self::Outgoing) -> Result<NoiseOutboundMessage, ExecServerError>;
fn run_connection(
self,
connection: NoiseStreamConnection<Self::Incoming, Self::Outgoing>,
) -> impl Future<Output = ()> + Send;
}
impl NoiseStreamHandler for ConnectionProcessor {
type Incoming = JsonRpcConnectionEvent;
type Outgoing = JSONRPCMessage;
fn decode(payload: Bytes) -> Result<Self::Incoming, ExecServerError> {
let event = JsonRpcConnectionEvent::message(serde_json::from_slice(&payload)?);
if let JsonRpcConnectionEvent::QueuedRequest { request_span, .. } = &event {
// The request span can remain open while queued or executing. Finish a
// payload-free receipt marker now so a stalled executor is distinguishable
// from a request that never arrived, without waiting for that span to close.
drop(tracing::info_span!(
target: "codex_otel.trace_safe",
parent: request_span,
"codex.exec_server.noise_request_received",
));
}
Ok(event)
}
fn encode(message: Self::Outgoing) -> Result<NoiseOutboundMessage, ExecServerError> {
let framed = frame_jsonrpc_message(&message)?;
let trace = match message {
JSONRPCMessage::Request(request) => request.trace,
JSONRPCMessage::Notification(_)
| JSONRPCMessage::Response(_)
| JSONRPCMessage::Error(_) => None,
};
Ok(NoiseOutboundMessage { framed, trace })
}
async fn run_connection(
self,
connection: NoiseStreamConnection<Self::Incoming, Self::Outgoing>,
) {
ConnectionProcessor::run_registered_connection(
&self,
JsonRpcConnection {
outgoing_tx: connection.outgoing_tx,
incoming_rx: connection.incoming_rx,
disconnected_rx: connection.disconnected_rx,
task_handles: vec![connection.writer_task],
transport: JsonRpcTransport::Plain,
},
connection.executor_registration,
)
.await;
}
}
#[cfg(test)]
#[path = "stream_handler_tests.rs"]
mod tests;

View File

@@ -0,0 +1,73 @@
use std::time::Instant;
use anyhow::Result;
use codex_exec_server_protocol::JSONRPCMessage;
use codex_exec_server_protocol::JSONRPCRequest;
use codex_exec_server_protocol::RequestId;
use pretty_assertions::assert_eq;
use super::NoiseStreamHandler;
use crate::connection::JsonRpcConnectionEvent;
use crate::server::ConnectionProcessor;
#[test]
fn local_decode_starts_request_span_before_queueing() -> Result<()> {
use opentelemetry::trace::TracerProvider as _;
use opentelemetry_sdk::trace::InMemorySpanExporter;
use opentelemetry_sdk::trace::SdkTracerProvider;
use tracing_subscriber::prelude::*;
let exporter = InMemorySpanExporter::default();
let provider = SdkTracerProvider::builder()
.with_simple_exporter(exporter.clone())
.build();
let _subscriber =
tracing::subscriber::set_default(tracing_subscriber::registry().with(
tracing_opentelemetry::layer().with_tracer(provider.tracer("noise-receipt-test")),
));
tracing::callsite::rebuild_interest_cache();
let request = JSONRPCRequest {
id: RequestId::Integer(1),
method: "test/queued".to_string(),
params: Some(serde_json::json!({"secret": "SYNTHETIC_PRIVATE_PAYLOAD"})),
trace: Some(codex_protocol::protocol::W3cTraceContext {
traceparent: Some("00-00000000000000000000000000000001-0000000000000002-01".to_owned()),
tracestate: None,
}),
};
let before_decode = Instant::now();
let event = <ConnectionProcessor as NoiseStreamHandler>::decode(
serde_json::to_vec(&JSONRPCMessage::Request(request.clone()))?.into(),
)?;
let after_decode = Instant::now();
let JsonRpcConnectionEvent::QueuedRequest {
request: actual_request,
request_span,
queued_at,
} = event
else {
panic!("local ingress must create the queued request synchronously");
};
assert_eq!(actual_request, request);
assert!(!request_span.is_disabled());
assert!((before_decode..=after_decode).contains(&queued_at));
let spans = exporter.get_finished_spans()?;
assert_eq!(
spans.len(),
1,
"receipt must export while the request is still queued"
);
assert_eq!(spans[0].name, "codex.exec_server.noise_request_received");
assert_eq!(
spans[0].span_context.trace_id().to_string(),
"00000000000000000000000000000001"
);
assert!(!format!("{spans:?}").contains("SYNTHETIC_PRIVATE_PAYLOAD"));
assert!(!format!("{spans:?}").contains("test/queued"));
let receipt_parent = spans[0].parent_span_id;
drop(request_span);
let spans = exporter.get_finished_spans()?;
assert_eq!(spans.len(), 2);
assert_eq!(receipt_parent, spans[1].span_context.span_id());
Ok(())
}

View File

@@ -0,0 +1,317 @@
use std::collections::VecDeque;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use codex_network_proxy::NetworkPolicyDecider;
use codex_sandboxing::SandboxType;
use tokio::sync::broadcast;
use tokio::sync::watch;
use crate::ExecServerError;
use crate::ProcessId;
use crate::protocol::ExecParams;
use crate::protocol::ProcessOutputChunk;
use crate::protocol::ProcessSandboxType;
use crate::protocol::ProcessSignal;
use crate::protocol::ReadResponse;
use crate::protocol::WriteResponse;
pub struct StartedExecProcess {
pub process: Arc<dyn ExecProcess>,
/// `None` means the exec-server peer did not report its sandbox type.
pub sandbox_type: Option<SandboxType>,
}
pub(crate) fn sandbox_type_from_protocol(
sandbox_type: Option<ProcessSandboxType>,
) -> Option<SandboxType> {
match sandbox_type {
None => None,
Some(ProcessSandboxType::None) => Some(SandboxType::None),
Some(ProcessSandboxType::MacosSeatbelt) => Some(SandboxType::MacosSeatbelt),
Some(ProcessSandboxType::LinuxSeccomp) => Some(SandboxType::LinuxSeccomp),
Some(ProcessSandboxType::WindowsRestrictedToken) => {
Some(SandboxType::WindowsRestrictedToken)
}
Some(ProcessSandboxType::WindowsMxc) => Some(SandboxType::WindowsMxc),
}
}
/// Pushed process events for consumers that want to follow process output as it
/// arrives instead of polling retained output with [`ExecProcess::read`].
///
/// The stream is scoped to one [`ExecProcess`] handle. `Output` events carry
/// stdout, stderr, or pty bytes. `Exited` reports the process exit status, while
/// `Closed` means all output streams have ended and no more output events will
/// arrive. `Failed` is used when the process session cannot continue, for
/// example because the remote environment connection disconnected.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExecProcessEvent {
Output(ProcessOutputChunk),
Exited {
seq: u64,
exit_code: i32,
sandbox_denied: Option<bool>,
},
Closed {
seq: u64,
},
Failed(String),
}
/// Replay buffer plus live fan-out for pushed process events.
///
/// New subscribers first drain a bounded replay history, then continue on the
/// live broadcast channel. The history is bounded by event count and retained
/// output bytes: count protects against many tiny events, while bytes protects
/// against a few very large output chunks.
#[derive(Clone)]
pub(crate) struct ExecProcessEventLog {
inner: Arc<ExecProcessEventLogInner>,
}
struct ExecProcessEventLogInner {
history: StdMutex<ExecProcessEventHistory>,
live_tx: broadcast::Sender<ExecProcessEvent>,
event_capacity: usize,
byte_capacity: usize,
}
#[derive(Default)]
struct ExecProcessEventHistory {
events: VecDeque<ExecProcessEvent>,
retained_bytes: usize,
}
impl ExecProcessEvent {
/// Sequence number used to order process-owned events.
///
/// `Failed` is intentionally unsequenced because it is synthesized by the
/// client when the session or transport fails, not emitted by the process.
pub(crate) fn seq(&self) -> Option<u64> {
match self {
ExecProcessEvent::Output(chunk) => Some(chunk.seq),
ExecProcessEvent::Exited { seq, .. } | ExecProcessEvent::Closed { seq } => Some(*seq),
ExecProcessEvent::Failed(_) => None,
}
}
fn retained_len(&self) -> usize {
match self {
ExecProcessEvent::Output(chunk) => chunk.chunk.0.len(),
ExecProcessEvent::Failed(message) => message.len(),
ExecProcessEvent::Exited { .. } | ExecProcessEvent::Closed { .. } => 0,
}
}
}
impl ExecProcessEventLog {
pub(crate) fn new(event_capacity: usize, byte_capacity: usize) -> Self {
let (live_tx, _live_rx) = broadcast::channel(event_capacity);
Self {
inner: Arc::new(ExecProcessEventLogInner {
history: StdMutex::new(ExecProcessEventHistory::default()),
live_tx,
event_capacity,
byte_capacity,
}),
}
}
pub(crate) fn publish(&self, event: ExecProcessEvent) {
let mut history = self
.inner
.history
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
history.retained_bytes += event.retained_len();
history.events.push_back(event.clone());
while history.events.len() > self.inner.event_capacity
|| history.retained_bytes > self.inner.byte_capacity
{
let Some(evicted) = history.events.pop_front() else {
break;
};
history.retained_bytes = history
.retained_bytes
.saturating_sub(evicted.retained_len());
}
let _ = self.inner.live_tx.send(event);
}
pub(crate) fn subscribe(&self) -> ExecProcessEventReceiver {
let history = self
.inner
.history
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let live_rx = self.inner.live_tx.subscribe();
let replay = history.events.iter().cloned().collect();
ExecProcessEventReceiver {
replay,
live_rx,
_keepalive: None,
}
}
}
pub struct ExecProcessEventReceiver {
replay: VecDeque<ExecProcessEvent>,
live_rx: broadcast::Receiver<ExecProcessEvent>,
_keepalive: Option<broadcast::Sender<ExecProcessEvent>>,
}
impl ExecProcessEventReceiver {
/// Returns a receiver that remains open without yielding events.
pub fn empty() -> Self {
let (live_tx, live_rx) = broadcast::channel(1);
Self {
replay: VecDeque::new(),
live_rx,
_keepalive: Some(live_tx),
}
}
/// Returns the next replayed or live event.
///
/// `Lagged` means this receiver fell behind the bounded live channel. The
/// caller should recover through [`ExecProcess::read`] using the last
/// delivered sequence number, then continue receiving pushed events.
pub async fn recv(&mut self) -> Result<ExecProcessEvent, broadcast::error::RecvError> {
if let Some(event) = self.replay.pop_front() {
return Ok(event);
}
self.live_rx.recv().await
}
}
/// Handle for an executor-managed process.
///
/// Implementations must support both retained-output reads and pushed events:
/// `read` is the request/response API for callers that want to page through
/// buffered output, while `subscribe_events` is the streaming API for callers
/// that want output and lifecycle changes delivered as they happen.
pub trait ExecProcess: Send + Sync {
fn process_id(&self) -> &ProcessId;
fn subscribe_wake(&self) -> watch::Receiver<u64>;
fn subscribe_events(&self) -> ExecProcessEventReceiver;
fn read(
&self,
after_seq: Option<u64>,
max_bytes: Option<usize>,
wait_ms: Option<u64>,
) -> ExecProcessFuture<'_, ReadResponse>;
fn write(&self, chunk: Vec<u8>) -> ExecProcessFuture<'_, WriteResponse>;
fn signal(&self, signal: ProcessSignal) -> ExecProcessFuture<'_, ()>;
fn terminate(&self) -> ExecProcessFuture<'_, ()>;
}
pub type ExecProcessFuture<'a, T> =
Pin<Box<dyn Future<Output = Result<T, ExecServerError>> + Send + 'a>>;
pub trait ExecBackend: Send + Sync {
fn start(&self, params: ExecParams) -> ExecBackendFuture<'_>;
/// Captures a local shell snapshot without starting the requested command.
/// Failures must remain retryable by real commands. Remote backends do not
/// support this operation; callers should leave them on the lazy path.
fn prewarm_shell_snapshot(&self, _params: ExecParams) -> ExecProcessFuture<'_, ()> {
Box::pin(async {
Err(ExecServerError::Protocol(
"exec backend does not support shell snapshot prewarming".to_string(),
))
})
}
/// Starts a process with an authoritative controller-side policy decider.
fn start_with_network_policy_decider(
&self,
_params: ExecParams,
_decider: Arc<dyn NetworkPolicyDecider>,
) -> ExecBackendFuture<'_> {
Box::pin(async {
Err(ExecServerError::Protocol(
"exec backend does not support remote network policy decisions".to_string(),
))
})
}
}
pub type ExecBackendFuture<'a> =
Pin<Box<dyn Future<Output = Result<StartedExecProcess, ExecServerError>> + Send + 'a>>;
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use tokio::time::Duration;
use tokio::time::timeout;
use super::ExecProcessEvent;
use super::ExecProcessEventLog;
use super::ExecProcessEventReceiver;
use crate::protocol::ExecOutputStream;
use crate::protocol::ProcessOutputChunk;
#[tokio::test]
async fn empty_event_receiver_stays_open() {
let mut events = ExecProcessEventReceiver::empty();
assert!(
timeout(Duration::from_millis(10), events.recv())
.await
.is_err()
);
}
#[tokio::test]
async fn event_history_replay_is_bounded_by_retained_bytes() {
let log = ExecProcessEventLog::new(/*event_capacity*/ 8, /*byte_capacity*/ 3);
log.publish(ExecProcessEvent::Output(ProcessOutputChunk {
seq: 1,
stream: ExecOutputStream::Stdout,
chunk: b"large".to_vec().into(),
}));
log.publish(ExecProcessEvent::Exited {
seq: 2,
exit_code: 0,
sandbox_denied: Some(false),
});
log.publish(ExecProcessEvent::Closed { seq: 3 });
let mut events = log.subscribe();
let replay = vec![
timeout(Duration::from_secs(1), events.recv())
.await
.expect("exit event replay should not time out")
.expect("exit event replay should be available"),
timeout(Duration::from_secs(1), events.recv())
.await
.expect("closed event replay should not time out")
.expect("closed event replay should be available"),
];
assert_eq!(
replay,
vec![
ExecProcessEvent::Exited {
seq: 2,
exit_code: 0,
sandbox_denied: Some(false),
},
ExecProcessEvent::Closed { seq: 3 },
]
);
}
}

View File

@@ -0,0 +1,498 @@
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
use crate::process_telemetry::ProcessTelemetry;
use codex_exec_server_protocol::JSONRPCErrorError;
use codex_file_system::WindowsSandboxSelection;
use codex_network_proxy::CUSTOM_CA_ENV_KEYS;
use codex_network_proxy::CredentialMaskingFailureMode;
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_network_proxy::ManagedProxyRouting;
use codex_network_proxy::NetworkPolicyAuditObserver;
use codex_network_proxy::NetworkPolicyDecider;
use codex_network_proxy::NetworkProxy;
use codex_network_proxy::NetworkProxyHandle;
use codex_network_proxy::NetworkProxyState;
use codex_network_proxy::RemoteCredentialBrokerCache;
use codex_network_proxy::is_managed_mitm_ca_trust_bundle_path;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::models::PermissionProfile;
use codex_sandboxing::SandboxCommand;
use codex_sandboxing::SandboxDirectSpawnTransformRequest;
use codex_sandboxing::SandboxManager;
use codex_sandboxing::SandboxTransformRequest;
use codex_sandboxing::SandboxType;
use codex_sandboxing::WindowsSandboxFilesystemOverrides;
use codex_sandboxing::WindowsSandboxProxySettingsMode;
use codex_sandboxing::WindowsSandboxSpawnRequest;
use codex_sandboxing::with_managed_mitm_ca_readable_root;
#[cfg(windows)]
use codex_shell_command::shell_detect::fallback_powershell_shell_for_windows_sandbox;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
#[cfg(unix)]
use crate::CODEX_ARG0_EXEC_HELPER_ARG1;
use crate::ExecServerRuntimeOptions;
use crate::process_telemetry::trace_process_id;
use crate::protocol::ExecParams;
use crate::rpc::internal_error;
use crate::rpc::invalid_params;
use crate::sandbox_selection::select_sandbox;
const CREDENTIAL_MASKING_FAILURE_MODE: CredentialMaskingFailureMode =
CredentialMaskingFailureMode::Warn;
pub(crate) struct PreparedExecRequest {
pub(crate) command: Vec<String>,
pub(crate) cwd: AbsolutePathBuf,
pub(crate) env: HashMap<String, String>,
pub(crate) arg0: Option<String>,
pub(crate) sandbox: SandboxType,
pub(crate) network_proxy_handle: Option<NetworkProxyHandle>,
windows_sandbox: Option<PreparedWindowsSandboxRequest>,
}
struct PreparedWindowsSandboxRequest {
permission_profile: PermissionProfile,
workspace_roots: Vec<AbsolutePathBuf>,
windows_sandbox_level: WindowsSandboxLevel,
proxy_enforced: bool,
network_proxy_restricting_sid: Option<String>,
proxy_settings_mode: WindowsSandboxProxySettingsMode,
filesystem_overrides: Option<WindowsSandboxFilesystemOverrides>,
}
impl PreparedExecRequest {
#[cfg(unix)]
pub(crate) fn credential_snapshot_proxy(&self, params: &ExecParams) -> Option<&NetworkProxy> {
let launch = params.network_proxy.as_ref()?;
if !launch.proxy.credential_masking_enabled() || !supports_credential_snapshot(params) {
return None;
}
self.network_proxy_handle.as_ref()?.proxy()
}
pub(crate) fn windows_sandbox_spawn_request(&self) -> Option<WindowsSandboxSpawnRequest<'_>> {
self.windows_sandbox
.as_ref()
.map(|request| WindowsSandboxSpawnRequest {
permission_profile: &request.permission_profile,
workspace_roots: &request.workspace_roots,
windows_sandbox_level: request.windows_sandbox_level,
proxy_enforced: request.proxy_enforced,
network_proxy_restricting_sid: request.network_proxy_restricting_sid.as_deref(),
proxy_settings_mode: request.proxy_settings_mode,
filesystem_overrides: request.filesystem_overrides.as_ref(),
})
}
}
fn supports_credential_snapshot(params: &ExecParams) -> bool {
cfg!(any(target_os = "linux", target_os = "macos"))
&& params.arg0.is_none()
&& params.shell_snapshot.as_ref().is_some_and(|snapshot| {
snapshot.shell.name == "zsh"
&& matches!(params.argv.as_slice(), [program, flag, _]
if program == &snapshot.shell.path
&& flag == "-lc"
&& Path::new(program).file_name().is_some_and(|name| name == "zsh"))
})
}
#[tracing::instrument(
name = "codex.exec_server.process_prepare_sandbox",
skip_all,
fields(process.id = trace_process_id(params.process_id.as_str())),
)]
pub(crate) async fn prepare_exec_request_with_telemetry(
params: &ExecParams,
env: HashMap<String, String>,
runtime_paths: Option<&ExecServerRuntimeOptions>,
network_policy_decider: Option<Arc<dyn NetworkPolicyDecider>>,
network_policy_audit_observer: Option<NetworkPolicyAuditObserver>,
credential_brokers: &RemoteCredentialBrokerCache,
telemetry: &ProcessTelemetry,
) -> Result<PreparedExecRequest, JSONRPCErrorError> {
if let Some(sandbox) = params.sandbox.as_ref()
&& sandbox.windows_sandbox_selection == WindowsSandboxSelection::Mxc
{
if params.arg0.is_some() {
return Err(invalid_params(
"MXC custom argv0 is not supported".to_owned(),
));
}
if !codex_sandboxing::windows_mxc_available() {
return Err(invalid_params(
"native MXC is unavailable on this executor".to_owned(),
));
}
}
let (env, managed_network, network_proxy_handle, network_proxy_restricting_sid) =
prepare_managed_network(
params,
credential_brokers,
runtime_paths.is_some_and(|paths| paths.proxy_private_ips_via_upstream),
env,
network_policy_decider,
network_policy_audit_observer,
telemetry,
)
.await?;
let Some(sandbox_context) = params.sandbox.as_ref() else {
return Ok(PreparedExecRequest {
command: params.argv.clone(),
cwd: native_path(&params.cwd, "cwd")?,
env,
arg0: params.arg0.clone(),
sandbox: SandboxType::None,
network_proxy_handle,
windows_sandbox: None,
});
};
let runtime_paths = runtime_paths
.ok_or_else(|| invalid_params("sandbox runtime paths are not configured".to_string()))?;
sandbox_context
.validate_file_system_paths_for_current_host()
.map_err(|err| invalid_params(err.to_string()))?;
let windows_sandbox_proxy_settings_mode = sandbox_context
.windows_sandbox_proxy_settings_mode
.unwrap_or_default();
// TODO(jif): Transport permissions before orchestrator-local paths are materialized,
// then resolve executor-local helper and workspace paths here.
let permissions = sandbox_context.permissions.clone();
let sandbox_policy_cwd = &sandbox_context.cwd;
let native_sandbox_policy_cwd = native_path(sandbox_policy_cwd, "sandbox cwd")?;
let native_workspace_roots = sandbox_context
.workspace_roots
.iter()
.map(|root| native_path(root, "sandbox workspace root"))
.collect::<Result<Vec<_>, _>>()?;
let workspace_roots = native_workspace_roots.as_slice();
let permissions = permissions.materialize_project_roots_with_workspace_roots(workspace_roots);
let managed_mitm_ca_trust_bundle_path = managed_network.as_ref().and_then(|_| {
CUSTOM_CA_ENV_KEYS.iter().find_map(|key| {
let path = env.get(*key)?;
if !is_managed_mitm_ca_trust_bundle_path(path) {
return None;
}
AbsolutePathBuf::from_absolute_path(path).ok()
})
});
let permissions = with_managed_mitm_ca_readable_root(
permissions,
managed_mitm_ca_trust_bundle_path.as_ref(),
native_sandbox_policy_cwd.as_path(),
);
#[cfg(unix)]
let (file_system_policy, network_policy) = permissions.to_runtime_permissions();
#[cfg(unix)]
let sandbox_helper_paths = params
.arg0
.iter()
.map(|_| runtime_paths.codex_self_exe.clone())
.collect::<Vec<_>>();
// Bubblewrap launches the configured helper, which may re-enter this executable to apply
// seccomp, so the outer filesystem sandbox must expose both paths.
#[cfg(target_os = "linux")]
let sandbox_helper_paths = {
let mut sandbox_helper_paths = sandbox_helper_paths;
if !sandbox_helper_paths.contains(&runtime_paths.codex_self_exe) {
sandbox_helper_paths.push(runtime_paths.codex_self_exe.clone());
}
sandbox_helper_paths.extend(runtime_paths.codex_linux_sandbox_exe.iter().cloned());
sandbox_helper_paths
};
#[cfg(unix)]
let file_system_policy = file_system_policy
.with_additional_readable_roots(native_sandbox_policy_cwd.as_path(), &sandbox_helper_paths);
#[cfg(unix)]
let permissions = PermissionProfile::from_runtime_permissions_with_enforcement(
permissions.enforcement(),
&file_system_policy,
network_policy,
);
let sandbox_manager = SandboxManager::new()
.with_linux_sandbox_pid_namespace(runtime_paths.linux_sandbox_pid_namespace);
#[cfg(target_os = "macos")]
let sandbox_manager = sandbox_manager
.with_allowed_symlinked_codex_home(runtime_paths.allowed_symlinked_codex_home.clone());
let (sandbox, windows_sandbox_level) = select_sandbox(
&sandbox_manager,
&permissions,
sandbox_context,
params.enforce_managed_network,
);
if sandbox == SandboxType::None {
return Err(invalid_params(
"sandbox intent cannot be enforced on this executor".to_string(),
));
}
let (program, args) = params
.argv
.split_first()
.ok_or_else(|| invalid_params("argv must not be empty".to_string()))?;
#[cfg(unix)]
let (program, args) = params.arg0.as_ref().map_or_else(
|| (program.into(), args.to_vec()),
|arg0| {
let mut helper_args = Vec::with_capacity(params.argv.len() + 2);
helper_args.push(CODEX_ARG0_EXEC_HELPER_ARG1.to_string());
helper_args.push(arg0.clone());
helper_args.extend(params.argv.iter().cloned());
(
runtime_paths
.codex_self_exe
.as_path()
.as_os_str()
.to_owned(),
helper_args,
)
},
);
#[cfg(not(unix))]
let (program, args) = (program.into(), args.to_vec());
#[cfg(windows)]
let program = if matches!(
sandbox_context.windows_sandbox_selection,
WindowsSandboxSelection::Elevated | WindowsSandboxSelection::Mxc
) && Path::new(&program).file_stem().is_some_and(|name| {
name.eq_ignore_ascii_case("pwsh") || name.eq_ignore_ascii_case("powershell")
}) && let Some(fallback) =
fallback_powershell_shell_for_windows_sandbox(Path::new(&program))
{
// Remote controllers cannot resolve a sandbox-compatible shell on this host.
fallback.shell_path.into_os_string()
} else {
program
};
let transform_request = SandboxDirectSpawnTransformRequest {
workspace_roots,
windows_sandbox_proxy_settings_mode,
transform: SandboxTransformRequest {
command: SandboxCommand {
program,
args,
cwd: params.cwd.clone(),
env,
managed_network,
additional_permissions: None,
},
permissions: &permissions,
workspace_roots: None,
sandbox,
enforce_managed_network: params.enforce_managed_network,
environment_id: None,
network: None,
sandbox_policy_cwd,
sandbox_exe: if cfg!(windows) {
Some(runtime_paths.codex_self_exe.as_path())
} else {
runtime_paths.codex_linux_sandbox_exe.as_deref()
},
use_legacy_landlock: sandbox_context.use_legacy_landlock,
windows_sandbox_level: windows_sandbox_level.unwrap_or(WindowsSandboxLevel::Disabled),
},
};
let mut request = if sandbox == SandboxType::WindowsRestrictedToken {
// The shared launcher invokes the native Windows session spawner directly.
sandbox_manager.transform(transform_request.transform)
} else {
sandbox_manager.transform_for_direct_spawn(transform_request)
}
.map_err(|err| invalid_params(format!("failed to prepare process sandbox: {err}")))?;
request.sandbox_override = sandbox_context.sandbox_override;
crate::run_integrity_checks(&request).await;
let windows_sandbox = if sandbox == SandboxType::WindowsRestrictedToken {
let windows_sandbox_level = windows_sandbox_level.ok_or_else(|| {
invalid_params("restricted token sandbox requires a sandbox level".to_string())
})?;
request.arg0 = params.arg0.clone();
let proxy_enforced = params.enforce_managed_network;
let filesystem_overrides = WindowsSandboxFilesystemOverrides::resolve(
sandbox,
&permissions,
&native_sandbox_policy_cwd,
windows_sandbox_level,
&request.env,
)
.map_err(|err| invalid_params(format!("failed to prepare process sandbox: {err}")))?;
Some(PreparedWindowsSandboxRequest {
permission_profile: permissions,
workspace_roots: native_workspace_roots,
windows_sandbox_level,
proxy_enforced,
network_proxy_restricting_sid,
proxy_settings_mode: windows_sandbox_proxy_settings_mode,
filesystem_overrides,
})
} else {
None
};
Ok(PreparedExecRequest {
command: request.command,
cwd: native_path(&request.cwd, "cwd")?,
env: request.env,
arg0: request.arg0,
sandbox: request.sandbox,
network_proxy_handle,
windows_sandbox,
})
}
async fn prepare_managed_network(
params: &ExecParams,
credential_brokers: &RemoteCredentialBrokerCache,
proxy_private_ips_via_upstream: bool,
env: HashMap<String, String>,
network_policy_decider: Option<Arc<dyn NetworkPolicyDecider>>,
network_policy_audit_observer: Option<NetworkPolicyAuditObserver>,
telemetry: &ProcessTelemetry,
) -> Result<
(
HashMap<String, String>,
Option<ManagedNetworkSandboxContext>,
Option<NetworkProxyHandle>,
Option<String>,
),
JSONRPCErrorError,
> {
let Some(launch) = &params.network_proxy else {
return Ok((env, params.managed_network.clone(), None, None));
};
#[cfg(windows)]
let routing = match params
.sandbox
.as_ref()
.map(|sandbox| sandbox.windows_sandbox_selection)
{
None => {
// Native Windows commands have no sandbox token SID for shared ingress.
let mut native_env = env;
codex_network_proxy::strip_managed_proxy_env(&mut native_env);
return Ok((native_env, params.managed_network.clone(), None, None));
}
Some(WindowsSandboxSelection::Mxc) => ManagedProxyRouting::DedicatedListeners,
Some(
WindowsSandboxSelection::Disabled
| WindowsSandboxSelection::RestrictedToken
| WindowsSandboxSelection::Elevated,
) => ManagedProxyRouting::SharedIngress,
};
#[cfg(not(windows))]
let routing = ManagedProxyRouting::SharedIngress;
let mut state = NetworkProxyState::from_remote_launch_config(
launch.clone(),
codex_utils_path_uri::Platform::native(),
credential_brokers,
&env,
)
.map_err(|err| invalid_params(format!("invalid network proxy config: {err}")))?;
let credential_masking = state
.current_cfg()
.await
.map_err(|err| {
internal_error(format!(
"failed to read executor network proxy config: {err}"
))
})?
.credential_broker;
state.set_proxy_private_ips_via_upstream(proxy_private_ips_via_upstream);
if let Some(observer) = network_policy_audit_observer {
state.set_policy_audit_observer(observer);
}
if let Some(launch_context) = &telemetry.launch_context {
state.set_launch_span_context(launch_context.clone());
}
state.set_process_log_metadata(codex_network_proxy::NetworkProxyProcessLogMetadata {
thread_id: telemetry.thread_id.clone(),
tool_call_id: telemetry.tool_call_id.clone(),
executor_identity: telemetry
.executor_registration
.as_ref()
.map(|registration| codex_network_proxy::ExecutorLogIdentity {
environment_id: registration.environment_id.clone(),
registration_id: registration.executor_registration_id.clone(),
}),
});
let mut builder = NetworkProxy::builder()
.state(Arc::new(state))
.managed_proxy_routing(routing);
if let Some(network_policy_decider) = network_policy_decider {
builder = builder.policy_decider_arc(network_policy_decider);
}
let proxy = builder
.build()
.await
.map_err(|err| internal_error(format!("failed to build executor network proxy: {err}")))?;
let handle = proxy
.run()
.await
.map_err(|err| internal_error(format!("failed to start executor network proxy: {err}")))?;
#[cfg(target_os = "windows")]
let network_proxy_restricting_sid = if routing == ManagedProxyRouting::SharedIngress {
Some(
proxy
.network_proxy_restricting_sid(/*environment_id*/ None)
.ok_or_else(|| {
internal_error(
"managed Windows proxy route is missing its restricting SID".to_string(),
)
})?,
)
} else {
None
};
#[cfg(not(target_os = "windows"))]
let network_proxy_restricting_sid = None;
let supported_shell = matches!(params.argv.as_slice(), [program, flag, _]
if Path::new(program).file_name().is_some_and(|name| name == "bash") && flag == "-c")
&& !["BASH_ENV", "ENV", "SSH_CLIENT", "SSH2_CLIENT"]
.iter()
.any(|key| env.contains_key(*key));
let mut prepared = proxy
.prepare_for_optional_environment(env, /*environment_id*/ None)
.map_err(|err| {
internal_error(format!("failed to prepare executor network proxy: {err}"))
})?;
if credential_masking {
if supports_credential_snapshot(params) {
// Requested snapshots trust startup profiles before masking their captured state.
proxy.restore_and_disable_brokered_credentials(&mut prepared.env, &mut []);
} else if cfg!(any(target_os = "linux", target_os = "macos"))
&& supported_shell
&& params.arg0.is_none()
&& params.shell_snapshot.is_none()
{
proxy
.handle_unmasked_credentials(&mut prepared.env, CREDENTIAL_MASKING_FAILURE_MODE)
.map_err(|err| invalid_params(err.to_string()))?;
} else {
tracing::warn!(
"Credential masking is unavailable for this shell startup; preserving shell profiles and snapshots and running with unmasked credentials."
);
// Restore this child's environment without disabling translation of placeholders
// issued to earlier commands in the same environment.
proxy.restore_and_disable_brokered_credentials(&mut prepared.env, &mut []);
}
}
Ok((
prepared.env,
Some(prepared.sandbox_context),
Some(handle),
network_proxy_restricting_sid,
))
}
fn native_path(path: &PathUri, label: &str) -> Result<AbsolutePathBuf, JSONRPCErrorError> {
path.to_abs_path().map_err(|err| {
invalid_params(format!(
"{label} URI `{path}` is not valid on this exec-server host: {err}"
))
})
}
#[cfg(test)]
#[path = "process_sandbox_tests.rs"]
mod tests;

View File

@@ -0,0 +1,750 @@
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use codex_exec_server_protocol::JSONRPCErrorError;
#[cfg(unix)]
use codex_file_system::WindowsSandboxSelection;
#[cfg(target_os = "macos")]
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_network_proxy::NetworkPolicyAuditObserver;
use codex_network_proxy::NetworkPolicyDecider;
use codex_network_proxy::NetworkProxyConfig;
#[cfg(target_os = "macos")]
use codex_network_proxy::NetworkUnixSocketPermission;
#[cfg(target_os = "macos")]
use codex_network_proxy::NetworkUnixSocketPermissions;
use codex_network_proxy::PROXY_ATTRIBUTION_TOKEN_ENV_KEY;
use codex_network_proxy::RemoteNetworkProxyConfig;
use codex_network_proxy::RemoteNetworkProxyLaunchConfig;
#[cfg(windows)]
use codex_protocol::config_types::WindowsSandboxLevel;
#[cfg(any(unix, windows))]
use codex_protocol::models::PermissionProfile;
#[cfg(target_os = "linux")]
use codex_sandboxing::landlock::CODEX_LINUX_SANDBOX_ARG0;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
#[cfg(unix)]
use tempfile::tempdir;
use test_case::test_case;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::time::timeout;
use super::PreparedExecRequest;
use super::prepare_exec_request_with_telemetry;
#[cfg(unix)]
use crate::CODEX_ARG0_EXEC_HELPER_ARG1;
use crate::ExecParams;
use crate::ExecServerRuntimeOptions;
#[cfg(any(unix, windows))]
use crate::FileSystemSandboxContext;
use crate::ProcessId;
use crate::process_telemetry::ProcessTelemetry;
async fn prepare_exec_request(
params: &ExecParams,
env: HashMap<String, String>,
runtime_paths: Option<&ExecServerRuntimeOptions>,
network_policy_decider: Option<Arc<dyn NetworkPolicyDecider>>,
network_policy_audit_observer: Option<NetworkPolicyAuditObserver>,
) -> Result<PreparedExecRequest, JSONRPCErrorError> {
prepare_exec_request_with_telemetry(
params,
env,
runtime_paths,
network_policy_decider,
network_policy_audit_observer,
&codex_network_proxy::RemoteCredentialBrokerCache::default(),
&ProcessTelemetry::default(),
)
.await
}
#[cfg(unix)]
#[tokio::test]
async fn sandbox_request_wraps_native_argv_on_executor() {
let command_directory = tempdir().expect("command directory");
let cwd = AbsolutePathBuf::from_absolute_path(command_directory.path()).expect("absolute cwd");
let cwd_uri = PathUri::from_abs_path(&cwd);
let self_exe = std::env::current_exe().expect("current executable");
let runtime_paths =
ExecServerRuntimeOptions::new(self_exe.clone(), Some(self_exe)).expect("runtime paths");
let sandbox = FileSystemSandboxContext::from_permission_profile(
PermissionProfile::workspace_write(),
cwd_uri.clone(),
);
let params = ExecParams {
metadata: Default::default(),
process_id: ProcessId::from("process-1"),
argv: vec![
"/bin/bash".to_string(),
"-lc".to_string(),
"pwd".to_string(),
],
cwd: cwd_uri,
shell_snapshot: None,
env_policy: None,
env: HashMap::new(),
tty: false,
pipe_stdin: false,
arg0: None,
sandbox: Some(sandbox),
enforce_managed_network: false,
managed_network: None,
network_proxy: None,
};
let prepared = prepare_exec_request(
&params,
HashMap::new(),
Some(&runtime_paths),
/*network_policy_decider*/ None,
/*network_policy_audit_observer*/ None,
)
.await
.expect("prepare sandboxed request");
assert_ne!(prepared.command, params.argv);
assert_eq!(prepared.cwd, cwd);
#[cfg(target_os = "linux")]
{
assert_eq!(
prepared.command.first(),
Some(&runtime_paths.codex_self_exe.to_string_lossy().into_owned())
);
let permission_profile_json = prepared
.command
.iter()
.position(|arg| arg == "--permission-profile")
.and_then(|index| prepared.command.get(index + 1))
.expect("sandbox wrapper permission profile");
let permission_profile: PermissionProfile =
serde_json::from_str(permission_profile_json).expect("permission profile JSON");
assert_eq!(
permission_profile,
PermissionProfile::workspace_write()
.materialize_project_roots_with_workspace_roots(std::slice::from_ref(&cwd))
);
let policy_directory = tempdir().expect("policy directory");
let explicit_cwd =
AbsolutePathBuf::from_absolute_path(policy_directory.path()).expect("policy cwd");
let mut params = params.clone();
for policy_cwd in [&cwd, &explicit_cwd] {
params.sandbox.as_mut().expect("sandbox").cwd = PathUri::from_abs_path(policy_cwd);
let prepared = prepare_exec_request(
&params,
HashMap::new(),
Some(&runtime_paths),
/*network_policy_decider*/ None,
/*network_policy_audit_observer*/ None,
)
.await
.expect("prepare sandboxed request");
let actual_cwds = prepared
.command
.windows(4)
.find(|args| args[0] == "--sandbox-policy-cwd")
.expect("sandbox wrapper cwd arguments");
assert_eq!(
actual_cwds,
[
"--sandbox-policy-cwd",
policy_cwd.to_string_lossy().as_ref(),
"--command-cwd",
cwd.to_string_lossy().as_ref(),
]
);
}
}
#[cfg(target_os = "macos")]
assert_eq!(
prepared.command.first().map(String::as_str),
Some("/usr/bin/sandbox-exec")
);
let mut params = params;
params.sandbox.as_mut().unwrap().windows_sandbox_selection = WindowsSandboxSelection::Mxc;
let error = prepare_exec_request(
&params,
HashMap::new(),
Some(&runtime_paths),
/*network_policy_decider*/ None,
/*network_policy_audit_observer*/ None,
)
.await
.err()
.expect("unsupported MXC must fail closed");
assert_eq!(error.message, "native MXC is unavailable on this executor");
}
#[cfg(unix)]
#[tokio::test]
async fn sandbox_request_routes_custom_arg0_to_inner_helper() {
let cwd: AbsolutePathBuf = std::env::current_dir()
.expect("current directory")
.try_into()
.expect("absolute cwd");
let cwd_uri = PathUri::from_abs_path(&cwd);
let self_exe = std::env::current_exe().expect("current executable");
let runtime_paths =
ExecServerRuntimeOptions::new(self_exe.clone(), Some(self_exe)).expect("runtime paths");
let sandbox = FileSystemSandboxContext::from_permission_profile(
PermissionProfile::workspace_write(),
cwd_uri.clone(),
);
let params = ExecParams {
metadata: Default::default(),
process_id: ProcessId::from("process-custom-arg0"),
argv: vec!["/bin/sh".to_string(), "-c".to_string(), "true".to_string()],
cwd: cwd_uri,
shell_snapshot: None,
env_policy: None,
env: HashMap::new(),
tty: false,
pipe_stdin: false,
arg0: Some("custom-arg0".to_string()),
sandbox: Some(sandbox),
enforce_managed_network: false,
managed_network: None,
network_proxy: None,
};
let prepared = prepare_exec_request(
&params,
HashMap::new(),
Some(&runtime_paths),
/*network_policy_decider*/ None,
/*network_policy_audit_observer*/ None,
)
.await
.expect("prepare sandboxed request");
let helper_mode = prepared
.command
.iter()
.position(|arg| arg == CODEX_ARG0_EXEC_HELPER_ARG1)
.expect("sandboxed command should invoke arg0 helper");
assert_eq!(
prepared.command[helper_mode..],
[
CODEX_ARG0_EXEC_HELPER_ARG1,
"custom-arg0",
"/bin/sh",
"-c",
"true",
]
);
#[cfg(target_os = "linux")]
assert_eq!(prepared.arg0, Some(CODEX_LINUX_SANDBOX_ARG0.to_string()));
#[cfg(target_os = "macos")]
assert_eq!(prepared.arg0, None);
}
#[cfg(target_os = "macos")]
fn managed_network_sandbox_request() -> (ExecParams, ExecServerRuntimeOptions) {
let cwd: AbsolutePathBuf = std::env::current_dir()
.expect("current directory")
.try_into()
.expect("absolute cwd");
let cwd_uri = PathUri::from_abs_path(&cwd);
let self_exe = std::env::current_exe().expect("current executable");
let runtime_paths =
ExecServerRuntimeOptions::new(self_exe.clone(), Some(self_exe)).expect("runtime paths");
let sandbox = FileSystemSandboxContext::from_permission_profile(
PermissionProfile::workspace_write(),
cwd_uri.clone(),
);
let params = ExecParams {
metadata: Default::default(),
process_id: ProcessId::from("process-managed-network"),
argv: vec!["/usr/bin/true".to_string()],
cwd: cwd_uri,
shell_snapshot: None,
env_policy: None,
env: HashMap::new(),
tty: false,
pipe_stdin: false,
arg0: None,
sandbox: Some(sandbox),
enforce_managed_network: true,
managed_network: None,
network_proxy: None,
};
(params, runtime_paths)
}
#[cfg(target_os = "macos")]
fn seatbelt_policy_arg(command: &[String]) -> &str {
command
.windows(2)
.find_map(|args| (args[0] == "-p").then_some(args[1].as_str()))
.expect("Seatbelt policy argument")
}
#[cfg(target_os = "macos")]
#[tokio::test]
async fn sandbox_request_preserves_prepared_managed_network_policy() {
let (mut params, runtime_paths) = managed_network_sandbox_request();
let socket_dir = tempfile::tempdir().expect("temporary socket directory");
let allowed_socket = socket_dir
.path()
.canonicalize()
.expect("canonical socket directory")
.join("allowed.sock")
.to_string_lossy()
.into_owned();
params.managed_network = Some(ManagedNetworkSandboxContext {
loopback_ports: vec![43123],
allow_local_binding: false,
allow_unix_sockets: vec![allowed_socket.clone()],
dangerously_allow_all_unix_sockets: false,
});
let prepared = prepare_exec_request(
&params,
HashMap::new(),
Some(&runtime_paths),
/*network_policy_decider*/ None,
/*network_policy_audit_observer*/ None,
)
.await
.expect("prepare managed-network sandbox request");
let policy = seatbelt_policy_arg(&prepared.command);
let unix_socket_definitions = prepared
.command
.iter()
.filter(|arg| arg.starts_with("-DUNIX_SOCKET_PATH_"))
.cloned()
.collect::<Vec<_>>();
assert!(policy.contains("(allow network-outbound (remote ip \"localhost:43123\"))"));
assert!(policy.contains("(allow system-socket (socket-domain AF_UNIX))"));
assert!(policy.contains(
"(allow network-outbound (remote unix-socket (subpath (param \"UNIX_SOCKET_PATH_0\"))))"
));
assert_eq!(
unix_socket_definitions,
vec![format!("-DUNIX_SOCKET_PATH_0={allowed_socket}")]
);
assert!(!policy.contains("(allow network-outbound (remote unix-socket))"));
assert!(!policy.contains("(allow network-outbound)\n"));
}
#[cfg(target_os = "macos")]
#[tokio::test]
async fn sandbox_request_only_allows_all_unix_sockets_when_configured() {
let (mut params, runtime_paths) = managed_network_sandbox_request();
params.managed_network = Some(ManagedNetworkSandboxContext {
loopback_ports: vec![43123],
..ManagedNetworkSandboxContext::default()
});
for allow_all in [false, true] {
params
.managed_network
.as_mut()
.expect("managed network context")
.dangerously_allow_all_unix_sockets = allow_all;
let prepared = prepare_exec_request(
&params,
HashMap::new(),
Some(&runtime_paths),
/*network_policy_decider*/ None,
/*network_policy_audit_observer*/ None,
)
.await
.expect("prepare managed-network sandbox request");
let policy = seatbelt_policy_arg(&prepared.command);
assert_eq!(
(
policy.contains("(allow system-socket (socket-domain AF_UNIX))"),
policy.contains("(allow network-bind (local unix-socket))"),
policy.contains("(allow network-outbound (remote unix-socket))"),
),
(allow_all, allow_all, allow_all)
);
assert!(!policy.contains("(allow network-outbound)\n"));
assert!(
!prepared
.command
.iter()
.any(|arg| arg.starts_with("-DUNIX_SOCKET_PATH_"))
);
}
}
#[cfg(target_os = "macos")]
#[tokio::test]
async fn sandbox_request_preserves_executor_local_proxy_unix_socket_policy() {
let (mut params, runtime_paths) = managed_network_sandbox_request();
let socket_dir = tempfile::tempdir().expect("temporary socket directory");
let socket_root = socket_dir
.path()
.canonicalize()
.expect("canonical socket directory");
let allowed_socket = socket_root
.join("allowed.sock")
.to_string_lossy()
.into_owned();
let denied_socket = socket_root
.join("denied.sock")
.to_string_lossy()
.into_owned();
let config = NetworkProxyConfig {
enabled: true,
enable_socks5: false,
unix_sockets: Some(NetworkUnixSocketPermissions {
entries: [
(allowed_socket.clone(), NetworkUnixSocketPermission::Allow),
(denied_socket, NetworkUnixSocketPermission::Deny),
]
.into_iter()
.collect(),
}),
..NetworkProxyConfig::default()
};
params.network_proxy = Some(RemoteNetworkProxyLaunchConfig::new(
RemoteNetworkProxyConfig::from_effective_config(&config)
.expect("supported remote proxy config"),
));
let prepared = prepare_exec_request(
&params,
HashMap::new(),
Some(&runtime_paths),
/*network_policy_decider*/ None,
/*network_policy_audit_observer*/ None,
)
.await
.expect("prepare sandbox request with executor-local proxy");
let policy = seatbelt_policy_arg(&prepared.command);
let proxy_addr: SocketAddr = prepared
.env
.get("HTTP_PROXY")
.expect("HTTP proxy env")
.strip_prefix("http://")
.expect("HTTP proxy scheme")
.parse()
.expect("HTTP proxy address");
let proxy_port = proxy_addr.port();
let unix_socket_definitions = prepared
.command
.iter()
.filter(|arg| arg.starts_with("-DUNIX_SOCKET_PATH_"))
.cloned()
.collect::<Vec<_>>();
assert!(policy.contains(&format!(
"(allow network-outbound (remote ip \"localhost:{proxy_port}\"))"
)));
assert!(policy.contains(
"(allow network-outbound (remote unix-socket (subpath (param \"UNIX_SOCKET_PATH_0\"))))"
));
assert_eq!(
unix_socket_definitions,
vec![format!("-DUNIX_SOCKET_PATH_0={allowed_socket}")]
);
assert!(!policy.contains("(allow network-outbound (remote unix-socket))"));
assert!(!policy.contains("(allow network-outbound)\n"));
prepared
.network_proxy_handle
.expect("running executor proxy")
.shutdown()
.await
.expect("shut down executor proxy");
}
#[tokio::test]
async fn native_request_preserves_native_launch_fields() {
let cwd: AbsolutePathBuf = std::env::current_dir()
.expect("current directory")
.try_into()
.expect("absolute cwd");
let cwd_uri = PathUri::from_abs_path(&cwd);
let env = HashMap::from([("TEST_ENV".to_string(), "value".to_string())]);
let params = ExecParams {
metadata: Default::default(),
process_id: ProcessId::from("process-1"),
argv: vec!["echo".to_string(), "hello".to_string()],
cwd: cwd_uri,
shell_snapshot: None,
env_policy: None,
env: HashMap::new(),
tty: false,
pipe_stdin: false,
arg0: Some("custom-arg0".to_string()),
sandbox: None,
enforce_managed_network: false,
managed_network: None,
network_proxy: None,
};
let prepared = prepare_exec_request(
&params,
env.clone(),
/*runtime_paths*/ None,
/*network_policy_decider*/ None,
/*network_policy_audit_observer*/ None,
)
.await
.expect("prepare native request");
assert_eq!(prepared.command, params.argv);
assert_eq!(prepared.cwd, cwd);
assert_eq!(prepared.env, env);
assert_eq!(prepared.arg0, params.arg0);
}
#[test_case(false, None, &["-c", "true"]; "unmasked")]
#[test_case(true, Some("BASH_ENV"), &["-c", "true"]; "masking_with_startup_hook")]
#[test_case(true, Some("SSH_CLIENT"), &["-c", "true"]; "masking_with_remote_shell_startup")]
#[test_case(true, None, &["-c", "-l", "true"]; "masking_with_extra_login_option")]
#[tokio::test]
async fn native_request_handles_remote_proxy_config_for_platform(
credential_masking: bool,
startup_env: Option<&str>,
shell_args: &[&str],
) {
let cwd: AbsolutePathBuf = std::env::current_dir()
.expect("current directory")
.try_into()
.expect("absolute cwd");
let mut config = NetworkProxyConfig {
enabled: true,
..NetworkProxyConfig::default()
};
config.set_allowed_domains(vec!["allowed.example".to_string()]);
let mut proxy_config = RemoteNetworkProxyConfig::from_effective_config(&config)
.expect("supported remote proxy config");
if credential_masking {
proxy_config.enable_credential_masking(Default::default());
}
let params = ExecParams {
metadata: Default::default(),
process_id: ProcessId::from("process-remote-proxy"),
argv: std::iter::once("/bin/bash")
.chain(shell_args.iter().copied())
.map(str::to_string)
.collect(),
cwd: PathUri::from_abs_path(&cwd),
shell_snapshot: None,
env_policy: None,
env: HashMap::new(),
tty: false,
pipe_stdin: false,
arg0: None,
sandbox: None,
enforce_managed_network: false,
managed_network: None,
network_proxy: Some(
RemoteNetworkProxyLaunchConfig::new(proxy_config)
.for_execution("remote".to_string(), "execution-1".to_string()),
),
};
let stale_proxy = "http://127.0.0.1:9".to_string();
let mut env = HashMap::from([
("HTTP_PROXY".to_string(), stale_proxy.clone()),
("TEST_ENV".to_string(), "value".to_string()),
("PATH".to_string(), "/devbox/bin:/usr/bin:/bin".to_string()),
(
"OPENAI_API_KEY".to_string(),
"sk-proj-executor-only-0000000000000000000000000000000000".to_string(),
),
(
PROXY_ATTRIBUTION_TOKEN_ENV_KEY.to_string(),
"foreign-token".to_string(),
),
]);
if let Some(key) = startup_env {
env.insert(key.to_string(), "startup-hook".to_string());
}
let prepared = prepare_exec_request(
&params,
env.clone(),
/*runtime_paths*/ None,
/*network_policy_decider*/ None,
/*network_policy_audit_observer*/ None,
)
.await
.expect("prepare request with executor-local proxy");
assert_eq!(prepared.command, params.argv);
for key in ["PATH", "OPENAI_API_KEY"].into_iter().chain(startup_env) {
assert_eq!(prepared.env.get(key), env.get(key), "{key}");
}
if cfg!(target_os = "windows") {
assert_eq!(prepared.env.get("HTTP_PROXY"), None);
assert_eq!(prepared.env.get("TEST_ENV"), Some(&"value".to_string()));
assert!(prepared.network_proxy_handle.is_none());
return;
}
let http_proxy = prepared.env.get("HTTP_PROXY").expect("HTTP proxy env");
assert_ne!(http_proxy, &stale_proxy);
assert!(http_proxy.starts_with("http://127.0.0.1:"));
assert!(!prepared.env.contains_key(PROXY_ATTRIBUTION_TOKEN_ENV_KEY));
let proxy_addr: SocketAddr = http_proxy
.strip_prefix("http://")
.expect("HTTP proxy scheme")
.parse()
.expect("HTTP proxy address");
let mut stream = tokio::net::TcpStream::connect(proxy_addr)
.await
.expect("connect to executor proxy");
stream
.write_all(b"CONNECT blocked.example:443 HTTP/1.1\r\nHost: blocked.example:443\r\n\r\n")
.await
.expect("write CONNECT request");
let mut response = [0_u8; 256];
let response_len = timeout(Duration::from_secs(2), stream.read(&mut response))
.await
.expect("proxy response timeout")
.expect("read proxy response");
assert!(String::from_utf8_lossy(&response[..response_len]).starts_with("HTTP/1.1 403"));
prepared
.network_proxy_handle
.expect("running executor proxy")
.shutdown()
.await
.expect("shut down executor proxy");
}
#[cfg(not(target_os = "windows"))]
#[tokio::test]
async fn disabled_remote_proxy_config_is_rejected_before_exporting_ports() {
let cwd: AbsolutePathBuf = std::env::current_dir()
.expect("current directory")
.try_into()
.expect("absolute cwd");
let mut proxy_config =
RemoteNetworkProxyConfig::from_effective_config(&NetworkProxyConfig::default())
.expect("serializable disabled proxy config");
proxy_config.enable_credential_masking(Default::default());
let params = ExecParams {
metadata: Default::default(),
process_id: ProcessId::from("process-disabled-remote-proxy"),
argv: vec![
"/bin/bash".to_string(),
"-lc".to_string(),
"true".to_string(),
],
cwd: PathUri::from_abs_path(&cwd),
shell_snapshot: None,
env_policy: None,
env: HashMap::new(),
tty: false,
pipe_stdin: false,
arg0: None,
sandbox: None,
enforce_managed_network: false,
managed_network: None,
network_proxy: Some(RemoteNetworkProxyLaunchConfig::new(proxy_config)),
};
let error = prepare_exec_request(
&params,
HashMap::new(),
/*runtime_paths*/ None,
/*network_policy_decider*/ None,
/*network_policy_audit_observer*/ None,
)
.await
.err()
.expect("disabled executor proxy launch must fail closed");
assert_eq!(error.code, -32602);
assert!(
error
.message
.contains("executor-local network proxy launch requires an enabled proxy")
);
}
#[cfg(windows)]
#[test_case(WindowsSandboxLevel::RestrictedToken ; "unelevated is rejected")]
#[test_case(WindowsSandboxLevel::Elevated ; "elevated is accepted")]
#[tokio::test]
async fn managed_network_honors_windows_sandbox_level(windows_sandbox_level: WindowsSandboxLevel) {
let cwd: AbsolutePathBuf = std::env::current_dir()
.expect("current directory")
.try_into()
.expect("absolute cwd");
let cwd_uri = PathUri::from_abs_path(&cwd);
let self_exe = std::env::current_exe().expect("current executable");
let runtime_paths = ExecServerRuntimeOptions::new(self_exe, None).expect("runtime paths");
let permissions = PermissionProfile::read_only();
let mut sandbox =
FileSystemSandboxContext::from_permission_profile(permissions.clone(), cwd_uri.clone());
sandbox.windows_sandbox_selection = windows_sandbox_level.into();
sandbox.windows_sandbox_proxy_settings_mode =
Some(codex_sandboxing::WindowsSandboxProxySettingsMode::Preserve);
let proxy_config = RemoteNetworkProxyConfig::from_effective_config(&NetworkProxyConfig {
enabled: true,
enable_socks5: false,
..NetworkProxyConfig::default()
})
.expect("supported remote proxy config");
let params = ExecParams {
metadata: Default::default(),
process_id: ProcessId::from("process-managed-network"),
argv: vec!["cmd.exe".to_string(), "/c".to_string(), "exit".to_string()],
cwd: cwd_uri,
shell_snapshot: None,
env_policy: None,
env: HashMap::new(),
tty: false,
pipe_stdin: false,
arg0: None,
sandbox: Some(sandbox),
enforce_managed_network: true,
managed_network: None,
network_proxy: Some(RemoteNetworkProxyLaunchConfig::new(proxy_config)),
};
let prepared = prepare_exec_request(
&params,
HashMap::new(),
Some(&runtime_paths),
/*network_policy_decider*/ None,
/*network_policy_audit_observer*/ None,
)
.await;
if windows_sandbox_level == WindowsSandboxLevel::RestrictedToken {
let error = prepared
.err()
.expect("managed networking must reject an unelevated Windows sandbox");
assert_eq!(error.code, -32602);
assert!(
error
.message
.contains("managed networking requires the elevated Windows sandbox backend")
);
return;
}
let mut prepared = prepared.expect("managed networking accepts an elevated Windows sandbox");
let spawn = prepared
.windows_sandbox_spawn_request()
.expect("Windows sandbox spawn request");
assert_eq!(spawn.windows_sandbox_level, WindowsSandboxLevel::Elevated);
assert!(spawn.proxy_enforced);
assert!(spawn.network_proxy_restricting_sid.is_some());
prepared
.network_proxy_handle
.take()
.expect("running executor proxy")
.shutdown()
.await
.expect("shut down executor proxy");
}

View File

@@ -0,0 +1,82 @@
//! Emits process lifecycle telemetry and bounds process identifiers recorded by tracing.
//! Lifecycle events retain the identity captured at launch across reconnects and later operations.
use std::sync::Arc;
use codex_sandboxing::SandboxType;
use opentelemetry::trace::SpanContext;
use crate::telemetry::ExecutorRegistration;
/// Log fields captured at launch, never refreshed from a resumed session.
#[derive(Clone, Default)]
pub(crate) struct ProcessTelemetry {
pub(crate) launch_context: Option<SpanContext>,
pub(crate) thread_id: Option<String>,
pub(crate) tool_call_id: Option<String>,
pub(crate) executor_registration: Option<Arc<ExecutorRegistration>>,
}
/// Lifecycle events with outcome fields only when a process has exited.
pub(crate) enum ProcessTelemetryEvent {
Start,
SpawnFailed,
SandboxDenied,
Exit {
exit_code: i32,
termination_requested: bool,
},
}
impl ProcessTelemetry {
pub(crate) fn log(&self, event: ProcessTelemetryEvent, sandbox: SandboxType) {
let (event_name, exit_code, termination_requested, reason) = match event {
ProcessTelemetryEvent::Start => ("codex.exec_server.process_start", None, None, None),
ProcessTelemetryEvent::SpawnFailed => {
("codex.exec_server.process_spawn_failed", None, None, None)
}
ProcessTelemetryEvent::SandboxDenied => (
"codex.exec_server.sandbox_denied",
None,
None,
Some("inferred_denial"),
),
ProcessTelemetryEvent::Exit {
exit_code,
termination_requested,
} => (
"codex.exec_server.process_exit",
Some(exit_code),
Some(termination_requested),
None,
),
};
let trace_id = self
.launch_context
.as_ref()
.map(|span| span.trace_id().to_string());
let span_id = self
.launch_context
.as_ref()
.map(|span| span.span_id().to_string());
tracing::event!(
target: "codex_otel.log_only",
tracing::Level::INFO,
event.name = event_name,
launch.trace_id = trace_id.as_deref(),
launch.span_id = span_id.as_deref(),
conversation.id = self.thread_id.as_deref(),
tool.call_id = self.tool_call_id.as_deref(),
executor.environment_id = self.executor_registration.as_ref().map(|registration| registration.environment_id.as_str()),
executor.registration_id = self.executor_registration.as_ref().map(|registration| registration.executor_registration_id.as_str()),
sandbox.type = ?sandbox,
process.exit_code = exit_code,
process.termination_requested = termination_requested,
reason,
);
}
}
pub(crate) fn trace_process_id(process_id: &str) -> Option<&str> {
(!process_id.is_empty() && process_id.len() <= 64).then_some(process_id)
}

View File

@@ -0,0 +1,45 @@
syntax = "proto3";
package codex.exec_server.relay.v1;
message RelayMessageFrame {
uint32 version = 1;
string stream_id = 2;
uint32 ack = 3;
uint32 ack_bits = 4;
oneof body {
RelayData data = 5;
RelayAck ack_frame = 6;
RelayResume resume = 7;
RelayReset reset = 8;
RelayHeartbeat heartbeat = 9;
RelayHandshake handshake = 10;
}
optional string traceparent = 11;
optional string tracestate = 12;
}
message RelayData {
uint32 seq = 1;
uint32 segment_index = 2;
uint32 segment_count = 3;
bytes payload = 4;
}
message RelayAck {}
message RelayResume {
uint32 next_seq = 1;
}
message RelayReset {
string reason = 1;
}
message RelayHeartbeat {}
message RelayHandshake {
bytes payload = 1;
}

View File

@@ -0,0 +1,65 @@
// This file is @generated by prost-build.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct RelayMessageFrame {
#[prost(uint32, tag = "1")]
pub version: u32,
#[prost(string, tag = "2")]
pub stream_id: ::prost::alloc::string::String,
#[prost(uint32, tag = "3")]
pub ack: u32,
#[prost(uint32, tag = "4")]
pub ack_bits: u32,
#[prost(oneof = "relay_message_frame::Body", tags = "5, 6, 7, 8, 9, 10")]
pub body: ::core::option::Option<relay_message_frame::Body>,
#[prost(string, optional, tag = "11")]
pub traceparent: ::core::option::Option<::prost::alloc::string::String>,
#[prost(string, optional, tag = "12")]
pub tracestate: ::core::option::Option<::prost::alloc::string::String>,
}
pub mod relay_message_frame {
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Body {
#[prost(message, tag = "5")]
Data(super::RelayData),
#[prost(message, tag = "6")]
AckFrame(super::RelayAck),
#[prost(message, tag = "7")]
Resume(super::RelayResume),
#[prost(message, tag = "8")]
Reset(super::RelayReset),
#[prost(message, tag = "9")]
Heartbeat(super::RelayHeartbeat),
#[prost(message, tag = "10")]
Handshake(super::RelayHandshake),
}
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct RelayData {
#[prost(uint32, tag = "1")]
pub seq: u32,
#[prost(uint32, tag = "2")]
pub segment_index: u32,
#[prost(uint32, tag = "3")]
pub segment_count: u32,
#[prost(bytes = "vec", tag = "4")]
pub payload: ::prost::alloc::vec::Vec<u8>,
}
#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct RelayAck {}
#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct RelayResume {
#[prost(uint32, tag = "1")]
pub next_seq: u32,
}
#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct RelayReset {
#[prost(string, tag = "1")]
pub reason: ::prost::alloc::string::String,
}
#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct RelayHeartbeat {}
#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct RelayHandshake {
#[prost(bytes = "vec", tag = "1")]
pub payload: ::prost::alloc::vec::Vec<u8>,
}

View File

@@ -0,0 +1,102 @@
use std::io;
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
#[cfg(windows)]
use std::os::windows::fs::OpenOptionsExt;
use std::path::Path;
use tokio::io::AsyncReadExt;
use crate::protocol::FsOpenMode;
pub(crate) async fn open(path: &Path, mode: FsOpenMode) -> io::Result<tokio::fs::File> {
let path = path.to_path_buf();
tokio::task::spawn_blocking(move || open_sync(&path, mode).map(tokio::fs::File::from_std))
.await
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
}
/// Opens a regular file without blocking on Unix FIFOs or impersonating Windows pipe servers.
pub(crate) fn open_sync(path: &Path, mode: FsOpenMode) -> io::Result<std::fs::File> {
let mut options = std::fs::OpenOptions::new();
match mode {
FsOpenMode::Read => {
options.read(true);
}
FsOpenMode::Replace => {
options.write(true).create(true).truncate(true);
}
}
configure_open(&mut options);
let file = options.open(path)?;
if !is_disk_file(&file) || !file.metadata()?.is_file() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("path `{}` is not a file", path.display()),
));
}
Ok(file)
}
/// Reads a regular UTF-8 file without following a symlink at its final path component.
pub async fn read_sensitive_file_to_string(path: &Path) -> io::Result<String> {
let mut options = std::fs::OpenOptions::new();
options.read(true);
configure_open(&mut options);
#[cfg(unix)]
options.custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW);
#[cfg(windows)]
{
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;
options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);
}
let mut file = tokio::fs::OpenOptions::from(options).open(path).await?;
let metadata = file.metadata().await?;
if !is_disk_file(&file) || !metadata.is_file() || metadata.file_type().is_symlink() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("path `{}` is not a regular file", path.display()),
));
}
let mut contents = String::new();
file.read_to_string(&mut contents).await?;
Ok(contents)
}
#[cfg(unix)]
fn configure_open(options: &mut std::fs::OpenOptions) {
options.custom_flags(libc::O_NONBLOCK);
}
#[cfg(windows)]
fn configure_open(options: &mut std::fs::OpenOptions) {
use windows_sys::Win32::Storage::FileSystem::SECURITY_IDENTIFICATION;
options.security_qos_flags(SECURITY_IDENTIFICATION);
}
#[cfg(not(any(unix, windows)))]
fn configure_open(_options: &mut std::fs::OpenOptions) {}
#[cfg(windows)]
pub(crate) fn is_disk_file(file: &impl std::os::windows::io::AsRawHandle) -> bool {
use windows_sys::Win32::Storage::FileSystem::FILE_TYPE_DISK;
use windows_sys::Win32::Storage::FileSystem::GetFileType;
// SAFETY: `file` owns this handle for the duration of the call.
unsafe { GetFileType(file.as_raw_handle()) == FILE_TYPE_DISK }
}
#[cfg(not(windows))]
fn is_disk_file<T>(_file: &T) -> bool {
true
}
#[cfg(test)]
#[path = "regular_file_tests.rs"]
mod tests;

View File

@@ -0,0 +1,47 @@
use super::read_sensitive_file_to_string;
use tempfile::TempDir;
#[tokio::test]
async fn read_sensitive_file_reads_regular_file() {
let directory = TempDir::new().expect("temporary directory");
let path = directory.path().join("role.toml");
tokio::fs::write(&path, "developer_instructions = 'stay focused'")
.await
.expect("write regular file");
assert_eq!(
read_sensitive_file_to_string(&path)
.await
.expect("read regular file"),
"developer_instructions = 'stay focused'",
);
}
#[tokio::test]
async fn read_sensitive_file_rejects_directory() {
let directory = TempDir::new().expect("temporary directory");
assert!(
read_sensitive_file_to_string(directory.path())
.await
.is_err()
);
}
#[cfg(any(unix, windows))]
#[tokio::test]
async fn read_sensitive_file_rejects_symlink() {
let directory = TempDir::new().expect("temporary directory");
let target = directory.path().join("target.toml");
let link = directory.path().join("role.toml");
tokio::fs::write(&target, "model_provider = 'attacker'")
.await
.expect("write symlink target");
#[cfg(unix)]
std::os::unix::fs::symlink(&target, &link).expect("create symlink");
#[cfg(windows)]
std::os::windows::fs::symlink_file(&target, &link).expect("create symlink");
assert!(read_sensitive_file_to_string(&link).await.is_err());
}

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More