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.

relay: read-only GET /internal/v1/devices/{id} for in-cluster callers (CUA-2339) (#6003)

cua-agents[bot]153a79718312
diff --git a/libs/cua-spacesd/crates/cua-relay/HOSTED.md b/libs/cua-spacesd/crates/cua-relay/HOSTED.md
index c8d4fe3f9f..6000e85feb 100644
--- a/libs/cua-spacesd/crates/cua-relay/HOSTED.md
+++ b/libs/cua-spacesd/crates/cua-relay/HOSTED.md
@@ -60,7 +60,7 @@ These flags exist only with the feature on (`cua-relay --help`).
| `CUA_RELAY_SPACES_API_TOKEN_URL` | the issuer's token endpoint | Where the relay gets its client-credentials token. |
| `CUA_RELAY_SPACES_API_CLIENT_ID` / `_CLIENT_SECRET` | `cua-relay-svc` / unset | The relay's service client. |
| `CUA_RELAY_ORG_CACHE_SECS` | `60` | How long a team access answer (yes or no) is cached. A miss with the API down refuses team access (personal machines are unaffected). |
-| `CUA_RELAY_INTERNAL_TOKEN` | unset | Bearer token the Spaces API presents on `POST /internal/v1/membership-changed {org, sub?}`, which drops the cached answers and re-checks open sessions, and on `GET /internal/v1/records/{id}` -> `{id, owner_sub, platform, kind}` (404 `record_not_found`), which the API checks before binding a machine to an org. Under `org`, a bound record is reachable only while its owner is a member of the same org. Also guards `DELETE /internal/v1/accounts/{sub}` (see [Account erasure](#account-erasure)). Use at least 32 characters (`openssl rand -hex 32`). The relay refuses to start with a shorter token. No token while `CUA_RELAY_TEAMS_SOURCE=org` or `CUA_RELAY_TEAM_ONLY_SHARING=on` logs a loud error and the relay keeps serving; `CUA_RELAY_STRICT_INTERNAL_TOKEN=on` makes that a startup failure too. The token is never printed. Keep `/internal/` off the ingress. |
+| `CUA_RELAY_INTERNAL_TOKEN` | unset | Bearer token the Spaces API presents on `POST /internal/v1/membership-changed {org, sub?}`, which drops the cached answers and re-checks open sessions, and on `GET /internal/v1/records/{id}` -> `{id, owner_sub, platform, kind}` (404 `record_not_found`), which the API checks before binding a machine to an org. Under `org`, a bound record is reachable only while its owner is a member of the same org. Also guards `DELETE /internal/v1/accounts/{sub}` (see [Account erasure](#account-erasure)). Also guards the read-only `GET /internal/v1/devices/{id}` -> `{id, account, public_jwk, state, enrolled, revoked}` (404 `device_not_found`), which in-cluster services call to check that a device is enrolled and not revoked. Use at least 32 characters (`openssl rand -hex 32`). The relay refuses to start with a shorter token. No token while `CUA_RELAY_TEAMS_SOURCE=org` or `CUA_RELAY_TEAM_ONLY_SHARING=on` logs a loud error and the relay keeps serving; `CUA_RELAY_STRICT_INTERNAL_TOKEN=on` makes that a startup failure too. The token is never printed. Keep `/internal/` off the ingress. |
| `CUA_RELAY_STRICT_INTERNAL_TOKEN` | `off` | `on` refuses to start when the internal token is missing while the organization teams source or team-only sharing is on (and team-only sharing lacks the service client secret). Off logs an error and keeps serving, so an existing deployment stays up. A token shorter than 32 characters is always refused. |
| `CUA_RELAY_LIVE_SESSION_AFTER_SECS` | `10` | How long a stream must stay open before its session counts as live (short calls never do). |
| `CUA_RELAY_POSTHOG_KEY` | unset | PostHog project capture key: hourly `relay_usage` and `relay_allowance_soft_limit` events (hashed user ids, no emails). Unset: usage goes to the logs (`cua_relay::usage`) only. |
diff --git a/libs/cua-spacesd/crates/cua-relay/src/hosted.rs b/libs/cua-spacesd/crates/cua-relay/src/hosted.rs
index e3a0f99c4a..63b345fae2 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/hosted.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/hosted.rs
@@ -287,6 +287,7 @@ pub(crate) fn routes(relay: &Relay) -> Router<Relay> {
)
.route("/internal/v1/records/{id}", get(internal_record))
.route("/internal/v1/shared", get(internal_shared))
+ .route("/internal/v1/devices/{id}", get(internal_device))
.route(
"/internal/v1/accounts/{sub}",
axum::routing::delete(crate::account_erase::erase),
@@ -449,6 +450,67 @@ async fn internal_record(
axum::Json(record_facts(&record)).into_response()
}
+/// `GET /internal/v1/devices/{id}`: one client device, read-only, for the
+/// in-cluster services that must know whether a device is enrolled and
+/// not revoked. 200 `{id, account,
+/// public_jwk: {kty: "EC", crv: "P-256", x, y}, state:
+/// pending|enrolled|expired|revoked, enrolled, revoked}`; 404
+/// `device_not_found`. Needs the internal token, like every
+/// `/internal/v1/*` route (and the ingress never routes `/internal/`).
+async fn internal_device(
+ State(relay): State<Relay>,
+ axum::extract::Path(id): axum::extract::Path<String>,
+ headers: HeaderMap,
+) -> Response {
+ if let Err(r) = require_internal(&relay, &headers) {
+ return r;
+ }
+ let not_found = || {
+ (
+ StatusCode::NOT_FOUND,
+ axum::Json(serde_json::json!({
+ "error": "device_not_found",
+ "detail": "no such device",
+ })),
+ )
+ .into_response()
+ };
+ if id.len() > 64 || !id.starts_with(crate::devices::DEVICE_ID_PREFIX) {
+ return not_found();
+ }
+ let Some(device) = relay.devices.get(&id) else {
+ return not_found();
+ };
+ axum::Json(device_facts(&device, crate::assertion::now_secs())).into_response()
+}
+
+/// The issuer's view of a device (`/internal/v1/devices/{id}`): its key as a
+/// JWK, so the issuer can match it against a device proof's `jwk` header.
+pub(crate) fn device_facts(device: &crate::devices::DeviceRecord, now: u64) -> serde_json::Value {
+ use crate::devices::DeviceState;
+ let state = device.state(now);
+ let public_jwk = crate::devices::decode_public_key(&device.public_key)
+ .ok()
+ .map(|raw| {
+ use base64::Engine as _;
+ let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;
+ serde_json::json!({
+ "kty": "EC",
+ "crv": "P-256",
+ "x": b64.encode(&raw[1..33]),
+ "y": b64.encode(&raw[33..65]),
+ })
+ });
+ serde_json::json!({
+ "id": device.id,
+ "account": device.account,
+ "public_jwk": public_jwk,
+ "state": state,
+ "enrolled": state == DeviceState::Enrolled,
+ "revoked": state == DeviceState::Revoked,
+ })
+}
+
/// `GET /internal/v1/shared?sub=&email=&email_verified=`: what other
/// accounts share directly with this one, for the "Shared with you" list
/// on the web (CUA-1764). `shared` are the records the account reaches now
diff --git a/libs/cua-spacesd/crates/cua-relay/tests/internal_devices.rs b/libs/cua-spacesd/crates/cua-relay/tests/internal_devices.rs
new file mode 100644
index 0000000000..275b5a1a00
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-relay/tests/internal_devices.rs
@@ -0,0 +1,219 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! `GET /internal/v1/devices/{id}` (CUA-2339): the read-only device lookup
+//! in-cluster services call. It needs the internal token, is
+//! absent when none is configured, refuses proxied requests, and reports
+//! the device's account, key and enrollment state.
+// The hosted relay's optional features (Cargo feature `hosted`).
+#![cfg(feature = "hosted")]
+
+use std::sync::Arc;
+
+use base64::Engine as _;
+use cua_relay::devices::{register_message, session_message};
+use cua_relay::oidc::testing::FakeIssuer;
+use cua_relay::oidc::{OidcConfig, OidcValidator};
+use cua_relay::org_access::OrgAccessConfig;
+use cua_relay::server::{Relay, RelayConfig};
+use reqwest::StatusCode;
+use ring::signature::KeyPair as _;
+use serde_json::{json, Value};
+
+const ISSUER: &str = "https://auth.test/realms/cua";
+const INTERNAL: &str = "internal-secret-for-device-lookup";
+
+fn b64() -> base64::engine::GeneralPurpose {
+ base64::engine::general_purpose::URL_SAFE_NO_PAD
+}
+
+async fn start(issuer: &FakeIssuer, internal: Option<&str>) -> String {
+ let relay = Relay::new(RelayConfig {
+ oidc: Some(Arc::new(OidcValidator::with_jwks(
+ OidcConfig::new(ISSUER),
+ issuer.jwks(),
+ ))),
+ org_access: OrgAccessConfig {
+ internal_token: internal.map(str::to_owned),
+ ..Default::default()
+ },
+ ..RelayConfig::default()
+ });
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}", listener.local_addr().unwrap());
+ tokio::spawn(async move {
+ let _ = relay.serve(listener, std::future::pending()).await;
+ });
+ base
+}
+
+struct Device {
+ pair: ring::signature::EcdsaKeyPair,
+ id: String,
+}
+
+impl Device {
+ fn new() -> Self {
+ let rng = ring::rand::SystemRandom::new();
+ let alg = &ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING;
+ let pkcs8 = ring::signature::EcdsaKeyPair::generate_pkcs8(alg, &rng).unwrap();
+ let pair = ring::signature::EcdsaKeyPair::from_pkcs8(alg, pkcs8.as_ref(), &rng).unwrap();
+ let id = cua_relay::devices::device_id(pair.public_key().as_ref());
+ Self { pair, id }
+ }
+
+ fn sign(&self, message: &str) -> String {
+ let rng = ring::rand::SystemRandom::new();
+ b64().encode(self.pair.sign(&rng, message.as_bytes()).unwrap().as_ref())
+ }
+
+ /// Enrolls by a fresh sign-in and opens a session.
+ async fn enroll(&self, base: &str, token: &str) -> String {
+ let http = reqwest::Client::new();
+ let ts = cua_relay::assertion::now_secs();
+ let r = http
+ .post(format!("{base}/v1/devices"))
+ .bearer_auth(token)
+ .json(&json!({
+ "public_key": b64().encode(self.pair.public_key().as_ref()),
+ "name": "laptop",
+ "ts": ts,
+ "sig": self.sign(&register_message(&self.id, ts)),
+ "bootstrap": true,
+ }))
+ .send()
+ .await
+ .unwrap();
+ assert!(r.status().is_success(), "{}", r.status());
+ let r = http
+ .post(format!("{base}/v1/devices/session"))
+ .bearer_auth(token)
+ .json(&json!({
+ "device_id": self.id,
+ "ts": ts,
+ "sig": self.sign(&session_message(&self.id, ts)),
+ }))
+ .send()
+ .await
+ .unwrap();
+ assert!(r.status().is_success(), "{}", r.status());
+ let v: Value = r.json().await.unwrap();
+ v["session"].as_str().unwrap().to_owned()
+ }
+}
+
+async fn lookup(base: &str, id: &str, token: Option<&str>) -> (StatusCode, String) {
+ let mut req = reqwest::Client::new().get(format!("{base}/internal/v1/devices/{id}"));
+ if let Some(t) = token {
+ req = req.bearer_auth(t);
+ }
+ let r = req.send().await.unwrap();
+ (r.status(), r.text().await.unwrap())
+}
+
+fn token(issuer: &FakeIssuer, sub: &str) -> String {
+ issuer.set_auth_time(sub, cua_relay::assertion::now_secs() as i64);
+ issuer.token(sub, None, "cua-relay", 300)
+}
+
+#[tokio::test]
+async fn reports_an_enrolled_device_with_its_key_and_account() {
+ let issuer = FakeIssuer::new(ISSUER);
+ let base = start(&issuer, Some(INTERNAL)).await;
+ let device = Device::new();
+ device.enroll(&base, &token(&issuer, "ada")).await;
+
+ let (status, body) = lookup(&base, &device.id, Some(INTERNAL)).await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ let v: Value = serde_json::from_str(&body).unwrap();
+ assert_eq!(v["id"], device.id);
+ assert_eq!(v["account"], "ada");
+ assert_eq!(v["state"], "enrolled");
+ assert_eq!(v["enrolled"], true);
+ assert_eq!(v["revoked"], false);
+ let public = device.pair.public_key().as_ref();
+ assert_eq!(
+ v["public_jwk"],
+ json!({
+ "kty": "EC", "crv": "P-256",
+ "x": b64().encode(&public[1..33]),
+ "y": b64().encode(&public[33..65]),
+ })
+ );
+
+ // Unknown ids and malformed ids are a plain 404.
+ for id in ["dev_000000000000000000000000", "not-a-device"] {
+ let (status, body) = lookup(&base, id, Some(INTERNAL)).await;
+ assert_eq!(status, StatusCode::NOT_FOUND);
+ assert!(body.contains("device_not_found"), "{body}");
+ }
+}
+
+#[tokio::test]
+async fn a_revoked_device_reads_as_revoked() {
+ let issuer = FakeIssuer::new(ISSUER);
+ let base = start(&issuer, Some(INTERNAL)).await;
+ let device = Device::new();
+ let ada = token(&issuer, "ada");
+ let session = device.enroll(&base, &ada).await;
+ let r = reqwest::Client::new()
+ .delete(format!("{base}/v1/devices/{}", device.id))
+ .bearer_auth(&ada)
+ .header("x-cua-device-session", session)
+ .send()
+ .await
+ .unwrap();
+ assert!(r.status().is_success(), "{}", r.status());
+ let (status, body) = lookup(&base, &device.id, Some(INTERNAL)).await;
+ assert_eq!(status, StatusCode::OK);
+ let v: Value = serde_json::from_str(&body).unwrap();
+ assert_eq!(v["state"], "revoked");
+ assert_eq!(v["enrolled"], false);
+ assert_eq!(v["revoked"], true);
+}
+
+#[tokio::test]
+async fn needs_the_internal_token_and_a_direct_request() {
+ let issuer = FakeIssuer::new(ISSUER);
+ let base = start(&issuer, Some(INTERNAL)).await;
+ let device = Device::new();
+ let ada = token(&issuer, "ada");
+ device.enroll(&base, &ada).await;
+
+ // No token, a wrong token, an account token: refused.
+ assert_eq!(
+ lookup(&base, &device.id, None).await.0,
+ StatusCode::UNAUTHORIZED
+ );
+ assert_eq!(
+ lookup(&base, &device.id, Some("internal-secret-for-device-lookuX"))
+ .await
+ .0,
+ StatusCode::UNAUTHORIZED
+ );
+ assert_eq!(
+ lookup(&base, &device.id, Some(&ada)).await.0,
+ StatusCode::UNAUTHORIZED
+ );
+ // Through a proxy (the ingress): as if the route did not exist.
+ let r = reqwest::Client::new()
+ .get(format!("{base}/internal/v1/devices/{}", device.id))
+ .bearer_auth(INTERNAL)
+ .header("X-Forwarded-For", "203.0.113.9")
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(r.status(), StatusCode::NOT_FOUND);
+ assert_eq!(r.text().await.unwrap(), "not found");
+}
+
+#[tokio::test]
+async fn is_absent_without_an_internal_token() {
+ let issuer = FakeIssuer::new(ISSUER);
+ let base = start(&issuer, None).await;
+ let device = Device::new();
+ device.enroll(&base, &token(&issuer, "ada")).await;
+ let (status, body) = lookup(&base, &device.id, Some(INTERNAL)).await;
+ assert_eq!(status, StatusCode::NOT_FOUND);
+ assert_eq!(body, "not found");
+}