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,99 @@
//! Sends registry requests with current credentials and at most one retry after a 401.
//! Transport failures and other HTTP errors are never replayed here.
//! A deadline before the first transport send remains a retryable unsent request.
use codex_http_client::HttpResponse;
use codex_http_client::Request;
use http::HeaderValue;
use http::StatusCode;
use tokio::time::Instant;
use tokio::time::timeout_at;
use super::EnvironmentRegistryClient;
use super::RegistryAuthMode;
use super::current_trace_context_headers;
use crate::ExecServerError;
pub(super) fn registry_auth_error(error: codex_api::AuthError) -> ExecServerError {
match error {
codex_api::AuthError::Transient(_) => ExecServerError::RequestNotSent(
"environment registry credential resolution is temporarily unavailable".to_string(),
),
error => super::direct::direct_auth_error(error),
}
}
impl EnvironmentRegistryClient {
pub(super) async fn send_authenticated(
&self,
request: Request,
deadline: Option<Instant>,
) -> Result<(HttpResponse, Option<HeaderValue>), ExecServerError> {
let request = request
.into_prepared()
.map_err(ExecServerError::EnvironmentRegistryConfig)?;
let mut sent = false;
let send = async {
let mut retried = false;
loop {
let (authenticated, credential) = if self.auth_mode != RegistryAuthMode::Legacy {
let (headers, credential) = self.resolve_auth().await?;
let mut authenticated = request.clone();
authenticated.headers.extend(headers);
(authenticated, credential)
} else {
(
self.auth_provider
.apply_auth(request.clone())
.await
.map_err(registry_auth_error)?,
None,
)
};
let prepared = authenticated
.prepare_body_for_send()
.map_err(ExecServerError::EnvironmentRegistryConfig)?;
let rejected_headers = prepared.headers.clone();
let mut outgoing = self
.http_for_auth()
.request(authenticated.method, authenticated.url)
.headers(prepared.headers)
.headers(current_trace_context_headers())
.body(prepared.body.unwrap_or_default());
if let Some(timeout) = authenticated.timeout {
outgoing = outgoing.timeout(timeout);
}
sent = true;
let response = outgoing.send().await?;
if !retried
&& response.status() == StatusCode::UNAUTHORIZED
&& self
.auth_provider
.refresh_after_unauthorized(rejected_headers)
.await
{
retried = true;
continue;
}
return Ok((response, credential));
}
};
if let Some(deadline) = deadline {
match timeout_at(deadline, send).await {
Ok(result) => result,
Err(_) if !sent => Err(ExecServerError::RequestNotSent(
"environment registry credential resolution timed out".to_string(),
)),
Err(_) => Err(ExecServerError::EnvironmentRegistryRequest(
codex_http_client::RouteAwareRequestError::Timeout,
)),
}
} else {
send.await
}
}
}
#[cfg(test)]
#[path = "auth_tests.rs"]
mod tests;

View File

@@ -0,0 +1,220 @@
//! Exercise live authentication at the registry request boundary.
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use codex_api::AuthProvider;
use http::HeaderMap;
use http::HeaderValue;
use http::Method;
use http::header::AUTHORIZATION;
use pretty_assertions::assert_eq;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use super::*;
use crate::NoiseChannelIdentity;
use crate::NoiseChannelPublicKey;
use crate::relay::HarnessKeyValidator;
use crate::remote::RegistryHarnessKeyValidator;
// Hyphens keep fixture credentials out of randomly generated Base64 public keys.
const OLD_AUTHORIZATION: &str = "Bearer test-old-token";
const NEW_AUTHORIZATION: &str = "Bearer test-new-token";
#[derive(Default)]
struct RotatingAuth {
refreshes: AtomicUsize,
stall: Option<AuthStage>,
reached: tokio::sync::Notify,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum AuthStage {
Initial,
Refresh,
Retry,
}
impl RotatingAuth {
async fn stall_at(&self, stage: AuthStage) {
if self.stall == Some(stage) {
self.reached.notify_one();
std::future::pending::<()>().await;
}
}
}
impl AuthProvider for RotatingAuth {
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), codex_api::AuthError> {
let token = if self.refreshes.load(Ordering::SeqCst) == 0 {
OLD_AUTHORIZATION
} else {
NEW_AUTHORIZATION
};
headers.insert(AUTHORIZATION, HeaderValue::from_static(token));
Ok(())
}
fn apply_auth_headers(&self, mut headers: HeaderMap) -> codex_api::AuthHeadersFuture<'_> {
Box::pin(async move {
self.stall_at(if self.refreshes.load(Ordering::SeqCst) == 0 {
AuthStage::Initial
} else {
AuthStage::Retry
})
.await;
self.add_auth_headers(&mut headers)?;
Ok(headers)
})
}
fn refresh_after_unauthorized(&self, rejected: HeaderMap) -> codex_api::AuthRefreshFuture<'_> {
assert!(rejected.contains_key(AUTHORIZATION));
Box::pin(async {
self.stall_at(AuthStage::Refresh).await;
self.refreshes.fetch_add(1, Ordering::SeqCst);
true
})
}
}
#[tokio::test]
async fn registry_deadline_covers_initial_auth_refresh_and_retry() -> anyhow::Result<()> {
for operation in ["connect", "register"] {
for stage in [AuthStage::Initial, AuthStage::Refresh, AuthStage::Retry] {
let server = MockServer::start().await;
Mock::given(wiremock::matchers::any())
.respond_with(ResponseTemplate::new(401))
.mount(&server)
.await;
let provider = Arc::new(RotatingAuth {
stall: Some(stage),
..Default::default()
});
let mut client = EnvironmentRegistryClient::new(server.uri(), provider.clone())?;
client.connect_timeout = Duration::from_secs(60);
let key = NoiseChannelIdentity::generate()?.public_key();
let task = tokio::spawn(async move {
if operation == "register" {
client.register_environment("env", &key).await.map(|_| ())
} else {
client.connect_environment("env", key).await.map(|_| ())
}
});
provider.reached.notified().await;
// Advance only after real socket I/O reached the selected auth stage.
tokio::time::pause();
tokio::time::advance(Duration::from_secs(61)).await;
let result = tokio::time::timeout(Duration::from_secs(1), task)
.await
.expect("registry operation must finish at its original deadline")?;
if operation == "register" && stage == AuthStage::Initial {
assert!(matches!(result, Err(ExecServerError::RequestNotSent(_))));
} else {
assert!(
matches!(result, Err(ExecServerError::EnvironmentRegistryRequest(error)) if error.is_timeout())
);
}
assert_eq!(
server.received_requests().await.unwrap().len(),
if stage == AuthStage::Initial { 0 } else { 1 }
);
tokio::time::resume();
}
}
Ok(())
}
#[tokio::test]
async fn noise_registry_operations_retry_with_new_credentials() -> anyhow::Result<()> {
for (operation, auth_mode) in [
("register", RegistryAuthMode::Legacy),
("connect", RegistryAuthMode::Legacy),
("validate", RegistryAuthMode::Legacy),
("register", RegistryAuthMode::ExecutorCredential),
("validate", RegistryAuthMode::ExecutorCredential),
] {
let server = MockServer::start().await;
let mut key = serde_json::to_value(NoiseChannelIdentity::generate()?.public_key())?;
// 32-byte Base64-encoded key material containing the former fixture credential `new`.
key["x25519_public_key"] = "newAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=".into();
let key: NoiseChannelPublicKey = serde_json::from_value(key)?;
Mock::given(header("authorization", OLD_AUTHORIZATION))
.respond_with(ResponseTemplate::new(401))
.expect(1)
.mount(&server)
.await;
Mock::given(header("authorization", NEW_AUTHORIZATION))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"environment_id": "env", "url": "wss://relay.example/ws",
"executor_registration_id": "registration",
"security_profile": "noise_hybrid_ik_v1",
"executor_public_key": key, "harness_key_authorization": "authorization",
"valid": true,
})))
.expect(1)
.mount(&server)
.await;
let provider = Arc::new(RotatingAuth::default());
let mut client = EnvironmentRegistryClient::new(server.uri(), provider.clone())?;
client.auth_mode = auth_mode;
match operation {
"register" => {
client.register_environment_with_retry("env", &key).await?;
}
"connect" => {
client.connect_environment("env", key).await?;
}
"validate" => {
RegistryHarnessKeyValidator {
client,
environment_id: "env".into(),
executor_registration_id: "registration".into(),
}
.validate_harness_key(&key, "authorization", Some(uuid::Uuid::new_v4()))
.await?;
}
_ => unreachable!(),
}
assert_eq!(provider.refreshes.load(Ordering::SeqCst), 1);
let requests = server.received_requests().await.unwrap();
assert_eq!(requests[0].body, requests[1].body);
assert_eq!(
requests[0].url.path(),
format!("/cloud/environment/env/{operation}")
);
assert_eq!(
requests[0].headers.get("x-codex-noise-stream-id"),
requests[1].headers.get("x-codex-noise-stream-id")
);
}
Ok(())
}
#[tokio::test]
async fn only_401_retries_and_only_once() -> anyhow::Result<()> {
for (status, attempts, refreshes) in [(401, 2, 1), (403, 1, 0), (500, 1, 0)] {
let server = MockServer::start().await;
Mock::given(wiremock::matchers::any())
.respond_with(ResponseTemplate::new(status))
.expect(attempts)
.mount(&server)
.await;
let provider = Arc::new(RotatingAuth::default());
let client = EnvironmentRegistryClient::new(server.uri(), provider.clone())?;
let (response, _) = client
.send_authenticated(
Request::new(Method::POST, server.uri()),
/*deadline*/ None,
)
.await?;
assert_eq!(response.status().as_u16(), status);
assert_eq!(provider.refreshes.load(Ordering::SeqCst), refreshes);
}
Ok(())
}

View File

@@ -0,0 +1,96 @@
//! Credential-free diagnostics for failed rendezvous connections.
//! Wire headers are untrusted: accept only known rejection codes and never inspect response bodies.
use std::io::ErrorKind;
use tokio_tungstenite::tungstenite::Error;
const REJECTION_REASON_HEADER: &str = "x-codex-rendezvous-rejection-reason";
#[derive(Debug, PartialEq, Eq)]
pub(super) struct ConnectionFailure {
pub error_kind: &'static str,
pub io_error_kind: Option<&'static str>,
pub http_status: Option<u16>,
pub rejection_reason: Option<&'static str>,
}
impl From<&Error> for ConnectionFailure {
fn from(error: &Error) -> Self {
let (error_kind, io_error_kind) = match error {
Error::Http(response) => {
return Self {
error_kind: "http",
io_error_kind: None,
http_status: Some(response.status().as_u16()),
rejection_reason: response
.headers()
.get(REJECTION_REASON_HEADER)
.and_then(|value| rejection_reason(value.as_bytes())),
};
}
Error::Io(error) => (
"io",
Some(match error.kind() {
ErrorKind::TimedOut => "timed_out",
ErrorKind::ConnectionRefused => "connection_refused",
ErrorKind::ConnectionReset => "connection_reset",
ErrorKind::ConnectionAborted => "connection_aborted",
ErrorKind::NotConnected => "not_connected",
ErrorKind::NetworkDown => "network_down",
ErrorKind::NetworkUnreachable => "network_unreachable",
ErrorKind::HostUnreachable => "host_unreachable",
ErrorKind::AddrNotAvailable => "addr_not_available",
ErrorKind::PermissionDenied => "permission_denied",
ErrorKind::BrokenPipe => "broken_pipe",
ErrorKind::UnexpectedEof => "unexpected_eof",
ErrorKind::Interrupted => "interrupted",
ErrorKind::WouldBlock => "would_block",
_ => "other",
}),
),
Error::Tls(_) => ("tls", None),
Error::Protocol(_) => ("protocol", None),
Error::ConnectionClosed | Error::AlreadyClosed => ("connection_closed", None),
Error::Capacity(_)
| Error::WriteBufferFull(_)
| Error::Utf8(_)
| Error::AttackAttempt
| Error::Url(_)
| Error::HttpFormat(_) => ("other", None),
};
Self {
error_kind,
io_error_kind,
http_status: None,
rejection_reason: None,
}
}
}
fn rejection_reason(header: &[u8]) -> Option<&'static str> {
match header {
b"expired" => Some("expired"),
b"missing_role" => Some("missing_role"),
b"missing_expiry" => Some("missing_expiry"),
b"missing_signature" => Some("missing_signature"),
b"missing_version" => Some("missing_version"),
b"missing_executor_registration_id" => Some("missing_executor_registration_id"),
b"unexpected_executor_registration_id" => Some("unexpected_executor_registration_id"),
b"malformed_query" => Some("malformed_query"),
b"invalid_role" => Some("invalid_role"),
b"invalid_expiry" => Some("invalid_expiry"),
b"invalid_signature" => Some("invalid_signature"),
b"invalid_secret" => Some("invalid_secret"),
b"extra_query_param" => Some("extra_query_param"),
b"pod_draining" => Some("pod_draining"),
b"unknown_route" => Some("unknown_route"),
b"wrong_rendezvous_cluster" => Some("wrong_rendezvous_cluster"),
b"route_unavailable" => Some("route_unavailable"),
_ => None,
}
}
#[cfg(test)]
#[path = "connection_diagnostics_tests.rs"]
mod tests;

View File

@@ -0,0 +1,116 @@
//! Verify that connection failures remain correlated without exposing wire payloads.
use pretty_assertions::assert_eq;
use tokio_tungstenite::tungstenite::Error;
use super::ConnectionFailure;
use super::REJECTION_REASON_HEADER;
#[test]
fn only_known_http_rejection_headers_are_reported() {
for (header, expected) in [
(Some("expired"), Some("expired")),
(Some("invalid_signature"), Some("invalid_signature")),
(Some("pod_draining"), Some("pod_draining")),
(Some("expired secret=credential"), None),
(Some("private-proxy-hostname"), None),
(None, None),
] {
let mut response = http::Response::builder().status(401);
if let Some(header) = header {
response = response.header(REJECTION_REASON_HEADER, header);
}
// A known legacy body must not override a header or stand in for a missing one.
let error = Error::Http(Box::new(
response.body(Some(b"pod_draining".to_vec())).unwrap(),
));
assert_eq!(
ConnectionFailure::from(&error),
ConnectionFailure {
error_kind: "http",
io_error_kind: None,
http_status: Some(401),
rejection_reason: expected,
}
);
}
}
#[test]
fn io_failure_reports_typed_kind_without_error_text() {
use std::io::ErrorKind;
for (kind, expected) in [
(ErrorKind::TimedOut, "timed_out"),
(ErrorKind::ConnectionRefused, "connection_refused"),
(ErrorKind::ConnectionReset, "connection_reset"),
(ErrorKind::ConnectionAborted, "connection_aborted"),
(ErrorKind::NotConnected, "not_connected"),
(ErrorKind::NetworkDown, "network_down"),
(ErrorKind::NetworkUnreachable, "network_unreachable"),
(ErrorKind::HostUnreachable, "host_unreachable"),
(ErrorKind::AddrNotAvailable, "addr_not_available"),
(ErrorKind::PermissionDenied, "permission_denied"),
(ErrorKind::BrokenPipe, "broken_pipe"),
(ErrorKind::UnexpectedEof, "unexpected_eof"),
(ErrorKind::Interrupted, "interrupted"),
(ErrorKind::WouldBlock, "would_block"),
(ErrorKind::Other, "other"),
(ErrorKind::InvalidData, "other"),
] {
let error = Error::Io(std::io::Error::new(kind, "private host and credentials"));
assert_eq!(
ConnectionFailure::from(&error),
ConnectionFailure {
error_kind: "io",
io_error_kind: Some(expected),
http_status: None,
rejection_reason: None,
}
);
}
}
#[tokio::test]
async fn websocket_rejection_preserves_status_and_sends_correlation_id() {
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
let server = MockServer::start().await;
let request_id = "req_0123456789abcdef0123456789abcdef";
Mock::given(method("GET"))
.and(header("x-request-id", request_id))
.respond_with(
ResponseTemplate::new(401)
.insert_header(REJECTION_REASON_HEADER, "expired")
.set_body_string("private proxy response that must not be logged"),
)
.expect(1)
.mount(&server)
.await;
let result = super::super::connect_rendezvous(
&format!("ws://{}/", server.address()),
request_id,
&crate::ExecServerTelemetry::default(),
&codex_http_client::HttpClientFactory::new(
codex_http_client::OutboundProxyPolicy::ReqwestDefault,
),
)
.await;
let error = match result {
Err(error) => error,
Ok(_) => panic!("expected the websocket upgrade to be rejected"),
};
assert_eq!(
ConnectionFailure::from(&error),
ConnectionFailure {
error_kind: "http",
io_error_kind: None,
http_status: Some(401),
rejection_reason: Some("expired"),
}
);
}

View File

@@ -0,0 +1,342 @@
use std::time::Instant;
use codex_api::AuthError;
use codex_api::AuthProvider;
use codex_http_client::NetworkPolicy;
use codex_http_client::NetworkPolicyDenied;
use codex_http_client::Request;
use codex_websocket_client::WebSocketConnection;
use codex_websocket_client::WebSocketConnector;
use http::Method;
use http::StatusCode;
use serde::Deserialize;
use serde::Serialize;
use tokio::time::sleep;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tracing::info;
use tracing::warn;
use super::EnvironmentRegistryClient;
use super::RegistryAuthMode;
use super::RemoteEnvironmentConfig;
use crate::ExecServerError;
use crate::client::is_retryable_recovery_error;
use crate::client::registry_recovery_retry_delay;
use crate::client_api::DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT;
use crate::client_transport::authenticate_websocket_request;
use crate::client_transport::connect_websocket_request;
use crate::connection::JsonRpcConnection;
use crate::server::ConnectionProcessor;
use crate::telemetry::ConnectionTransport;
use crate::trace_context::current_trace_context_headers;
const DIRECT_TRANSPORT: &str = "direct_jsonrpc_v1";
#[derive(Debug, Serialize)]
struct DirectRegistrationRequest {
transport: &'static str,
}
#[derive(Debug, Deserialize)]
struct DirectRegistrationResponse {
environment_id: String,
transport: String,
registration_id: String,
url: String,
}
impl EnvironmentRegistryClient {
async fn register_direct_environment_when_available(
&self,
environment_id: &str,
policy: &NetworkPolicy,
) -> Result<DirectRegistrationResponse, ExecServerError> {
let destination = super::endpoint_url(
&self.base_url,
&format!("/cloud/environment/{environment_id}/direct/register"),
);
let mut retry_attempt = 0;
loop {
match self.register_direct_environment(environment_id).await {
Err(error) if is_policy_recoverable(&error, policy, &destination) => {}
result => return result,
}
sleep(registry_recovery_retry_delay(environment_id, retry_attempt)).await;
retry_attempt = retry_attempt.saturating_add(1);
}
}
#[tracing::instrument(
name = "codex.exec_server.remote.register",
skip_all,
fields(
otel.kind = "client",
otel.name = "codex.exec_server.remote.register",
result = tracing::field::Empty,
)
)]
async fn register_direct_environment(
&self,
environment_id: &str,
) -> Result<DirectRegistrationResponse, ExecServerError> {
let started_at = Instant::now();
let response = async {
if self.auth_mode == RegistryAuthMode::ExecutorCredential {
return Err(ExecServerError::EnvironmentRegistryConfig(
"direct transport does not support scoped executor credentials".to_string(),
));
}
let url = super::endpoint_url(
&self.base_url,
&format!("/cloud/environment/{environment_id}/direct/register"),
);
let request = Request::new(Method::POST, url)
.with_json(&DirectRegistrationRequest {
transport: DIRECT_TRANSPORT,
})
.into_prepared()
.map_err(ExecServerError::EnvironmentRegistryConfig)?;
let request = self
.auth_provider
.apply_auth(request)
.await
.map_err(direct_auth_error)?;
let prepared = request
.prepare_body_for_send()
.map_err(ExecServerError::EnvironmentRegistryConfig)?;
let response = self
.http
.request(request.method, request.url)
.headers(prepared.headers)
.headers(current_trace_context_headers())
.body(prepared.body.unwrap_or_default())
.timeout(self.connect_timeout)
.send()
.await?;
let response: DirectRegistrationResponse = self.parse_json_response(response).await?;
if response.environment_id != environment_id {
return Err(ExecServerError::Protocol(
"environment registry returned a different environment id".to_string(),
));
}
if response.transport != DIRECT_TRANSPORT {
return Err(ExecServerError::Protocol(format!(
"environment registry returned unsupported direct transport `{}`",
response.transport
)));
}
if response.registration_id.trim().is_empty() || response.url.trim().is_empty() {
return Err(ExecServerError::Protocol(
"environment registry returned incomplete direct connection data".to_string(),
));
}
require_tls_or_loopback(&response.url, "wss")?;
Ok(response)
}
.await;
let result = if response.is_ok() { "success" } else { "error" };
tracing::Span::current().record("result", result);
self.telemetry
.remote_registration_completed(result, started_at.elapsed());
response
}
}
pub(super) async fn run_direct_environment(
config: RemoteEnvironmentConfig,
client: EnvironmentRegistryClient,
processor: ConnectionProcessor,
) -> Result<(), ExecServerError> {
require_tls_or_loopback(&config.base_url, "https")?;
let mut retry_attempt = 0;
let mut registration = client
.register_direct_environment_when_available(
&config.environment_id,
config.http_client_factory.network_policy(),
)
.await?;
loop {
match connect_direct(
&registration.url,
config.auth_provider.as_ref(),
config.auth_mode,
&config.http_client_factory,
)
.await
{
Ok(websocket) => {
retry_attempt = 0;
info!(
environment_id = registration.environment_id,
registration_id = registration.registration_id,
"direct exec-server connected"
);
processor
.run_connection(
JsonRpcConnection::from_direct_websocket(
websocket,
format!(
"direct exec-server websocket {}",
websocket_diagnostic_url(&registration.url)
),
),
ConnectionTransport::WebSocket,
)
.await;
config.telemetry.remote_reconnect("disconnected");
}
Err(error)
if (is_retryable_recovery_error(&error)
|| is_policy_recoverable(
&error,
config.http_client_factory.network_policy(),
&registration.url,
))
&& !matches!(
&error,
ExecServerError::WebSocketConnect {
source: tokio_tungstenite::tungstenite::Error::Http(response),
..
} if response.status().is_client_error()
&& !matches!(
response.status(),
StatusCode::REQUEST_TIMEOUT
| StatusCode::CONFLICT
| StatusCode::TOO_MANY_REQUESTS
)
) =>
{
// A handshake conflict rejects this registration; other transient failures
// reconnect using the existing URL.
if matches!(
&error,
ExecServerError::WebSocketConnect {
source: tokio_tungstenite::tungstenite::Error::Http(response),
..
} if response.status() == StatusCode::CONFLICT
) {
registration = client
.register_direct_environment_when_available(
&config.environment_id,
config.http_client_factory.network_policy(),
)
.await?;
}
warn!("direct exec-server connection failed; retrying");
config.telemetry.remote_reconnect("connect_failed");
}
Err(error) => return Err(error),
}
sleep(registry_recovery_retry_delay(
&config.environment_id,
retry_attempt,
))
.await;
retry_attempt = retry_attempt.saturating_add(1);
}
}
fn is_policy_recoverable(
error: &ExecServerError,
policy: &NetworkPolicy,
destination: &str,
) -> bool {
match error.application_network_policy_denial() {
Some(NetworkPolicyDenied::Unavailable) => true,
Some(NetworkPolicyDenied::Revoked) => url::Url::parse(destination).is_ok_and(|url| {
matches!(
policy.acquire(&url),
Ok(_) | Err(NetworkPolicyDenied::Unavailable)
)
}),
Some(NetworkPolicyDenied::Destination | NetworkPolicyDenied::UnsupportedTransport)
| None => false,
}
}
async fn connect_direct(
url: &str,
auth_provider: &dyn AuthProvider,
auth_mode: RegistryAuthMode,
http_client_factory: &codex_http_client::HttpClientFactory,
) -> Result<WebSocketConnection, ExecServerError> {
if auth_mode == RegistryAuthMode::ExecutorCredential {
return Err(ExecServerError::EnvironmentRegistryConfig(
"direct transport does not support scoped executor credentials".to_string(),
));
}
let mut request =
url.into_client_request()
.map_err(|source| ExecServerError::WebSocketConnect {
url: websocket_diagnostic_url(url),
source,
})?;
request
.headers_mut()
.extend(current_trace_context_headers());
authenticate_websocket_request(&mut request, auth_provider)
.await
.map_err(direct_auth_error)?;
let authenticated_url = request.uri().to_string();
require_tls_or_loopback(&authenticated_url, "wss")?;
let connector = WebSocketConnector::new(http_client_factory)
.map_err(|error| ExecServerError::WebSocketConfiguration(error.to_string()))?
.with_tcp_nodelay();
connect_websocket_request(
request,
websocket_diagnostic_url(&authenticated_url),
connector,
DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT,
/*use_loopback_direct*/ false,
)
.await
}
pub(super) fn require_tls_or_loopback(
url: &str,
secure_scheme: &str,
) -> Result<(), ExecServerError> {
let parsed = url::Url::parse(url).map_err(|error| {
ExecServerError::EnvironmentRegistryConfig(format!("invalid remote endpoint URL: {error}"))
})?;
if parsed.scheme() == secure_scheme {
return Ok(());
}
let loopback = match parsed.host() {
Some(url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"),
Some(url::Host::Ipv4(host)) => host.is_loopback(),
Some(url::Host::Ipv6(host)) => host.is_loopback(),
None => false,
};
if loopback
&& secure_scheme
.strip_suffix('s')
.is_some_and(|scheme| parsed.scheme() == scheme)
{
return Ok(());
}
Err(ExecServerError::EnvironmentRegistryConfig(format!(
"remote transport requires {secure_scheme} for non-loopback endpoints"
)))
}
fn websocket_diagnostic_url(url: &str) -> String {
url.split(['?', '#']).next().unwrap_or(url).to_string()
}
pub(super) fn direct_auth_error(error: AuthError) -> ExecServerError {
let message = format!("failed to resolve environment registry authentication: {error}");
match error {
AuthError::Policy(denied) => ExecServerError::ApplicationNetworkPolicy(denied),
AuthError::Build(_) => ExecServerError::EnvironmentRegistryAuth(message),
AuthError::Transient(_) => ExecServerError::Disconnected(message),
}
}
#[cfg(test)]
#[path = "direct_tests.rs"]
mod tests;

View File

@@ -0,0 +1,623 @@
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use std::time::Instant;
use anyhow::Result;
use base64::Engine;
use codex_api::AuthProvider;
use codex_http_client::DestinationPolicy;
use codex_http_client::HttpClientFactory;
use codex_http_client::NetworkPolicyController;
use codex_http_client::OutboundProxyPolicy;
use futures::SinkExt;
use futures::StreamExt;
use http::HeaderMap;
use http::HeaderValue;
use pretty_assertions::assert_eq;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::net::TcpListener;
use tokio::time::timeout;
use tokio_tungstenite::accept_hdr_async;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::handshake::server::Request as HandshakeRequest;
use tokio_tungstenite::tungstenite::handshake::server::Response as HandshakeResponse;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::*;
use crate::ExecServerRuntimeOptions;
use crate::RemoteEnvironmentTransport;
#[derive(Debug)]
struct StaticAuthProvider;
impl AuthProvider for StaticAuthProvider {
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), codex_api::AuthError> {
headers.insert(
http::header::AUTHORIZATION,
HeaderValue::from_static("AWS4-HMAC-SHA256 test-signature"),
);
Ok(())
}
fn apply_auth(
&self,
mut request: codex_http_client::Request,
) -> codex_api::AuthProviderFuture<'_> {
Box::pin(async move {
if request.method == http::Method::GET {
assert_eq!(request.headers.len(), 1);
assert!(request.headers.contains_key(http::header::HOST));
assert!(request.url.starts_with("http"));
}
self.add_auth_headers(&mut request.headers)?;
Ok(request)
})
}
}
#[derive(Debug)]
struct QueryAuthProvider;
#[tokio::test]
async fn direct_environment_accepts_large_file_writes() -> Result<()> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let registry = MockServer::start().await;
Mock::given(method("POST"))
.and(path(
"/cloud/environment/environment-requested/direct/register",
))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"environment_id": "environment-requested",
"transport": DIRECT_TRANSPORT,
"registration_id": "registration-1",
"url": format!("ws://{}", listener.local_addr()?),
})))
.expect(1)
.mount(&registry)
.await;
let config = RemoteEnvironmentConfig::new_with_transport(
registry.uri(),
"environment-requested".to_string(),
RemoteEnvironmentTransport::Direct,
Arc::new(StaticAuthProvider),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)?;
let runtime_paths = ExecServerRuntimeOptions::new(
std::env::current_exe()?,
/*codex_linux_sandbox_exe*/ None,
)?;
let task = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(
crate::run_remote_environment(config, runtime_paths),
));
let (socket, _) = timeout(Duration::from_secs(5), listener.accept()).await??;
let mut websocket = tokio_tungstenite::accept_async(socket).await?;
websocket
.send(Message::Text(
serde_json::json!({
"id": 1, "method": "initialize", "params": {"clientName": "direct-test"},
})
.to_string()
.into(),
))
.await?;
let response = timeout(Duration::from_secs(5), websocket.next())
.await?
.expect("initialize response")?;
let response: serde_json::Value = serde_json::from_slice(&response.into_data())?;
assert_eq!(response["id"], 1);
assert!(response.get("result").is_some(), "{response}");
websocket
.send(Message::Text(
serde_json::json!({
"method": "initialized", "params": {},
})
.to_string()
.into(),
))
.await?;
let directory = tempfile::tempdir()?;
let output = directory.path().join("report.txt");
let path = codex_utils_path_uri::PathUri::from_host_native_path(&output)?;
let data = "report contents\n".repeat(1024);
// Exercise both JSON-RPC WebSocket encodings on the production direct runner.
for binary in [false, true] {
let request = serde_json::json!({
"id": 2, "method": "fs/writeFile", "params": {
"path": path,
"dataBase64": base64::engine::general_purpose::STANDARD.encode(&data),
},
})
.to_string();
assert!(
request.len() > crate::client_inbound_request_limit::MAX_CLIENT_INBOUND_REQUEST_LEN
);
let frame = if binary {
Message::Binary(request.into_bytes().into())
} else {
Message::Text(request.into())
};
websocket.send(frame).await?;
let response = timeout(Duration::from_secs(5), websocket.next())
.await?
.expect("large write must not disconnect the executor")?;
let response: serde_json::Value = serde_json::from_slice(&response.into_data())?;
assert_eq!(response["id"], 2);
assert_eq!(response["result"], serde_json::json!({}), "{response}");
assert_eq!(tokio::fs::read(&output).await?, data.as_bytes());
}
registry.verify().await;
task.abort();
Ok(())
}
impl AuthProvider for QueryAuthProvider {
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), codex_api::AuthError> {
Ok(())
}
fn apply_auth(
&self,
mut request: codex_http_client::Request,
) -> codex_api::AuthProviderFuture<'_> {
Box::pin(async move {
let mut url = url::Url::parse(&request.url)
.map_err(|error| codex_api::AuthError::Build(error.to_string()))?;
url.query_pairs_mut().append_pair("auth", "signed-query");
request.url = url.into();
Ok(request)
})
}
}
struct ScopedExecutorAuth;
impl AuthProvider for ScopedExecutorAuth {
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), codex_api::AuthError> {
headers.insert(
http::header::AUTHORIZATION,
HeaderValue::from_static("Bearer synthetic-scoped-token"),
);
Ok(())
}
}
#[tokio::test]
async fn direct_transport_rejects_scoped_credentials_before_sending() -> Result<()> {
let registry = MockServer::start().await;
let mut client = EnvironmentRegistryClient::new(registry.uri(), Arc::new(ScopedExecutorAuth))?;
client.auth_mode = RegistryAuthMode::ExecutorCredential;
let error = client
.register_direct_environment("environment-requested")
.await
.expect_err("scoped credentials must not be sent on direct registration");
assert!(matches!(
error,
ExecServerError::EnvironmentRegistryConfig(_)
));
assert!(registry.received_requests().await.unwrap().is_empty());
let listener = TcpListener::bind("127.0.0.1:0").await?;
let url = format!("ws://{}/connect", listener.local_addr()?);
let error = match connect_direct(
&url,
&ScopedExecutorAuth,
RegistryAuthMode::ExecutorCredential,
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)
.await
{
Err(error) => error,
Ok(_) => panic!("scoped credentials must not be sent to the WebSocket"),
};
assert!(matches!(
error,
ExecServerError::EnvironmentRegistryConfig(_)
));
assert!(
timeout(Duration::from_millis(50), listener.accept())
.await
.is_err()
);
Ok(())
}
#[tokio::test]
async fn direct_websocket_signs_only_host_and_preserves_handshake_headers() -> Result<()> {
let mut request = "wss://executor.example.com/connect".into_client_request()?;
request
.headers_mut()
.insert("traceparent", HeaderValue::from_static("trace-context"));
authenticate_websocket_request(&mut request, &StaticAuthProvider).await?;
assert!(request.headers().contains_key("sec-websocket-key"));
assert_eq!(request.headers()["traceparent"], "trace-context");
assert_eq!(
request.headers()[http::header::AUTHORIZATION],
"AWS4-HMAC-SHA256 test-signature"
);
Ok(())
}
#[tokio::test]
async fn direct_websocket_uses_authenticated_url_query_parameters() -> Result<()> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let url = format!("ws://{}/connect?existing=value", listener.local_addr()?);
let acceptor = tokio::spawn(async move {
let (socket, _) = listener.accept().await?;
let callback = |request: &HandshakeRequest, response: HandshakeResponse| {
assert_eq!(request.uri().path(), "/connect");
assert_eq!(
request.uri().query(),
Some("existing=value&auth=signed-query")
);
Ok(response)
};
accept_hdr_async(socket, callback).await.map(|_| ())
});
let connection = connect_direct(
&url,
&QueryAuthProvider,
RegistryAuthMode::Legacy,
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)
.await?;
drop(connection);
acceptor.await??;
Ok(())
}
#[test]
fn direct_endpoints_require_tls_except_on_loopback() {
for (url, scheme, allowed) in [
("https://registry.example.com", "https", true),
("wss://executor.example.com/connect", "wss", true),
("http://127.0.0.1:8080", "https", true),
("ws://localhost:8080/connect", "wss", true),
("http://registry.example.com", "https", false),
("ws://executor.example.com/connect", "wss", false),
] {
assert_eq!(
require_tls_or_loopback(url, scheme).is_ok(),
allowed,
"{url}"
);
}
}
#[test]
fn direct_authentication_retries_only_transient_credential_failures() {
for (error, retryable) in [
(AuthError::Transient("temporary".to_string()), true),
(AuthError::Build("invalid".to_string()), false),
] {
assert_eq!(
is_retryable_recovery_error(&direct_auth_error(error)),
retryable
);
}
}
#[tokio::test]
async fn direct_registration_validates_connection_data() -> Result<()> {
for (field, invalid_value) in [
("environment_id", "different-environment"),
("transport", "noise_hybrid_ik_v1"),
("registration_id", ""),
("url", ""),
("url", "ws://executor.example.com/connect"),
] {
let registry = MockServer::start().await;
let mut response = serde_json::json!({
"environment_id": "environment-requested",
"transport": DIRECT_TRANSPORT,
"registration_id": "registration-1",
"url": "wss://executor.example.com/connect",
});
response[field] = serde_json::json!(invalid_value);
Mock::given(method("POST"))
.and(path(
"/cloud/environment/environment-requested/direct/register",
))
.respond_with(ResponseTemplate::new(200).set_body_json(response))
.expect(1)
.mount(&registry)
.await;
let client = EnvironmentRegistryClient::new(registry.uri(), Arc::new(StaticAuthProvider))?;
let error = client
.register_direct_environment("environment-requested")
.await
.expect_err("invalid registration must be rejected");
if invalid_value.starts_with("ws://") {
assert!(matches!(
error,
ExecServerError::EnvironmentRegistryConfig(_)
));
} else {
assert!(matches!(error, ExecServerError::Protocol(_)));
}
registry.verify().await;
}
Ok(())
}
#[tokio::test(flavor = "current_thread")]
async fn direct_registration_uses_proxy_policy_without_logging_secrets() -> Result<()> {
use tracing_subscriber::Layer;
use tracing_subscriber::layer::SubscriberExt;
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"))
.with_filter(
tracing_subscriber::filter::Targets::new()
.with_target("codex_http_client", tracing::Level::TRACE)
.with_target("codex_exec_server", tracing::Level::TRACE),
),
);
let _guard = tracing::subscriber::set_default(subscriber);
tracing::debug!(target: "codex_exec_server", "direct registry log capture sentinel");
let proxy = MockServer::start().await;
let registry_url = "http://direct-registry-proxy.invalid/registry-path-secret";
let request_url =
format!("{registry_url}/cloud/environment/environment-requested/direct/register");
codex_http_client::cache_system_proxy_route_for_test(&request_url, proxy.uri());
Mock::given(method("POST"))
.and(path(
"/registry-path-secret/cloud/environment/environment-requested/direct/register",
))
.and(header("authorization", "AWS4-HMAC-SHA256 test-signature"))
.respond_with(
ResponseTemplate::new(200)
.insert_header("set-cookie", "session=registry-cookie-secret")
.insert_header(
"location",
"https://registry.example/?token=registry-location-secret",
)
.set_body_json(serde_json::json!({
"environment_id": "environment-requested",
"transport": DIRECT_TRANSPORT,
"registration_id": "registration-1",
"url": "wss://executor.example/connect?token=websocket-query-secret",
})),
)
.expect(1)
.mount(&proxy)
.await;
let client = EnvironmentRegistryClient::new_with_telemetry(
registry_url.to_string(),
Arc::new(StaticAuthProvider),
crate::ExecServerTelemetry::default(),
HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy),
)?;
let response = client
.register_direct_environment("environment-requested")
.await?;
assert_eq!(
response.url,
"wss://executor.example/connect?token=websocket-query-secret"
);
let requests = proxy
.received_requests()
.await
.expect("record proxy requests");
assert_eq!(requests.len(), 1);
assert_eq!(requests[0].url.as_str(), request_url);
assert_eq!(requests[0].body, br#"{"transport":"direct_jsonrpc_v1"}"#);
proxy.verify().await;
std::io::Seek::rewind(&mut log_file)?;
let mut logs = String::new();
std::io::Read::read_to_string(&mut log_file, &mut logs)?;
assert!(logs.contains("direct registry log capture sentinel"));
for secret in [
"test-signature",
"registry-path-secret",
"registry-cookie-secret",
"registry-location-secret",
"websocket-query-secret",
] {
assert!(!logs.contains(secret), "registry logs exposed {secret}");
}
Ok(())
}
#[tokio::test]
async fn direct_registration_handles_policy_outages_and_permanent_failures() -> Result<()> {
for (successful_registrations, policy_unavailable) in [(0, false), (1, false), (0, true)] {
let controller = NetworkPolicyController::default();
let policy = controller.policy();
controller.publish(policy.revision(), DestinationPolicy::Unrestricted);
if policy_unavailable && successful_registrations == 0 {
controller.unavailable(policy.revision());
}
let listener = TcpListener::bind("127.0.0.1:0").await?;
let websocket_url = format!("ws://{}/connect", listener.local_addr()?);
let registry = MockServer::start().await;
let registration_count = AtomicUsize::new(0);
Mock::given(method("POST"))
.and(path(
"/cloud/environment/environment-requested/direct/register",
))
.respond_with(move |_: &wiremock::Request| {
let attempt = registration_count.fetch_add(1, Ordering::Relaxed);
if policy_unavailable || attempt < successful_registrations {
ResponseTemplate::new(200).set_body_json(serde_json::json!({
"environment_id": "environment-requested",
"transport": DIRECT_TRANSPORT,
"registration_id": "registration-1",
"url": websocket_url,
}))
} else {
ResponseTemplate::new(503)
}
})
.expect((successful_registrations + 1) as u64)
.mount(&registry)
.await;
let config = RemoteEnvironmentConfig::new_with_transport(
registry.uri(),
"environment-requested".to_string(),
RemoteEnvironmentTransport::Direct,
Arc::new(StaticAuthProvider),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
.with_network_policy(policy.clone().for_current_account()),
)?;
let runtime_paths = ExecServerRuntimeOptions::new(
std::env::current_exe()?,
/*codex_linux_sandbox_exe*/ None,
)?;
let task = tokio::spawn(crate::run_remote_environment(config, runtime_paths));
if successful_registrations == 1 {
let (mut socket, _) = timeout(Duration::from_secs(5), listener.accept()).await??;
let mut request = [0; 4096];
let _ = socket.read(&mut request).await?;
socket
.write_all(b"HTTP/1.1 409 Conflict\r\nContent-Length: 0\r\n\r\n")
.await?;
socket.shutdown().await?;
}
if policy_unavailable {
timeout(Duration::from_secs(1), listener.accept())
.await
.expect_err("unavailable policy opened a connection");
controller.publish(policy.revision(), DestinationPolicy::Unrestricted);
let (socket, _) = timeout(Duration::from_secs(5), listener.accept()).await??;
let _websocket = tokio_tungstenite::accept_async(socket).await?;
registry.verify().await;
task.abort();
let _ = task.await;
continue;
}
let error = timeout(Duration::from_secs(5), task)
.await??
.expect_err("registration failure should stop the runner");
assert!(matches!(
error,
ExecServerError::EnvironmentRegistryHttp {
status: StatusCode::SERVICE_UNAVAILABLE,
..
}
));
registry.verify().await;
}
Ok(())
}
#[tokio::test]
async fn direct_websocket_reuses_registration_and_stops_on_permanent_errors() -> Result<()> {
for (status, should_retry) in [
(Some(StatusCode::BAD_REQUEST), false),
(Some(StatusCode::UNAUTHORIZED), false),
(Some(StatusCode::FORBIDDEN), false),
(Some(StatusCode::NOT_FOUND), false),
(Some(StatusCode::METHOD_NOT_ALLOWED), false),
(Some(StatusCode::GONE), false),
(Some(StatusCode::REQUEST_TIMEOUT), true),
(Some(StatusCode::CONFLICT), true),
(Some(StatusCode::TOO_MANY_REQUESTS), true),
(Some(StatusCode::INTERNAL_SERVER_ERROR), true),
(Some(StatusCode::SERVICE_UNAVAILABLE), true),
(None, true), // Close the TCP socket without sending an HTTP response.
] {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let websocket_url = format!("ws://{}", listener.local_addr()?);
let registry = MockServer::start().await;
let expected_calls = if status == Some(StatusCode::CONFLICT) {
2
} else {
1
};
let registration_count = AtomicUsize::new(0);
Mock::given(method("POST"))
.and(path(
"/cloud/environment/environment-requested/direct/register",
))
.and(header("authorization", "AWS4-HMAC-SHA256 test-signature"))
.respond_with(move |_: &wiremock::Request| {
let registration = registration_count.fetch_add(1, Ordering::Relaxed) + 1;
ResponseTemplate::new(200).set_body_json(serde_json::json!({
"environment_id": "environment-requested",
"transport": DIRECT_TRANSPORT,
"registration_id": format!("registration-{registration}"),
"url": format!("{websocket_url}/registration-{registration}"),
}))
})
.expect(expected_calls)
.mount(&registry)
.await;
let config = RemoteEnvironmentConfig::new_with_transport(
registry.uri(),
"environment-requested".to_string(),
RemoteEnvironmentTransport::Direct,
Arc::new(StaticAuthProvider),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)?;
let runtime_paths = ExecServerRuntimeOptions::new(
std::env::current_exe()?,
/*codex_linux_sandbox_exe*/ None,
)?;
let task = tokio::spawn(crate::run_remote_environment(config, runtime_paths));
let (mut socket, _) = timeout(Duration::from_secs(5), listener.accept()).await??;
let mut request = [0; 4096];
let _ = socket.read(&mut request).await?;
if let Some(status) = status {
let response = format!(
"HTTP/1.1 {} {}\r\nContent-Length: 0\r\n\r\n",
status.as_u16(),
status.canonical_reason().unwrap_or_default()
);
socket.write_all(response.as_bytes()).await?;
}
socket.shutdown().await?;
drop(socket);
if should_retry {
let expected_path = format!("/registration-{expected_calls}");
let check_registration = |request: &HandshakeRequest, response: HandshakeResponse| {
assert_eq!(request.uri().path(), expected_path);
Ok(response)
};
let (socket, _) = timeout(Duration::from_secs(5), listener.accept()).await??;
let websocket = accept_hdr_async(socket, &check_registration).await?;
let retry_delay =
registry_recovery_retry_delay("environment-requested", /*attempt*/ 0);
let retry_started = Instant::now();
drop(websocket);
let (socket, _) = timeout(Duration::from_secs(5), listener.accept()).await??;
assert!(retry_started.elapsed() >= retry_delay);
let _websocket = accept_hdr_async(socket, &check_registration).await?;
registry.verify().await;
task.abort();
let _ = task.await;
} else {
let error = timeout(Duration::from_secs(5), task)
.await??
.expect_err("permanent WebSocket client error should be terminal");
assert!(matches!(
error,
ExecServerError::WebSocketConnect {
source: tokio_tungstenite::tungstenite::Error::Http(response),
..
} if Some(response.status()) == status
));
}
}
Ok(())
}

View File

@@ -0,0 +1,412 @@
use std::io::Write;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use anyhow::Result;
use codex_api::AuthProvider;
use codex_api::SharedAuthProvider;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_http_client::cache_system_proxy_route_for_test;
use http::HeaderMap;
use http::HeaderValue;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::net::TcpListener;
use tokio::time::timeout;
use tokio_tungstenite::accept_async;
use tracing_subscriber::Layer;
use tracing_subscriber::layer::SubscriberExt;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_partial_json;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::query_param;
use super::*;
const HARNESS_KEY_AUTHORIZATION: &str = "authorization-that-must-not-leak";
#[derive(Debug)]
struct StaticRegistryAuthProvider;
impl AuthProvider for StaticRegistryAuthProvider {
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), codex_api::AuthError> {
let _ = headers.insert(
http::header::AUTHORIZATION,
HeaderValue::from_static("Bearer registry-token"),
);
Ok(())
}
}
fn static_registry_auth_provider() -> SharedAuthProvider {
Arc::new(StaticRegistryAuthProvider)
}
#[tokio::test(flavor = "current_thread")]
async fn registry_requests_do_not_log_sensitive_urls_or_response_headers() -> Result<()> {
let log_buffer = Arc::new(Mutex::new(Vec::new()));
let writer_buffer = Arc::clone(&log_buffer);
let subscriber = tracing_subscriber::registry().with(
tracing_subscriber::fmt::layer()
.with_ansi(false)
.with_writer(move || RegistryLogWriter(Arc::clone(&writer_buffer)))
.with_filter(
tracing_subscriber::filter::Targets::new()
.with_target("codex_http_client", tracing::Level::TRACE)
.with_target("codex_exec_server", tracing::Level::TRACE),
),
);
let _guard = tracing::subscriber::set_default(subscriber);
tracing::debug!(target: "codex_exec_server", "registry log capture sentinel");
let server = MockServer::start().await;
let harness_public_key = NoiseChannelIdentity::generate()?.public_key();
let executor_public_key = NoiseChannelIdentity::generate()?.public_key();
for (operation, response, cookie_secret, location_secret) in [
(
"register",
serde_json::json!({
"environment_id": "environment-requested",
"url": "wss://rendezvous.test/environment",
"security_profile": NOISE_RELAY_SECURITY_PROFILE,
"executor_registration_id": "registration-1",
}),
"register-cookie-secret",
"register-location-secret",
),
(
"connect",
serde_json::json!({
"environment_id": "environment-requested",
"url": "wss://rendezvous.test/harness",
"security_profile": NOISE_RELAY_SECURITY_PROFILE,
"executor_registration_id": "registration-1",
"executor_public_key": executor_public_key.clone(),
"harness_key_authorization": HARNESS_KEY_AUTHORIZATION,
}),
"connect-cookie-secret",
"connect-location-secret",
),
(
"validate",
serde_json::json!({ "valid": true }),
"validate-cookie-secret",
"validate-location-secret",
),
] {
Mock::given(method("POST"))
.and(path("/registry-path-secret"))
.and(query_param(
"registry_token",
format!(
"registry-query-secret/cloud/environment/environment-requested/{operation}"
),
))
.respond_with(
ResponseTemplate::new(200)
.insert_header("set-cookie", format!("session={cookie_secret}"))
.insert_header(
"location",
format!("https://registry.example/private?token={location_secret}"),
)
.set_body_json(response),
)
.expect(if operation == "validate" { 2 } else { 1 })
.mount(&server)
.await;
}
let registry_url =
server
.uri()
.replacen("http://", "http://registry-user:registry-password@", 1);
let registry_url =
format!("{registry_url}/registry-path-secret?registry_token=registry-query-secret");
let client = EnvironmentRegistryClient::new(registry_url, static_registry_auth_provider())?;
client
.register_environment("environment-requested", &executor_public_key)
.await?;
client
.connect_environment("environment-requested", harness_public_key.clone())
.await?;
let validator = RegistryHarnessKeyValidator {
client,
environment_id: "environment-requested".to_string(),
executor_registration_id: "registration-1".to_string(),
};
let stream_id = uuid::Uuid::new_v4();
validator
.validate_harness_key(
&harness_public_key,
HARNESS_KEY_AUTHORIZATION,
Some(stream_id),
)
.await?;
validator
.validate_harness_key(
&harness_public_key,
HARNESS_KEY_AUTHORIZATION,
/*stream_id*/ None,
)
.await?;
let requests = server.received_requests().await.expect("recorded requests");
let validation_requests: Vec<_> = requests
.iter()
.filter(|request| {
request
.url
.query_pairs()
.any(|(key, value)| key == "registry_token" && value.ends_with("/validate"))
})
.collect();
assert_eq!(validation_requests.len(), 2);
assert_eq!(
validation_requests[0]
.headers
.get("x-codex-noise-stream-id")
.map(|value| value.to_str().unwrap()),
Some(stream_id.to_string().as_str())
);
assert!(
validation_requests[1]
.headers
.get("x-codex-noise-stream-id")
.is_none()
);
let logs = String::from_utf8(log_buffer.lock().expect("log buffer lock").clone())?;
assert!(logs.contains("registry log capture sentinel"));
for secret in [
"registry-user",
"registry-password",
"registry-path-secret",
"registry-query-secret",
"registry-token",
HARNESS_KEY_AUTHORIZATION,
"register-cookie-secret",
"register-location-secret",
"connect-cookie-secret",
"connect-location-secret",
"validate-cookie-secret",
"validate-location-secret",
] {
assert!(!logs.contains(secret), "logs exposed {secret}:\n{logs}");
}
Ok(())
}
#[tokio::test]
async fn reconnect_reuses_registration_until_url_is_rejected() -> Result<()> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let rendezvous_url = format!("ws://{}", listener.local_addr()?);
let registry = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/cloud/environment/environment-requested/register"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"environment_id": "environment-requested",
"url": rendezvous_url,
"security_profile": NOISE_RELAY_SECURITY_PROFILE,
"executor_registration_id": "registration-1",
})))
.expect(2)
.mount(&registry)
.await;
let config = RemoteEnvironmentConfig::new(
registry.uri(),
"environment-requested".to_string(),
static_registry_auth_provider(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)?;
let environment_task =
tokio_util::task::AbortOnDropHandle::new(tokio::spawn(run_remote_environment(
config,
ExecServerRuntimeOptions::new(
std::env::current_exe()?,
/*codex_linux_sandbox_exe*/ None,
)?,
)));
let (first_socket, _peer_addr) = timeout(Duration::from_secs(5), listener.accept()).await??;
let mut first_websocket = accept_async(first_socket).await?;
first_websocket.close(None).await?;
// An ordinary disconnect and a stalled upgrade both retry without registering again.
let (mut stalled_socket, _peer_addr) =
timeout(Duration::from_secs(5), listener.accept()).await??;
let mut request = [0u8; 4096];
assert!(stalled_socket.read(&mut request).await? > 0);
tokio::time::pause();
tokio::time::advance(DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT).await;
tokio::time::resume();
// Keep the stalled socket open until the executor starts its next attempt.
let (mut rejected_socket, _peer_addr) =
timeout(Duration::from_secs(5), listener.accept()).await??;
drop(stalled_socket);
let _ = rejected_socket.read(&mut request).await?;
rejected_socket
.write_all(b"HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n")
.await?;
rejected_socket.shutdown().await?;
// The 4xx response discards the old registration before this attempt.
let (final_socket, _peer_addr) = timeout(Duration::from_secs(5), listener.accept()).await??;
let _final_websocket = accept_async(final_socket).await?;
registry.verify().await;
environment_task.abort();
let _ = environment_task.await;
Ok(())
}
#[tokio::test]
async fn noise_connect_provider_uses_supplied_system_proxy_policy() -> Result<()> {
let proxy = MockServer::start().await;
let registry_url = "http://registry-policy-proxy.test";
let request_url = format!("{registry_url}/cloud/environment/environment-requested/connect");
cache_system_proxy_route_for_test(&request_url, proxy.uri());
let harness_public_key = NoiseChannelIdentity::generate()?.public_key();
let executor_public_key = NoiseChannelIdentity::generate()?.public_key();
Mock::given(method("POST"))
.and(path("/cloud/environment/environment-requested/connect"))
.and(header("authorization", "Bearer registry-token"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"environment_id": "environment-requested",
"url": "wss://rendezvous.test/cloud-agent/default/ws/environment/environment-requested",
"security_profile": NOISE_RELAY_SECURITY_PROFILE,
"executor_registration_id": "registration-1",
"executor_public_key": executor_public_key.clone(),
"harness_key_authorization": HARNESS_KEY_AUTHORIZATION,
})))
.expect(1)
.mount(&proxy)
.await;
let provider = NoiseRendezvousEnvironmentConfig::new(
registry_url.to_string(),
"environment-requested".to_string(),
"registry-token".to_string(),
/*chatgpt_account_id*/ None,
)?
.into_connect_provider(HttpClientFactory::new(
OutboundProxyPolicy::RespectSystemProxy,
))?;
let bundle = timeout(
Duration::from_secs(5),
provider.connect_bundle(harness_public_key),
)
.await??;
let requests = proxy
.received_requests()
.await
.expect("proxy request recording should be enabled");
assert_eq!(requests.len(), 1);
assert_eq!(requests[0].url.as_str(), request_url);
assert_eq!(bundle.executor_public_key, executor_public_key);
Ok(())
}
#[tokio::test]
async fn validate_harness_key_requires_explicit_valid_response() {
let server = MockServer::start().await;
let harness_public_key = NoiseChannelIdentity::generate()
.expect("identity")
.public_key();
Mock::given(method("POST"))
.and(path("/cloud/environment/environment-requested/validate"))
.and(header("authorization", "Bearer registry-token"))
.and(body_partial_json(serde_json::json!({
"executor_registration_id": "registration-1",
"harness_public_key": harness_public_key.clone(),
"harness_key_authorization": HARNESS_KEY_AUTHORIZATION,
})))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"valid": false,
})))
.mount(&server)
.await;
let client = EnvironmentRegistryClient::new(server.uri(), static_registry_auth_provider())
.expect("client");
let error = RegistryHarnessKeyValidator {
client,
environment_id: "environment-requested".to_string(),
executor_registration_id: "registration-1".to_string(),
}
.validate_harness_key(
&harness_public_key,
HARNESS_KEY_AUTHORIZATION,
/*stream_id*/ None,
)
.await
.expect_err("a false validation response must fail closed");
assert!(matches!(
error,
ExecServerError::Protocol(message)
if message == "environment registry rejected Noise relay harness key"
));
}
#[tokio::test]
async fn validate_harness_key_does_not_expose_error_body() {
let server = MockServer::start().await;
let harness_public_key = NoiseChannelIdentity::generate()
.expect("identity")
.public_key();
Mock::given(method("POST"))
.and(path("/cloud/environment/environment-requested/validate"))
.respond_with(ResponseTemplate::new(500).set_body_string(HARNESS_KEY_AUTHORIZATION))
.mount(&server)
.await;
let client = EnvironmentRegistryClient::new(server.uri(), static_registry_auth_provider())
.expect("client");
let error = RegistryHarnessKeyValidator {
client,
environment_id: "environment-requested".to_string(),
executor_registration_id: "registration-1".to_string(),
}
.validate_harness_key(
&harness_public_key,
HARNESS_KEY_AUTHORIZATION,
/*stream_id*/ None,
)
.await
.expect_err("validation HTTP error should fail closed");
let display = error.to_string();
assert!(!display.contains(HARNESS_KEY_AUTHORIZATION));
assert!(matches!(
error,
ExecServerError::EnvironmentRegistryHttp { message, .. }
if message == "environment registry harness key validation failed"
));
}
struct RegistryLogWriter(Arc<Mutex<Vec<u8>>>);
impl Write for RegistryLogWriter {
fn write(&mut self, buffer: &[u8]) -> std::io::Result<usize> {
self.0
.lock()
.expect("log buffer lock")
.extend_from_slice(buffer);
Ok(buffer.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}

View File

@@ -0,0 +1,42 @@
//! Spread executor reconnects and retain backoff until a connection has been stable.
use std::time::Duration;
const INITIAL_BACKOFF: Duration = Duration::from_secs(1);
const MAX_BACKOFF: Duration = Duration::from_secs(30);
// Longer than the first keepalive interval plus its pong timeout (30s + 60s).
const STABLE_CONNECTION_DURATION: Duration = Duration::from_secs(120);
pub(super) struct ReconnectBackoff {
delay: Duration,
}
impl ReconnectBackoff {
pub(super) fn new() -> Self {
Self {
delay: INITIAL_BACKOFF,
}
}
pub(super) fn connection_closed(&mut self, connected_for: Duration) {
if connected_for >= STABLE_CONNECTION_DURATION {
self.delay = INITIAL_BACKOFF;
}
}
pub(super) fn next_delay(&mut self, random_sample: u64) -> Duration {
let delay = reconnect_delay(self.delay, random_sample);
self.delay = (self.delay * 2).min(MAX_BACKOFF);
delay
}
}
fn reconnect_delay(backoff: Duration, random_sample: u64) -> Duration {
let upper_ms = backoff.as_millis() as u64;
let lower_ms = upper_ms / 2;
Duration::from_millis(lower_ms + random_sample % (upper_ms - lower_ms + 1))
}
#[cfg(test)]
#[path = "reconnect_backoff_tests.rs"]
mod tests;

View File

@@ -0,0 +1,48 @@
//! Reconnect delays vary across samples while retaining a nonzero floor and the original cap.
use std::time::Duration;
use pretty_assertions::assert_eq;
use super::ReconnectBackoff;
use super::STABLE_CONNECTION_DURATION;
use super::reconnect_delay;
#[test]
fn reconnect_jitter_stays_within_each_backoff_window() {
for seconds in [1, 2, 4, 8, 16, 30] {
let backoff = Duration::from_secs(seconds);
let half_ms = seconds * 500;
assert_eq!(reconnect_delay(backoff, /*random_sample*/ 0), backoff / 2);
assert_eq!(reconnect_delay(backoff, half_ms), backoff);
for sample in [1, 1234, 987654, u64::MAX] {
let delay = reconnect_delay(backoff, sample);
assert!((backoff / 2..=backoff).contains(&delay));
}
assert_ne!(
reconnect_delay(backoff, /*random_sample*/ 1),
reconnect_delay(backoff, /*random_sample*/ 2)
);
}
}
#[test]
fn flapping_connections_retain_backoff_until_a_stable_session() {
let mut backoff = ReconnectBackoff::new();
for seconds in [1, 2, 4, 8, 16, 30, 30] {
backoff.connection_closed(STABLE_CONNECTION_DURATION - Duration::from_millis(1));
assert_eq!(
backoff.next_delay(/*random_sample*/ 0),
Duration::from_millis(seconds * 500)
);
}
backoff.connection_closed(STABLE_CONNECTION_DURATION);
assert_eq!(
backoff.next_delay(/*random_sample*/ 0),
Duration::from_millis(500)
);
assert_eq!(
backoff.next_delay(/*random_sample*/ 0),
Duration::from_secs(1)
);
}

View File

@@ -0,0 +1,77 @@
//! Retry explicit registration conflicts and authentication outages before registration writes.
//! Ambiguous failures must not be replayed: a timed-out request can still replace a newer registration.
//! The enclosing remote-transport future owns cancellation; retries spawn no background work.
use http::StatusCode;
use tokio::time::sleep;
use tracing::warn;
use super::EnvironmentRegistryClient;
use crate::EnvironmentRegistryRegistrationResponse;
use crate::ExecServerError;
use crate::NoiseChannelPublicKey;
use crate::client::registry_recovery_retry_delay;
impl EnvironmentRegistryClient {
pub(super) async fn register_environment_with_retry(
&self,
environment_id: &str,
executor_public_key: &NoiseChannelPublicKey,
) -> Result<EnvironmentRegistryRegistrationResponse, ExecServerError> {
// Competing executors for the same environment must not retry in lockstep.
let retry_key = uuid::Uuid::new_v4().to_string();
let mut attempt = 0_u32;
loop {
match self
.register_environment(environment_id, executor_public_key)
.await
{
Ok(response) => return Ok(response),
// Credential resolution failed before any registration was sent.
// Keep the executor alive without replaying an ambiguous write.
Err(ExecServerError::RequestNotSent(_)) => {
let delay = registry_recovery_retry_delay(&retry_key, attempt);
attempt = attempt.saturating_add(1);
warn!(
noise_event = "registration",
noise_outcome = "retry",
retry_attempt = attempt,
retry_delay_ms = delay.as_millis() as u64,
"Noise executor retrying unavailable credential resolution"
);
sleep(delay).await;
}
Err(ExecServerError::EnvironmentRegistryHttp { status, code, .. })
if matches!(
(status, code.as_deref()),
(
StatusCode::SERVICE_UNAVAILABLE,
Some("registration_conflict")
) | (
StatusCode::BAD_GATEWAY,
Some("authentication_service_unavailable")
)
) =>
{
let delay = registry_recovery_retry_delay(&retry_key, attempt);
attempt = attempt.saturating_add(1);
// Do not log response bodies or transport errors: they can contain credentials.
warn!(
noise_event = "registration",
noise_outcome = "retry",
retry_attempt = attempt,
retry_delay_ms = delay.as_millis() as u64,
status = status.as_u16(),
"Noise executor retrying uncommitted registry registration"
);
sleep(delay).await;
}
Err(error) => return Err(error),
}
}
}
}
#[cfg(test)]
#[path = "registration_retry_tests.rs"]
mod tests;

View File

@@ -0,0 +1,248 @@
//! Confirmed conflicts and pre-write auth outages permit replay; ambiguous results remain terminal.
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use codex_api::AuthProvider;
use codex_http_client::RouteAwareRequestError;
use http::HeaderMap;
use pretty_assertions::assert_eq;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::net::TcpListener;
use tokio::sync::Notify;
use tokio::time::advance;
use tokio::time::sleep;
use tokio::time::timeout;
use tokio_util::task::AbortOnDropHandle;
use tracing::instrument::WithSubscriber;
use tracing_subscriber::prelude::*;
use super::EnvironmentRegistryClient;
use super::ExecServerError;
use crate::NoiseChannelIdentity;
const ENVIRONMENT_ID: &str = "registration-retry-test";
const CONFLICT_BODY: &str =
r#"{"error":{"code":"registration_conflict","message":"registration unavailable"}}"#;
const CONFLICT_WITH_STRING_DETAIL_BODY: &str = r#"{"error":{"code":"registration_conflict","message":"registration unavailable"},"detail":"additional diagnostics"}"#;
const CONFLICT_WITH_STRUCTURED_DETAIL_BODY: &str = r#"{"error":{"code":"registration_conflict","message":"registration unavailable"},"detail":{"code":"registration_denied","message":"additional diagnostics"}}"#;
const AUTH_UNAVAILABLE_BODY: &str = r#"{"detail":{"code":"authentication_service_unavailable","message":"Authentication service unavailable"}}"#;
const ERROR_BODY: &str =
r#"{"error":{"code":"registration_denied","message":"registration unavailable"}}"#;
const ERROR_WITH_AUTH_DETAIL_BODY: &str = r#"{"error":{"code":"registration_denied","message":"registration unavailable"},"detail":{"code":"authentication_service_unavailable","message":"Authentication service unavailable"}}"#;
const SUCCESS_BODY: &str = r#"{"environment_id":"registration-retry-test","url":"ws://localhost/relay","security_profile":"noise_hybrid_ik_v1","executor_registration_id":"committed-registration"}"#;
#[derive(Debug, Default)]
struct RegistrationAuthProvider {
calls: AtomicUsize,
fail_first: bool,
stall_first: bool,
}
impl AuthProvider for RegistrationAuthProvider {
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), codex_api::AuthError> {
Ok(())
}
fn apply_auth_headers(&self, headers: HeaderMap) -> codex_api::AuthHeadersFuture<'_> {
if self.calls.fetch_add(1, Ordering::Relaxed) == 0 && self.fail_first {
return Box::pin(async {
if self.stall_first {
std::future::pending::<()>().await;
}
Err(codex_api::AuthError::Transient(
"metadata unavailable".to_string(),
))
});
}
Box::pin(async move { Ok(headers) })
}
}
#[tokio::test]
async fn transient_credential_failure_retries_before_sending_registration() -> anyhow::Result<()> {
for stall_first in [false, true] {
let server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::any())
.respond_with(
wiremock::ResponseTemplate::new(200).set_body_raw(SUCCESS_BODY, "application/json"),
)
.expect(1)
.mount(&server)
.await;
let provider = Arc::new(RegistrationAuthProvider {
fail_first: true,
stall_first,
..Default::default()
});
let mut client = EnvironmentRegistryClient::new(server.uri(), provider.clone())?;
client.connect_timeout = Duration::from_secs(1);
let response = timeout(
Duration::from_secs(10),
client.register_environment_with_retry(
ENVIRONMENT_ID,
&NoiseChannelIdentity::generate()?.public_key(),
),
)
.await??;
assert_eq!(response.environment_id, ENVIRONMENT_ID);
assert_eq!(provider.calls.load(Ordering::Relaxed), 2);
server.verify().await;
}
Ok(())
}
struct RetryObserved(Arc<Notify>);
impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for RetryObserved {
fn on_event(&self, event: &tracing::Event<'_>, _: tracing_subscriber::layer::Context<'_, S>) {
if event.metadata().target() == "codex_exec_server::remote::registration_retry"
&& event.metadata().fields().field("retry_attempt").is_some()
{
self.0.notify_one();
}
}
}
#[test_case::test_case(200, "not JSON", Duration::ZERO; "malformed_success")]
#[test_case::test_case(200, SUCCESS_BODY, Duration::from_secs(60); "committed_success_body_timeout")]
#[test_case::test_case(503, CONFLICT_BODY, Duration::ZERO; "confirmed_conflict_backoff_is_cancellable")]
#[test_case::test_case(503, CONFLICT_WITH_STRING_DETAIL_BODY, Duration::ZERO; "conflict_with_string_detail")]
#[test_case::test_case(503, CONFLICT_WITH_STRUCTURED_DETAIL_BODY, Duration::ZERO; "conflict_with_structured_detail")]
#[test_case::test_case(503, CONFLICT_BODY, Duration::from_secs(60); "conflict_code_not_received")]
#[test_case::test_case(503, "not JSON", Duration::ZERO; "malformed_unavailable")]
#[test_case::test_case(503, "{}", Duration::ZERO; "missing_conflict_code")]
#[test_case::test_case(503, ERROR_BODY, Duration::ZERO; "different_error_code")]
#[test_case::test_case(502, CONFLICT_BODY, Duration::ZERO; "gateway_error")]
#[test_case::test_case(502, AUTH_UNAVAILABLE_BODY, Duration::ZERO; "auth_outage_backoff_is_cancellable")]
#[test_case::test_case(502, ERROR_WITH_AUTH_DETAIL_BODY, Duration::ZERO; "canonical_error_overrides_auth_detail")]
#[test_case::test_case(502, AUTH_UNAVAILABLE_BODY, Duration::from_secs(60); "auth_outage_code_not_received")]
#[test_case::test_case(502, "not JSON", Duration::ZERO; "unconfirmed_gateway_error")]
#[test_case::test_case(502, r#"{"detail":"Authentication service unavailable"}"#, Duration::ZERO; "legacy_auth_outage")]
#[test_case::test_case(503, AUTH_UNAVAILABLE_BODY, Duration::ZERO; "auth_outage_wrong_status")]
#[test_case::test_case(408, CONFLICT_BODY, Duration::ZERO; "request_timeout")]
#[test_case::test_case(429, CONFLICT_BODY, Duration::ZERO; "too_many_requests")]
#[test_case::test_case(401, ERROR_BODY, Duration::from_secs(60); "unauthorized_stalled_body")]
#[test_case::test_case(403, ERROR_BODY, Duration::from_secs(60); "forbidden_stalled_body")]
#[test_case::test_case(404, ERROR_BODY, Duration::from_secs(60); "environment_deleted_stalled_body")]
#[test_case::test_case(401, ERROR_BODY, Duration::from_millis(50); "delayed_unauthorized_details")]
#[test_case::test_case(403, ERROR_BODY, Duration::from_millis(50); "delayed_forbidden_details")]
#[test_case::test_case(404, ERROR_BODY, Duration::from_millis(50); "delayed_error_details")]
#[tokio::test]
async fn registration_requires_a_confirmed_pre_write_failure_before_replay(
status: u16,
body: &'static str,
body_delay: Duration,
) -> anyhow::Result<()> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let registry_url = format!("http://{}", listener.local_addr()?);
let _server = AbortOnDropHandle::new(tokio::spawn(async move {
let (mut stream, _) = listener.accept().await?;
// Drain the complete request before responding so unread bytes cannot cause a reset.
let mut reader = BufReader::new(&mut stream);
let mut content_length = 0;
loop {
let mut line = String::new();
anyhow::ensure!(reader.read_line(&mut line).await? > 0, "missing headers");
if line == "\r\n" {
break;
}
if let Some((name, value)) = line.split_once(':')
&& name.eq_ignore_ascii_case("content-length")
{
content_length = value.trim().parse::<usize>()?;
}
}
anyhow::ensure!(content_length <= 16_384, "registration request too large");
reader.read_exact(&mut vec![0; content_length]).await?;
drop(reader);
let headers = format!(
"HTTP/1.1 {status} Registration Result\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n",
body.len()
);
stream.write_all(headers.as_bytes()).await?;
sleep(body_delay).await;
stream.write_all(body.as_bytes()).await?;
std::future::pending::<()>().await;
anyhow::Ok(())
}));
let auth = Arc::new(RegistrationAuthProvider::default());
let mut client = EnvironmentRegistryClient::new(registry_url, auth.clone())?;
client.connect_timeout = Duration::from_millis(500);
let key = NoiseChannelIdentity::generate()?.public_key();
let retry = Arc::new(Notify::new());
let subscriber = tracing_subscriber::registry().with(RetryObserved(retry.clone()));
let mut registration = Box::pin(
client
.register_environment_with_retry(ENVIRONMENT_ID, &key)
.with_subscriber(subscriber),
);
if body_delay.is_zero()
&& ((status == 503
&& matches!(
body,
CONFLICT_BODY
| CONFLICT_WITH_STRING_DETAIL_BODY
| CONFLICT_WITH_STRUCTURED_DETAIL_BODY
))
|| (status == 502 && body == AUTH_UNAVAILABLE_BODY))
{
timeout(Duration::from_secs(1), async {
tokio::select! {
_ = retry.notified() => anyhow::Ok(()),
_ = &mut registration => anyhow::bail!("a confirmed pre-write failure must enter backoff"),
}
})
.await??;
// The retry event fires in the same poll that enters backoff, without a timing guess.
drop(registration);
tokio::time::pause();
advance(Duration::from_secs(60)).await;
tokio::task::yield_now().await;
assert_eq!(auth.calls.load(Ordering::Relaxed), 1);
return Ok(());
}
let error = timeout(Duration::from_secs(1), registration)
.await?
.expect_err("an unconfirmed registration outcome must not be replayed");
assert_eq!(auth.calls.load(Ordering::Relaxed), 1);
match error {
ExecServerError::Json(_) if status == 200 && body_delay.is_zero() => {}
ExecServerError::EnvironmentRegistryRequest(RouteAwareRequestError::Timeout)
if status == 200 && body_delay > client.connect_timeout => {}
ExecServerError::EnvironmentRegistryAuth(message) if matches!(status, 401 | 403) => {
if body_delay < client.connect_timeout {
assert!(message.ends_with(": registration unavailable"));
}
}
ExecServerError::EnvironmentRegistryHttp {
status: actual,
code,
message,
} if !matches!(status, 200 | 401 | 403) => {
let expected_code = match (body_delay < client.connect_timeout, body) {
(true, ERROR_BODY | ERROR_WITH_AUTH_DETAIL_BODY) => Some("registration_denied"),
(true, CONFLICT_BODY) => Some("registration_conflict"),
(true, AUTH_UNAVAILABLE_BODY) => Some("authentication_service_unavailable"),
_ => None,
};
assert_eq!((actual.as_u16(), code.as_deref()), (status, expected_code));
if expected_code == Some("authentication_service_unavailable") {
assert_eq!(message, "Authentication service unavailable");
} else if expected_code.is_some() {
assert_eq!(message, "registration unavailable");
}
}
error => anyhow::bail!("unexpected registration failure kind: {error:?}"),
}
Ok(())
}