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.

cua-relay: stable probe contract header (x-cua-relay-route) (#6470)

cua-agents[bot]549e8ac6fe10
diff --git a/libs/cua-spacesd/crates/cua-relay/README.md b/libs/cua-spacesd/crates/cua-relay/README.md
index 1d349ed86a..b52e3c6ba8 100644
--- a/libs/cua-spacesd/crates/cua-relay/README.md
+++ b/libs/cua-spacesd/crates/cua-relay/README.md
@@ -595,6 +595,35 @@ jobs), snapshots up to 64 MiB, keyrings 4 MiB, the rest 64 KiB.
seven series are present from process start.
- `GET /v1/info` keeps `state_writable` (false while a store is failing).
+**Probe contract (`x-cua-relay-route`).** External probes match the
+status code and this header, never the wording of a refusal: the text a
+person reads changes with the relay's mode (phone support on answers an
+unknown id as an account computer) and with copy edits. Every response of
+`/healthz` (on every listener), `/readyz` and the client route
+(`/m/<id>/...`, host mode, any path forwarded to a computer) carries one of
+these values (`src/route_marker.rs`):
+
+| Value | Meaning |
+|---|---|
+| `ok` | `/healthz` (204), or `/readyz` ready (200) |
+| `not-ready` | `/readyz` 503 |
+| `forwarded` | the computer answered; status and body are its own (a computer cannot set this header itself) |
+| `refused-auth` | relay 401: no credential or one it does not accept |
+| `refused-denied` | relay 403: not shared, stopped sharing, revoked ticket |
+| `refused-limit` | relay 429 or 503: plan, rate or capacity limit |
+| `refused` | any other relay 4xx |
+| `offline` | the computer is not connected (502) |
+| `error` | any other relay 5xx |
+| `relay` | the relay answered itself without refusing (a redirect, a page it serves) |
+
+gRPC refusals (HTTP 200 with `grpc-status`) carry the marker of the
+relay's own status. An anonymous `GET /m/00000000-0000-0000-0000-000000000000/healthz`
+answers `401` with `refused-auth` in every mode (phone support on or off,
+admin token set or not, account sign-in on or off), and an edge or
+load-balancer error page carries no marker at all. The values are fixed:
+`tests/probe_contract.rs` fails if one changes or disappears. Changing them
+means changing the probes in trycua/cloud in the same release.
+
**Log lines to alert on** (stable message and `alert` field):
`state persist failed` (`alert=state_persist_failed`, with `store` and
`error`; at most one line per store per second, `since_last_line` counts
diff --git a/libs/cua-spacesd/crates/cua-relay/src/handover.rs b/libs/cua-spacesd/crates/cua-relay/src/handover.rs
index 62f2563957..8a597b5c08 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/handover.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/handover.rs
@@ -29,7 +29,7 @@
use std::fs::{File, OpenOptions, TryLockError};
use std::path::{Path, PathBuf};
-use axum::{http::StatusCode, routing::get, Router};
+use axum::{routing::get, Router};
/// The lock file's name in the state directory.
pub const LOCK_FILE: &str = ".relay.lock";
@@ -111,7 +111,7 @@ impl StateLock {
/// probe port, answering in standby too, when the main port does not
/// accept yet.
pub async fn serve_health(listener: tokio::net::TcpListener) -> std::io::Result<()> {
- let router = Router::new().route("/healthz", get(|| async { StatusCode::NO_CONTENT }));
+ let router = Router::new().route("/healthz", get(crate::route_marker::healthz));
axum::serve(listener, router).await
}
diff --git a/libs/cua-spacesd/crates/cua-relay/src/lib.rs b/libs/cua-spacesd/crates/cua-relay/src/lib.rs
index c5b72fef55..cde949eda8 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/lib.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/lib.rs
@@ -53,6 +53,7 @@ pub mod phone;
pub mod pool;
pub mod proxies;
pub mod push_api;
+pub mod route_marker;
pub mod server;
pub mod share_web;
pub mod storage;
diff --git a/libs/cua-spacesd/crates/cua-relay/src/route_marker.rs b/libs/cua-spacesd/crates/cua-relay/src/route_marker.rs
new file mode 100644
index 0000000000..4e923839a8
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-relay/src/route_marker.rs
@@ -0,0 +1,175 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The probe contract: `x-cua-relay-route`.
+//!
+//! Monitoring must not depend on the wording of a refusal. The text a
+//! person reads ("sign in: …") changes with the relay's mode and with
+//! copy edits; on 4 Nov 2026 turning phone support on changed it and two
+//! probes that matched it paged falsely (INC-27). Probes match the status
+//! code and this header instead.
+//!
+//! Every response of the client route (`/m/<id>/…`, host mode, and any
+//! other path the relay hands to a computer) and of `/healthz` and
+//! `/readyz` carries the header, with one value of [`RouteMarker`]. The
+//! values are stable: changing or removing one is a breaking change for
+//! every probe (see `tests/probe_contract.rs`, and "Probe contract" in the
+//! README). A computer cannot set it: whatever a computer sends under that
+//! name is replaced with `forwarded`.
+
+use axum::http::{HeaderValue, StatusCode};
+use axum::response::Response;
+
+use crate::conn_metrics::{Offline, RelayStatus};
+
+/// The header name.
+pub const HEADER: &str = "x-cua-relay-route";
+
+/// What answered a request, and why, in one fixed word.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum RouteMarker {
+ /// `/healthz` and a ready `/readyz`: the relay is up.
+ Ok,
+ /// `/readyz` answering 503: the state volume or a store is failing.
+ NotReady,
+ /// The computer answered; status and body are its own.
+ Forwarded,
+ /// 401 from the relay: no credential, or one it does not accept. The
+ /// refusal an anonymous probe of `/m/<unknown id>/…` gets in every mode.
+ RefusedAuth,
+ /// 403 from the relay: signed in but not allowed (not shared, stopped
+ /// sharing, revoked ticket, old computer for a phone).
+ RefusedDenied,
+ /// 429 or 503 from the relay: a plan, rate or capacity limit.
+ RefusedLimit,
+ /// Any other 4xx from the relay (bad request, not found).
+ Refused,
+ /// The computer is not connected (502).
+ Offline,
+ /// Any other 5xx from the relay (tunnel or handshake failure).
+ Error,
+ /// The relay answered itself without refusing: a redirect (legacy share
+ /// URL, share sign-in) or a page it serves.
+ Relay,
+}
+
+impl RouteMarker {
+ /// Every value, for tests and docs.
+ pub const ALL: [RouteMarker; 10] = [
+ RouteMarker::Ok,
+ RouteMarker::NotReady,
+ RouteMarker::Forwarded,
+ RouteMarker::RefusedAuth,
+ RouteMarker::RefusedDenied,
+ RouteMarker::RefusedLimit,
+ RouteMarker::Refused,
+ RouteMarker::Offline,
+ RouteMarker::Error,
+ RouteMarker::Relay,
+ ];
+
+ /// The header value. Fixed: see the module docs.
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ RouteMarker::Ok => "ok",
+ RouteMarker::NotReady => "not-ready",
+ RouteMarker::Forwarded => "forwarded",
+ RouteMarker::RefusedAuth => "refused-auth",
+ RouteMarker::RefusedDenied => "refused-denied",
+ RouteMarker::RefusedLimit => "refused-limit",
+ RouteMarker::Refused => "refused",
+ RouteMarker::Offline => "offline",
+ RouteMarker::Error => "error",
+ RouteMarker::Relay => "relay",
+ }
+ }
+
+ /// The marker of a relay-made response with HTTP status `status`.
+ pub fn of_refusal(status: StatusCode) -> Self {
+ match status.as_u16() {
+ 401 => RouteMarker::RefusedAuth,
+ 403 => RouteMarker::RefusedDenied,
+ 429 | 503 => RouteMarker::RefusedLimit,
+ s if (400..500).contains(&s) => RouteMarker::Refused,
+ s if s >= 500 => RouteMarker::Error,
+ _ => RouteMarker::Relay,
+ }
+ }
+}
+
+/// `GET /healthz` on every listener (main, probe port, STUN-only): 204 and
+/// `ok`.
+pub async fn healthz() -> Response {
+ use axum::response::IntoResponse as _;
+ let mut response = StatusCode::NO_CONTENT.into_response();
+ stamp(&mut response, RouteMarker::Ok);
+ response
+}
+
+/// Sets the header on `response`, replacing any value already there.
+pub(crate) fn stamp(response: &mut Response, marker: RouteMarker) {
+ response
+ .headers_mut()
+ .insert(HEADER, HeaderValue::from_static(marker.as_str()));
+}
+
+/// Stamps a finished client-route response. A forwarded response was
+/// already stamped `forwarded` (by `harden_response`, over anything the
+/// computer sent); everything else the relay made itself.
+pub(crate) fn stamp_client_route(response: &mut Response) {
+ if response.headers().contains_key(HEADER) {
+ return;
+ }
+ let ext = response.extensions();
+ let marker = if ext.get::<Offline>().is_some() {
+ RouteMarker::Offline
+ } else if let Some(RelayStatus(status)) = ext.get::<RelayStatus>() {
+ // Also for gRPC refusals, sent as HTTP 200 with a grpc-status: the
+ // relay's own status is what the marker reports.
+ RouteMarker::of_refusal(*status)
+ } else {
+ RouteMarker::Relay
+ };
+ stamp(response, marker);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// The wire values are the contract. A change here breaks probes in
+ /// trycua/cloud: update them in the same change, never after.
+ #[test]
+ fn values_are_fixed() {
+ let values: Vec<_> = RouteMarker::ALL.iter().map(|m| m.as_str()).collect();
+ assert_eq!(
+ values,
+ [
+ "ok",
+ "not-ready",
+ "forwarded",
+ "refused-auth",
+ "refused-denied",
+ "refused-limit",
+ "refused",
+ "offline",
+ "error",
+ "relay",
+ ]
+ );
+ assert_eq!(HEADER, "x-cua-relay-route");
+ }
+
+ #[test]
+ fn refusal_classes() {
+ let of = |s: u16| RouteMarker::of_refusal(StatusCode::from_u16(s).unwrap());
+ assert_eq!(of(401), RouteMarker::RefusedAuth);
+ assert_eq!(of(403), RouteMarker::RefusedDenied);
+ assert_eq!(of(429), RouteMarker::RefusedLimit);
+ assert_eq!(of(503), RouteMarker::RefusedLimit);
+ assert_eq!(of(400), RouteMarker::Refused);
+ assert_eq!(of(404), RouteMarker::Refused);
+ assert_eq!(of(502), RouteMarker::Error);
+ assert_eq!(of(308), RouteMarker::Relay);
+ }
+}
diff --git a/libs/cua-spacesd/crates/cua-relay/src/server.rs b/libs/cua-spacesd/crates/cua-relay/src/server.rs
index 995f1cee4f..65e8249d77 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/server.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/server.rs
@@ -618,7 +618,7 @@ impl Relay {
pub fn router(&self) -> Router {
Router::new()
// Liveness: the process answers. Never touches the disk.
- .route("/healthz", get(|| async { StatusCode::NO_CONTENT }))
+ .route("/healthz", get(crate::route_marker::healthz))
// The state volume: a write probe, free space, each store's
// last write (503 when the probe or a store fails).
.route("/readyz", get(readyz))
@@ -1595,12 +1595,17 @@ async fn readyz(State(relay): State<Relay>, headers: HeaderMap) -> Response {
} else {
body["mesh_nodes_connected"] = serde_json::json!(relay.mesh.connected());
}
- let status = if ready {
- StatusCode::OK
+ let (status, marker) = if ready {
+ (StatusCode::OK, crate::route_marker::RouteMarker::Ok)
} else {
- StatusCode::SERVICE_UNAVAILABLE
+ (
+ StatusCode::SERVICE_UNAVAILABLE,
+ crate::route_marker::RouteMarker::NotReady,
+ )
};
- (status, axum::Json(body)).into_response()
+ let mut response = (status, axum::Json(body)).into_response();
+ crate::route_marker::stamp(&mut response, marker);
+ response
}
/// `GET /metrics`: the state counters in Prometheus text format (no
@@ -2544,6 +2549,8 @@ async fn proxy(state: State<Relay>, request: Request) -> Response {
response
.extensions_mut()
.insert(crate::conn_metrics::Kind::Client);
+ // The probe contract (`x-cua-relay-route`, src/route_marker.rs).
+ crate::route_marker::stamp_client_route(&mut response);
response
}
@@ -3185,6 +3192,12 @@ fn harden_response(
share: Option<&ShareCtx>,
phone: bool,
) {
+ // The computer answered. It cannot claim to be the relay: whatever it
+ // sent under the probe-contract header is replaced.
+ headers.insert(
+ crate::route_marker::HEADER,
+ HeaderValue::from_static(crate::route_marker::RouteMarker::Forwarded.as_str()),
+ );
match share {
Some(sh) if sh.isolated => {
headers.remove("service-worker-allowed");
diff --git a/libs/cua-spacesd/crates/cua-relay/tests/probe_contract.rs b/libs/cua-spacesd/crates/cua-relay/tests/probe_contract.rs
new file mode 100644
index 0000000000..d717507e7e
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-relay/tests/probe_contract.rs
@@ -0,0 +1,290 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The probe contract (`x-cua-relay-route`, src/route_marker.rs): what
+//! external monitoring matches instead of refusal wording (INC-27).
+//!
+//! Checked in every mode the hosted and self-hosted relays run in:
+//! {phone support off, on} x {admin token unset, set} x {account sign-in
+//! off, on}. A failure here means a probe in trycua/cloud
+//! (blackbox `spaces_relay_*` modules, the status-page checker) would
+//! page: change them in the same release, never after.
+
+use std::sync::Arc;
+use std::time::Duration;
+
+use cua_push::{MockProvider, PushHub, Registry};
+use cua_relay::client::JoinConfig;
+use cua_relay::oidc::testing::FakeIssuer;
+use cua_relay::oidc::{OidcConfig, OidcValidator};
+use cua_relay::push_api::PushConfig;
+use cua_relay::route_marker::{RouteMarker, HEADER};
+use cua_relay::server::{Relay, RelayConfig};
+use tokio::net::TcpListener;
+use tokio_util::sync::CancellationToken;
+
+const ISSUER: &str = "https://auth.test/realms/cua";
+const TOKEN: &str = "probe-contract-machine-token";
+const MACHINE: &str = "probe-contract-machine";
+/// The id the blackbox probe asks for: nobody registers it.
+const NIL: &str = "00000000-0000-0000-0000-000000000000";
+
+#[derive(Clone, Copy, Debug)]
+struct Mode {
+ push: bool,
+ admin: bool,
+ oidc: bool,
+}
+
+fn modes() -> Vec<Mode> {
+ let mut all = Vec::new();
+ for push in [false, true] {
+ for admin in [false, true] {
+ for oidc in [false, true] {
+ all.push(Mode { push, admin, oidc });
+ }
+ }
+ }
+ all
+}
+
+struct Env {
+ base: String,
+ http: reqwest::Client,
+ stop: CancellationToken,
+ tasks: Vec<tokio::task::JoinHandle<()>>,
+}
+
+impl Drop for Env {
+ fn drop(&mut self) {
+ self.stop.cancel();
+ for t in &self.tasks {
+ t.abort();
+ }
+ }
+}
+
+/// A relay in `mode` with one static-token computer joined. The computer's
+/// `/health` answers 200 and tries to claim the relay's marker.
+async fn start(mode: Mode) -> Env {
+ let issuer = FakeIssuer::new(ISSUER);
+ let relay = Relay::new(RelayConfig {
+ tokens: vec![TOKEN.into()],
+ admin_token: mode.admin.then(|| "probe-contract-admin".into()),
+ oidc: mode.oidc.then(|| {
+ Arc::new(OidcValidator::with_jwks(
+ OidcConfig::new(ISSUER),
+ issuer.jwks(),
+ ))
+ }),
+ push: mode.push.then(|| {
+ PushConfig::new(Arc::new(PushHub::new(
+ Registry::in_memory(),
+ Arc::new(MockProvider::new()),
+ )))
+ }),
+ ..RelayConfig::default()
+ });
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}", listener.local_addr().unwrap());
+ let serving = relay.clone();
+ let mut tasks = vec![tokio::spawn(async move {
+ let _ = serving.serve(listener, std::future::pending()).await;
+ })];
+
+ let local = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let local_addr = local.local_addr().unwrap();
+ tasks.push(tokio::spawn(async move {
+ let app = axum::Router::new().route(
+ "/health",
+ axum::routing::get(|| async { ([(HEADER, "refused-auth")], "fine") }),
+ );
+ let _ = axum::serve(local, app).await;
+ }));
+ let config = JoinConfig::new(
+ base.replace("http://", "ws://"),
+ TOKEN.into(),
+ MACHINE.into(),
+ local_addr,
+ );
+ let stop = CancellationToken::new();
+ let stopped = stop.clone();
+ tasks.push(tokio::spawn(async move {
+ let _ = cua_relay::client::session(&config, &stopped).await;
+ }));
+ tokio::time::timeout(Duration::from_secs(5), async {
+ while !relay.machine_ids().contains(&MACHINE.to_string()) {
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ })
+ .await
+ .expect("computer never came online");
+ Env {
+ base,
+ http: reqwest::Client::builder().no_proxy().build().unwrap(),
+ stop,
+ tasks,
+ }
+}
+
+fn marker(r: &reqwest::Response) -> Option<String> {
+ r.headers()
+ .get(HEADER)
+ .map(|v| v.to_str().unwrap().to_owned())
+}
+
+#[tokio::test]
+async fn health_carries_ok_in_every_mode() {
+ for mode in modes() {
+ let env = start(mode).await;
+ let r = env
+ .http
+ .get(format!("{}/healthz", env.base))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(r.status(), 204, "{mode:?}");
+ assert_eq!(marker(&r).as_deref(), Some("ok"), "{mode:?}");
+
+ let r = env
+ .http
+ .get(format!("{}/readyz", env.base))
+ .send()
+ .await
+ .unwrap();
+ let expected = if r.status() == 200 { "ok" } else { "not-ready" };
+ assert_eq!(
+ marker(&r).as_deref(),
+ Some(expected),
+ "{mode:?} {}",
+ r.status()
+ );
+ }
+}
+
+/// The blackbox probe: an anonymous GET of an id nobody registered. The
+/// refusal's wording differs by mode (that is what paged in INC-27); its
+/// status and marker do not.
+#[tokio::test]
+async fn an_anonymous_unknown_id_is_refused_auth_in_every_mode() {
+ let mut bodies = std::collections::BTreeSet::new();
+ for mode in modes() {
+ let env = start(mode).await;
+ // With phone support off the machine's own `/health` is forwarded
+ // without a credential (so an unknown id is `offline`, not refused).
+ if !mode.push {
+ let r = env
+ .http
+ .get(format!("{}/m/{NIL}/health", env.base))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(r.status(), 502, "{mode:?}");
+ assert_eq!(marker(&r).as_deref(), Some("offline"), "{mode:?}");
+ }
+ let paths = if mode.push {
+ &["healthz", "health", "cua.env.v1.SystemService/Health"][..]
+ } else {
+ &["healthz", "cua.env.v1.SystemService/Health"][..]
+ };
+ for path in paths {
+ let r = env
+ .http
+ .get(format!("{}/m/{NIL}/{path}", env.base))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(r.status(), 401, "{mode:?} {path}");
+ assert_eq!(
+ marker(&r).as_deref(),
+ Some("refused-auth"),
+ "{mode:?} {path}"
+ );
+ bodies.insert(r.text().await.unwrap());
+ }
+ // A gRPC caller gets HTTP 200 with grpc-status 16; same marker.
+ let r = env
+ .http
+ .post(format!(
+ "{}/m/{NIL}/cua.env.v1.SystemService/Health",
+ env.base
+ ))
+ .header("content-type", "application/grpc-web+proto")
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(r.status(), 200, "{mode:?}");
+ assert_eq!(
+ r.headers().get("grpc-status").map(|v| v.to_str().unwrap()),
+ Some("16"),
+ "{mode:?}"
+ );
+ assert_eq!(marker(&r).as_deref(), Some("refused-auth"), "{mode:?}");
+ }
+ // The point of the contract: the text is free to vary.
+ assert!(bodies.len() > 1, "{bodies:?}");
+}
+
+#[tokio::test]
+async fn forwarded_and_offline_in_every_mode() {
+ for mode in modes() {
+ let env = start(mode).await;
+ // The computer answered; its attempt to send the relay's marker is replaced.
+ let r = env
+ .http
+ .get(format!("{}/m/{MACHINE}/health", env.base))
+ .bearer_auth(TOKEN)
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(r.status(), 200, "{mode:?}");
+ let values: Vec<_> = r.headers().get_all(HEADER).iter().collect();
+ assert_eq!(values.len(), 1, "{mode:?} {values:?}");
+ assert_eq!(marker(&r).as_deref(), Some("forwarded"), "{mode:?}");
+
+ if !mode.push || !mode.oidc {
+ // With phone support and sign-in on, an unknown id is answered as
+ // an account computer (refused-auth above), never as offline.
+ let r = env
+ .http
+ .get(format!("{}/m/not-connected-here/health", env.base))
+ .bearer_auth(TOKEN)
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(r.status(), 502, "{mode:?}");
+ assert_eq!(marker(&r).as_deref(), Some("offline"), "{mode:?}");
+ }
+ }
+}
+
+#[test]
+fn every_value_is_a_valid_header_value() {
+ for m in RouteMarker::ALL {
+ let v = m.as_str();
+ assert!(
+ !v.is_empty() && v.bytes().all(|b| b.is_ascii_lowercase() || b == b'-'),
+ "{v}"
+ );
+ }
+}
+
+/// The probe port (`CUA_RELAY_HEALTH_LISTEN`) and STUN-only pods answer
+/// `/healthz` from their own listener: same status, same marker.
+#[tokio::test]
+async fn the_probe_port_carries_ok() {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}", listener.local_addr().unwrap());
+ let task = tokio::spawn(cua_relay::handover::serve_health(listener));
+ let r = reqwest::Client::builder()
+ .no_proxy()
+ .build()
+ .unwrap()
+ .get(format!("{base}/healthz"))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(r.status(), 204);
+ assert_eq!(marker(&r).as_deref(), Some("ok"));
+ task.abort();
+}