Base: codex-main originale (prima del fork aKode)
This commit is contained in:
67
codex-rs/exec-server/src/environment/accepted.rs
Normal file
67
codex-rs/exec-server/src/environment/accepted.rs
Normal 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
|
||||
}
|
||||
}
|
||||
116
codex-rs/exec-server/src/environment/connect_options.rs
Normal file
116
codex-rs/exec-server/src/environment/connect_options.rs
Normal 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;
|
||||
343
codex-rs/exec-server/src/environment/connect_options_tests.rs
Normal file
343
codex-rs/exec-server/src/environment/connect_options_tests.rs
Normal 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);
|
||||
}
|
||||
49
codex-rs/exec-server/src/environment/discovery_recovery.rs
Normal file
49
codex-rs/exec-server/src/environment/discovery_recovery.rs
Normal 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
62
codex-rs/exec-server/src/environment/discovery_v2.rs
Normal file
62
codex-rs/exec-server/src/environment/discovery_v2.rs
Normal 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;
|
||||
139
codex-rs/exec-server/src/environment/discovery_v2_tests.rs
Normal file
139
codex-rs/exec-server/src/environment/discovery_v2_tests.rs
Normal 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(¶ms)?,
|
||||
serde_json::to_value(¶ms)?
|
||||
]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user