Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-spacesd): connect hosted machines through HTTP proxies (#4778)

injaneity853e2c57aedb
diff --git a/libs/cua-spacesd/Cargo.lock b/libs/cua-spacesd/Cargo.lock
index aeff0100f2..089b8babf0 100644
--- a/libs/cua-spacesd/Cargo.lock
+++ b/libs/cua-spacesd/Cargo.lock
@@ -1535,6 +1535,7 @@ dependencies = [
"hyper",
"hyper-util",
"jsonwebtoken",
+ "native-tls",
"rand 0.8.8",
"reqwest",
"ring",
@@ -1543,6 +1544,7 @@ dependencies = [
"subtle",
"tempfile",
"tokio",
+ "tokio-native-tls",
"tokio-tungstenite 0.24.0",
"tokio-util",
"tracing",
diff --git a/libs/cua-spacesd/crates/cua-relay/Cargo.toml b/libs/cua-spacesd/crates/cua-relay/Cargo.toml
index 5107b4721a..92cce08eef 100644
--- a/libs/cua-spacesd/crates/cua-relay/Cargo.toml
+++ b/libs/cua-spacesd/crates/cua-relay/Cargo.toml
@@ -18,7 +18,7 @@ http.workspace = true
http-body.workspace = true
http-body-util.workspace = true
hyper.workspace = true
-hyper-util.workspace = true
+hyper-util = { workspace = true, features = ["client-proxy"] }
# Account mode: OIDC access-token validation (JWKS) and relay-signed
# EdDSA principal assertions. ring is already the workspace's TLS crypto.
jsonwebtoken = "9"
@@ -39,4 +39,6 @@ uuid.workspace = true
yamux.workspace = true
[dev-dependencies]
+native-tls.workspace = true
+tokio-native-tls.workspace = true
tempfile.workspace = true
diff --git a/libs/cua-spacesd/crates/cua-relay/README.md b/libs/cua-spacesd/crates/cua-relay/README.md
index 224665d6ef..c442ec728e 100644
--- a/libs/cua-spacesd/crates/cua-relay/README.md
+++ b/libs/cua-spacesd/crates/cua-relay/README.md
@@ -49,6 +49,29 @@ unaffected (no relay in the path). See `cua-machine-seal` and
`cua_teleport::send`/`cua_spaces_ext::daemon::keyvault` for the current
state of this work.
+## Hosted-machine proxy transport
+
+The host join uses `HTTPS_PROXY` for `wss`/`https` relay URLs and `HTTP_PROXY`
+for `ws`/`http`, with `ALL_PROXY` as fallback. Each uppercase variable takes
+precedence over its lowercase spelling, including when empty; an empty
+scheme-specific value still permits `ALL_PROXY`. `NO_PROXY`/`no_proxy` uses
+hyper-util's domain, IP and CIDR matching, without resolving names for CIDRs.
+There is no automatic localhost bypass. Bypass is evaluated before validating
+the selected proxy. These settings must be inherited by the join process.
+
+This host transport supports unauthenticated HTTP proxies returning status 200
+to CONNECT. HTTPS/SOCKS proxies, proxy URL credentials, paths and queries are
+rejected. Proxy use in a CGI environment (`REQUEST_METHOD` present) is rejected.
+A selected proxy failure never falls back to a direct connection. Native origin
+TLS verification is unchanged, including platform trust configuration such as
+`SSL_CERT_FILE` on OpenSSL platforms. HTTP CONNECT itself is not encrypted;
+use a `wss` relay URL for origin encryption. A `ws` origin remains plaintext
+inside the tunnel. Controller/SDK proxy support is separate from this host path.
+
+The existing 20-second connection deadline and reconnect backoff also cover
+proxy dialing and CONNECT. Diagnostics report the failed stage or HTTP status
+without printing proxy credentials, relay URL queries or response bodies.
+
## How it works
```text
diff --git a/libs/cua-spacesd/crates/cua-relay/src/client.rs b/libs/cua-spacesd/crates/cua-relay/src/client.rs
index 9f5b779f56..6d1ff8ed60 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/client.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/client.rs
@@ -135,12 +135,11 @@ pub fn load_or_create_machine_id(path: &Path) -> std::io::Result<String> {
/// The WebSocket URL of the relay's connect endpoint.
pub fn connect_url(relay_url: &str) -> Result<String, String> {
- let mut url =
- url::Url::parse(relay_url).map_err(|e| format!("relay url {relay_url:?}: {e}"))?;
+ let mut url = url::Url::parse(relay_url).map_err(|_| "invalid relay URL".to_owned())?;
let scheme = match url.scheme() {
"wss" | "https" => "wss",
"ws" | "http" => "ws",
- other => return Err(format!("unsupported relay scheme {other:?}")),
+ _ => return Err("unsupported relay scheme".into()),
};
url.set_scheme(scheme)
.map_err(|_| "cannot set scheme".to_owned())?;
@@ -177,7 +176,7 @@ pub async fn run(config: JoinConfig, shutdown: CancellationToken) {
let end = session(&config, &shutdown).await;
match &end {
SessionEnd::Shutdown => return,
- SessionEnd::Refused(reason) => tracing::warn!(%reason, "relay refused the machine"),
+ SessionEnd::Refused(reason) => tracing::warn!(%reason, "relay join refused"),
SessionEnd::Lost(reason) => tracing::info!(%reason, "relay connection lost"),
}
// A session that stayed up for a while resets the backoff.
@@ -202,7 +201,7 @@ pub async fn session(config: &JoinConfig, shutdown: &CancellationToken) -> Sessi
};
let mut request = match url.as_str().into_client_request() {
Ok(r) => r,
- Err(e) => return SessionEnd::Refused(e.to_string()),
+ Err(_) => return SessionEnd::Refused("invalid relay WebSocket request".into()),
};
let headers = request.headers_mut();
let header = |v: &str| http::HeaderValue::from_str(v).map_err(|e| e.to_string());
@@ -225,7 +224,7 @@ pub async fn session(config: &JoinConfig, shutdown: &CancellationToken) -> Sessi
}
_ => return SessionEnd::Refused("invalid header value".into()),
}
- let connect = tokio_tungstenite::connect_async(request);
+ let connect = crate::transport::connect(request);
let socket = tokio::select! {
r = tokio::time::timeout(Duration::from_secs(20), connect) => match r {
Ok(Ok((socket, response))) => {
@@ -235,15 +234,12 @@ pub async fn session(config: &JoinConfig, shutdown: &CancellationToken) -> Sessi
}
socket
}
- Ok(Err(tokio_tungstenite::tungstenite::Error::Http(response))) => {
- return SessionEnd::Refused(format!("HTTP {}", response.status()));
- }
- Ok(Err(e)) => return SessionEnd::Lost(e.to_string()),
+ Ok(Err(end)) => return end,
Err(_) => return SessionEnd::Lost("connect timed out".into()),
},
_ = shutdown.cancelled() => return SessionEnd::Shutdown,
};
- tracing::info!(relay = %config.relay_url, machine = %config.machine_id, "joined relay");
+ tracing::info!(machine = %config.machine_id, "joined relay");
let (inbound_tx, mut inbound_rx) = mpsc::channel(256);
let (handle, mut driver) = mux::spawn(
WsIo::new(socket),
diff --git a/libs/cua-spacesd/crates/cua-relay/src/lib.rs b/libs/cua-spacesd/crates/cua-relay/src/lib.rs
index 3ad12c7530..6e2783605a 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/lib.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/lib.rs
@@ -32,6 +32,7 @@ pub mod directory;
pub mod mux;
pub mod oidc;
pub mod server;
+mod transport;
pub mod ws;
/// Machine connect path on the relay.
diff --git a/libs/cua-spacesd/crates/cua-relay/src/transport.rs b/libs/cua-spacesd/crates/cua-relay/src/transport.rs
new file mode 100644
index 0000000000..225a317244
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-relay/src/transport.rs
@@ -0,0 +1,212 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Host join transport only. TLS, WebSocket validation and the whole-connect
+//! deadline remain owned by tungstenite and `client::session` respectively.
+use std::ffi::OsString;
+
+use bytes::Bytes;
+use http::{Method, Request, StatusCode, Uri};
+use http_body_util::Empty;
+use hyper_util::{client::proxy::matcher::Matcher, rt::TokioIo};
+use tokio::{
+ io::{AsyncRead, AsyncWrite},
+ net::TcpStream,
+};
+use tokio_tungstenite::{tungstenite, MaybeTlsStream, WebSocketStream};
+
+use crate::client::SessionEnd;
+
+pub(super) trait Io: AsyncRead + AsyncWrite + Send + Unpin {}
+impl<T: AsyncRead + AsyncWrite + Send + Unpin> Io for T {}
+type Stream = Box<dyn Io>;
+
+fn lost(stage: &'static str) -> SessionEnd {
+ SessionEnd::Lost(stage.into())
+}
+
+/// Never include URLs, headers, response bodies or nested dependency errors in
+/// diagnostics. A dependency's Display/Debug is not a secret-redaction contract.
+pub(super) async fn connect(
+ request: tungstenite::handshake::client::Request,
+) -> Result<
+ (
+ WebSocketStream<MaybeTlsStream<Stream>>,
+ tungstenite::handshake::client::Response,
+ ),
+ SessionEnd,
+> {
+ let destination = destination(request.uri()).map_err(|e| SessionEnd::Refused(e.into()))?;
+ let proxy = route(&destination, |key| std::env::var_os(key))
+ .map_err(|e| SessionEnd::Refused(format!("proxy configuration: {e}")))?;
+ let stream: Stream = match proxy {
+ Some(proxy) => Box::new(proxy_stream(&proxy, &destination).await?),
+ None => Box::new(
+ dial(&destination)
+ .await
+ .map_err(|_| lost("direct dial failed"))?,
+ ),
+ };
+ tokio_tungstenite::client_async_tls_with_config(request, stream, None, None)
+ .await
+ .map_err(|e| match e {
+ tungstenite::Error::Http(response) => {
+ SessionEnd::Refused(format!("HTTP {}", response.status()))
+ }
+ tungstenite::Error::Tls(_) => lost("origin TLS failed"),
+ tungstenite::Error::Io(_) => lost("origin handshake I/O failed"),
+ _ => lost("WebSocket upgrade failed"),
+ })
+}
+
+fn destination(uri: &Uri) -> Result<Uri, &'static str> {
+ let (scheme, port) = match uri.scheme_str() {
+ Some("wss") => ("https", 443),
+ Some("ws") => ("http", 80),
+ _ => return Err("unsupported relay scheme"),
+ };
+ let host = uri.host().ok_or("missing relay host")?;
+ if uri.authority().is_some_and(|a| a.as_str().contains('@')) {
+ return Err("relay URL userinfo is unsupported");
+ }
+ Uri::builder()
+ .scheme(scheme)
+ .authority(format!("{host}:{}", uri.port_u16().unwrap_or(port)))
+ .path_and_query("/")
+ .build()
+ .map_err(|_| "invalid relay authority")
+}
+
+/// Only the winning environment values participate. The matcher owns the
+/// NO_PROXY grammar; the explicit guard prevents its permissive parser from
+/// silently turning malformed/unsupported proxy configuration into direct I/O.
+fn route(uri: &Uri, env: impl Fn(&str) -> Option<OsString>) -> Result<Option<Uri>, &'static str> {
+ let value = |upper, lower| env(upper).or_else(|| env(lower));
+ let specific = match uri.scheme_str() {
+ Some("https") => value("HTTPS_PROXY", "https_proxy"),
+ _ => value("HTTP_PROXY", "http_proxy"),
+ };
+ let Some(raw) = specific
+ .filter(|v| !v.is_empty())
+ .or_else(|| value("ALL_PROXY", "all_proxy").filter(|v| !v.is_empty()))
+ else {
+ return Ok(None);
+ };
+ let no = value("NO_PROXY", "no_proxy").unwrap_or_default();
+ let no = no.to_str().ok_or("NO_PROXY is not Unicode")?;
+ // Matcher keeps its NoProxy type private. This is solely a bypass query;
+ // the placeholder is never returned as a route or used for network I/O.
+ let bypass = Matcher::builder()
+ .all("http://proxy.invalid")
+ .no(no)
+ .build();
+ if bypass.intercept(uri).is_none() {
+ return Ok(None);
+ }
+ if env("REQUEST_METHOD").is_some() {
+ return Err("proxy use in a CGI environment is unsupported");
+ }
+ let raw = raw.to_str().ok_or("proxy URL is not Unicode")?;
+ if raw.contains('#') {
+ return Err("proxy URL fragments are unsupported");
+ }
+ let parsed: Uri = raw.parse().map_err(|_| "invalid proxy URL")?;
+ if parsed.scheme_str().is_some_and(|s| s != "http") {
+ return Err("only HTTP proxies are supported");
+ }
+ let authority = parsed.authority().ok_or("invalid proxy authority")?;
+ if authority.as_str().contains('@') {
+ return Err("proxy authentication is unsupported");
+ }
+ if authority.as_str() != authority.host() {
+ let port = authority
+ .as_str()
+ .strip_prefix(authority.host())
+ .and_then(|p| p.strip_prefix(':'))
+ .and_then(|p| p.parse::<u16>().ok());
+ if port.is_none_or(|p| p == 0) {
+ return Err("invalid proxy port");
+ }
+ }
+ if parsed
+ .path_and_query()
+ .is_some_and(|p| p.as_str() != "/" && !p.as_str().is_empty())
+ {
+ return Err("proxy URL paths and queries are unsupported");
+ }
+ let proxy = Matcher::builder()
+ .all(raw)
+ .build()
+ .intercept(uri)
+ .ok_or("invalid proxy URL")?;
+ if proxy.uri().host().is_none() || proxy.uri().port().is_some_and(|p| p.as_u16() == 0) {
+ return Err("invalid proxy authority");
+ }
+ Ok(Some(proxy.uri().clone()))
+}
+
+async fn dial(uri: &Uri) -> std::io::Result<TcpStream> {
+ // URI IPv6 hosts include brackets, while lookup_host's host tuple does not.
+ let host = uri
+ .host()
+ .unwrap_or_default()
+ .trim_start_matches('[')
+ .trim_end_matches(']');
+ TcpStream::connect((host, uri.port_u16().unwrap_or(80))).await
+}
+
+async fn proxy_stream(
+ proxy: &Uri,
+ destination: &Uri,
+) -> Result<TokioIo<hyper::upgrade::Upgraded>, SessionEnd> {
+ let socket = dial(proxy).await.map_err(|_| lost("proxy dial failed"))?;
+ let (mut sender, connection) = hyper::client::conn::http1::Builder::new()
+ .max_headers(64)
+ .max_buf_size(16 * 1024)
+ .handshake(TokioIo::new(socket))
+ .await
+ .map_err(|_| lost("proxy HTTP handshake failed"))?;
+ let authority = destination
+ .authority()
+ .expect("validated destination")
+ .as_str();
+ let request = Request::builder()
+ .method(Method::CONNECT)
+ .uri(authority)
+ .header(http::header::HOST, authority)
+ .body(Empty::<Bytes>::new())
+ .map_err(|_| lost("invalid CONNECT request"))?;
+ let exchange = async move {
+ let response = sender
+ .send_request(request)
+ .await
+ .map_err(|_| lost("proxy CONNECT failed"))?;
+ if response.status() == StatusCode::PROXY_AUTHENTICATION_REQUIRED {
+ return Err(lost("proxy authentication required: HTTP 407"));
+ }
+ if response.status() != StatusCode::OK {
+ // Hyper 1.11 does not upgrade CONNECT 204. Support the deployed 200
+ // contract explicitly, without waiting on a refused response body.
+ return Err(SessionEnd::Lost(format!(
+ "proxy CONNECT refused: HTTP {}",
+ response.status()
+ )));
+ }
+ hyper::upgrade::on(response)
+ .await
+ .map_err(|_| lost("proxy CONNECT upgrade failed"))
+ };
+ // No detached task: failure, timeout or cancellation drops both futures and
+ // their I/O. Upgraded retains Hyper's read-ahead bytes on the successful path.
+ let driver = async {
+ connection
+ .with_upgrades()
+ .await
+ .map_err(|_| lost("proxy CONNECT I/O failed"))
+ };
+ let (stream, ()) = tokio::try_join!(exchange, driver)?;
+ Ok(TokioIo::new(stream))
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/libs/cua-spacesd/crates/cua-relay/src/transport/tests.rs b/libs/cua-spacesd/crates/cua-relay/src/transport/tests.rs
new file mode 100644
index 0000000000..ac5d78fd35
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-relay/src/transport/tests.rs
@@ -0,0 +1,271 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+use super::*;
+use std::time::Duration;
+use tokio::{
+ io::{AsyncReadExt, AsyncWriteExt},
+ net::TcpListener,
+};
+
+fn selection(url: &str, vars: &[(&str, &str)]) -> Result<Option<Uri>, &'static str> {
+ route(&url.parse().unwrap(), |key| {
+ vars.iter()
+ .find(|(k, _)| *k == key)
+ .map(|(_, v)| OsString::from(v))
+ })
+}
+
+#[test]
+fn proxy_precedence_and_bypass() {
+ let url = "https://relay.cua.ai:443/";
+ for (vars, expected) in [
+ (vec![], None),
+ (
+ vec![("https_proxy", "http://lower:80")],
+ Some("http://lower:80/"),
+ ),
+ (
+ vec![
+ ("HTTPS_PROXY", "http://upper:80"),
+ ("https_proxy", "http://lower:80"),
+ ],
+ Some("http://upper:80/"),
+ ),
+ (
+ vec![("HTTPS_PROXY", ""), ("https_proxy", "http://lower:80")],
+ None,
+ ),
+ (
+ vec![("HTTPS_PROXY", ""), ("ALL_PROXY", "http://all:80")],
+ Some("http://all:80/"),
+ ),
+ (vec![("HTTP_PROXY", "http://wrong:80")], None),
+ (
+ vec![("HTTPS_PROXY", "socks5://bad"), ("NO_PROXY", ".cua.ai")],
+ None,
+ ),
+ (
+ vec![("HTTPS_PROXY", "http://proxy"), ("NO_PROXY", "other, *")],
+ None,
+ ),
+ ] {
+ assert_eq!(
+ selection(url, &vars).unwrap().as_ref().map(Uri::to_string),
+ expected.map(String::from),
+ "{vars:?}"
+ );
+ }
+ assert!(selection(
+ "http://127.0.0.1/",
+ &[("HTTP_PROXY", "http://proxy"), ("NO_PROXY", "127.0.0.0/8")]
+ )
+ .unwrap()
+ .is_none());
+ assert!(
+ selection("http://127.0.0.1/", &[("HTTP_PROXY", "http://proxy")])
+ .unwrap()
+ .is_some()
+ );
+}
+
+#[test]
+fn unsupported_configuration_is_not_direct() {
+ for proxy in [
+ "https://proxy",
+ "socks5://proxy",
+ "http://user:secret@proxy",
+ "http://proxy/path",
+ "http://proxy/?secret",
+ "http://proxy:0",
+ "http://proxy:99999",
+ "http://proxy:bad",
+ "bad proxy",
+ ] {
+ assert!(
+ selection("https://relay.cua.ai/", &[("HTTPS_PROXY", proxy)]).is_err(),
+ "{proxy}"
+ );
+ }
+ assert!(selection(
+ "https://relay.cua.ai/",
+ &[("HTTPS_PROXY", "http://proxy"), ("REQUEST_METHOD", "GET")]
+ )
+ .is_err());
+ assert!(selection(
+ "https://relay.cua.ai/",
+ &[
+ ("HTTPS_PROXY", "http://proxy"),
+ ("REQUEST_METHOD", "GET"),
+ ("NO_PROXY", "relay.cua.ai")
+ ]
+ )
+ .unwrap()
+ .is_none());
+}
+
+#[cfg(unix)]
+#[test]
+fn non_unicode_winner_is_rejected_but_bypass_still_applies() {
+ use std::os::unix::ffi::OsStringExt;
+ let uri = "https://relay.cua.ai/".parse().unwrap();
+ assert!(route(&uri, |key| (key == "HTTPS_PROXY")
+ .then(|| OsString::from_vec(vec![255])))
+ .is_err());
+ assert!(route(&uri, |key| match key {
+ "HTTPS_PROXY" => Some(OsString::from_vec(vec![255])),
+ "NO_PROXY" => Some("relay.cua.ai".into()),
+ _ => None,
+ })
+ .unwrap()
+ .is_none());
+}
+
+#[test]
+fn relay_destinations() {
+ for (url, expected) in [
+ (
+ "wss://relay.cua.ai/path?secret",
+ "https://relay.cua.ai:443/",
+ ),
+ ("ws://[::1]:123/a", "http://[::1]:123/"),
+ ] {
+ assert_eq!(
+ destination(&url.parse().unwrap()).unwrap().to_string(),
+ expected
+ );
+ }
+ assert!(destination(&"ws://user:[email protected]/".parse().unwrap()).is_err());
+}
+
+async fn fake_proxy(response: Vec<u8>) -> (Uri, tokio::task::JoinHandle<()>) {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let uri = format!("http://{}/", listener.local_addr().unwrap())
+ .parse()
+ .unwrap();
+ let task = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let mut head = Vec::new();
+ while !head.ends_with(b"\r\n\r\n") {
+ head.push(socket.read_u8().await.unwrap());
+ }
+ assert_eq!(
+ String::from_utf8(head).unwrap(),
+ "CONNECT relay.invalid:443 HTTP/1.1\r\nhost: relay.invalid:443\r\n\r\n"
+ );
+ socket.write_all(&response).await.unwrap();
+ let mut rest = Vec::new();
+ let result = tokio::time::timeout(Duration::from_secs(2), socket.read_to_end(&mut rest))
+ .await
+ .expect("orphan proxy socket");
+ assert!(
+ result.is_ok() || result.unwrap_err().kind() == std::io::ErrorKind::ConnectionReset
+ );
+ });
+ (uri, task)
+}
+
+#[tokio::test]
+async fn connect_retains_read_ahead_and_accepts_informational_response() {
+ let (proxy, task) =
+ fake_proxy(b"HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\n\r\nread-ahead".to_vec())
+ .await;
+ let mut stream = proxy_stream(&proxy, &"https://relay.invalid:443/".parse().unwrap())
+ .await
+ .unwrap();
+ let mut bytes = [0; 10];
+ stream.read_exact(&mut bytes).await.unwrap();
+ assert_eq!(&bytes, b"read-ahead");
+ drop(stream);
+ task.await.unwrap();
+}
+
+#[tokio::test]
+async fn refused_connect_and_bounded_headers_close_without_fallback_or_secrets() {
+ let mut responses: Vec<(Vec<u8>, String)> = [201, 204, 302, 403, 407, 500].iter().map(|status| {
+ let expected = if *status == 407 { "proxy authentication required: HTTP 407".to_owned() } else { format!("proxy CONNECT refused: HTTP {}", StatusCode::from_u16(*status).unwrap()) };
+ let body = if *status == 204 { "\r\n" } else { "Content-Length: 99999\r\n\r\nSECRET-CANARY" };
+ (format!("HTTP/1.1 {status} SECRET-CANARY\r\nProxy-Authenticate: SECRET-CANARY\r\n{body}").into_bytes(), expected)
+ }).collect();
+ responses.push((
+ format!("HTTP/1.1 200 OK\r\n{}\r\n", "X: a\r\n".repeat(65)).into_bytes(),
+ "proxy CONNECT failed".into(),
+ ));
+ responses.push((
+ format!("HTTP/1.1 200 OK\r\nX: {}", "a".repeat(17000)).into_bytes(),
+ "proxy CONNECT failed".into(),
+ ));
+ responses.push((
+ b"not HTTP SECRET-CANARY\r\n\r\n".to_vec(),
+ "proxy CONNECT failed".into(),
+ ));
+ for (response, expected) in responses {
+ let (proxy, task) = fake_proxy(response).await;
+ let error = match tokio::time::timeout(
+ Duration::from_secs(1),
+ proxy_stream(&proxy, &"https://relay.invalid:443/".parse().unwrap()),
+ )
+ .await
+ .unwrap()
+ {
+ Ok(_) => panic!("unexpected tunnel"),
+ Err(e) => e,
+ };
+ assert_eq!(format!("{error:?}"), format!("Lost({expected:?})"));
+ assert!(!format!("{error:?}").contains("SECRET-CANARY"));
+ task.await.unwrap();
+ }
+}
+
+#[tokio::test]
+async fn cancellation_drops_partial_connect_and_driver() {
+ let (proxy, task) = fake_proxy(b"HTTP/1.1 200".to_vec()).await;
+ assert!(tokio::time::timeout(
+ Duration::from_millis(100),
+ proxy_stream(&proxy, &"https://relay.invalid:443/".parse().unwrap())
+ )
+ .await
+ .is_err());
+ task.await.unwrap();
+}
+
+#[test]
+fn proxy_fragments_are_rejected_unless_bypassed() {
+ for raw in ["http://proxy/#secret", "http://proxy#secret"] {
+ assert!(selection("https://relay.cua.ai/", &[("HTTPS_PROXY", raw)]).is_err());
+ assert!(selection(
+ "https://relay.cua.ai/",
+ &[("HTTPS_PROXY", raw), ("NO_PROXY", "relay.cua.ai")]
+ )
+ .unwrap()
+ .is_none());
+ }
+}
+
+#[tokio::test]
+async fn proxy_authentication_required_is_distinct_and_redacted() {
+ let (proxy, task) = fake_proxy(
+ b"HTTP/1.1 407 SECRET-CANARY\r\nProxy-Authenticate: SECRET-CANARY\r\n\r\n".to_vec(),
+ )
+ .await;
+ let error = match proxy_stream(&proxy, &"https://relay.invalid:443/".parse().unwrap()).await {
+ Ok(_) => panic!("unexpected tunnel"),
+ Err(error) => error,
+ };
+ task.await.unwrap();
+ assert!(
+ matches!(error, SessionEnd::Lost(reason) if reason == "proxy authentication required: HTTP 407")
+ );
+}
+
+#[tokio::test]
+async fn repeated_informational_responses_remain_cancellable() {
+ let (proxy, task) = fake_proxy(b"HTTP/1.1 100 Continue\r\n\r\n".repeat(1024)).await;
+ assert!(tokio::time::timeout(
+ Duration::from_millis(100),
+ proxy_stream(&proxy, &"https://relay.invalid:443/".parse().unwrap())
+ )
+ .await
+ .is_err());
+ task.await.unwrap();
+}
diff --git a/libs/cua-spacesd/crates/cua-relay/tests/fixtures/untrusted-cert.pem b/libs/cua-spacesd/crates/cua-relay/tests/fixtures/untrusted-cert.pem
new file mode 100644
index 0000000000..66251ba51f
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-relay/tests/fixtures/untrusted-cert.pem
@@ -0,0 +1,17 @@
+-----BEGIN CERTIFICATE-----
+MIICpDCCAYwCCQCJ5caTs4mKtjANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDDAls
+b2NhbGhvc3QwHhcNMjYxMDA2MDM1NDIwWhcNMzYxMDAzMDM1NDIwWjAUMRIwEAYD
+VQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDg
+ohnWiTfXu/KSGIp0QQoamaiVmqbjG+siu5/1STMUFUl0rL0zktkTBb+ZQroqP+KK
+x4oNCDfuIkVFKRZNjuMxaIz85ihesmqBOkowzd/QZ7MaUZJBx7ev4yZJkU9yX+Y8
+hbBH651dKuoW4BreMvAS6edWpYxzokqda7F3ltA2HikK7fGSbR77/mW5v1DgjyAK
+8g8bEsz+ZUrfJD9hJSS1OIwhGKCPw9Yocu2e/t+P7+1jlKTWQH5c93ncAVsc/E8T
+tnyZKmbX2JkoUg1njRo3yIfAYY+ToJQ/kEFUu7iO9aV93CUNaRAtNSGhk48kDyEY
+ZnacwACM8VydlkCeGDfvAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAMvK/M07rJ8F
+au0N2azl6TAhc141sO2RckPhTO8o0qPayI7oabHQizvSUsZAFDwo3iLrH9KOKvom
+UK9kkX/1e1mkrUxnAFqbci4qACPcY+EBMmkbud4+vl2Ugm9jbkAutHgZ1sxqQHU5
+pECe2moQS+RmDudCT7f627Fkykp1aoiHuc2dXnLoM+Aj1WMy5u7fiq0+DoxLXsLZ
+iR62cq+9n9IynH+YS+7vzhi09Smu5WbcsOyBDhLmBTaLTqAoy0RAoG1zBXpBU12B
+m0XxR25YHQpwZ+WNW/bhrEteXm94Ja8wIQj95dxv3yO4e2960aW9GQ8DHgZjgUW6
+V3kDvEI+OzA=
+-----END CERTIFICATE-----
diff --git a/libs/cua-spacesd/crates/cua-relay/tests/fixtures/untrusted-key.pem b/libs/cua-spacesd/crates/cua-relay/tests/fixtures/untrusted-key.pem
new file mode 100644
index 0000000000..0ec780edc5
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-relay/tests/fixtures/untrusted-key.pem
@@ -0,0 +1,28 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDgohnWiTfXu/KS
+GIp0QQoamaiVmqbjG+siu5/1STMUFUl0rL0zktkTBb+ZQroqP+KKx4oNCDfuIkVF
+KRZNjuMxaIz85ihesmqBOkowzd/QZ7MaUZJBx7ev4yZJkU9yX+Y8hbBH651dKuoW
+4BreMvAS6edWpYxzokqda7F3ltA2HikK7fGSbR77/mW5v1DgjyAK8g8bEsz+ZUrf
+JD9hJSS1OIwhGKCPw9Yocu2e/t+P7+1jlKTWQH5c93ncAVsc/E8TtnyZKmbX2Jko
+Ug1njRo3yIfAYY+ToJQ/kEFUu7iO9aV93CUNaRAtNSGhk48kDyEYZnacwACM8Vyd
+lkCeGDfvAgMBAAECggEBAJb93whJ6/NjLkXtoQNLxJLkvmDxN0RpO8B5BahGr8LM
+HDgE9Jh6GNekgYlvRNupXYmTXsQrxgyXlKBMYeV4KlbHxB0qR/B/VP/QQpZTjCH1
+0nnaYsk8icf8k3vX5OMoewYrhraRNZGuivMdaHH7I0xTVWD0nlgLusPd48hS41m7
+4YXf1c4lxOtPnugUMbCJz2ebz7Yui6GwV8R+KZoN9KWcx7hZim9XNunM9J5iAcJK
+V8Xi1/YbcwmZ9YcYPT3gXFnI1LSZK1lc/W0mY5A+0kgMC56Kg1v9MUrlm6Ywxd8y
+lXTOWzn3O4MLb8iWSxFnmVGyqcrmPQJVRxQ3qTUE9AECgYEA+jkKnzmpZdUaOlsp
+nl7nAawobs7m9EcN8M3xEIO1mtsOdxszxLrkZURTNgWbAdHQ/41BcX49hZg0ZmVO
+klcXkcRsbloza40PBOfulSF06fJ2hWb0H4CfFrxFLqI/fVGirgo5RdJM/pa5HAMA
+U6YCuegoJhwKWcbhQWWw+eP3x28CgYEA5dHPcubdgfYenku2/1ndHj7sQ/qjFYwy
+u2nYm30iF8RaH1BpM3YFyFV38S54TEWpzrXh9lHJCbVSRZj5kGoKzWIKlOW9E/bA
+/EL4SCQMsNLY4U2Ddpd0PqJJGwsd8sLRpkJzSey8UBq1p1wa2ONEGys+6/swS0D4
+dSs2BaLqV4ECgYAQiTJ9gUcDlsir8JhYgfcMMj9dy0iR/hwavNFggQPAXxeeoWqT
+ZrJvSsug90/eF+qS6NfZUzlnmb5kwe8mVqEVHgD4bfeV9PV4IoeuzU43o7FXcY1S
+g6J/0yNTSJ+ffYSdsclFJve1n2pOQpiD7qWheYkls5avhigetUSzzu/x+wKBgQDT
+XukhkNxhz2/Rv2mL6abJTq4Wx8p+4vc2D9+9ApX8rgcFjftz7TTcUF+EX20dGWVY
+TUiKOCZi23XTtSKzhBRzWZzJ3ZLNbcGJQj8AeseBSitW7OfghuPPR4tdaBgfUrdn
+5u4KK8X3FtnEF55JpJzbMCcq+1grnpHlkdyZyoEmAQKBgCdXJvuEyUHWKPhHKpVc
++5HE96vMhGGgeNkCp8uZWwvST1LGEhM06hLqB21kuML94JFoQcRieOAvc4DRS4fT
+My1inH6AxtBPT5vllYQdxv/w51aBdlSFKNIawWA2KZkW/6N3GQ9aScyQRpt9Mu2Z
+UAUGKcAwXZesqC0hj58T/n0U
+-----END PRIVATE KEY-----
diff --git a/libs/cua-spacesd/crates/cua-relay/tests/linux_native_trust.rs b/libs/cua-spacesd/crates/cua-relay/tests/linux_native_trust.rs
new file mode 100644
index 0000000000..85bc6cc15f
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-relay/tests/linux_native_trust.rs
@@ -0,0 +1,166 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Linux OpenSSL trust fixture: no trust-store writes or external connections.
+//! Ignored elsewhere because native TLS uses different platform trust APIs.
+use cua_relay::{
+ assertion::OWNER_HEADER,
+ client::{JoinConfig, SessionEnd},
+};
+use std::{process::Command, time::Duration};
+use tokio::{
+ io::{AsyncReadExt, AsyncWriteExt},
+ net::TcpListener,
+};
+use tokio_util::sync::CancellationToken;
+
+const MODE: &str = "CUA_TEST_LINUX_TRUST_MODE";
+const ADDRESS: &str = "CUA_TEST_LINUX_TRUST_ADDRESS";
+
+#[test]
+#[cfg_attr(not(target_os = "linux"), ignore = "requires Linux native TLS/OpenSSL")]
+#[allow(clippy::result_large_err)] // tungstenite fixes callback error type.
+fn linux_native_trust_and_hostname() {
+ if std::env::var_os(MODE).is_none() {
+ let files = tempfile::tempdir().unwrap();
+ let trusted = files.path().join("trusted.pem");
+ let empty = files.path().join("empty.pem");
+ let roots = files.path().join("empty-roots");
+ std::fs::write(&trusted, include_bytes!("fixtures/untrusted-cert.pem")).unwrap();
+ std::fs::write(&empty, "").unwrap();
+ std::fs::create_dir(&roots).unwrap();
+ for mode in [
+ "trusted-direct",
+ "trusted-proxy",
+ "wrong-host-proxy",
+ "untrusted-proxy",
+ ] {
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let address = listener.local_addr().unwrap();
+ drop(listener);
+ let mut child = Command::new(std::env::current_exe().unwrap());
+ child.args(["--exact", "linux_native_trust_and_hostname", "--nocapture"]);
+ for key in [
+ "HTTP_PROXY",
+ "http_proxy",
+ "HTTPS_PROXY",
+ "https_proxy",
+ "ALL_PROXY",
+ "all_proxy",
+ "NO_PROXY",
+ "no_proxy",
+ "REQUEST_METHOD",
+ ] {
+ child.env_remove(key);
+ }
+ child
+ .env(MODE, mode)
+ .env(ADDRESS, address.to_string())
+ .env(
+ "SSL_CERT_FILE",
+ if mode == "untrusted-proxy" {
+ &empty
+ } else {
+ &trusted
+ },
+ )
+ .env("SSL_CERT_DIR", &roots);
+ if mode != "trusted-direct" {
+ child.env("HTTPS_PROXY", format!("http://{address}"));
+ }
+ let output = child.output().unwrap();
+ assert!(
+ output.status.success(),
+ "{mode}: {}\n{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+ return;
+ }
+ tokio::runtime::Runtime::new().unwrap().block_on(async {
+ let mode = std::env::var(MODE).unwrap();
+ let address = std::env::var(ADDRESS).unwrap();
+ let direct = mode == "trusted-direct";
+ let success = direct || mode == "trusted-proxy";
+ let host = if mode == "wrong-host-proxy" {
+ "wrong.invalid"
+ } else {
+ "localhost"
+ };
+ let listener = TcpListener::bind(&address).await.unwrap();
+ let port = if direct {
+ listener.local_addr().unwrap().port()
+ } else {
+ 443
+ };
+ let identity = native_tls::Identity::from_pkcs8(
+ include_bytes!("fixtures/untrusted-cert.pem"),
+ include_bytes!("fixtures/untrusted-key.pem"),
+ )
+ .unwrap();
+ let acceptor =
+ tokio_native_tls::TlsAcceptor::from(native_tls::TlsAcceptor::new(identity).unwrap());
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ if !direct {
+ let mut head = Vec::new();
+ while !head.ends_with(b"\r\n\r\n") {
+ head.push(socket.read_u8().await.unwrap());
+ }
+ let head = String::from_utf8(head).unwrap();
+ assert!(head.starts_with(&format!("CONNECT {host}:443 HTTP/1.1\r\n")));
+ assert!(!head.to_ascii_lowercase().contains("authorization"));
+ socket.write_all(b"HTTP/1.1 200 OK\r\n\r\n").await.unwrap();
+ }
+ match acceptor.accept(socket).await {
+ Ok(tls) => {
+ assert!(success, "negative TLS case accepted");
+ let mut ws = tokio_tungstenite::accept_hdr_async(
+ tls,
+ |request: &http::Request<()>, mut response: http::Response<()>| {
+ assert_eq!(
+ request.headers()["authorization"],
+ "Bearer linux-fixture-canary"
+ );
+ response
+ .headers_mut()
+ .insert(OWNER_HEADER, "linux-trust-fixture".parse().unwrap());
+ Ok(response)
+ },
+ )
+ .await
+ .unwrap();
+ ws.close(None).await.unwrap();
+ }
+ Err(_) => assert!(!success, "positive TLS case rejected"),
+ }
+ });
+ let config = JoinConfig::new(
+ format!("wss://{host}:{port}/"),
+ "linux-fixture-canary".into(),
+ "linux-trust-machine".into(),
+ "127.0.0.1:1".parse().unwrap(),
+ );
+ let end = tokio::time::timeout(
+ Duration::from_secs(5),
+ cua_relay::client::session(&config, &CancellationToken::new()),
+ )
+ .await
+ .unwrap();
+ tokio::time::timeout(Duration::from_secs(2), server)
+ .await
+ .expect("TLS fixture server did not finish")
+ .unwrap();
+ if success {
+ assert_eq!(
+ config.account.owner().as_deref(),
+ Some("linux-trust-fixture"),
+ "{end:?}"
+ );
+ } else {
+ assert!(matches!(end, SessionEnd::Lost(reason) if reason == "origin TLS failed"));
+ assert!(config.account.owner().is_none());
+ }
+ });
+}
diff --git a/libs/cua-spacesd/crates/cua-relay/tests/proxy.rs b/libs/cua-spacesd/crates/cua-relay/tests/proxy.rs
new file mode 100644
index 0000000000..97a88f6e07
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-relay/tests/proxy.rs
@@ -0,0 +1,325 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Real machine join through a forward proxy. Environment is confined to a child
+//! test process; no production injection switch or global environment mutation.
+use std::{process::Command, time::Duration};
+
+use cua_relay::{
+ client::{JoinConfig, SessionEnd},
+ server::{Relay, RelayConfig},
+};
+use tokio::{
+ io::{AsyncReadExt, AsyncWriteExt},
+ net::{TcpListener, TcpStream},
+};
+use tokio_util::sync::CancellationToken;
+
+const TOKEN: &str = "machine-secret-canary";
+const ID: &str = "proxy-machine";
+const CHILD: &str = "CUA_RELAY_PROXY_TEST_CHILD";
+
+#[test]
+fn machine_join_uses_http_proxy() {
+ if std::env::var_os(CHILD).is_none() {
+ let mut child = Command::new(std::env::current_exe().unwrap());
+ child.args(["--exact", "machine_join_uses_http_proxy", "--nocapture"]);
+ for key in [
+ "HTTP_PROXY",
+ "http_proxy",
+ "HTTPS_PROXY",
+ "https_proxy",
+ "ALL_PROXY",
+ "all_proxy",
+ "NO_PROXY",
+ "no_proxy",
+ "REQUEST_METHOD",
+ ] {
+ child.env_remove(key);
+ }
+ let proxy = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let addr = proxy.local_addr().unwrap();
+ drop(proxy);
+ let result = child
+ .env(CHILD, addr.to_string())
+ .env("HTTP_PROXY", format!("http://{addr}"))
+ .output()
+ .unwrap();
+ assert!(
+ result.status.success(),
+ "{}\n{}",
+ String::from_utf8_lossy(&result.stdout),
+ String::from_utf8_lossy(&result.stderr)
+ );
+ return;
+ }
+ tokio::runtime::Runtime::new().unwrap().block_on(async {
+ let relay = Relay::new(RelayConfig { tokens: vec![TOKEN.into()], ..RelayConfig::default() });
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let serving = relay.clone();
+ let relay_task = tokio::spawn(async move { serving.serve(listener, std::future::pending()).await });
+ let proxy = TcpListener::bind(std::env::var(CHILD).unwrap()).await.unwrap();
+ let proxy_task = tokio::spawn(async move {
+ let (mut inbound, _) = proxy.accept().await.unwrap();
+ let mut head = Vec::new();
+ while !head.ends_with(b"\r\n\r\n") {
+ head.push(inbound.read_u8().await.unwrap());
+ assert!(head.len() < 4096);
+ }
+ let head = String::from_utf8(head).unwrap();
+ assert!(head.starts_with("CONNECT relay.invalid:80 HTTP/1.1\r\n"), "{head}");
+ assert!(!head.contains(TOKEN));
+ assert!(!head.to_ascii_lowercase().contains("authorization"));
+ let mut upstream = TcpStream::connect(addr).await.unwrap();
+ // Every status/header boundary may be fragmented by the network.
+ for byte in b"HTTP/1.1 200 Connection established\r\n\r\n" {
+ inbound.write_all(&[*byte]).await.unwrap();
+ tokio::task::yield_now().await;
+ }
+ tokio::io::copy_bidirectional(&mut inbound, &mut upstream).await.unwrap();
+ });
+ let local = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let local_addr = local.local_addr().unwrap();
+ let local_task = tokio::spawn(async move {
+ axum::serve(local, axum::Router::new().route("/health", axum::routing::get(|| async { "through-machine" }))).await.unwrap();
+ });
+ let config = JoinConfig::new("ws://relay.invalid".into(), TOKEN.into(), ID.into(), local_addr);
+ let stop = CancellationToken::new();
+ let stopped = stop.clone();
+ let mut join = tokio::spawn(async move { cua_relay::client::session(&config, &stopped).await });
+ let online = async {
+ while !relay.machine_ids().contains(&ID.to_string()) {
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ };
+ tokio::select! {
+ ended = &mut join => panic!("join ended before becoming online: {ended:?}"),
+ result = tokio::time::timeout(Duration::from_secs(5), online) => result.expect("proxy join never became online"),
+ }
+ let response = reqwest::Client::builder().no_proxy().build().unwrap()
+ .get(format!("http://{addr}/m/{ID}/health")).bearer_auth(TOKEN)
+ .send().await.unwrap();
+ assert_eq!(response.status(), 200);
+ assert_eq!(response.text().await.unwrap(), "through-machine");
+ stop.cancel();
+ assert!(matches!(join.await.unwrap(), SessionEnd::Shutdown));
+ // Established-session mux task lifetime is existing client behavior.
+ // Partial CONNECT cancellation is covered in transport's unit tests.
+ proxy_task.abort();
+ local_task.abort();
+ relay_task.abort();
+ });
+}
+
+#[test]
+fn proxy_tunnel_keeps_native_tls_verification() {
+ if std::env::var_os(CHILD).is_none() {
+ let proxy = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let addr = proxy.local_addr().unwrap();
+ drop(proxy);
+ let mut child = Command::new(std::env::current_exe().unwrap());
+ child.args([
+ "--exact",
+ "proxy_tunnel_keeps_native_tls_verification",
+ "--nocapture",
+ ]);
+ for key in [
+ "HTTP_PROXY",
+ "http_proxy",
+ "HTTPS_PROXY",
+ "https_proxy",
+ "ALL_PROXY",
+ "all_proxy",
+ "NO_PROXY",
+ "no_proxy",
+ "REQUEST_METHOD",
+ ] {
+ child.env_remove(key);
+ }
+ let result = child
+ .env(CHILD, addr.to_string())
+ .env("HTTPS_PROXY", format!("http://{addr}"))
+ .output()
+ .unwrap();
+ assert!(
+ result.status.success(),
+ "{}\n{}",
+ String::from_utf8_lossy(&result.stdout),
+ String::from_utf8_lossy(&result.stderr)
+ );
+ return;
+ }
+ tokio::runtime::Runtime::new().unwrap().block_on(async {
+ let proxy = TcpListener::bind(std::env::var(CHILD).unwrap())
+ .await
+ .unwrap();
+ // This is a public test-only identity, never installed in a trust store.
+ let identity = native_tls::Identity::from_pkcs8(
+ include_bytes!("fixtures/untrusted-cert.pem"),
+ include_bytes!("fixtures/untrusted-key.pem"),
+ )
+ .unwrap();
+ let tls =
+ tokio_native_tls::TlsAcceptor::from(native_tls::TlsAcceptor::new(identity).unwrap());
+ let proxy_task = tokio::spawn(async move {
+ let (mut stream, _) = proxy.accept().await.unwrap();
+ let mut head = Vec::new();
+ while !head.ends_with(b"\r\n\r\n") {
+ head.push(stream.read_u8().await.unwrap());
+ }
+ assert!(String::from_utf8(head)
+ .unwrap()
+ .starts_with("CONNECT relay.invalid:443 HTTP/1.1\r\n"));
+ stream.write_all(b"HTTP/1.1 200 OK\r\n\r\n").await.unwrap();
+ // Schannel can finish the server handshake before the client
+ // rejects its certificate. The client must send no application
+ // data, regardless of when the server observes the rejection.
+ if let Ok(mut stream) = tls.accept(stream).await {
+ let mut byte = [0];
+ let read = tokio::time::timeout(Duration::from_secs(2), stream.read(&mut byte))
+ .await
+ .expect("rejected TLS connection remained open");
+ assert!(
+ matches!(read, Ok(0) | Err(_)),
+ "client sent application data to an untrusted origin"
+ );
+ }
+ });
+ let config = JoinConfig::new(
+ "wss://relay.invalid/?origin-secret-canary".into(),
+ TOKEN.into(),
+ ID.into(),
+ "127.0.0.1:1".parse().unwrap(),
+ );
+ let end = tokio::time::timeout(
+ Duration::from_secs(5),
+ cua_relay::client::session(&config, &CancellationToken::new()),
+ )
+ .await
+ .unwrap();
+ assert!(
+ matches!(&end, SessionEnd::Lost(reason) if reason == "origin TLS failed"),
+ "{end:?}"
+ );
+ assert!(!format!("{end:?}").contains("canary"));
+ tokio::time::timeout(Duration::from_secs(2), proxy_task)
+ .await
+ .expect("TLS fixture server did not finish")
+ .unwrap();
+ });
+}
+
+#[test]
+#[allow(clippy::result_large_err)] // tungstenite callback fixes the error response type.
+fn reconnect_through_proxy_rereads_token_and_checks_pinned_keys() {
+ if std::env::var_os(CHILD).is_none() {
+ let proxy = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let addr = proxy.local_addr().unwrap();
+ drop(proxy);
+ let mut child = Command::new(std::env::current_exe().unwrap());
+ child.args([
+ "--exact",
+ "reconnect_through_proxy_rereads_token_and_checks_pinned_keys",
+ "--nocapture",
+ ]);
+ for key in [
+ "HTTP_PROXY",
+ "http_proxy",
+ "HTTPS_PROXY",
+ "https_proxy",
+ "ALL_PROXY",
+ "all_proxy",
+ "NO_PROXY",
+ "no_proxy",
+ "REQUEST_METHOD",
+ ] {
+ child.env_remove(key);
+ }
+ let result = child
+ .env(CHILD, addr.to_string())
+ .env("HTTP_PROXY", format!("http://{addr}"))
+ .output()
+ .unwrap();
+ assert!(
+ result.status.success(),
+ "{}\n{}",
+ String::from_utf8_lossy(&result.stdout),
+ String::from_utf8_lossy(&result.stderr)
+ );
+ return;
+ }
+ tokio::runtime::Runtime::new().unwrap().block_on(async {
+ use base64::Engine as _;
+ use cua_relay::assertion::{RelayKey, JWKS_HEADER, OWNER_HEADER};
+ let proxy = TcpListener::bind(std::env::var(CHILD).unwrap())
+ .await
+ .unwrap();
+ let files = tempfile::tempdir().unwrap();
+ let token_path = files.path().join("token");
+ std::fs::write(&token_path, "first-token").unwrap();
+ let mut config = JoinConfig::new(
+ "ws://relay.invalid".into(),
+ "stale-token".into(),
+ ID.into(),
+ "127.0.0.1:1".parse().unwrap(),
+ );
+ config.relay_token_file = Some(token_path.clone());
+ config.max_backoff = Duration::from_millis(10);
+ let pinned = RelayKey::generate();
+ config
+ .account
+ .pin_jwks_json(&pinned.jwks().to_string())
+ .unwrap();
+ let account = config.account.clone();
+ let header =
+ base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(pinned.jwks().to_string());
+ let stop = CancellationToken::new();
+ let stopped = stop.clone();
+ let run = tokio::spawn(cua_relay::client::run(config, stopped));
+ let test = async {
+ for token in ["first-token", "second-token"] {
+ let (mut stream, _) = proxy.accept().await.unwrap();
+ let mut head = Vec::new();
+ while !head.ends_with(b"\r\n\r\n") {
+ head.push(stream.read_u8().await.unwrap());
+ }
+ assert!(!String::from_utf8(head).unwrap().contains("token"));
+ stream.write_all(b"HTTP/1.1 200 OK\r\n\r\n").await.unwrap();
+ let mut socket = tokio_tungstenite::accept_hdr_async(
+ stream,
+ |request: &http::Request<()>, mut response: http::Response<()>| {
+ assert_eq!(
+ request.headers()["authorization"],
+ format!("Bearer {token}")
+ );
+ assert_eq!(request.headers()[cua_relay::MACHINE_ID_HEADER], ID);
+ response
+ .headers_mut()
+ .insert(JWKS_HEADER, header.parse().unwrap());
+ response
+ .headers_mut()
+ .insert(OWNER_HEADER, "proxy-test-owner".parse().unwrap());
+ Ok(response)
+ },
+ )
+ .await
+ .unwrap();
+ std::fs::write(&token_path, "second-token").unwrap();
+ // Wait until session processed the key-bearing 101 before closing.
+ while account.owner().as_deref() != Some("proxy-test-owner") {
+ tokio::task::yield_now().await;
+ }
+ socket.close(None).await.unwrap();
+ }
+ };
+ tokio::time::timeout(Duration::from_secs(5), test)
+ .await
+ .unwrap();
+ stop.cancel();
+ tokio::time::timeout(Duration::from_secs(1), run)
+ .await
+ .unwrap()
+ .unwrap();
+ });
+}
diff --git a/libs/cua-spacesd/crates/cua-relay/tests/transport_failures.rs b/libs/cua-spacesd/crates/cua-relay/tests/transport_failures.rs
new file mode 100644
index 0000000000..80dc6d2198
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-relay/tests/transport_failures.rs
@@ -0,0 +1,163 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Exercise the actual session route and cancellation owner, with reachable
+//! origin listeners that detect any unintended direct fallback.
+use cua_relay::client::JoinConfig;
+use std::{process::Command, time::Duration};
+use tokio::{
+ io::{AsyncReadExt, AsyncWriteExt},
+ net::{TcpListener, TcpStream},
+};
+use tokio_util::sync::CancellationToken;
+
+const CHILD: &str = "CUA_TEST_TRANSPORT_FAILURE";
+const ADDRESS: &str = "CUA_TEST_PROXY_ADDRESS";
+
+#[test]
+fn session_failure_and_cancellation_contract() {
+ if std::env::var_os(CHILD).is_none() {
+ for mode in [
+ "proxy407",
+ "proxy403",
+ "proxy-eof",
+ "proxy-dial",
+ "bad-config",
+ "ws-invalid",
+ "ws403",
+ "ws-eof",
+ "cancel-connect",
+ "cancel-tls",
+ "cancel-ws",
+ ] {
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let address = listener.local_addr().unwrap();
+ drop(listener);
+ let mut child = Command::new(std::env::current_exe().unwrap());
+ child.args([
+ "--exact",
+ "session_failure_and_cancellation_contract",
+ "--nocapture",
+ ]);
+ for key in [
+ "HTTP_PROXY",
+ "http_proxy",
+ "HTTPS_PROXY",
+ "https_proxy",
+ "ALL_PROXY",
+ "all_proxy",
+ "NO_PROXY",
+ "no_proxy",
+ "REQUEST_METHOD",
+ ] {
+ child.env_remove(key);
+ }
+ let proxy = if mode == "bad-config" {
+ "http://secret-user:[email protected]".to_owned()
+ } else {
+ format!("http://{address}")
+ };
+ let output = child
+ .env(CHILD, mode)
+ .env(ADDRESS, address.to_string())
+ .env("HTTP_PROXY", &proxy)
+ .env("HTTPS_PROXY", &proxy)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{mode}: {}\n{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+ return;
+ }
+ tokio::runtime::Runtime::new().unwrap().block_on(async {
+ let mode = std::env::var(CHILD).unwrap();
+ let origin = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = origin.local_addr().unwrap();
+ let proxy = TcpListener::bind(std::env::var(ADDRESS).unwrap()).await.unwrap();
+ let stop = CancellationToken::new();
+ let stopped = stop.clone();
+ let (ready, waiting) = tokio::sync::oneshot::channel();
+ let scenario = mode.clone();
+ let mut server = Some(tokio::spawn(async move {
+ if matches!(scenario.as_str(), "proxy-dial" | "bad-config") {
+ drop(proxy);
+ ready.send(()).unwrap();
+ return;
+ }
+ // Signal readiness only after the listener exists.
+ let (mut socket, _) = proxy.accept().await.unwrap();
+ let connect = read_head(&mut socket).await;
+ assert!(connect.starts_with(&format!("CONNECT {address} HTTP/1.1\r\n")));
+ assert!(!connect.to_ascii_lowercase().contains("authorization"));
+ match scenario.as_str() {
+ "proxy407" => socket.write_all(b"HTTP/1.1 407 secret-reason\r\nProxy-Authenticate: secret-challenge\r\nContent-Length: 10000\r\n\r\nsecret-body").await.unwrap(),
+ "proxy403" => socket.write_all(b"HTTP/1.1 403 secret-reason\r\nContent-Length: 10000\r\n\r\nsecret-body").await.unwrap(),
+ "proxy-eof" => { socket.write_all(b"HTTP/1.1 20").await.unwrap(); return; }
+ "cancel-connect" => socket.write_all(b"HTTP/1.1 200").await.unwrap(),
+ _ => {
+ socket.write_all(b"HTTP/1.1 200 OK\r\n\r\n").await.unwrap();
+ if scenario == "cancel-tls" {
+ let mut hello = [0; 4096];
+ assert!(socket.read(&mut hello).await.unwrap() > 0);
+ assert_eq!(hello[0], 22, "expected TLS handshake record");
+ } else {
+ let ws = read_head(&mut socket).await;
+ assert!(ws.contains("Bearer origin-token-canary"));
+ match scenario.as_str() {
+ "ws-invalid" => socket.write_all(b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: secret-invalid-accept\r\n\r\n").await.unwrap(),
+ "ws403" => socket.write_all(b"HTTP/1.1 403 secret-reason\r\nContent-Length: 11\r\n\r\nsecret-body").await.unwrap(),
+ "ws-eof" => return,
+ "cancel-ws" => {},
+ _ => unreachable!(),
+ }
+ }
+ }
+ }
+ if scenario.starts_with("cancel-") { ready.send(()).unwrap(); }
+ // Rejection/cancellation must release the socket owned by the dial.
+ let mut rest = Vec::new();
+ let result = tokio::time::timeout(Duration::from_secs(2), socket.read_to_end(&mut rest)).await.expect("handshake socket survived session completion");
+ assert!(result.is_ok() || result.unwrap_err().kind() == std::io::ErrorKind::ConnectionReset);
+ }));
+ if matches!(mode.as_str(), "proxy-dial" | "bad-config") { server.take().unwrap().await.unwrap(); }
+ let scheme = if mode == "cancel-tls" { "wss" } else { "ws" };
+ let config = JoinConfig::new(format!("{scheme}://{address}/?url-secret-canary"), "origin-token-canary".into(), "failure-machine".into(), "127.0.0.1:1".parse().unwrap());
+ let session = tokio::spawn(async move { cua_relay::client::session(&config, &stopped).await });
+ if mode.starts_with("cancel-") {
+ tokio::time::timeout(Duration::from_secs(2), waiting).await.unwrap().unwrap();
+ stop.cancel();
+ }
+ let end = tokio::select! {
+ result = tokio::time::timeout(Duration::from_secs(3), session) => result.expect("session did not finish").unwrap(),
+ _ = origin.accept() => panic!("selected proxy route opened a direct origin connection"),
+ };
+ let expected = match mode.as_str() {
+ "proxy407" => "Lost(\"proxy authentication required: HTTP 407\")",
+ "proxy403" => "Lost(\"proxy CONNECT refused: HTTP 403 Forbidden\")",
+ "proxy-eof" => "Lost(\"proxy CONNECT failed\")",
+ "proxy-dial" => "Lost(\"proxy dial failed\")",
+ "bad-config" => "Refused(\"proxy configuration: proxy authentication is unsupported\")",
+ "ws-invalid" | "ws-eof" => "Lost(\"WebSocket upgrade failed\")",
+ "ws403" => "Refused(\"HTTP 403 Forbidden\")",
+ _ => "Shutdown",
+ };
+ assert_eq!(format!("{end:?}"), expected);
+ assert!(!format!("{end:?}").contains("secret"));
+ assert!(!format!("{end:?}").contains("canary"));
+ assert!(tokio::time::timeout(Duration::from_millis(50), origin.accept()).await.is_err(), "selected proxy route fell back to a directly reachable origin");
+ if let Some(server) = server { server.await.unwrap(); }
+ });
+}
+
+async fn read_head(socket: &mut TcpStream) -> String {
+ let mut bytes = Vec::new();
+ while !bytes.ends_with(b"\r\n\r\n") {
+ bytes.push(socket.read_u8().await.unwrap());
+ assert!(bytes.len() < 8192);
+ }
+ String::from_utf8(bytes).unwrap()
+}
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/context.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/context.rs
index 5a4aac1f0a..5909c8c50e 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/context.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/context.rs
@@ -471,7 +471,7 @@ impl ServerContext {
if let Some(p) = previous {
p.stop.cancel();
}
- tracing::info!(relay = %relay_url, machine = %machine_id, "attached to relay");
+ tracing::info!(machine = %machine_id, "attached to relay");
tokio::spawn(cua_relay::client::run(join, stop));
Ok(())
}