Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(relay): log why each 401 is refused (#4503)
ddupont7da7429f3028
diff --git a/libs/cua-spacesd/crates/cua-relay/src/api.rs b/libs/cua-spacesd/crates/cua-relay/src/api.rsindex 805168b6c3..e8063d27ae 100644--- a/libs/cua-spacesd/crates/cua-relay/src/api.rs+++ b/libs/cua-spacesd/crates/cua-relay/src/api.rs@@ -29,6 +29,7 @@ use axum::routing::{get, post};use axum::{Json, Router};use serde::{Deserialize, Serialize};+use crate::auth_log::{self, Reason, Route};use crate::device_api::{flag_grace, gate, session_header, Gate};use crate::devices::AuditEvent;use crate::directory::{@@ -198,7 +199,10 @@ async fn caller(relay: &Relay, headers: &HeaderMap) -> Result<Caller, Response>.directory.machine_for_token(token).map(Caller::Machine)- .ok_or_else(|| error(StatusCode::UNAUTHORIZED, "invalid machine token"));+ .ok_or_else(|| {+ auth_log::rejected(headers, Route::Machines, Reason::UnknownMachineToken, None);+ error(StatusCode::UNAUTHORIZED, "invalid machine token")+ });}let Some(oidc) = &relay.config.oidc else {return Err(error(@@ -207,6 +211,7 @@ async fn caller(relay: &Relay, headers: &HeaderMap) -> Result<Caller, Response>));};let Some(token) = account_token(headers) else {+ auth_log::rejected(headers, Route::Machines, Reason::MissingToken, None);return Err(error(StatusCode::UNAUTHORIZED, "missing account token"));};oidc.validate(token)@@ -216,6 +221,7 @@ async fn caller(relay: &Relay, headers: &HeaderMap) -> Result<Caller, Response>Caller::Account(who, g)}).map_err(|e| {+ auth_log::rejected(headers, Route::Machines, e.reason, Some(&e.facts));error(StatusCode::UNAUTHORIZED,format!("invalid account token: {e}"),diff --git a/libs/cua-spacesd/crates/cua-relay/src/auth_log.rs b/libs/cua-spacesd/crates/cua-relay/src/auth_log.rsnew file mode 100644index 0000000000..4d69fa85a6--- /dev/null+++ b/libs/cua-spacesd/crates/cua-relay/src/auth_log.rs@@ -0,0 +1,381 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++//! One structured log line per 401 the relay answers, so a failed sign-in+//! or host setup can be traced to its cause from the relay's logs alone.+//!+//! Every line goes to target [`TARGET`] at `info` with the fields:+//!+//! - `reason`: a [`Reason`] category (`expired`, `wrong_audience`, ...);+//! - `route`: the endpoint class ([`Route`]);+//! - `client`: the client kind, bucketed from the credential and the+//! `User-Agent` (`spacesd`, `machine`, `cli`, `app`, `sdk`, `browser`,+//! `other`); the raw header is never logged;+//! - `token_issuer` / `token_audience`: only values the relay knows to be+//! public (its configured issuer and audiences, `*.cua.ai` issuers, a few+//! well-known audiences); anything else is logged as `other`;+//! - `clock_skew_secs`: for time-based failures, how far off the token or+//! proof was: seconds past `exp` (`expired`), seconds until `nbf`+//! (`not_yet_valid`), or the proof's timestamp minus the relay's clock+//! (`device_proof_stale`; positive when the device clock is ahead).+//!+//! Tokens, token fragments, emails, account and user ids, IP addresses,+//! machine ids and device names are never logged.++use axum::http::{header, HeaderMap};++/// The `tracing` target of the 401 log lines.+pub const TARGET: &str = "cua_relay::auth";++/// Why a request was refused with 401.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Reason {+ /// No credential where one is required.+ MissingToken,+ /// Not a JWT, undecodable claims or an unusable key.+ Malformed,+ /// A symmetric (HS*) or otherwise unsupported signing algorithm.+ UnsupportedAlgorithm,+ /// Signed by a key the issuer does not publish (another issuer or+ /// environment, or a rotated key).+ UnknownSigningKey,+ /// The issuer's JWKS could not be fetched.+ JwksUnavailable,+ /// The signature does not verify.+ BadSignature,+ /// `iss` is not the configured issuer.+ WrongIssuer,+ /// `aud` holds none of the configured audiences.+ WrongAudience,+ /// `exp` has passed (beyond the leeway).+ Expired,+ /// `nbf` is in the future.+ NotYetValid,+ /// A required claim (`exp`, `iss`, `aud`, `sub`) is missing.+ MissingClaim,+ /// A machine token the directory does not know (revoked, rotated,+ /// unregistered).+ UnknownMachineToken,+ /// A static relay token that is not configured.+ InvalidRelayToken,+ /// Wrong admin token.+ InvalidAdminToken,+ /// A device proof outside the allowed clock window.+ DeviceProofStale,+ /// A device proof whose signature does not verify.+ DeviceProofBadSignature,+ /// A device proof that was already used.+ DeviceProofReplayed,+ /// A request to a static-token machine without any spacesd credential+ /// (`--require-client-credentials`).+ SpacesdCredentialMissing,+}++impl Reason {+ /// The category as logged.+ pub fn as_str(self) -> &'static str {+ match self {+ Self::MissingToken => "missing_token",+ Self::Malformed => "malformed",+ Self::UnsupportedAlgorithm => "unsupported_algorithm",+ Self::UnknownSigningKey => "unknown_signing_key",+ Self::JwksUnavailable => "jwks_unavailable",+ Self::BadSignature => "bad_signature",+ Self::WrongIssuer => "wrong_issuer",+ Self::WrongAudience => "wrong_audience",+ Self::Expired => "expired",+ Self::NotYetValid => "not_yet_valid",+ Self::MissingClaim => "missing_claim",+ Self::UnknownMachineToken => "unknown_machine_token",+ Self::InvalidRelayToken => "invalid_relay_token",+ Self::InvalidAdminToken => "invalid_admin_token",+ Self::DeviceProofStale => "device_proof_stale",+ Self::DeviceProofBadSignature => "device_proof_bad_signature",+ Self::DeviceProofReplayed => "device_proof_replayed",+ Self::SpacesdCredentialMissing => "spacesd_credential_missing",+ }+ }+}++/// The endpoint class a 401 came from.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Route {+ /// `/relay/v1/connect` (a machine joining).+ Connect,+ /// `/relay/v1/machines` (admin).+ Admin,+ /// `/v1/machines…` (directory API).+ Machines,+ /// `/v1/devices…` (device enrollment).+ Devices,+ /// A client request forwarded to a machine.+ Proxy,+}++impl Route {+ /// The class as logged.+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Connect => "connect",+ Self::Admin => "admin",+ Self::Machines => "machines",+ Self::Devices => "devices",+ Self::Proxy => "proxy",+ }+ }+}++/// Audiences that are public names, logged as they are.+const KNOWN_AUDIENCES: &[&str] = &[+ crate::oidc::DEFAULT_AUDIENCE,+ "account",+ "cua",+ "cua-cli",+ "cua-app",+ "cua-spaces",+ "cua-cloud",+];++/// Token details safe to log, kept on a failed account-token validation.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct TokenFacts {+ /// `iss`, if public (else `other`).+ pub issuer: Option<String>,+ /// `aud` values, if public (each unknown one as `other`), comma-joined.+ pub audience: Option<String>,+ /// Seconds past `exp` (expired) or until `nbf` (not yet valid).+ pub clock_skew_secs: Option<i64>,+}++impl TokenFacts {+ /// Reads `iss`, `aud`, `exp` and `nbf` from an (unverified) JWT,+ /// keeping only what is safe to log. `issuer` and `audiences` are the+ /// relay's own configuration.+ pub fn from_token(token: &str, reason: Reason, issuer: &str, audiences: &[String]) -> Self {+ let Some(claims) = unverified_claims(token) else {+ return Self::default();+ };+ let now = crate::assertion::now_secs() as i64;+ let clock_skew_secs = match reason {+ Reason::Expired => claims.get("exp").and_then(|v| v.as_i64()).map(|e| now - e),+ Reason::NotYetValid => claims.get("nbf").and_then(|v| v.as_i64()).map(|n| n - now),+ _ => None,+ };+ let iss = claims+ .get("iss")+ .and_then(|v| v.as_str())+ .map(|s| public_issuer(s, issuer).to_owned());+ let aud = match claims.get("aud") {+ Some(serde_json::Value::String(a)) => Some(vec![a.as_str()]),+ Some(serde_json::Value::Array(a)) => {+ Some(a.iter().filter_map(|v| v.as_str()).take(8).collect())+ }+ _ => None,+ }+ .map(|values| {+ values+ .into_iter()+ .map(|a| public_audience(a, audiences))+ .collect::<Vec<_>>()+ .join(",")+ });+ Self {+ issuer: iss,+ audience: aud,+ clock_skew_secs,+ }+ }+}++fn unverified_claims(token: &str) -> Option<serde_json::Map<String, serde_json::Value>> {+ use base64::Engine as _;+ let payload = token.split('.').nth(1)?;+ let raw = base64::engine::general_purpose::URL_SAFE_NO_PAD+ .decode(payload.trim_end_matches('='))+ .ok()?;+ match serde_json::from_slice(&raw).ok()? {+ serde_json::Value::Object(map) => Some(map),+ _ => None,+ }+}++/// `iss` as logged: the configured issuer or a `cua.ai` URL, else `other`.+fn public_issuer<'a>(iss: &'a str, configured: &str) -> &'a str {+ if iss.trim_end_matches('/') == configured.trim_end_matches('/') {+ return iss;+ }+ let host = url::Url::parse(iss)+ .ok()+ .filter(|u| u.scheme() == "https" && u.username().is_empty() && u.password().is_none())+ .and_then(|u| u.host_str().map(str::to_owned));+ match host {+ Some(h) if (h == "cua.ai" || h.ends_with(".cua.ai")) && iss.len() <= 128 => iss,+ _ => "other",+ }+}++/// An `aud` value as logged: configured or well known, else `other`.+fn public_audience<'a>(aud: &'a str, configured: &[String]) -> &'a str {+ if configured.iter().any(|c| c == aud) || KNOWN_AUDIENCES.contains(&aud) {+ aud+ } else {+ "other"+ }+}++/// The client kind: from the credential when it says (machine token,+/// spacesd join), else a bucket of the `User-Agent`.+pub fn client_kind(headers: &HeaderMap) -> &'static str {+ let machine_token = crate::server::bearer(headers, header::AUTHORIZATION.as_str())+ .is_some_and(|t| t.starts_with(crate::directory::MACHINE_TOKEN_PREFIX));+ if machine_token {+ return "machine";+ }+ if headers.contains_key(crate::VERSION_HEADER) || headers.contains_key(crate::MACHINE_ID_HEADER)+ {+ return "spacesd";+ }+ let Some(ua) = headers+ .get(header::USER_AGENT)+ .and_then(|v| v.to_str().ok())+ else {+ // The SDK's relay client (host setup, `cua` and the app's core)+ // sends no User-Agent.+ return "sdk";+ };+ let lower = ua.to_ascii_lowercase();+ if lower.starts_with("cua-cli/") || lower.starts_with("cua-host/") || lower.starts_with("cua/")+ {+ "cli"+ } else if lower.contains("spacesd") {+ "spacesd"+ } else if lower.contains("cfnetwork")+ || lower.contains("cua spaces")+ || lower.contains("cua%20")+ {+ "app"+ } else if lower.starts_with("mozilla/") {+ "browser"+ } else {+ "other"+ }+}++/// Logs one 401.+pub fn rejected(headers: &HeaderMap, route: Route, reason: Reason, facts: Option<&TokenFacts>) {+ let facts = facts.cloned().unwrap_or_default();+ tracing::info!(+ target: TARGET,+ reason = reason.as_str(),+ route = route.as_str(),+ client = client_kind(headers),+ token_issuer = facts.issuer.as_deref(),+ token_audience = facts.audience.as_deref(),+ clock_skew_secs = facts.clock_skew_secs,+ "401 unauthenticated"+ );+}++#[cfg(test)]+mod tests {+ use super::*;+ use axum::http::HeaderValue;++ fn jwt(claims: serde_json::Value) -> String {+ use base64::Engine as _;+ let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;+ format!(+ "{}.{}.sig",+ b64.encode(br#"{"alg":"ES256"}"#),+ b64.encode(claims.to_string())+ )+ }++ #[test]+ fn facts_keep_only_public_issuer_and_audience() {+ let audiences = vec!["cua-relay".to_owned()];+ let issuer = "https://auth.cua.ai/realms/cua";+ let facts = TokenFacts::from_token(+ &jwt(serde_json::json!({+ "iss": "https://auth.cua.ai/realms/cua/", "aud": ["account", "secret-client-123"],+ "sub": "u1", "email": "[email protected]", "exp": 1,+ })),+ Reason::WrongAudience,+ issuer,+ &audiences,+ );+ assert_eq!(+ facts.issuer.as_deref(),+ Some("https://auth.cua.ai/realms/cua/")+ );+ assert_eq!(facts.audience.as_deref(), Some("account,other"));+ assert_eq!(facts.clock_skew_secs, None, "only time failures get skew");++ let foreign = TokenFacts::from_token(+ &jwt(serde_json::json!({"iss": "https://evil.example/private-tenant-42", "aud": "x"})),+ Reason::WrongIssuer,+ issuer,+ &audiences,+ );+ assert_eq!(foreign.issuer.as_deref(), Some("other"));+ assert_eq!(foreign.audience.as_deref(), Some("other"));+ // A cua.ai look-alike with credentials in the URL is not public.+ assert_eq!(+ public_issuer("https://user:[email protected]/", issuer),+ "other"+ );+ assert_eq!(+ public_issuer("https://auth.cua.ai.evil.example/", issuer),+ "other"+ );+ }++ #[test]+ fn skew_is_measured_for_time_failures() {+ let now = crate::assertion::now_secs() as i64;+ let expired = TokenFacts::from_token(+ &jwt(serde_json::json!({"exp": now - 600})),+ Reason::Expired,+ "https://i",+ &[],+ );+ let skew = expired.clock_skew_secs.unwrap();+ assert!((599..=605).contains(&skew), "{skew}");+ let early = TokenFacts::from_token(+ &jwt(serde_json::json!({"nbf": now + 120})),+ Reason::NotYetValid,+ "https://i",+ &[],+ );+ let skew = early.clock_skew_secs.unwrap();+ assert!((115..=120).contains(&skew), "{skew}");+ assert_eq!(+ TokenFacts::from_token("garbage", Reason::Malformed, "https://i", &[]),+ TokenFacts::default()+ );+ }++ #[test]+ fn client_kinds() {+ let with = |pairs: &[(&'static str, &str)]| {+ let mut h = HeaderMap::new();+ for (k, v) in pairs {+ h.insert(*k, HeaderValue::from_str(v).unwrap());+ }+ client_kind(&h)+ };+ assert_eq!(with(&[]), "sdk");+ assert_eq!(with(&[("authorization", "Bearer cmt_abc")]), "machine");+ assert_eq!(with(&[(crate::VERSION_HEADER, "0.2.2")]), "spacesd");+ assert_eq!(with(&[("user-agent", "cua-cli/0.9.0")]), "cli");+ assert_eq!(+ with(&[("user-agent", "Cua%20Spaces/5 CFNetwork/1568 Darwin/25.5.0")]),+ "app"+ );+ assert_eq!(+ with(&[("user-agent", "Mozilla/5.0 (Macintosh)")]),+ "browser"+ );+ assert_eq!(with(&[("user-agent", "curl/8.7.1")]), "other");+ }+}diff --git a/libs/cua-spacesd/crates/cua-relay/src/device_api.rs b/libs/cua-spacesd/crates/cua-relay/src/device_api.rsindex 0b3c2c1021..761a1ee131 100644--- a/libs/cua-spacesd/crates/cua-relay/src/device_api.rs+++ b/libs/cua-spacesd/crates/cua-relay/src/device_api.rs@@ -27,6 +27,7 @@ use axum::{Json, Router};use serde::{Deserialize, Serialize};use crate::assertion::now_secs;+use crate::auth_log::{self, Reason, Route, TokenFacts};use crate::devices::{AuditEvent, DeviceError, DeviceRecord, DeviceState, Registration, DEVICE_SESSION_HEADER,ENROLLMENT_HEADER,@@ -215,6 +216,27 @@ fn device_error(e: DeviceError) -> Response {error(status, code, e.to_string())}+/// Logs a device-proof 401 (other device errors are not 401s). `ts` is the+/// proof's timestamp, for the clock skew of a stale proof.+fn log_proof_failure(headers: &HeaderMap, e: &DeviceError, ts: u64) {+ let DeviceError::Proof(message) = e else {+ return;+ };+ let (reason, skew) = match message.as_str() {+ crate::devices::PROOF_STALE => (+ Reason::DeviceProofStale,+ Some(ts as i64 - now_secs() as i64),+ ),+ crate::devices::PROOF_REPLAYED => (Reason::DeviceProofReplayed, None),+ _ => (Reason::DeviceProofBadSignature, None),+ };+ let facts = TokenFacts {+ clock_skew_secs: skew,+ ..TokenFacts::default()+ };+ auth_log::rejected(headers, Route::Devices, reason, Some(&facts));+}+/// The account behind the request (machine tokens are refused).async fn account(relay: &Relay, headers: &HeaderMap) -> Result<Identity, Response> {let Some(oidc) = &relay.config.oidc else {@@ -241,6 +263,7 @@ async fn account(relay: &Relay, headers: &HeaderMap) -> Result<Identity, Respons));}let Some(token) = account_token(headers) else {+ auth_log::rejected(headers, Route::Devices, Reason::MissingToken, None);return Err(error(StatusCode::UNAUTHORIZED,"unauthenticated",@@ -248,6 +271,7 @@ async fn account(relay: &Relay, headers: &HeaderMap) -> Result<Identity, Respons));};oidc.validate(token).await.map_err(|e| {+ auth_log::rejected(headers, Route::Devices, e.reason, Some(&e.facts));error(StatusCode::UNAUTHORIZED,"unauthenticated",@@ -324,7 +348,10 @@ async fn register(})).into_response()}- Err(e) => device_error(e),+ Err(e) => {+ log_proof_failure(&headers, &e, body.ts);+ device_error(e)+ }}}@@ -354,7 +381,10 @@ async fn session("device": relay.devices.get(&body.device_id).map(|d| view(&d, Some(&d.id))),})).into_response(),- Err(e) => device_error(e),+ Err(e) => {+ log_proof_failure(&headers, &e, body.ts);+ device_error(e)+ }}}diff --git a/libs/cua-spacesd/crates/cua-relay/src/devices.rs b/libs/cua-spacesd/crates/cua-relay/src/devices.rsindex 780b033cab..b75d50cd5e 100644--- a/libs/cua-spacesd/crates/cua-relay/src/devices.rs+++ b/libs/cua-spacesd/crates/cua-relay/src/devices.rs@@ -457,6 +457,14 @@ struct Session {expires: u64,}+/// [`DeviceError::Proof`] message: the proof's timestamp is outside the+/// allowed clock window.+pub const PROOF_STALE: &str = "the device clock is off or the proof is stale";+/// [`DeviceError::Proof`] message: the signature does not verify.+pub const PROOF_BAD_SIGNATURE: &str = "invalid device signature";+/// [`DeviceError::Proof`] message: the proof was already used.+pub const PROOF_REPLAYED: &str = "device proof already used";+/// Errors, mapped to HTTP statuses by the API.#[derive(Debug, Clone, PartialEq, Eq)]pub enum DeviceError {@@ -860,12 +868,10 @@ impl DeviceStore {) -> Result<(), DeviceError> {let now = now_secs();if ts.abs_diff(now) > PROOF_SKEW_SECS {- return Err(DeviceError::Proof(- "the device clock is off or the proof is stale".into(),- ));+ return Err(DeviceError::Proof(PROOF_STALE.into()));}if !verify(key, message, sig) {- return Err(DeviceError::Proof("invalid device signature".into()));+ return Err(DeviceError::Proof(PROOF_BAD_SIGNATURE.into()));}// Keyed by the signature's `r` (the first half): an ECDSA signature// has a second valid form with the same `r`, so the whole signature@@ -876,7 +882,7 @@ impl DeviceStore {proofs.retain(|_, exp| *exp > now);let fingerprint = hex::encode(ring::digest::digest(&ring::digest::SHA256, r).as_ref());if proofs.contains_key(&fingerprint) {- return Err(DeviceError::Proof("device proof already used".into()));+ return Err(DeviceError::Proof(PROOF_REPLAYED.into()));}proofs.insert(fingerprint, now + 2 * PROOF_SKEW_SECS + 1);Ok(())diff --git a/libs/cua-spacesd/crates/cua-relay/src/lib.rs b/libs/cua-spacesd/crates/cua-relay/src/lib.rsindex 4007f2e94a..3ad12c7530 100644--- a/libs/cua-spacesd/crates/cua-relay/src/lib.rs+++ b/libs/cua-spacesd/crates/cua-relay/src/lib.rs@@ -24,6 +24,7 @@pub mod api;pub mod assertion;+pub mod auth_log;pub mod client;pub mod device_api;pub mod devices;diff --git a/libs/cua-spacesd/crates/cua-relay/src/oidc.rs b/libs/cua-spacesd/crates/cua-relay/src/oidc.rsindex 97467d9ad6..5e3e12f737 100644--- a/libs/cua-spacesd/crates/cua-relay/src/oidc.rs+++ b/libs/cua-spacesd/crates/cua-relay/src/oidc.rs@@ -11,6 +11,8 @@ use std::time::{Duration, Instant};use jsonwebtoken::jwk::{AlgorithmParameters, JwkSet};use jsonwebtoken::{Algorithm, DecodingKey, Validation};+use crate::auth_log::Reason;+/// Default audience relay account tokens must carry.pub const DEFAULT_AUDIENCE: &str = "cua-relay";@@ -223,21 +225,45 @@ impl OidcValidator {}/// Validates an account token.- pub async fn validate(&self, token: &str) -> Result<Identity, String> {- let header = jsonwebtoken::decode_header(token).map_err(|_| "not a JWT".to_owned())?;+ pub async fn validate(&self, token: &str) -> Result<Identity, TokenError> {+ self.validate_inner(token)+ .await+ .map_err(|(reason, message)| {+ let facts = crate::auth_log::TokenFacts::from_token(+ token,+ reason,+ &self.config.issuer,+ &self.config.audiences,+ );+ TokenError {+ reason,+ message,+ facts,+ }+ })+ }++ async fn validate_inner(&self, token: &str) -> Result<Identity, (Reason, String)> {+ let header = jsonwebtoken::decode_header(token)+ .map_err(|_| (Reason::Malformed, "not a JWT".to_owned()))?;if matches!(header.alg,Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512) {- return Err("symmetric JWTs are not accepted".into());+ return Err((+ Reason::UnsupportedAlgorithm,+ "symmetric JWTs are not accepted".into(),+ ));}let _ = self.refresh(false).await;let key = match self.key_for(header.kid.as_deref(), header.alg) {Some(key) => key,None => {- self.refresh(true).await?;+ self.refresh(true)+ .await+ .map_err(|e| (Reason::JwksUnavailable, e))?;self.key_for(header.kid.as_deref(), header.alg)- .ok_or("unknown signing key")?+ .ok_or((Reason::UnknownSigningKey, "unknown signing key".to_owned()))?}};let mut validation = Validation::new(header.alg);@@ -249,7 +275,7 @@ impl OidcValidator {validation.set_required_spec_claims(&["exp", "iss", "aud", "sub"]);validation.leeway = 30;let data = jsonwebtoken::decode::<serde_json::Value>(token, &key, &validation)- .map_err(|e| format!("account token: {e}"))?;+ .map_err(|e| (jwt_reason(e.kind()), format!("account token: {e}")))?;let claims = data.claims;let text = |name: &str| {claims@@ -258,7 +284,8 @@ impl OidcValidator {.filter(|s| !s.is_empty()).map(str::to_owned)};- let user = text("sub").ok_or("account token has no sub")?;+ let user =+ text("sub").ok_or((Reason::MissingClaim, "account token has no sub".to_owned()))?;let account = text(&self.config.account_claim).unwrap_or_else(|| user.clone());// Sharing by email grants access, so only an address the issuer// verified counts (some issuers encode the flag as a string).@@ -298,6 +325,40 @@ impl OidcValidator {}}+/// A refused account token: the message (shown to the caller, as before)+/// and the facts the relay logs about it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct TokenError {+ /// Why, as logged.+ pub reason: Reason,+ /// The caller-facing message.+ pub message: String,+ /// Safe-to-log token details.+ pub facts: crate::auth_log::TokenFacts,+}++impl std::fmt::Display for TokenError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(&self.message)+ }+}++impl std::error::Error for TokenError {}++fn jwt_reason(kind: &jsonwebtoken::errors::ErrorKind) -> Reason {+ use jsonwebtoken::errors::ErrorKind as K;+ match kind {+ K::InvalidSignature => Reason::BadSignature,+ K::ExpiredSignature => Reason::Expired,+ K::ImmatureSignature => Reason::NotYetValid,+ K::InvalidIssuer => Reason::WrongIssuer,+ K::InvalidAudience => Reason::WrongAudience,+ K::MissingRequiredClaim(_) => Reason::MissingClaim,+ K::InvalidAlgorithm | K::MissingAlgorithm => Reason::UnsupportedAlgorithm,+ _ => Reason::Malformed,+ }+}+/// A fake OIDC issuer for tests: ES256 keys generated in-process.pub mod testing {use super::*;diff --git a/libs/cua-spacesd/crates/cua-relay/src/server.rs b/libs/cua-spacesd/crates/cua-relay/src/server.rsindex 7fbe0230bc..2b97eb3121 100644--- a/libs/cua-spacesd/crates/cua-relay/src/server.rs+++ b/libs/cua-spacesd/crates/cua-relay/src/server.rs@@ -43,6 +43,7 @@ use tokio_util::compat::FuturesAsyncReadCompatExt as _;use tokio_util::sync::CancellationToken;use crate::assertion::{self, AssertionClaims, RelayKey, ASSERTION_HEADER};+use crate::auth_log::{self, Reason, Route};use crate::devices::{DevicePolicy, DeviceStore, DEVICE_SESSION_HEADER};use crate::directory::{Directory, MACHINE_TOKEN_PREFIX};use crate::mux::{self, Counted, Counters, MuxHandle};@@ -603,7 +604,15 @@ async fn machine_connect("machine token belongs to another machine id",)}- None => return text(StatusCode::UNAUTHORIZED, "invalid relay token"),+ None => {+ let reason = match bearer(&headers, header::AUTHORIZATION.as_str()) {+ None => Reason::MissingToken,+ Some(t) if t.starts_with(MACHINE_TOKEN_PREFIX) => Reason::UnknownMachineToken,+ Some(_) => Reason::InvalidRelayToken,+ };+ auth_log::rejected(&headers, Route::Connect, reason, None);+ return text(StatusCode::UNAUTHORIZED, "invalid relay token");+ }}};let version = headers@@ -744,6 +753,12 @@ async fn machine_list(State(relay): State<Relay>, headers: HeaderMap) -> Responst.len() == admin.len() && bool::from(t.as_bytes().ct_eq(admin.as_bytes()))});if !ok {+ let reason = if headers.contains_key(header::AUTHORIZATION) {+ Reason::InvalidAdminToken+ } else {+ Reason::MissingToken+ };+ auth_log::rejected(&headers, Route::Admin, reason, None);return text(StatusCode::UNAUTHORIZED, "invalid admin token");}axum::Json(relay.status()).into_response()@@ -870,12 +885,13 @@ async fn authorize_account_client((Some(token), Some(oidc)) => match oidc.validate(token).await {Ok(identity) => Some(identity),Err(e) if !has_forwardable_credential(request.uri(), headers, forwarded) => {+ auth_log::rejected(headers, Route::Proxy, e.reason, Some(&e.facts));return Err(refuse(headers,StatusCode::UNAUTHORIZED,GrpcCode::Unauthenticated,format!("invalid account token: {e}"),- ))+ ));}Err(_) => None,},@@ -938,12 +954,13 @@ async fn authorize_account_client(// (Credential headers are stripped below, so they do not count.)None if has_forwardable_credential(request.uri(), headers, forwarded) => None,None => {+ auth_log::rejected(headers, Route::Proxy, Reason::MissingToken, None);return Err(refuse(headers,StatusCode::UNAUTHORIZED,GrpcCode::Unauthenticated,"sign in: this machine accepts cua.ai account tokens",- ))+ ));}};let headers = request.headers_mut();@@ -998,6 +1015,12 @@ async fn proxy(State(relay): State<Relay>, mut request: Request) -> Response {} else if relay.config.require_client_credentials&& !has_client_credential(request.uri(), request.headers(), &forwarded){+ auth_log::rejected(+ request.headers(),+ Route::Proxy,+ Reason::SpacesdCredentialMissing,+ None,+ );return refuse(request.headers(),StatusCode::UNAUTHORIZED,diff --git a/libs/cua-spacesd/crates/cua-relay/tests/auth_rejection_logs.rs b/libs/cua-spacesd/crates/cua-relay/tests/auth_rejection_logs.rsnew file mode 100644index 0000000000..380743439d--- /dev/null+++ b/libs/cua-spacesd/crates/cua-relay/tests/auth_rejection_logs.rs@@ -0,0 +1,358 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++//! Every 401 the relay answers logs one `cua_relay::auth` line naming the+//! reason, route and client kind, and never a token, token fragment, email,+//! account id, IP address, machine id or device name.++use std::io::Write;+use std::sync::{Arc, Mutex, OnceLock};++use base64::Engine as _;+use cua_relay::devices::{register_message, DevicePolicy};+use cua_relay::oidc::testing::FakeIssuer;+use cua_relay::oidc::{OidcConfig, OidcValidator};+use cua_relay::server::{Relay, RelayConfig};+use ring::signature::KeyPair as _;+use serde_json::json;++const ISSUER: &str = "https://auth.test/realms/cua";+const EMAIL: &str = "[email protected]";+const SUB: &str = "user-7f3a9c0e-sub";+const DEVICE_NAME: &str = "adas-secret-laptop";+const ADMIN_TOKEN: &str = "admin-token-do-not-log-9b1e";++#[derive(Clone, Default)]+struct Buffer(Arc<Mutex<Vec<u8>>>);++impl Write for Buffer {+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {+ self.0.lock().unwrap().extend_from_slice(buf);+ Ok(buf.len())+ }+ fn flush(&mut self) -> std::io::Result<()> {+ Ok(())+ }+}++/// Everything logged in this test binary.+fn logs() -> &'static Buffer {+ static LOGS: OnceLock<Buffer> = OnceLock::new();+ LOGS.get_or_init(|| {+ let buffer = Buffer::default();+ let writer = buffer.clone();+ tracing_subscriber::fmt()+ .with_ansi(false)+ .with_max_level(tracing::Level::DEBUG)+ .with_writer(move || writer.clone())+ .init();+ buffer+ })+}++fn take_logs() -> String {+ let mut buf = logs().0.lock().unwrap();+ let text = String::from_utf8_lossy(&buf).into_owned();+ buf.clear();+ text+}++/// The one auth line logged since the last call.+fn auth_line() -> String {+ let text = take_logs();+ let lines: Vec<&str> = text+ .lines()+ .filter(|l| l.contains("cua_relay::auth"))+ .collect();+ assert_eq!(lines.len(), 1, "exactly one auth line in:\n{text}");+ lines[0].to_owned()+}++fn assert_fields(line: &str, reason: &str, route: &str, client: &str) {+ assert!(line.contains("401 unauthenticated"), "{line}");+ assert!(line.contains(&format!("reason=\"{reason}\"")), "{line}");+ assert!(line.contains(&format!("route=\"{route}\"")), "{line}");+ assert!(line.contains(&format!("client=\"{client}\"")), "{line}");+}++fn b64() -> base64::engine::GeneralPurpose {+ base64::engine::general_purpose::URL_SAFE_NO_PAD+}++async fn start(oidc: OidcConfig, issuer: &FakeIssuer) -> String {+ let relay = Relay::new(RelayConfig {+ oidc: Some(Arc::new(OidcValidator::with_jwks(oidc, issuer.jwks()))),+ admin_token: Some(ADMIN_TOKEN.into()),+ device_policy: DevicePolicy {+ grace_secs: 3600,+ ..DevicePolicy::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+}++async fn get(url: &str, token: Option<&str>, ua: Option<&str>) -> reqwest::StatusCode {+ let mut r = reqwest::Client::new().get(url);+ if let Some(t) = token {+ r = r.bearer_auth(t);+ }+ if let Some(ua) = ua {+ r = r.header("user-agent", ua);+ }+ r.send().await.unwrap().status()+}++#[tokio::test]+async fn each_401_logs_its_reason_and_no_secret() {+ logs();+ let issuer = FakeIssuer::new(ISSUER);+ let base = start(OidcConfig::new(ISSUER), &issuer).await;+ let machines = format!("{base}/v1/machines");+ let mut secrets: Vec<String> = vec![+ EMAIL.into(),+ SUB.into(),+ DEVICE_NAME.into(),+ ADMIN_TOKEN.into(),+ "127.0.0.1".into(),+ ];+ let check = |token: &str, line: &str, secrets: &mut Vec<String>| {+ secrets.push(token.to_owned());+ for part in token.split('.') {+ secrets.push(part.to_owned());+ }+ for s in secrets.iter().filter(|s| s.len() >= 8) {+ assert!(!line.contains(s.as_str()), "{s:?} leaked into {line}");+ // No 12-char fragment of a token either.+ if !s.contains('@') && s.len() >= 12 {+ for start in (0..=s.len() - 12).step_by(4) {+ if let Some(frag) = s.get(start..start + 12) {+ assert!(!line.contains(frag), "fragment {frag:?} leaked: {line}");+ }+ }+ }+ }+ };++ // Missing token.+ assert_eq!(get(&machines, None, Some("cua-cli/0.9.0")).await, 401);+ assert_fields(&auth_line(), "missing_token", "machines", "cli");++ // Wrong audience: the token's public audience is logged.+ let token = issuer.token(SUB, Some(EMAIL), "account", 300);+ assert_eq!(get(&machines, Some(&token), None).await, 401);+ let line = auth_line();+ assert_fields(&line, "wrong_audience", "machines", "sdk");+ assert!(+ line.contains(&format!("token_issuer=\"{ISSUER}\"")),+ "{line}"+ );+ assert!(line.contains("token_audience=\"account\""), "{line}");+ assert!(!line.contains("clock_skew_secs"), "{line}");+ check(&token, &line, &mut secrets);++ // An audience that is not a public name is not logged.+ let token = issuer.token(SUB, Some(EMAIL), "private-client-7731", 300);+ assert_eq!(get(&machines, Some(&token), None).await, 401);+ let line = auth_line();+ assert_fields(&line, "wrong_audience", "machines", "sdk");+ assert!(line.contains("token_audience=\"other\""), "{line}");+ check(&token, &line, &mut secrets);++ // Expired (beyond the 30 s leeway), with the clock skew.+ let token = issuer.token(SUB, Some(EMAIL), "cua-relay", -600);+ let ua = "Cua%20Spaces/5 CFNetwork/1568 Darwin/25.5.0";+ assert_eq!(get(&machines, Some(&token), Some(ua)).await, 401);+ let line = auth_line();+ assert_fields(&line, "expired", "machines", "app");+ let skew: i64 = line+ .split("clock_skew_secs=")+ .nth(1)+ .and_then(|s| s.split_whitespace().next())+ .and_then(|s| s.parse().ok())+ .unwrap_or_else(|| panic!("no skew in {line}"));+ assert!((599..=610).contains(&skew), "{skew}");+ check(&token, &line, &mut secrets);++ // Bad signature: one token's signature on another token's claims.+ let a = issuer.token(SUB, Some(EMAIL), "cua-relay", 300);+ let b = issuer.token("someone-else", None, "cua-relay", 300);+ let forged = format!(+ "{}.{}",+ a.rsplit_once('.').unwrap().0,+ b.rsplit_once('.').unwrap().1+ );+ assert_eq!(get(&machines, Some(&forged), None).await, 401);+ let line = auth_line();+ assert_fields(&line, "bad_signature", "machines", "sdk");+ check(&forged, &line, &mut secrets);++ // Signed by a key the issuer does not publish.+ let stranger = FakeIssuer::new(ISSUER);+ let token = stranger.token(SUB, Some(EMAIL), "cua-relay", 300);+ assert_eq!(get(&machines, Some(&token), None).await, 401);+ let line = auth_line();+ assert_fields(&line, "unknown_signing_key", "machines", "sdk");+ check(&token, &line, &mut secrets);++ // Malformed.+ assert_eq!(get(&machines, Some("not-a-jwt-secretish"), None).await, 401);+ let line = auth_line();+ assert_fields(&line, "malformed", "machines", "sdk");+ check("not-a-jwt-secretish", &line, &mut secrets);++ // Unknown (revoked) machine token.+ let token = "cmt_0123456789abcdef0123456789abcdef";+ assert_eq!(get(&machines, Some(token), None).await, 401);+ let line = auth_line();+ assert_fields(&line, "unknown_machine_token", "machines", "machine");+ check(token, &line, &mut secrets);++ // Device enrollment: missing token, then a stale proof with its skew.+ let devices = format!("{base}/v1/devices");+ assert_eq!(get(&devices, None, None).await, 401);+ assert_fields(&auth_line(), "missing_token", "devices", "sdk");+ 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 device_id = cua_relay::devices::device_id(pair.public_key().as_ref());+ secrets.push(device_id.clone());+ let ts = cua_relay::assertion::now_secs() - 900;+ let sig = b64().encode(+ pair.sign(&rng, register_message(&device_id, ts).as_bytes())+ .unwrap()+ .as_ref(),+ );+ let token = issuer.token(SUB, Some(EMAIL), "cua-relay", 300);+ let status = reqwest::Client::new()+ .post(&devices)+ .bearer_auth(&token)+ .json(&json!({+ "public_key": b64().encode(pair.public_key().as_ref()),+ "name": DEVICE_NAME,+ "ts": ts,+ "sig": sig,+ }))+ .send()+ .await+ .unwrap()+ .status();+ assert_eq!(status, 401);+ let line = auth_line();+ assert_fields(&line, "device_proof_stale", "devices", "sdk");+ assert!(+ line.contains("clock_skew_secs=-90") || line.contains("clock_skew_secs=-89"),+ "{line}"+ );+ check(&token, &line, &mut secrets);+ check(&sig, &line, &mut secrets);++ // Admin.+ assert_eq!(+ get(+ &format!("{base}/relay/v1/machines"),+ Some("wrong-admin"),+ None+ )+ .await,+ 401+ );+ assert_fields(&auth_line(), "invalid_admin_token", "admin", "sdk");++ // Proxy: an account machine without a token, and a static-token+ // machine without any spacesd credential.+ let token = issuer.token(SUB, Some(EMAIL), "cua-relay", 300);+ let machine_id = format!("m{}", uuid::Uuid::new_v4().simple());+ secrets.push(machine_id.clone());+ let status = reqwest::Client::new()+ .post(&machines)+ .bearer_auth(&token)+ .json(&json!({"id": machine_id, "name": DEVICE_NAME}))+ .send()+ .await+ .unwrap()+ .status();+ assert!(status.is_success(), "{status}");+ take_logs();+ let ua = "Mozilla/5.0 (Macintosh)";+ assert_eq!(+ get(&format!("{base}/m/{machine_id}/v1/x"), None, Some(ua)).await,+ 401+ );+ let line = auth_line();+ assert_fields(&line, "missing_token", "proxy", "browser");+ check(&token, &line, &mut secrets);+ assert_eq!(+ get(&format!("{base}/m/notregistered01/v1/x"), None, None).await,+ 401+ );+ assert_fields(&auth_line(), "spacesd_credential_missing", "proxy", "sdk");++ // Machine join with an unknown relay token.+ let mut request =+ tokio_tungstenite::tungstenite::client::IntoClientRequest::into_client_request(format!(+ "{}{}",+ base.replace("http://", "ws://"),+ cua_relay::CONNECT_PATH+ ))+ .unwrap();+ let h = request.headers_mut();+ h.insert(cua_relay::MACHINE_ID_HEADER, machine_id.parse().unwrap());+ h.insert(cua_relay::VERSION_HEADER, "0.2.2".parse().unwrap());+ h.insert(+ "authorization",+ "Bearer static-relay-token-guess".parse().unwrap(),+ );+ let err = tokio_tungstenite::connect_async(request).await.unwrap_err();+ assert!(err.to_string().contains("401"), "{err}");+ let line = auth_line();+ assert_fields(&line, "invalid_relay_token", "connect", "spacesd");+ check("static-relay-token-guess", &line, &mut secrets);++ wrong_issuer_is_named_only_when_public().await;+}++/// Wrong issuer: named only when public. (Called from the test above: the+/// log buffer is shared, so the cases run in sequence.)+async fn wrong_issuer_is_named_only_when_public() {+ // Configured for another issuer: a cua.ai issuer is logged as-is.+ let issuer = FakeIssuer::new("https://auth.cua.ai/realms/other");+ let base = start(OidcConfig::new(ISSUER), &issuer).await;+ let token = issuer.token(SUB, Some(EMAIL), "cua-relay", 300);+ assert_eq!(+ get(&format!("{base}/v1/machines"), Some(&token), None).await,+ 401+ );+ let text = take_logs();+ let line = text+ .lines()+ .find(|l| l.contains("reason=\"wrong_issuer\""))+ .unwrap_or_else(|| panic!("no wrong_issuer line in:\n{text}"));+ assert!(+ line.contains("token_issuer=\"https://auth.cua.ai/realms/other\""),+ "{line}"+ );+ assert!(!line.contains(EMAIL) && !line.contains(SUB), "{line}");++ // A private issuer URL is not.+ let private = FakeIssuer::new("https://idp.internal.example/tenant-4471");+ let base = start(OidcConfig::new(ISSUER), &private).await;+ let token = private.token(SUB, None, "cua-relay", 300);+ assert_eq!(+ get(&format!("{base}/v1/machines"), Some(&token), None).await,+ 401+ );+ let text = take_logs();+ let line = text+ .lines()+ .find(|l| l.contains("reason=\"wrong_issuer\""))+ .unwrap_or_else(|| panic!("no wrong_issuer line in:\n{text}"));+ assert!(line.contains("token_issuer=\"other\""), "{line}");+ assert!(!line.contains("tenant-4471"), "{line}");+}