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(sdk): honor HTTP proxies for controller RPC (#4795)

injaneity23e23d4cc321
diff --git a/.github/workflows/ci-cua-sdk.yml b/.github/workflows/ci-cua-sdk.yml
index 57e920317b..0a1fb51008 100644
--- a/.github/workflows/ci-cua-sdk.yml
+++ b/.github/workflows/ci-cua-sdk.yml
@@ -84,10 +84,10 @@ jobs:
key: cua-sdk
- name: Format
if: runner.os == 'Linux'
- run: cargo fmt -p cua-sdk -p cua-daemon -p cua-cli -p cua-bindgen -p cua-media-protocol -p cua-media-transport -p cua-media-codec -p cua-media-client -p cua-viewer -p cua-logging -p cua-teleport -p cua-teleport-bundle -p cua-chromium-storage -p cua-spaces-ext -p cua-spaces-ffi -p cua-spaces-cli -- --check
+ run: cargo fmt -p cua-sdk -p cua-daemon -p cua-cli -p cua-bindgen -p cua-spacesd-client -p cua-media-protocol -p cua-media-transport -p cua-media-codec -p cua-media-client -p cua-viewer -p cua-logging -p cua-teleport -p cua-teleport-bundle -p cua-chromium-storage -p cua-spaces-ext -p cua-spaces-ffi -p cua-spaces-cli -- --check
- name: Clippy (native)
run: >
- cargo clippy --locked -p cua-sdk -p cua-daemon -p cua-cli -p cua-bindgen
+ cargo clippy --locked -p cua-sdk -p cua-daemon -p cua-cli -p cua-bindgen -p cua-spacesd-client
-p cua-media-protocol -p cua-media-transport -p cua-media-client -p cua-viewer -p cua-logging
-p cua-teleport -p cua-teleport-bundle -p cua-chromium-storage -p cua-volume
-p cua-spaces-ext -p cua-spaces-ffi -p cua-spaces-cli
@@ -102,7 +102,7 @@ jobs:
run: cargo test --locked -p cua-spaces --test relay --test cloud_discovery -- --test-threads=4
- name: Test (embedded, daemon over UDS and loopback, CLI, Cua Spaces extensions)
run: >
- cargo test --locked --no-fail-fast -p cua-sdk -p cua-daemon -p cua-cli
+ cargo test --locked --no-fail-fast -p cua-sdk -p cua-daemon -p cua-cli -p cua-spacesd-client
-p cua-teleport -p cua-teleport-bundle -p cua-chromium-storage -p cua-volume
-p cua-spaces-ext -p cua-spaces-ffi -p cua-spaces-cli -- --test-threads=4
env:
diff --git a/apps/cua-spaces/src-tauri/Cargo.lock b/apps/cua-spaces/src-tauri/Cargo.lock
index a2d5eb9054..25642448c7 100644
--- a/apps/cua-spaces/src-tauri/Cargo.lock
+++ b/apps/cua-spaces/src-tauri/Cargo.lock
@@ -1689,6 +1689,7 @@ dependencies = [
"prost",
"rand 0.9.5",
"rustls",
+ "rustls-native-certs",
"serde",
"serde_json",
"sha2 0.10.9",
@@ -1702,6 +1703,7 @@ dependencies = [
"tower",
"tracing",
"url",
+ "webpki-roots 1.0.9",
]
[[package]]
diff --git a/examples/streaming/rust/Cargo.lock b/examples/streaming/rust/Cargo.lock
index 124e31d236..84bd41b76d 100644
--- a/examples/streaming/rust/Cargo.lock
+++ b/examples/streaming/rust/Cargo.lock
@@ -1490,6 +1490,7 @@ dependencies = [
"prost",
"rand 0.9.5",
"rustls",
+ "rustls-native-certs",
"serde",
"serde_json",
"sha2 0.10.9",
@@ -1503,6 +1504,7 @@ dependencies = [
"tower",
"tracing",
"url",
+ "webpki-roots 1.0.9",
]
[[package]]
diff --git a/libs/cua-spacesd/Cargo.lock b/libs/cua-spacesd/Cargo.lock
index b1e45c8092..be6f536bdb 100644
--- a/libs/cua-spacesd/Cargo.lock
+++ b/libs/cua-spacesd/Cargo.lock
@@ -1612,6 +1612,7 @@ dependencies = [
"prost",
"rand 0.9.5",
"rustls",
+ "rustls-native-certs",
"serde",
"serde_json",
"sha2 0.10.9",
@@ -1625,6 +1626,7 @@ dependencies = [
"tower",
"tracing",
"url",
+ "webpki-roots 1.0.9",
]
[[package]]
@@ -7835,3 +7837,14 @@ dependencies = [
"syn 3.0.4",
"winnow 1.0.4",
]
+[[package]]
+name = "rustls-native-certs"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"
+dependencies = [
+ "openssl-probe",
+ "rustls-pki-types",
+ "schannel",
+ "security-framework 3.7.0",
+]
diff --git a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
index fbf8a2f933..051f75f186 100644
--- a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
+++ b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
@@ -2583,6 +2583,7 @@ dependencies = [
"prost",
"rand 0.9.5",
"rustls",
+ "rustls-native-certs",
"serde",
"serde_json",
"sha2 0.10.9",
@@ -2596,6 +2597,7 @@ dependencies = [
"tower",
"tracing",
"url",
+ "webpki-roots 1.0.9",
]
[[package]]
diff --git a/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock b/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock
index ca5699f537..d0ce459d9d 100644
--- a/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock
+++ b/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock
@@ -1454,6 +1454,7 @@ dependencies = [
"prost",
"rand 0.9.5",
"rustls",
+ "rustls-native-certs",
"serde",
"serde_json",
"sha2 0.10.9",
@@ -1467,6 +1468,7 @@ dependencies = [
"tower",
"tracing",
"url",
+ "webpki-roots 1.0.9",
]
[[package]]
@@ -7374,3 +7376,14 @@ dependencies = [
"syn 3.0.4",
"winnow 1.0.4",
]
+[[package]]
+name = "rustls-native-certs"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"
+dependencies = [
+ "openssl-probe",
+ "rustls-pki-types",
+ "schannel",
+ "security-framework 3.7.0",
+]
diff --git a/libs/cua/Cargo.lock b/libs/cua/Cargo.lock
index 857b97a919..93e7df734d 100644
--- a/libs/cua/Cargo.lock
+++ b/libs/cua/Cargo.lock
@@ -2823,13 +2823,16 @@ dependencies = [
"pbjson-types",
"prost",
"rand 0.9.5",
+ "rcgen",
"rustls",
+ "rustls-native-certs",
"serde",
"serde_json",
"sha2 0.10.9",
"tempfile",
"thiserror 2.0.20",
"tokio",
+ "tokio-rustls",
"tokio-stream",
"tokio-tungstenite 0.29.0",
"tonic",
@@ -2838,6 +2841,7 @@ dependencies = [
"tower",
"tracing",
"url",
+ "webpki-roots 1.0.9",
]
[[package]]
diff --git a/libs/cua/bench/streaming/Cargo.lock b/libs/cua/bench/streaming/Cargo.lock
index 3e80ad6164..d0cabb8427 100644
--- a/libs/cua/bench/streaming/Cargo.lock
+++ b/libs/cua/bench/streaming/Cargo.lock
@@ -405,6 +405,7 @@ dependencies = [
"prost",
"rand 0.9.5",
"rustls",
+ "rustls-native-certs",
"serde",
"serde_json",
"sha2",
@@ -418,6 +419,7 @@ dependencies = [
"tower",
"tracing",
"url",
+ "webpki-roots 1.0.9",
]
[[package]]
@@ -837,13 +839,16 @@ version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
dependencies = [
+ "base64 0.22.1",
"bytes",
"futures-channel",
"futures-util",
"http",
"http-body",
"hyper",
+ "ipnet",
"libc",
+ "percent-encoding",
"pin-project-lite",
"socket2",
"tokio",
@@ -965,6 +970,12 @@ dependencies = [
"hashbrown 0.17.1",
]
+[[package]]
+name = "ipnet"
+version = "2.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
+
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
@@ -2708,3 +2719,68 @@ name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+[[package]]
+name = "core-foundation"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "core-foundation-sys"
+version = "0.8.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
+
+[[package]]
+name = "openssl-probe"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
+
+[[package]]
+name = "rustls-native-certs"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"
+dependencies = [
+ "openssl-probe",
+ "rustls-pki-types",
+ "schannel",
+ "security-framework",
+]
+
+[[package]]
+name = "schannel"
+version = "0.1.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "security-framework"
+version = "3.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
+dependencies = [
+ "bitflags",
+ "core-foundation",
+ "core-foundation-sys",
+ "libc",
+ "security-framework-sys",
+]
+
+[[package]]
+name = "security-framework-sys"
+version = "2.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
diff --git a/libs/cua/crates/cua-spacesd-client/Cargo.toml b/libs/cua/crates/cua-spacesd-client/Cargo.toml
index 040707a619..f9177787fd 100644
--- a/libs/cua/crates/cua-spacesd-client/Cargo.toml
+++ b/libs/cua/crates/cua-spacesd-client/Cargo.toml
@@ -25,8 +25,10 @@ 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"] }
hyper-rustls.workspace = true
+rustls-native-certs = "0.8"
+webpki-roots = "1"
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
tower.workspace = true
tokio = { workspace = true }
@@ -45,5 +47,7 @@ serde.workspace = true
serde_json.workspace = true
[dev-dependencies]
+rcgen = { version = "0.14", default-features = false, features = ["crypto", "ring"] }
+tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] }
cua-spacesd-client = { path = ".", features = ["testing"] }
tempfile.workspace = true
diff --git a/libs/cua/crates/cua-spacesd-client/src/connector.rs b/libs/cua/crates/cua-spacesd-client/src/connector.rs
new file mode 100644
index 0000000000..de2321bd71
--- /dev/null
+++ b/libs/cua/crates/cua-spacesd-client/src/connector.rs
@@ -0,0 +1,273 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Environment routing below the existing RPC/HTTP TLS connectors. A selected
+//! proxy is mandatory: a configuration or CONNECT failure never becomes direct IO.
+
+use bytes::Bytes;
+use http::{Method, Request, StatusCode, Uri};
+use http_body_util::Empty;
+use hyper::{
+ rt::{Read, ReadBufCursor, Write},
+ upgrade::Upgraded,
+};
+use hyper_util::{
+ client::{
+ legacy::connect::{Connected, Connection, HttpConnector},
+ proxy::matcher::Matcher,
+ },
+ rt::TokioIo,
+};
+use std::{
+ ffi::OsString,
+ future::Future,
+ io,
+ pin::Pin,
+ task::{Context, Poll},
+ time::Duration,
+};
+use tokio::net::TcpStream;
+use tower::Service;
+
+#[derive(Clone)]
+pub(crate) struct ProxyConnector {
+ tcp: HttpConnector,
+ timeout: Duration,
+}
+
+impl ProxyConnector {
+ pub(crate) fn new(timeout: Duration, keepalive: Option<Duration>) -> Self {
+ let mut tcp = HttpConnector::new();
+ tcp.enforce_http(false);
+ tcp.set_connect_timeout(Some(timeout));
+ tcp.set_keepalive(keepalive);
+ tcp.set_nodelay(true);
+ Self { tcp, timeout }
+ }
+}
+
+impl Service<Uri> for ProxyConnector {
+ type Response = RoutedIo;
+ type Error = io::Error;
+ type Future = Pin<Box<dyn Future<Output = io::Result<RoutedIo>> + Send>>;
+
+ fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<io::Result<()>> {
+ Poll::Ready(Ok(()))
+ }
+
+ fn call(&mut self, origin: Uri) -> Self::Future {
+ let route = selected_proxy(&origin, |key| std::env::var_os(key));
+ let mut tcp = self.tcp.clone();
+ let timeout = self.timeout;
+ Box::pin(async move {
+ let proxy = route.map_err(io::Error::other)?;
+ let connect = async {
+ match proxy {
+ None => tcp
+ .call(origin)
+ .await
+ .map(RoutedIo::Direct)
+ .map_err(io::Error::other),
+ Some(proxy) => {
+ let socket = tcp
+ .call(proxy)
+ .await
+ .map_err(|_| io::Error::other("proxy TCP connection failed"))?;
+ connect_tunnel(socket, &origin).await.map(RoutedIo::Tunnel)
+ }
+ }
+ };
+ tokio::time::timeout(timeout, connect)
+ .await
+ .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "connection timed out"))?
+ })
+ }
+}
+
+// Keep the library's NO_PROXY grammar, while refusing configuration that its
+// permissive proxy parser would otherwise discard. Uppercase presence wins;
+// an empty scheme-specific setting permits ALL_PROXY, not its lowercase twin.
+fn selected_proxy(
+ origin: &Uri,
+ env: impl Fn(&str) -> Option<OsString>,
+) -> Result<Option<Uri>, &'static str> {
+ let setting = |upper, lower| env(upper).or_else(|| env(lower));
+ let scheme = if origin.scheme_str() == Some("https") {
+ setting("HTTPS_PROXY", "https_proxy")
+ } else {
+ setting("HTTP_PROXY", "http_proxy")
+ };
+ let selected = scheme
+ .filter(|v| !v.is_empty())
+ .or_else(|| setting("ALL_PROXY", "all_proxy").filter(|v| !v.is_empty()));
+ let Some(selected) = selected else {
+ return Ok(None);
+ };
+ let exclusions = setting("NO_PROXY", "no_proxy").unwrap_or_default();
+ let exclusions = exclusions.to_str().ok_or("NO_PROXY is not Unicode")?;
+ // A non-routable placeholder asks only whether NO_PROXY excludes this URI.
+ if Matcher::builder()
+ .all("http://proxy.invalid")
+ .no(exclusions)
+ .build()
+ .intercept(origin)
+ .is_none()
+ {
+ return Ok(None);
+ }
+ if env("REQUEST_METHOD").is_some() {
+ return Err("proxy use in a CGI environment is unsupported");
+ }
+ let selected = selected.to_str().ok_or("proxy URL is not Unicode")?;
+ validate_proxy(selected).map(Some)
+}
+
+fn validate_proxy(value: &str) -> Result<Uri, &'static str> {
+ // Validate the raw spelling before URL normalization can remove fragments,
+ // credentials, dot paths or whitespace. Never include the value in errors.
+ if value.contains('#') {
+ return Err("proxy URL fragments are unsupported");
+ }
+ if value.contains('@') {
+ return Err("proxy authentication is unsupported");
+ }
+ let authority = match value.split_once("://") {
+ Some(("http", rest)) => rest,
+ Some(_) => return Err("only HTTP proxies are supported"),
+ None => value,
+ };
+ let authority = authority.strip_suffix('/').unwrap_or(authority);
+ if authority.contains(['/', '?', '\\']) || authority.chars().any(char::is_whitespace) {
+ return Err("invalid proxy authority or path");
+ }
+ let normalized = format!("http://{authority}/");
+ let parsed = url::Url::parse(&normalized).map_err(|_| "invalid proxy URL")?;
+ if parsed.host_str().is_none() || parsed.port() == Some(0) || authority.ends_with(':') {
+ return Err("invalid proxy authority or port");
+ }
+ parsed.as_str().parse().map_err(|_| "invalid proxy URL")
+}
+
+async fn connect_tunnel(socket: TokioIo<TcpStream>, origin: &Uri) -> io::Result<Upgraded> {
+ let host = origin
+ .host()
+ .ok_or_else(|| io::Error::other("missing origin host"))?;
+ let port = origin
+ .port_u16()
+ .unwrap_or(if origin.scheme_str() == Some("https") {
+ 443
+ } else {
+ 80
+ });
+ let target = format!("{host}:{port}");
+ let request = Request::builder()
+ .method(Method::CONNECT)
+ .uri(&target)
+ .header(http::header::HOST, &target)
+ .body(Empty::<Bytes>::new())
+ .map_err(|_| io::Error::other("invalid CONNECT destination"))?;
+ let (mut requests, connection) = hyper::client::conn::http1::Builder::new()
+ .max_headers(64)
+ .max_buf_size(16 * 1024)
+ .handshake(socket)
+ .await
+ .map_err(|_| io::Error::other("proxy HTTP handshake failed"))?;
+ let response = async move {
+ let response = requests
+ .send_request(request)
+ .await
+ .map_err(|_| io::Error::other("proxy CONNECT exchange failed"))?;
+ match response.status() {
+ StatusCode::OK => hyper::upgrade::on(response)
+ .await
+ .map_err(|_| io::Error::other("proxy CONNECT upgrade failed")),
+ StatusCode::PROXY_AUTHENTICATION_REQUIRED => {
+ Err(io::Error::other("proxy authentication required: HTTP 407"))
+ }
+ status => Err(io::Error::other(format!(
+ "proxy CONNECT refused: HTTP {}",
+ status.as_u16()
+ ))),
+ }
+ };
+ // Both futures belong to this call. Failure, deadline or cancellation drops
+ // the socket; successful upgrade retains bytes read beyond the HTTP headers.
+ let drive = async {
+ connection
+ .with_upgrades()
+ .await
+ .map_err(|_| io::Error::other("proxy CONNECT I/O failed"))
+ };
+ let (upgraded, ()) = tokio::try_join!(response, drive)?;
+ Ok(upgraded)
+}
+
+pub(crate) enum RoutedIo {
+ Direct(TokioIo<TcpStream>),
+ Tunnel(Upgraded),
+}
+
+impl Connection for RoutedIo {
+ fn connected(&self) -> Connected {
+ match self {
+ Self::Direct(io) => io.connected(),
+ // CONNECT carries origin-form requests, not forward-proxy requests.
+ Self::Tunnel(_) => Connected::new(),
+ }
+ }
+}
+impl Read for RoutedIo {
+ fn poll_read(
+ self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ buf: ReadBufCursor<'_>,
+ ) -> Poll<io::Result<()>> {
+ match self.get_mut() {
+ Self::Direct(io) => Pin::new(io).poll_read(cx, buf),
+ Self::Tunnel(io) => Pin::new(io).poll_read(cx, buf),
+ }
+ }
+}
+impl Write for RoutedIo {
+ fn poll_write(
+ self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ buf: &[u8],
+ ) -> Poll<io::Result<usize>> {
+ match self.get_mut() {
+ Self::Direct(io) => Pin::new(io).poll_write(cx, buf),
+ Self::Tunnel(io) => Pin::new(io).poll_write(cx, buf),
+ }
+ }
+ fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+ match self.get_mut() {
+ Self::Direct(io) => Pin::new(io).poll_flush(cx),
+ Self::Tunnel(io) => Pin::new(io).poll_flush(cx),
+ }
+ }
+ fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+ match self.get_mut() {
+ Self::Direct(io) => Pin::new(io).poll_shutdown(cx),
+ Self::Tunnel(io) => Pin::new(io).poll_shutdown(cx),
+ }
+ }
+ fn is_write_vectored(&self) -> bool {
+ match self {
+ Self::Direct(io) => io.is_write_vectored(),
+ Self::Tunnel(io) => io.is_write_vectored(),
+ }
+ }
+ fn poll_write_vectored(
+ self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ bufs: &[io::IoSlice<'_>],
+ ) -> Poll<io::Result<usize>> {
+ match self.get_mut() {
+ Self::Direct(io) => Pin::new(io).poll_write_vectored(cx, bufs),
+ Self::Tunnel(io) => Pin::new(io).poll_write_vectored(cx, bufs),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/libs/cua/crates/cua-spacesd-client/src/connector/tests.rs b/libs/cua/crates/cua-spacesd-client/src/connector/tests.rs
new file mode 100644
index 0000000000..b320edafee
--- /dev/null
+++ b/libs/cua/crates/cua-spacesd-client/src/connector/tests.rs
@@ -0,0 +1,226 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+use super::*;
+use tokio::{
+ io::{AsyncReadExt, AsyncWriteExt},
+ net::TcpListener,
+};
+
+#[test]
+fn environment_selection_and_explicit_bypass() {
+ let route = |url: &str, values: &[(&str, &str)]| {
+ selected_proxy(&url.parse().unwrap(), |key| {
+ values
+ .iter()
+ .find(|(k, _)| *k == key)
+ .map(|(_, v)| OsString::from(v))
+ })
+ .map(|v| v.map(|v| v.to_string()))
+ };
+ let env = [
+ ("HTTPS_PROXY", "http://secure:81"),
+ ("https_proxy", "http://ignored:82"),
+ ("HTTP_PROXY", "http://plain:83"),
+ ("ALL_PROXY", "fallback:84"),
+ ];
+ assert_eq!(
+ route("https://relay.invalid/", &env),
+ Ok(Some("http://secure:81/".into()))
+ );
+ assert_eq!(
+ route("http://relay.invalid/", &env),
+ Ok(Some("http://plain:83/".into()))
+ );
+ assert_eq!(
+ route(
+ "https://relay.invalid/",
+ &[
+ ("HTTPS_PROXY", ""),
+ ("https_proxy", "ignored:80"),
+ ("ALL_PROXY", "fallback:84")
+ ]
+ ),
+ Ok(Some("http://fallback:84/".into()))
+ );
+ assert_eq!(
+ route("https://relay.invalid/", &[("https_proxy", "proxy:80")]),
+ Ok(Some("http://proxy/".into()))
+ );
+ assert_eq!(route("https://relay.invalid/", &[]), Ok(None));
+ assert_eq!(
+ route("https://relay.invalid/", &[("HTTP_PROXY", "proxy:80")]),
+ Ok(None)
+ );
+ for (origin, no) in [
+ ("https://relay.invalid/", "relay.invalid"),
+ ("https://sub.relay.invalid/", ".relay.invalid"),
+ ("http://127.0.0.1/", "127.0.0.0/8"),
+ ("https://[::1]/", "::1"),
+ ("https://relay.invalid/", "*"),
+ ] {
+ assert_eq!(
+ route(
+ origin,
+ &[
+ ("ALL_PROXY", "http://secret@proxy/#fragment"),
+ ("NO_PROXY", no)
+ ]
+ ),
+ Ok(None)
+ );
+ }
+ assert_eq!(
+ route(
+ "https://relay.invalid/",
+ &[
+ ("ALL_PROXY", "proxy:80"),
+ ("NO_PROXY", ""),
+ ("no_proxy", "*")
+ ]
+ ),
+ Ok(Some("http://proxy/".into()))
+ );
+ assert_eq!(
+ route("http://localhost/", &[("HTTP_PROXY", "proxy:80")]),
+ Ok(Some("http://proxy/".into()))
+ );
+ assert_eq!(
+ route(
+ "https://relay.invalid/",
+ &[("HTTPS_PROXY", "proxy:80"), ("REQUEST_METHOD", "GET")]
+ ),
+ Err("proxy use in a CGI environment is unsupported")
+ );
+}
+
+#[test]
+fn proxy_configuration_is_strict_and_redacted() {
+ for (value, expected) in [
+ (
+ "http://proxy/#secret",
+ "proxy URL fragments are unsupported",
+ ),
+ ("http://proxy#secret", "proxy URL fragments are unsupported"),
+ (
+ "http://user:secret@proxy",
+ "proxy authentication is unsupported",
+ ),
+ ("http://@proxy", "proxy authentication is unsupported"),
+ ("https://proxy", "only HTTP proxies are supported"),
+ ("socks5://proxy", "only HTTP proxies are supported"),
+ ("http://proxy/path", "invalid proxy authority or path"),
+ ("http://proxy/?secret", "invalid proxy authority or path"),
+ ("http://proxy/../", "invalid proxy authority or path"),
+ ("http://proxy\\secret", "invalid proxy authority or path"),
+ ("http://proxy ", "invalid proxy authority or path"),
+ ("http://proxy:65536", "invalid proxy URL"),
+ ("http://proxy:0", "invalid proxy authority or port"),
+ ("http://proxy:", "invalid proxy authority or port"),
+ ("http://", "invalid proxy URL"),
+ ] {
+ assert_eq!(validate_proxy(value), Err(expected), "case {value}");
+ }
+ for (value, expected) in [
+ ("proxy:8080", "http://proxy:8080/"),
+ ("http://[::1]:3128/", "http://[::1]:3128/"),
+ ] {
+ assert_eq!(validate_proxy(value).unwrap().to_string(), expected);
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::ffi::OsStringExt;
+ let result = selected_proxy(&"https://relay.invalid".parse().unwrap(), |key| {
+ (key == "HTTPS_PROXY").then(|| OsString::from_vec(vec![0xff]))
+ });
+ assert_eq!(result, Err("proxy URL is not Unicode"));
+ }
+}
+
+async fn fixture(response: &'static [u8]) -> (TokioIo<TcpStream>, tokio::task::JoinHandle<()>) {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let socket = TcpStream::connect(listener.local_addr().unwrap())
+ .await
+ .unwrap();
+ let server = 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!(head.len() < 4096);
+ }
+ assert_eq!(
+ String::from_utf8(head).unwrap(),
+ "CONNECT [::1]:443 HTTP/1.1\r\nhost: [::1]:443\r\n\r\n"
+ );
+ // Force a status-line split rather than relying on TCP packet boundaries.
+ socket.write_all(&response[..1]).await.unwrap();
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ socket.write_all(&response[1..]).await.unwrap();
+ let mut end = Vec::new();
+ socket.read_to_end(&mut end).await.unwrap();
+ assert!(end.is_empty());
+ });
+ (TokioIo::new(socket), server)
+}
+
+#[tokio::test]
+async fn fragmented_connect_preserves_read_ahead_and_closes() {
+ let (socket, server) = fixture(b"HTTP/1.1 200 OK\r\n\r\ntunneled-prefix").await;
+ let stream = connect_tunnel(
+ socket,
+ &"https://[::1]/secret?token=secret".parse().unwrap(),
+ )
+ .await
+ .unwrap();
+ let mut stream = TokioIo::new(stream);
+ let mut prefix = [0; 15];
+ stream.read_exact(&mut prefix).await.unwrap();
+ assert_eq!(&prefix, b"tunneled-prefix");
+ drop(stream);
+ tokio::time::timeout(Duration::from_secs(2), server)
+ .await
+ .unwrap()
+ .unwrap();
+}
+
+#[tokio::test]
+async fn refusal_does_not_wait_for_body_and_redacts_response() {
+ for (response, expected) in [
+ (&b"HTTP/1.1 407 secret-reason\r\nProxy-Authenticate: secret-challenge\r\nContent-Length: 999\r\n\r\n"[..], "proxy authentication required: HTTP 407"),
+ (&b"HTTP/1.1 403 secret-reason\r\nContent-Length: 999\r\n\r\n"[..], "proxy CONNECT refused: HTTP 403"),
+ ] {
+ let (socket, server) = fixture(response).await;
+ let result = tokio::time::timeout(Duration::from_secs(2), connect_tunnel(socket, &"https://[::1]/".parse().unwrap())).await.unwrap();
+ assert_eq!(result.err().unwrap().to_string(), expected);
+ tokio::time::timeout(Duration::from_secs(2), server).await.unwrap().unwrap();
+ }
+}
+
+#[tokio::test]
+async fn dropping_connect_future_closes_the_owned_socket() {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let socket = TcpStream::connect(listener.local_addr().unwrap())
+ .await
+ .unwrap();
+ let (mut peer, _) = listener.accept().await.unwrap();
+ let task = tokio::spawn(async move {
+ connect_tunnel(
+ TokioIo::new(socket),
+ &"https://relay.invalid/".parse().unwrap(),
+ )
+ .await
+ });
+ let mut head = Vec::new();
+ while !head.ends_with(b"\r\n\r\n") {
+ head.push(peer.read_u8().await.unwrap());
+ }
+ task.abort();
+ let _ = task.await;
+ let mut remaining = Vec::new();
+ tokio::time::timeout(Duration::from_secs(1), peer.read_to_end(&mut remaining))
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(remaining.is_empty());
+}
diff --git a/libs/cua/crates/cua-spacesd-client/src/http.rs b/libs/cua/crates/cua-spacesd-client/src/http.rs
index f38a07795d..2b989b91a0 100644
--- a/libs/cua/crates/cua-spacesd-client/src/http.rs
+++ b/libs/cua/crates/cua-spacesd-client/src/http.rs
@@ -14,13 +14,11 @@ use std::time::Duration;
use bytes::Bytes;
use http::{HeaderName, HeaderValue, Method, Request, header};
use http_body_util::{BodyExt, Full, Limited};
-use hyper_util::{
- client::legacy::{Client, connect::HttpConnector},
- rt::TokioExecutor,
-};
+use hyper_util::{client::legacy::Client, rt::TokioExecutor};
use crate::{
SpacesdClient,
+ connector::ProxyConnector,
error::{Error, Result},
transport::{ENV_TOKEN_HEADER, FLEET_CLAIM_HEADER, HeaderInjector, ensure_crypto_provider},
};
@@ -44,7 +42,7 @@ const RESERVED: &[&str] = &[
cua_proto::metadata::PRINCIPAL_BIN,
];
-pub(crate) type HttpClient = Client<hyper_rustls::HttpsConnector<HttpConnector>, Full<Bytes>>;
+pub(crate) type HttpClient = Client<hyper_rustls::HttpsConnector<ProxyConnector>, Full<Bytes>>;
/// One HTTP request to the spacesd.
#[derive(Clone, Debug, Default)]
@@ -77,13 +75,9 @@ pub struct HttpReply {
pub(crate) fn build_client(connect_timeout: Duration) -> Result<HttpClient> {
ensure_crypto_provider();
- let mut http = HttpConnector::new();
- http.enforce_http(false);
- http.set_connect_timeout(Some(connect_timeout));
- http.set_nodelay(true);
+ let http = ProxyConnector::new(connect_timeout, None);
let https = hyper_rustls::HttpsConnectorBuilder::new()
- .with_provider_and_webpki_roots(rustls::crypto::ring::default_provider())
- .map_err(|e| Error::Transport(e.to_string()))?
+ .with_tls_config(crate::tls::client_config()?)
.https_or_http()
.enable_http1()
.wrap_connector(http);
diff --git a/libs/cua/crates/cua-spacesd-client/src/lib.rs b/libs/cua/crates/cua-spacesd-client/src/lib.rs
index ee1c8abbd1..39c8250445 100644
--- a/libs/cua/crates/cua-spacesd-client/src/lib.rs
+++ b/libs/cua/crates/cua-spacesd-client/src/lib.rs
@@ -15,6 +15,14 @@
//! - Transports: native gRPC (HTTP/2, h2c or TLS) or gRPC-Web over
//! HTTP/1.1 (Fleet gateway, relays, anything HTTP/1-only). `Auto` probes
//! `GetCapabilities` over HTTP/2 and falls back to gRPC-Web.
+//! - Proxies: RPC and raw HTTP connections honor `HTTP_PROXY` / `HTTPS_PROXY`,
+//! then `ALL_PROXY`, with `NO_PROXY` exclusions (including hosts and CIDRs).
+//! Uppercase values take precedence over lowercase, even when empty; an empty
+//! scheme-specific value permits `ALL_PROXY`. Unauthenticated HTTP proxies
+//! use CONNECT for both HTTP and HTTPS origins. Origin TLS verification stays
+//! enabled. Proxy credentials, HTTPS/SOCKS proxies and CGI proxy use are refused;
+//! a selected proxy failure never falls back to a direct connection. This does
+//! not change the separate WebSocket media and tunnel transports.
//! - Auth: `authorization: Bearer <token>`; `x-cua-principal-bin`; through
//! the Fleet gateway the Fleet bearer plus `X-Cua-Fleet-Claim`, with the
//! env token moved to `x-cua-env-authorization`.
@@ -22,6 +30,7 @@
mod client;
mod computer;
+mod connector;
pub mod diagnose;
mod endpoint;
pub mod error;
@@ -30,6 +39,7 @@ mod fs;
mod http;
pub mod manifest;
mod process;
+mod tls;
pub mod transport;
pub mod tunnel;
diff --git a/libs/cua/crates/cua-spacesd-client/src/tls.rs b/libs/cua/crates/cua-spacesd-client/src/tls.rs
new file mode 100644
index 0000000000..dd7abb9152
--- /dev/null
+++ b/libs/cua/crates/cua-spacesd-client/src/tls.rs
@@ -0,0 +1,67 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Same bundled + native trust policy as the SDK's reqwest auth/discovery clients.
+use crate::{Error, Result};
+use rustls::{ClientConfig, RootCertStore};
+use std::sync::Arc;
+
+pub(crate) fn root_store() -> Result<RootCertStore> {
+ let mut roots = RootCertStore::empty();
+ roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
+ // SSL_CERT_FILE / SSL_CERT_DIR, when present, select the native input.
+ // Match reqwest: tolerate unavailable/empty native stores and partial parse
+ // failures, but fail when every returned native certificate is invalid DER.
+ // Never include native loader errors (which may contain private paths).
+ let native = rustls_native_certs::load_native_certs();
+ let (valid, invalid) = roots.add_parsable_certificates(native.certs);
+ if valid == 0 && invalid > 0 {
+ return Err(Error::Transport(
+ "zero valid certificates found in native root store".into(),
+ ));
+ }
+ Ok(roots)
+}
+
+pub(crate) fn client_config() -> Result<ClientConfig> {
+ Ok(
+ ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
+ .with_safe_default_protocol_versions()
+ .map_err(|e| Error::Transport(e.to_string()))?
+ .with_root_certificates(root_store()?)
+ .with_no_client_auth(),
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn empty_native_source_retains_bundled_roots() {
+ const CHILD: &str = "CUA_TEST_BUNDLED_ROOTS_CHILD";
+ if std::env::var_os(CHILD).is_some() {
+ let roots = super::root_store().unwrap();
+ assert_eq!(roots.roots, webpki_roots::TLS_SERVER_ROOTS);
+ return;
+ }
+ let dir = tempfile::tempdir().unwrap();
+ let empty = dir.path().join("empty.pem");
+ std::fs::write(&empty, "").unwrap();
+ for path in [empty, dir.path().join("missing.pem")] {
+ let output = std::process::Command::new(std::env::current_exe().unwrap())
+ .args([
+ "--exact",
+ "tls::tests::empty_native_source_retains_bundled_roots",
+ ])
+ .env(CHILD, "1")
+ .env("SSL_CERT_FILE", path)
+ .env_remove("SSL_CERT_DIR")
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+ }
+}
diff --git a/libs/cua/crates/cua-spacesd-client/src/transport.rs b/libs/cua/crates/cua-spacesd-client/src/transport.rs
index 0d32971f2a..1992e41e5e 100644
--- a/libs/cua/crates/cua-spacesd-client/src/transport.rs
+++ b/libs/cua/crates/cua-spacesd-client/src/transport.rs
@@ -233,35 +233,31 @@ fn native_channel(cfg: &ChannelConfig) -> Result<RawChannel> {
ep = ep
.tls_config(
ClientTlsConfig::new()
- .with_webpki_roots()
+ .trust_anchors(crate::tls::root_store()?.roots)
.domain_name(cfg.endpoint.host().to_string()),
)
.map_err(|e| Error::Transport(e.to_string()))?;
}
// Lazy: tonic reconnects transparently (with backoff) on the next call
// after a connection drops.
- let channel = ep.connect_lazy();
+ let channel = ep.connect_with_connector_lazy(crate::connector::ProxyConnector::new(
+ cfg.connect_timeout,
+ Some(cfg.keepalive.interval),
+ ));
Ok(BoxCloneSyncService::new(
channel.map_err(|e| Box::new(e) as BoxError),
))
}
fn grpc_web_channel(cfg: &ChannelConfig) -> Result<RawChannel> {
- use hyper_util::{
- client::legacy::{Client, connect::HttpConnector},
- rt::TokioExecutor,
- };
- let mut http = HttpConnector::new();
- http.enforce_http(false);
- http.set_connect_timeout(Some(cfg.connect_timeout));
- http.set_keepalive(Some(cfg.keepalive.interval));
- http.set_nodelay(true);
+ use hyper_util::{client::legacy::Client, rt::TokioExecutor};
+ let http =
+ crate::connector::ProxyConnector::new(cfg.connect_timeout, Some(cfg.keepalive.interval));
// Name the crypto provider explicitly: other crates in a dependency graph
// (e.g. reqwest via oci-client) may enable a second rustls backend, and
// rustls then refuses to pick a process default on its own.
let https = hyper_rustls::HttpsConnectorBuilder::new()
- .with_provider_and_webpki_roots(rustls::crypto::ring::default_provider())
- .map_err(|e| Error::Transport(e.to_string()))?
+ .with_tls_config(crate::tls::client_config()?)
.https_or_http()
.enable_http1()
.wrap_connector(http);
diff --git a/libs/cua/crates/cua-spacesd-client/tests/environment_proxy.rs b/libs/cua/crates/cua-spacesd-client/tests/environment_proxy.rs
new file mode 100644
index 0000000000..dd59403d32
--- /dev/null
+++ b/libs/cua/crates/cua-spacesd-client/tests/environment_proxy.rs
@@ -0,0 +1,304 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Public-client routing contract. Each case has an isolated process environment.
+use cua_spacesd_client::{
+ ConnectOptions, Error, HttpCall, SpacesdClient, TransportPreference,
+ testing::{MockAuth, MockServer},
+};
+use std::{
+ process::Command,
+ sync::{
+ Arc,
+ atomic::{AtomicUsize, Ordering},
+ },
+ time::Duration,
+};
+use tokio::{
+ io::{AsyncReadExt, AsyncWriteExt},
+ net::{TcpListener, TcpStream},
+ task::JoinSet,
+};
+
+const MODE: &str = "CUA_TEST_CONTROLLER_PROXY_MODE";
+const ADDRESS: &str = "CUA_TEST_CONTROLLER_PROXY_ADDRESS";
+const TOKEN: &str = "controller-fixture-canary";
+
+#[test]
+fn relay_rpc_uses_environment_proxy() {
+ if std::env::var_os(MODE).is_none() {
+ let mut failures = Vec::new();
+ for mode in [
+ "native",
+ "grpc-web",
+ "auto",
+ "http",
+ "refused",
+ "config",
+ "timeout",
+ "cancel",
+ "direct",
+ "bypass",
+ "tls-native",
+ "tls-web",
+ "tls-http",
+ ] {
+ 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", "relay_rpc_uses_environment_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);
+ }
+ if mode != "direct" {
+ child.env(
+ if mode.starts_with("tls-") {
+ "HTTPS_PROXY"
+ } else {
+ "HTTP_PROXY"
+ },
+ format!("http://{address}"),
+ );
+ if mode.starts_with("tls-") {
+ child.env("HTTP_PROXY", "http://invalid-http-proxy.invalid:9");
+ }
+ }
+ if mode == "config" {
+ child.env("HTTP_PROXY", "http://user:[email protected]");
+ }
+ if mode == "bypass" {
+ child.env("NO_PROXY", "127.0.0.0/8");
+ }
+ let output = child
+ .env(MODE, mode)
+ .env(ADDRESS, address.to_string())
+ .output()
+ .unwrap();
+ if !output.status.success() {
+ failures.push(format!(
+ "{mode}: {}\n{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ ));
+ }
+ }
+ assert!(failures.is_empty(), "{}", failures.join("\n"));
+ return;
+ }
+ tokio::runtime::Runtime::new().unwrap().block_on(run_case());
+}
+
+async fn head(socket: &mut TcpStream) -> String {
+ let mut head = Vec::new();
+ while !head.ends_with(b"\r\n\r\n") {
+ assert!(head.len() < 4096);
+ head.push(socket.read_u8().await.unwrap());
+ }
+ String::from_utf8(head).unwrap()
+}
+
+async fn run_case() {
+ let mode = std::env::var(MODE).unwrap();
+ let mock = MockServer::start(MockAuth {
+ token: Some(TOKEN.into()),
+ prefix: Some("/m/proxy-machine".into()),
+ ..Default::default()
+ })
+ .await;
+ let proxy = TcpListener::bind(std::env::var(ADDRESS).unwrap())
+ .await
+ .unwrap();
+ let upstream = mock.addr;
+ let attempts = Arc::new(AtomicUsize::new(0));
+ let accepted = Arc::new(tokio::sync::Notify::new());
+ let closed = Arc::new(tokio::sync::Notify::new());
+ let tls_rejected = Arc::new(tokio::sync::Notify::new());
+ let proxy_task = {
+ let mode = mode.clone();
+ let attempts = attempts.clone();
+ let accepted = accepted.clone();
+ let closed = closed.clone();
+ let tls_rejected = tls_rejected.clone();
+ tokio::spawn(async move {
+ let mut connections = JoinSet::new();
+ loop {
+ tokio::select! {
+ socket = proxy.accept() => {
+ let (mut socket, _) = socket.unwrap();
+ let attempt = attempts.fetch_add(1, Ordering::SeqCst);
+ let mode = mode.clone(); let accepted = accepted.clone(); let closed = closed.clone(); let tls_rejected = tls_rejected.clone();
+ connections.spawn(async move {
+ let connect = head(&mut socket).await;
+ let target = if mode == "refused" { upstream.to_string() } else if mode.starts_with("tls-") { "relay.invalid:443".into() } else { "relay.invalid:80".into() };
+ assert_eq!(connect, format!("CONNECT {target} HTTP/1.1\r\nhost: {target}\r\n\r\n"));
+ assert!(!connect.contains(TOKEN));
+ if mode == "refused" || (mode == "auto" && attempt == 0) {
+ socket.write_all(b"HTTP/1.1 403 private-reason\r\nContent-Length: 999\r\n\r\n").await.unwrap();
+ return;
+ }
+ if mode == "timeout" || mode == "cancel" {
+ accepted.notify_one();
+ let mut bytes = Vec::new();
+ tokio::time::timeout(Duration::from_secs(3), socket.read_to_end(&mut bytes)).await.unwrap().unwrap();
+ assert!(bytes.is_empty());
+ closed.notify_one();
+ return;
+ }
+ socket.write_all(b"HTTP/1.1 200 OK\r\n\r\n").await.unwrap();
+ if mode.starts_with("tls-") {
+ let identity = rcgen::generate_simple_self_signed(vec!["relay.invalid".into()]).unwrap();
+ let key = rustls::pki_types::PrivatePkcs8KeyDer::from(identity.signing_key.serialize_der());
+ let config = rustls::ServerConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
+ .with_safe_default_protocol_versions().unwrap().with_no_client_auth()
+ .with_single_cert(vec![identity.cert.der().clone()], key.into()).unwrap();
+ let hello = tokio_rustls::LazyConfigAcceptor::new(rustls::server::Acceptor::default(), socket).await.unwrap();
+ assert_eq!(hello.client_hello().server_name(), Some("relay.invalid"));
+ let alpn: Vec<_> = hello.client_hello().alpn().into_iter().flatten().collect();
+ if mode == "tls-native" { assert_eq!(alpn, vec![&b"h2"[..]]); }
+ else { assert!(alpn.is_empty()); } // Existing HTTP/1-only builder omits ALPN.
+ let error = hello.into_stream(Arc::new(config)).await.expect_err("untrusted origin must be rejected");
+ assert!(error.to_string().contains("UnknownCA"), "{error:?}");
+ tls_rejected.notify_one();
+ } else if mode == "http" {
+ let request = head(&mut socket).await;
+ assert!(request.starts_with("GET /m/proxy-machine/mcp?fixture=1 HTTP/1.1\r\n"));
+ assert!(request.contains(&format!("authorization: Bearer {TOKEN}\r\n")));
+ socket.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}").await.unwrap();
+ } else {
+ let mut origin = TcpStream::connect(upstream).await.unwrap();
+ let _ = tokio::io::copy_bidirectional(&mut socket, &mut origin).await;
+ }
+ });
+ },
+ completed = connections.join_next(), if !connections.is_empty() => { completed.unwrap().unwrap(); }
+ }
+ }
+ })
+ };
+ let endpoint = if matches!(mode.as_str(), "direct" | "bypass" | "refused" | "config") {
+ format!("http://{upstream}/m/proxy-machine")
+ } else if mode.starts_with("tls-") {
+ "https://relay.invalid/m/proxy-machine".into()
+ } else {
+ "http://relay.invalid/m/proxy-machine".into()
+ };
+ let preference = match mode.as_str() {
+ "grpc-web" | "tls-web" => TransportPreference::GrpcWeb,
+ "auto" | "refused" | "config" => TransportPreference::Auto,
+ _ => TransportPreference::Native,
+ };
+ let mut options = ConnectOptions::parse(&endpoint)
+ .unwrap()
+ .token(TOKEN)
+ .transport(preference)
+ .probe(!matches!(mode.as_str(), "http" | "tls-http"))
+ .probe_timeout(Duration::from_secs(2));
+ options.connect_timeout = if mode == "timeout" {
+ Duration::from_millis(100)
+ } else {
+ Duration::from_secs(2)
+ };
+ if mode == "cancel" {
+ let task = tokio::spawn(SpacesdClient::connect(options));
+ tokio::time::timeout(Duration::from_secs(2), accepted.notified())
+ .await
+ .unwrap();
+ task.abort();
+ let _ = task.await;
+ // Tonic owns its connection worker independently of the cancelled RPC.
+ // Its outstanding CONNECT must still end at the configured two-second budget.
+ tokio::time::timeout(Duration::from_secs(3), closed.notified())
+ .await
+ .expect("cancelled RPC must not leave an unbounded connection attempt");
+ } else {
+ let result = SpacesdClient::connect(options).await;
+ if matches!(
+ mode.as_str(),
+ "refused" | "config" | "timeout" | "tls-native" | "tls-web"
+ ) {
+ assert!(
+ matches!(&result, Err(Error::SpacesdNotAvailable { .. })),
+ "{result:?}"
+ );
+ let diagnostic = format!("{result:?}");
+ for secret in [TOKEN, "proxy-secret", "private-reason"] {
+ assert!(!diagnostic.contains(secret));
+ }
+ if mode == "timeout" {
+ tokio::time::timeout(Duration::from_secs(1), closed.notified())
+ .await
+ .unwrap();
+ }
+ assert_eq!(mock.state.observed.grpc_requests.load(Ordering::SeqCst), 0);
+ assert_eq!(
+ mock.state.observed.grpc_web_requests.load(Ordering::SeqCst),
+ 0
+ );
+ } else {
+ let client = result.expect("client must use its selected route");
+ if mode == "tls-http" {
+ let error = client
+ .http(HttpCall {
+ method: "GET".into(),
+ path: "/mcp".into(),
+ ..Default::default()
+ })
+ .await
+ .unwrap_err();
+ assert!(matches!(error, Error::Transport(_)), "{error:?}");
+ } else if mode == "http" {
+ let reply = client
+ .http(HttpCall {
+ method: "GET".into(),
+ path: "/mcp?fixture=1".into(),
+ ..Default::default()
+ })
+ .await
+ .unwrap();
+ assert_eq!(reply.body, b"{}");
+ } else {
+ assert_eq!(client.capabilities().await.unwrap().protocol_version, 1);
+ assert_eq!(
+ client
+ .run("echo proxy-ok")
+ .await
+ .unwrap()
+ .stdout_str()
+ .trim(),
+ "proxy-ok"
+ );
+ }
+ if mode == "auto" {
+ assert_eq!(mock.state.observed.grpc_requests.load(Ordering::SeqCst), 0);
+ assert!(mock.state.observed.grpc_web_requests.load(Ordering::SeqCst) > 0);
+ assert_eq!(attempts.load(Ordering::SeqCst), 2);
+ }
+ drop(client);
+ }
+ }
+ if matches!(mode.as_str(), "direct" | "bypass" | "config") {
+ assert_eq!(attempts.load(Ordering::SeqCst), 0);
+ } else {
+ assert!(attempts.load(Ordering::SeqCst) > 0);
+ }
+ if mode.starts_with("tls-") {
+ tokio::time::timeout(Duration::from_secs(2), tls_rejected.notified())
+ .await
+ .unwrap();
+ }
+ drop(mock);
+ assert!(!proxy_task.is_finished(), "proxy fixture failed");
+ proxy_task.abort();
+ let _ = proxy_task.await;
+}
diff --git a/libs/cua/crates/cua-spacesd-client/tests/native_roots.rs b/libs/cua/crates/cua-spacesd-client/tests/native_roots.rs
new file mode 100644
index 0000000000..86a04ad37f
--- /dev/null
+++ b/libs/cua/crates/cua-spacesd-client/tests/native_roots.rs
@@ -0,0 +1,253 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Managed TLS trust through the public client and a real HTTP CONNECT proxy.
+use base64::Engine;
+use cua_spacesd_client::{
+ ConnectOptions, HttpCall, SpacesdClient, TransportPreference,
+ testing::{MockAuth, MockServer},
+};
+use std::{path::Path, process::Command, sync::Arc, time::Duration};
+use tokio::{
+ io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
+ net::{TcpListener, TcpStream},
+};
+
+const MODE: &str = "CUA_TEST_NATIVE_ROOTS";
+const FIXTURE: &str = "CUA_TEST_NATIVE_ROOTS_FIXTURE";
+const TOKEN: &str = "native-roots-fixture-canary";
+
+fn pem(der: &[u8]) -> String {
+ format!(
+ "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----\n",
+ base64::engine::general_purpose::STANDARD.encode(der)
+ )
+}
+
+fn fixture(path: &Path, trust: &str) {
+ let mut ca = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
+ ca.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
+ ca.key_usages = vec![rcgen::KeyUsagePurpose::KeyCertSign];
+ let key = rcgen::KeyPair::generate().unwrap();
+ let root = ca.self_signed(&key).unwrap();
+ let issuer = rcgen::Issuer::new(ca, key);
+ let host = if trust == "wrong-host" {
+ "other.invalid"
+ } else {
+ "relay.invalid"
+ };
+ let leaf = rcgen::CertificateParams::new(vec![host.into()]).unwrap();
+ let leaf_key = rcgen::KeyPair::generate().unwrap();
+ let leaf = leaf.signed_by(&leaf_key, &issuer).unwrap();
+ std::fs::write(path.join("leaf.der"), leaf.der()).unwrap();
+ std::fs::write(path.join("key.der"), leaf_key.serialize_der()).unwrap();
+ let roots = match trust {
+ "missing" => return,
+ "empty" => String::new(),
+ "invalid" => pem(b"not a DER certificate"),
+ "bad-pem" => {
+ "-----BEGIN CERTIFICATE-----\n!not-base64!\n-----END CERTIFICATE-----\n".into()
+ }
+ "mixed" => pem(root.der()) + &pem(b"invalid DER"),
+ "unrelated" => pem(
+ rcgen::generate_simple_self_signed(vec!["unrelated.invalid".into()])
+ .unwrap()
+ .cert
+ .der(),
+ ),
+ _ => pem(root.der()),
+ };
+ std::fs::write(path.join("roots.pem"), roots).unwrap();
+}
+
+#[test]
+fn managed_roots_preserve_verified_tls() {
+ if let Ok(mode) = std::env::var(MODE) {
+ tokio::runtime::Runtime::new().unwrap().block_on(run(&mode));
+ return;
+ }
+ let mut failures = Vec::new();
+ for transport in ["native", "web", "http"] {
+ for trust in [
+ "trusted",
+ "wrong-host",
+ "unrelated",
+ "empty",
+ "missing",
+ "bad-pem",
+ "invalid",
+ "mixed",
+ ] {
+ let dir = tempfile::tempdir().unwrap();
+ fixture(dir.path(), trust);
+ let mode = format!("{transport}/{trust}");
+ let mut child = Command::new(std::env::current_exe().unwrap());
+ child.args([
+ "--exact",
+ "managed_roots_preserve_verified_tls",
+ "--nocapture",
+ ]);
+ for key in [
+ "HTTP_PROXY",
+ "http_proxy",
+ "HTTPS_PROXY",
+ "https_proxy",
+ "ALL_PROXY",
+ "all_proxy",
+ "NO_PROXY",
+ "no_proxy",
+ "REQUEST_METHOD",
+ "SSL_CERT_DIR",
+ ] {
+ child.env_remove(key);
+ }
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let address = listener.local_addr().unwrap();
+ drop(listener);
+ let output = child
+ .env(MODE, &mode)
+ .env(FIXTURE, dir.path())
+ .env("SSL_CERT_FILE", dir.path().join("roots.pem"))
+ .env("HTTPS_PROXY", format!("http://{address}"))
+ .env("CUA_TEST_NATIVE_ROOTS_PROXY", address.to_string())
+ .output()
+ .unwrap();
+ if !output.status.success() {
+ failures.push(format!(
+ "{mode}: {}\n{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ ));
+ }
+ }
+ }
+ assert!(failures.is_empty(), "{}", failures.join("\n"));
+}
+
+async fn head(socket: &mut (impl AsyncRead + Unpin)) -> String {
+ let mut data = Vec::new();
+ while !data.ends_with(b"\r\n\r\n") {
+ assert!(data.len() < 4096);
+ data.push(socket.read_u8().await.unwrap());
+ }
+ String::from_utf8(data).unwrap()
+}
+
+async fn run(mode: &str) {
+ let (transport, trust) = mode.split_once('/').unwrap();
+ let mock = MockServer::start(MockAuth {
+ token: Some(TOKEN.into()),
+ prefix: Some("/m/trusted".into()),
+ ..Default::default()
+ })
+ .await;
+ let proxy = TcpListener::bind(std::env::var("CUA_TEST_NATIVE_ROOTS_PROXY").unwrap())
+ .await
+ .unwrap();
+ let path = std::path::PathBuf::from(std::env::var_os(FIXTURE).unwrap());
+ let mut config = rustls::ServerConfig::builder_with_provider(Arc::new(
+ rustls::crypto::ring::default_provider(),
+ ))
+ .with_safe_default_protocol_versions()
+ .unwrap()
+ .with_no_client_auth()
+ .with_single_cert(
+ vec![std::fs::read(path.join("leaf.der")).unwrap().into()],
+ rustls::pki_types::PrivatePkcs8KeyDer::from(std::fs::read(path.join("key.der")).unwrap())
+ .into(),
+ )
+ .unwrap();
+ if transport == "native" {
+ config.alpn_protocols = vec![b"h2".to_vec()];
+ }
+ let transport_owned = transport.to_owned();
+ let trust_owned = trust.to_owned();
+ let upstream = mock.addr;
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = proxy.accept().await.unwrap();
+ assert_eq!(
+ head(&mut socket).await,
+ "CONNECT relay.invalid:443 HTTP/1.1\r\nhost: relay.invalid:443\r\n\r\n"
+ );
+ socket.write_all(b"HTTP/1.1 200 OK\r\n\r\n").await.unwrap();
+ let hello =
+ tokio_rustls::LazyConfigAcceptor::new(rustls::server::Acceptor::default(), socket)
+ .await
+ .unwrap();
+ assert_eq!(hello.client_hello().server_name(), Some("relay.invalid"));
+ let stream = hello.into_stream(Arc::new(config)).await;
+ if !matches!(trust_owned.as_str(), "trusted" | "mixed") {
+ assert!(
+ stream.is_err(),
+ "untrusted or wrong-host TLS must fail before application data"
+ );
+ return;
+ }
+ let mut stream = stream.expect("trusted matching-host TLS must succeed");
+ if transport_owned == "http" {
+ let request = head(&mut stream).await;
+ assert!(request.starts_with("GET /m/trusted/mcp?fixture=1 HTTP/1.1\r\n"));
+ assert!(request.contains(&format!("authorization: Bearer {TOKEN}\r\n")));
+ stream
+ .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}")
+ .await
+ .unwrap();
+ } else {
+ let mut origin = TcpStream::connect(upstream).await.unwrap();
+ let _ = tokio::io::copy_bidirectional(&mut stream, &mut origin).await;
+ }
+ });
+ let mut options = ConnectOptions::parse("https://relay.invalid/m/trusted")
+ .unwrap()
+ .token(TOKEN)
+ .transport(if transport == "web" {
+ TransportPreference::GrpcWeb
+ } else {
+ TransportPreference::Native
+ })
+ .probe(transport != "http")
+ .probe_timeout(Duration::from_secs(1));
+ options.connect_timeout = Duration::from_secs(2);
+ let result = async {
+ let client = SpacesdClient::connect(options).await?;
+ if transport == "http" {
+ let reply = client
+ .http(HttpCall {
+ method: "GET".into(),
+ path: "/mcp?fixture=1".into(),
+ ..Default::default()
+ })
+ .await?;
+ assert_eq!(reply.body, b"{}");
+ } else {
+ assert_eq!(client.capabilities().await?.protocol_version, 1);
+ }
+ Ok::<_, cua_spacesd_client::Error>(())
+ };
+ let result = tokio::time::timeout(Duration::from_secs(5), result)
+ .await
+ .unwrap();
+ if matches!(trust, "trusted" | "mixed") {
+ result.expect("SSL_CERT_FILE CA must be accepted");
+ } else {
+ let error = result.expect_err("verification must fail closed");
+ assert!(!format!("{error:?}").contains(TOKEN));
+ if trust == "invalid" {
+ assert!(
+ error
+ .to_string()
+ .contains("zero valid certificates found in native root store"),
+ "{error:?}"
+ );
+ }
+ }
+ if trust == "invalid" {
+ server.abort();
+ let _ = server.await;
+ } else {
+ tokio::time::timeout(Duration::from_secs(2), server)
+ .await
+ .unwrap()
+ .unwrap();
+ }
+}
diff --git a/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock b/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock
index b4ca493fdd..2367f92b82 100644
--- a/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock
+++ b/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock
@@ -1478,6 +1478,7 @@ dependencies = [
"prost",
"rand 0.9.5",
"rustls",
+ "rustls-native-certs",
"serde",
"serde_json",
"sha2 0.10.9",
@@ -1491,6 +1492,7 @@ dependencies = [
"tower",
"tracing",
"url",
+ "webpki-roots 1.0.9",
]
[[package]]
diff --git a/tests/e2e/cua-sdk/rust/Cargo.lock b/tests/e2e/cua-sdk/rust/Cargo.lock
index 2634a145c5..0cead01098 100644
--- a/tests/e2e/cua-sdk/rust/Cargo.lock
+++ b/tests/e2e/cua-sdk/rust/Cargo.lock
@@ -1501,6 +1501,7 @@ dependencies = [
"prost",
"rand 0.9.5",
"rustls",
+ "rustls-native-certs",
"serde",
"serde_json",
"sha2 0.10.9",
@@ -1514,6 +1515,7 @@ dependencies = [
"tower",
"tracing",
"url",
+ "webpki-roots 1.0.9",
]
[[package]]
diff --git a/tests/e2e/local-runtimes/Cargo.lock b/tests/e2e/local-runtimes/Cargo.lock
index 21ff15d8b4..b55411836f 100644
--- a/tests/e2e/local-runtimes/Cargo.lock
+++ b/tests/e2e/local-runtimes/Cargo.lock
@@ -919,6 +919,7 @@ dependencies = [
"prost",
"rand 0.9.5",
"rustls",
+ "rustls-native-certs",
"serde",
"serde_json",
"sha2 0.10.9",
@@ -932,6 +933,7 @@ dependencies = [
"tower",
"tracing",
"url",
+ "webpki-roots 1.0.9",
]
[[package]]