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.

feat(relay): strict device approval for phones only (CUA_RELAY_DEVICE_REQUIRE_APPROVAL=phones) (#6452)

ddupont3271e514e91d
diff --git a/libs/cua-spacesd/crates/cua-relay/README.md b/libs/cua-spacesd/crates/cua-relay/README.md
index 8c94ece64e..1d349ed86a 100644
--- a/libs/cua-spacesd/crates/cua-relay/README.md
+++ b/libs/cua-spacesd/crates/cua-relay/README.md
@@ -170,7 +170,14 @@ without printing proxy credentials, relay URL queries or response bodies.
`CUA_RELAY_DEVICE_REQUIRE_APPROVAL=true` restores the strict policy: a
fresh sign-in then enrolls only the account's first device, a re-key of a
machine it already has, or (verified email) a sign-in proving MFA; other
- new devices wait for an approval. Devices report a machine id (a hash of
+ new devices wait for an approval. `CUA_RELAY_DEVICE_REQUIRE_APPROVAL=phones`
+ applies that strict rule to phone-class devices only (a device whose
+ sign-in token was issued to a `CUA_RELAY_PHONE_CLIENTS` client, or that
+ reports a phone platform, including the 30-day re-verification); every
+ other device (the CLI, the desktop app, per-browser devices of the account
+ app, unattended device-code installs) keeps the default policy. The relay
+ refuses to start with `phones` unless `CUA_RELAY_PUSH=on` and at least one
+ phone client is set. Devices report a machine id (a hash of
the host's hardware or install identity, stored keyed per account): when
a new key of the same machine enrolls, it replaces the machine's older
records (revoked as superseded, audited as `device_rekeyed`, left out of
@@ -460,7 +467,7 @@ register machines: `CUA_RELAY_TOKENS`/`CUA_RELAY_TOKEN_FILE` or
| `CUA_RELAY_DEVICE_TTL_DAYS` | `30` | Days an enrollment lasts without use (each device session renews it). |
| `CUA_RELAY_DEVICE_GRACE_DAYS` | `0` (ended) | Days unenrolled devices keep access after enrollment is first on. Set this only for a time-boxed rollout window (S3): a stolen account token alone reaches every machine while it is open. |
| `CUA_RELAY_DEVICE_BOOTSTRAP_MAX_AUTH_AGE_SECS` | `600` | Max sign-in age that enrolls a device without an approval. |
-| `CUA_RELAY_DEVICE_REQUIRE_APPROVAL` | off | Strict enrollment: a fresh sign-in enrolls only an account's first device, a re-key of a known machine, or (verified email) a sign-in proving MFA; other new devices need an approval from an enrolled device. |
+| `CUA_RELAY_DEVICE_REQUIRE_APPROVAL` | `false` | `true`: strict enrollment: a fresh sign-in enrolls only an account's first device, a re-key of a known machine, or (verified email) a sign-in proving MFA; other new devices need an approval from an enrolled device. `phones`: the same rule for phone-class devices only (token issued to a `CUA_RELAY_PHONE_CLIENTS` client, or a phone platform), every other device keeps the default; needs `CUA_RELAY_PUSH=on` and a non-empty `CUA_RELAY_PHONE_CLIENTS`, else the relay refuses to start. Any other value is an error. |
| `CUA_RELAY_PUSH` | `off` | Push notifications for the phone app (`on` needs account mode). On also turns on the phone viewer rules below. Off, `/v1/push/...` answers 404 and the relay behaves exactly as before. See "The phone app". |
| `CUA_RELAY_PUSH_FILE` | next to the state file | The account's registered phones and preferences (`machines.json` gives `machines.push.json`; in memory without a state file). Holds device tokens: 0600, back it up with the devices file. |
| `CUA_PUSH_APNS_KEY_FILE`, `CUA_PUSH_APNS_KEY_ID`, `CUA_PUSH_APNS_TEAM_ID`, `CUA_PUSH_APNS_TOPIC` | unset | The APNs authentication key (a `.p8` file from the Apple Developer account), its ids and the app's bundle id (default `ai.cua.spaces.mobile`). With push on and no key, phones register and alerts wait; a key file that is named but unreadable, or without its ids, stops the relay at start. Never put the key in the image or the repository: mount it as a secret. |
diff --git a/libs/cua-spacesd/crates/cua-relay/src/devices.rs b/libs/cua-spacesd/crates/cua-relay/src/devices.rs
index cae666babc..b6bb9a3b0e 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/devices.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/devices.rs
@@ -36,7 +36,8 @@
//!
//! The strict policy ([`DevicePolicy::require_approval`],
//! `--device-require-approval` / `CUA_RELAY_DEVICE_REQUIRE_APPROVAL`, off by
-//! default) restores approval for brand-new devices: a fresh sign-in then
+//! default; `phones` limits it to phone-class devices, see
+//! [`DevicePolicy::approval_phones_only`]) restores approval for brand-new devices: a fresh sign-in then
//! enrolls only an account's first device (or its only one, after it
//! expired; while no device enrolled through a real second factor exists),
//! a re-key of a machine that already has a live device on the account
@@ -1082,6 +1083,48 @@ pub struct DevicePolicy {
/// sign-in proving MFA; other new devices need an approval. Off by
/// default: a fresh sign-in enrolls any device of the account.
pub require_approval: bool,
+ /// Narrows [`Self::require_approval`] to phone-class devices (a device
+ /// that reported a phone platform or whose sign-in token was issued to
+ /// a phone client): every other device keeps the default policy. Has no
+ /// effect unless `require_approval` is on.
+ pub approval_phones_only: bool,
+}
+
+impl DevicePolicy {
+ /// Reads `CUA_RELAY_DEVICE_REQUIRE_APPROVAL`: `true`/`on`/`yes`/`1` (every
+ /// new device needs approval), `false`/`off`/`no`/`0` or empty (the
+ /// default policy), or `phones` (approval only for phone-class devices).
+ /// Returns `(require_approval, approval_phones_only)`; any other value is
+ /// an error, never a silent "off".
+ pub fn parse_approval(value: &str) -> Result<(bool, bool), String> {
+ match value.trim().to_ascii_lowercase().as_str() {
+ "true" | "on" | "yes" | "1" | "y" | "t" => Ok((true, false)),
+ "false" | "off" | "no" | "0" | "n" | "f" | "" => Ok((false, false)),
+ "phones" => Ok((true, true)),
+ other => Err(format!(
+ "CUA_RELAY_DEVICE_REQUIRE_APPROVAL={other:?}: use true, false or phones"
+ )),
+ }
+ }
+
+ /// Fails closed: the `phones` scope names no one unless phone support is
+ /// on (`phone_clients`: `None` when `CUA_RELAY_PUSH` is off) and at least
+ /// one phone client id is set, and a relay that would then approve
+ /// nothing must not start.
+ pub fn check_approval_scope(
+ phones_only: bool,
+ phone_clients: Option<&[String]>,
+ ) -> Result<(), String> {
+ if phones_only && phone_clients.is_none_or(<[String]>::is_empty) {
+ return Err("CUA_RELAY_DEVICE_REQUIRE_APPROVAL=phones needs CUA_RELAY_PUSH=on and a non-empty CUA_RELAY_PHONE_CLIENTS; without phone clients it would require approval for no device".into());
+ }
+ Ok(())
+ }
+
+ /// Whether the strict policy applies to a device of this class.
+ pub fn strict_for(&self, phone: bool) -> bool {
+ self.require_approval && (phone || !self.approval_phones_only)
+ }
}
impl Default for DevicePolicy {
@@ -1097,6 +1140,7 @@ impl Default for DevicePolicy {
bootstrap_max_auth_age_secs: 600,
session_ttl_secs: 3600,
require_approval: false,
+ approval_phones_only: false,
}
}
}
@@ -1803,7 +1847,7 @@ impl DeviceStore {
let by = if !r.bootstrap {
None
} else if fresh_sign_in.is_some()
- && (!policy.require_approval
+ && (!policy.strict_for(device.is_phone())
|| enrolled
|| is_rekey
|| !Self::has_enrolled(state, account, now, true)
@@ -1993,18 +2037,23 @@ impl DeviceStore {
let until = match record.state(now) {
DeviceState::Enrolled => record.enrolled_until.unwrap_or(now),
DeviceState::Pending => {
- return Err(DeviceError::Forbidden(if self.policy.require_approval {
- "this device is waiting for approval from an enrolled device".into()
- } else {
- "this device is not enrolled yet: sign in again (`cua auth login`) to enroll it, or approve it from an enrolled device".into()
- }))
+ return Err(DeviceError::Forbidden(
+ if self.policy.strict_for(record.is_phone()) {
+ "this device is waiting for approval from an enrolled device".into()
+ } else {
+ "this device is not enrolled yet: sign in again (`cua auth login`) to enroll it, or approve it from an enrolled device".into()
+ },
+ ))
}
DeviceState::Expired => {
- return Err(DeviceError::Forbidden(if self.policy.require_approval {
- "this device needs re-verification: approve it from an enrolled device".into()
- } else {
- "this device's enrollment expired after a period without use: sign in again (`cua auth login`) to re-verify it, or approve it from an enrolled device".into()
- }))
+ return Err(DeviceError::Forbidden(
+ if self.policy.strict_for(record.is_phone()) {
+ "this device needs re-verification: approve it from an enrolled device"
+ .into()
+ } else {
+ "this device's enrollment expired after a period without use: sign in again (`cua auth login`) to re-verify it, or approve it from an enrolled device".into()
+ },
+ ))
}
DeviceState::Revoked => {
return Err(DeviceError::Forbidden("this device was revoked".into()))
@@ -3499,6 +3548,198 @@ pub(crate) mod tests {
);
}
+ /// Registers `key` on a fresh sign-in (verified email) as a phone or a
+ /// computer, as the relay does for a token issued to a phone client.
+ fn register_class(
+ store: &DeviceStore,
+ account: &str,
+ key: &TestKey,
+ phone: bool,
+ mfa: bool,
+ platform: &str,
+ ) -> Registered {
+ let ts = now_secs();
+ let public = key.public();
+ let sig = key.sign(&register_message(&key.id(), ts));
+ store
+ .register(&Registration {
+ account,
+ user: account,
+ public_key: &public,
+ name: "device",
+ platform,
+ machine_id: None,
+ ts,
+ sig: &sig,
+ bootstrap: true,
+ auth_time: Some(now_secs()),
+ email_verified: true,
+ mfa,
+ phone,
+ capabilities: None,
+ })
+ .unwrap()
+ }
+
+ #[test]
+ fn the_approval_value_is_parsed_strictly() {
+ for v in ["true", "TRUE", "on", "yes", "1", " true "] {
+ assert_eq!(DevicePolicy::parse_approval(v), Ok((true, false)), "{v}");
+ }
+ for v in ["false", "off", "no", "0", ""] {
+ assert_eq!(DevicePolicy::parse_approval(v), Ok((false, false)), "{v}");
+ }
+ assert_eq!(DevicePolicy::parse_approval("phones"), Ok((true, true)));
+ assert_eq!(DevicePolicy::parse_approval(" Phones "), Ok((true, true)));
+ for v in ["phone", "maybe", "2", "computers"] {
+ assert!(DevicePolicy::parse_approval(v).is_err(), "{v}");
+ }
+ }
+
+ #[test]
+ fn phones_scope_fails_closed_without_phone_clients() {
+ let some = vec!["cua-spaces-mobile".to_owned()];
+ assert!(DevicePolicy::check_approval_scope(true, Some(&some)).is_ok());
+ assert!(DevicePolicy::check_approval_scope(true, Some(&[])).is_err());
+ assert!(DevicePolicy::check_approval_scope(true, None).is_err());
+ // Other values never need phone clients.
+ assert!(DevicePolicy::check_approval_scope(false, None).is_ok());
+ }
+
+ /// {mode} x {phone, computer} x {account already has an enrolled device,
+ /// or not} x {MFA, or not}: whether a fresh sign-in enrolls the new
+ /// device at once (`true`) or leaves it waiting for an approval.
+ #[test]
+ fn approval_mode_matrix_for_a_new_device() {
+ // (require_approval, phones_only)
+ let modes = [
+ ("false", (false, false)),
+ ("true", (true, false)),
+ ("phones", (true, true)),
+ ];
+ for (name, (require, phones_only)) in modes {
+ for phone in [true, false] {
+ for has_device in [false, true] {
+ for mfa in [false, true] {
+ let store = DeviceStore::in_memory(DevicePolicy {
+ require_approval: require,
+ approval_phones_only: phones_only,
+ ..enforcing()
+ });
+ if has_device {
+ let first = TestKey::new();
+ let r = register_class(&store, "acct", &first, false, false, "macos");
+ assert_eq!(r.device.state(now_secs()), DeviceState::Enrolled);
+ }
+ let key = TestKey::new();
+ let platform = if phone { "ios" } else { "macos" };
+ let r = register_class(&store, "acct", &key, phone, mfa, platform);
+ let strict = require && (phone || !phones_only);
+ let expect = !has_device || !strict || mfa;
+ let got = r.device.state(now_secs()) == DeviceState::Enrolled;
+ assert_eq!(
+ got, expect,
+ "mode={name} phone={phone} has_device={has_device} mfa={mfa}"
+ );
+ assert_eq!(r.code.is_some(), !expect);
+ assert_eq!(r.device.is_phone(), phone);
+ }
+ }
+ }
+ }
+ }
+
+ /// Under `phones` a phone must be approved by an enrolled device while a
+ /// computer still enrolls on its fresh sign-in, and the approval then
+ /// works as before.
+ #[test]
+ fn phones_scope_holds_a_new_phone_for_approval_but_not_a_computer() {
+ let store = DeviceStore::in_memory(DevicePolicy {
+ require_approval: true,
+ approval_phones_only: true,
+ ..enforcing()
+ });
+ let first = TestKey::new();
+ register_class(&store, "acct", &first, false, false, "macos");
+ let runner = TestKey::new();
+ let r = register_class(&store, "acct", &runner, false, false, "linux");
+ assert_eq!(r.device.state(now_secs()), DeviceState::Enrolled);
+ assert!(session(&store, "acct", &runner).is_ok());
+ let phone = TestKey::new();
+ let r = register_class(&store, "acct", &phone, true, false, "ios");
+ let code = r.code.expect("waits for approval");
+ let err = session(&store, "acct", &phone).unwrap_err();
+ assert!(
+ matches!(&err, DeviceError::Forbidden(m) if m.contains("waiting for approval")),
+ "{err:?}"
+ );
+ // A phone claim is sticky and registering again on a fresh sign-in
+ // does not skip the approval.
+ let again = register_class(&store, "acct", &phone, true, false, "macos");
+ assert_eq!(again.device.state(now_secs()), DeviceState::Pending);
+ assert_ne!(again.code.as_deref(), Some(code.as_str()), "a new code");
+ store
+ .approve("acct", &first.id(), again.code.as_deref(), None, true)
+ .unwrap();
+ assert!(session(&store, "acct", &phone).is_ok());
+ }
+
+ /// The 30-day idle rule applies per class: after the enrollment ran
+ /// out, a fresh sign-in re-verifies a computer under `phones` but not a
+ /// phone, and the messages say what is needed.
+ #[test]
+ fn phones_scope_applies_the_idle_rule_to_phones_only() {
+ let store = DeviceStore::in_memory(DevicePolicy {
+ require_approval: true,
+ approval_phones_only: true,
+ ttl_secs: 2,
+ ..enforcing()
+ });
+ let anchor = TestKey::new();
+ register_class(&store, "acct", &anchor, false, false, "macos");
+ let computer = TestKey::new();
+ let phone = TestKey::new();
+ register_class(&store, "acct", &computer, false, false, "linux");
+ // The phone enrolls through the anchor (approval), as in production.
+ let code = register_class(&store, "acct", &phone, true, false, "ios")
+ .code
+ .unwrap();
+ store
+ .approve("acct", &anchor.id(), Some(&code), None, false)
+ .unwrap();
+ std::thread::sleep(std::time::Duration::from_secs(3));
+ let now = now_secs();
+ for k in [&anchor, &computer, &phone] {
+ assert_eq!(store.get(&k.id()).unwrap().state(now), DeviceState::Expired);
+ }
+ // Keep one live strong device so "first device" cannot apply.
+ let live = TestKey::new();
+ assert_eq!(
+ register_class(&store, "acct", &live, false, false, "macos")
+ .device
+ .state(now_secs()),
+ DeviceState::Enrolled
+ );
+ let r = register_class(&store, "acct", &computer, false, false, "linux");
+ assert_eq!(
+ r.device.state(now_secs()),
+ DeviceState::Enrolled,
+ "computer re-verifies"
+ );
+ let r = register_class(&store, "acct", &phone, true, false, "ios");
+ assert_eq!(
+ r.device.state(now_secs()),
+ DeviceState::Expired,
+ "phone needs approval"
+ );
+ assert!(r.code.is_some());
+ let err = session(&store, "acct", &phone).unwrap_err();
+ assert!(
+ matches!(&err, DeviceError::Forbidden(m) if m.contains("needs re-verification")),
+ "{err:?}"
+ );
+ }
+
/// `require_approval` restores the strict rule: a fresh sign-in enrolls
/// the first device, but a brand-new second one needs an approval
/// unless the token proves MFA with a verified email.
diff --git a/libs/cua-spacesd/crates/cua-relay/src/main.rs b/libs/cua-spacesd/crates/cua-relay/src/main.rs
index 97c495af74..dc11500427 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/main.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/main.rs
@@ -206,9 +206,18 @@ struct Args {
/// device, a re-key of a computer it already has, or (verified email) a
/// sign-in proving MFA; any other new device needs an approval from an
/// enrolled device. Off by default: a fresh sign-in enrolls any device
- /// of the account.
- #[arg(long, env = "CUA_RELAY_DEVICE_REQUIRE_APPROVAL")]
- device_require_approval: bool,
+ /// of the account. `phones` applies the strict rule only to phone-class
+ /// devices (enrolled by a `CUA_RELAY_PHONE_CLIENTS` client or reporting
+ /// a phone platform); every other device keeps the default. It needs
+ /// `CUA_RELAY_PUSH=on` and a non-empty `CUA_RELAY_PHONE_CLIENTS`.
+ #[arg(
+ long,
+ env = "CUA_RELAY_DEVICE_REQUIRE_APPROVAL",
+ num_args = 0..=1,
+ default_missing_value = "true",
+ default_value = "false"
+ )]
+ device_require_approval: String,
/// Devices and audit log file (default: `<state file>.devices.json`).
#[arg(long, env = "CUA_RELAY_DEVICES_FILE")]
devices_file: Option<std::path::PathBuf>,
@@ -611,6 +620,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
} else {
None
};
+ let (require_approval, approval_phones_only) =
+ cua_relay::devices::DevicePolicy::parse_approval(&args.device_require_approval)?;
+ cua_relay::devices::DevicePolicy::check_approval_scope(
+ approval_phones_only,
+ push.as_ref().map(|p| p.phone_clients()),
+ )?;
let relay = Relay::try_new(RelayConfig {
tcp_shares,
push,
@@ -637,7 +652,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
ttl_secs: args.device_ttl_days.max(1) * 86_400,
grace_secs: args.device_grace_days * 86_400,
bootstrap_max_auth_age_secs: args.device_bootstrap_max_auth_age_secs,
- require_approval: args.device_require_approval,
+ require_approval,
+ approval_phones_only,
..cua_relay::devices::DevicePolicy::default()
},
devices_file: args.devices_file,
diff --git a/libs/cua-spacesd/crates/cua-relay/tests/approval_phones_mode.rs b/libs/cua-spacesd/crates/cua-relay/tests/approval_phones_mode.rs
new file mode 100644
index 0000000000..55f2a0dc4a
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-relay/tests/approval_phones_mode.rs
@@ -0,0 +1,290 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! `CUA_RELAY_DEVICE_REQUIRE_APPROVAL=phones`: strict device approval for
+//! phone-class devices only. The class comes from the enrolling token's
+//! authorized party (`azp`) against `CUA_RELAY_PHONE_CLIENTS`, or from a
+//! reported phone platform; every other device keeps the default policy.
+//! The matrix: {mode} x {client} x {account already has a device} x {MFA}.
+
+use std::sync::Arc;
+
+use base64::Engine as _;
+use cua_push::{MockProvider, PushHub, Registry};
+use cua_relay::devices::{register_message, session_message, DevicePolicy};
+use cua_relay::oidc::testing::FakeIssuer;
+use cua_relay::oidc::{OidcConfig, OidcValidator};
+use cua_relay::push_api::PushConfig;
+use cua_relay::server::{Relay, RelayConfig};
+use ring::signature::KeyPair as _;
+use serde_json::{json, Value};
+
+const ISSUER: &str = "https://auth.test/realms/cua";
+const PHONE: &str = "cua-spaces-mobile";
+/// Clients that are not phone clients: the CLI, the desktop app, the account
+/// app (per-browser devices) and an unattended device-code install.
+const COMPUTER_CLIENTS: [&str; 4] = [
+ "cua-cli",
+ "cua-desktop",
+ "cua-account-app",
+ "cua-device-code",
+];
+
+fn b64() -> base64::engine::GeneralPurpose {
+ base64::engine::general_purpose::URL_SAFE_NO_PAD
+}
+
+struct Key {
+ pair: ring::signature::EcdsaKeyPair,
+ id: String,
+}
+
+impl Key {
+ 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())
+ }
+}
+
+struct Env {
+ base: String,
+ issuer: FakeIssuer,
+ http: reqwest::Client,
+}
+
+async fn start(require_approval: bool, phones_only: bool) -> Env {
+ let issuer = FakeIssuer::new(ISSUER);
+ let hub = Arc::new(PushHub::new(
+ Registry::in_memory(),
+ Arc::new(MockProvider::new()),
+ ));
+ let mut oidc = OidcConfig::new(ISSUER);
+ oidc.authorized_parties = std::iter::once(PHONE)
+ .chain(COMPUTER_CLIENTS)
+ .map(String::from)
+ .collect();
+ let relay = Relay::new(RelayConfig {
+ oidc: Some(Arc::new(OidcValidator::with_jwks(oidc, issuer.jwks()))),
+ device_policy: DevicePolicy {
+ grace_secs: 0,
+ require_approval,
+ approval_phones_only: phones_only,
+ ..DevicePolicy::default()
+ },
+ push: Some(PushConfig::new(hub).with_phone_clients(vec![PHONE.into()])),
+ ..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;
+ });
+ Env {
+ base,
+ issuer,
+ http: reqwest::Client::new(),
+ }
+}
+
+impl Env {
+ /// Registers `key` signed in through `client` with a fresh sign-in and a
+ /// verified email, `mfa` or not. Returns the JSON answer.
+ async fn register(
+ &self,
+ user: &str,
+ client: &str,
+ platform: &str,
+ mfa: bool,
+ key: &Key,
+ ) -> Value {
+ self.issuer
+ .set_auth_time(user, cua_relay::assertion::now_secs() as i64);
+ self.issuer
+ .set_amr(user, if mfa { &["pwd", "otp"] } else { &["pwd"] });
+ let token = self.issuer.token_for_client(
+ user,
+ Some(&format!("{user}@example.com")),
+ "cua-relay",
+ 600,
+ client,
+ );
+ let ts = cua_relay::assertion::now_secs();
+ let r = self
+ .http
+ .post(format!("{}/v1/devices", self.base))
+ .bearer_auth(token)
+ .json(&json!({
+ "public_key": b64().encode(key.pair.public_key().as_ref()),
+ "name": "device", "platform": platform, "ts": ts,
+ "sig": key.sign(&register_message(&key.id, ts)), "bootstrap": true,
+ }))
+ .send()
+ .await
+ .unwrap();
+ assert!(r.status().is_success(), "register: {}", r.status());
+ r.json().await.unwrap()
+ }
+
+ /// Whether `key` can open a device session.
+ async fn can_open_session(&self, user: &str, client: &str, key: &Key) -> bool {
+ let token = self.issuer.token_for_client(
+ user,
+ Some(&format!("{user}@example.com")),
+ "cua-relay",
+ 600,
+ client,
+ );
+ let ts = cua_relay::assertion::now_secs();
+ self.http
+ .post(format!("{}/v1/devices/session", self.base))
+ .bearer_auth(token)
+ .json(&json!({"device_id": key.id, "ts": ts,
+ "sig": key.sign(&session_message(&key.id, ts))}))
+ .send()
+ .await
+ .unwrap()
+ .status()
+ .is_success()
+ }
+}
+
+#[tokio::test]
+async fn approval_mode_matrix_over_http() {
+ let modes = [
+ ("false", false, false),
+ ("true", true, false),
+ ("phones", true, true),
+ ];
+ let mut n = 0;
+ for (mode, require, phones_only) in modes {
+ let env = start(require, phones_only).await;
+ let clients = std::iter::once((PHONE, "ios", true))
+ .chain(COMPUTER_CLIENTS.iter().map(|c| (*c, "linux", false)));
+ for (client, platform, phone) in clients {
+ for has_device in [false, true] {
+ for mfa in [false, true] {
+ n += 1;
+ let user = format!("u{n}");
+ if has_device {
+ let first = Key::new();
+ let r = env.register(&user, "cua-cli", "macos", false, &first).await;
+ assert_eq!(r["device"]["state"], "enrolled", "the first device enrolls");
+ }
+ let key = Key::new();
+ let r = env.register(&user, client, platform, mfa, &key).await;
+ let strict = require && (phone || !phones_only);
+ let expect = !has_device || !strict || mfa;
+ let ctx = format!(
+ "mode={mode} client={client} has_device={has_device} mfa={mfa}: {r}"
+ );
+ assert_eq!(r["device"]["state"] == "enrolled", expect, "{ctx}");
+ assert_eq!(r["code"].is_null(), expect, "{ctx}");
+ assert_eq!(r["device"]["phone"], phone, "{ctx}");
+ assert_eq!(
+ env.can_open_session(&user, client, &key).await,
+ expect,
+ "{ctx}"
+ );
+ }
+ }
+ }
+ }
+ assert_eq!(n, 3 * 5 * 4);
+}
+
+/// The class is decided by the token's client, not by what the device says:
+/// a phone client reporting a computer platform is still a phone (it cannot
+/// skip approval), and a non-phone client reporting a phone platform becomes
+/// a phone (it only makes itself the stricter, smaller class).
+#[tokio::test]
+async fn the_class_comes_from_the_token_client_not_the_claimed_platform() {
+ let env = start(true, true).await;
+ let first = Key::new();
+ env.register("ada", "cua-cli", "macos", false, &first).await;
+
+ let sneaky_phone = Key::new();
+ let r = env
+ .register("ada", PHONE, "macos", false, &sneaky_phone)
+ .await;
+ assert_eq!(r["device"]["state"], "pending", "{r}");
+ assert_eq!(r["device"]["phone"], true, "{r}");
+
+ let claims_phone = Key::new();
+ let r = env
+ .register("ada", "cua-cli", "ios", false, &claims_phone)
+ .await;
+ assert_eq!(r["device"]["state"], "pending", "{r}");
+ assert_eq!(r["device"]["phone"], true, "{r}");
+
+ // A computer client is unaffected on the same account.
+ let computer = Key::new();
+ let r = env
+ .register("ada", "cua-device-code", "linux", false, &computer)
+ .await;
+ assert_eq!(r["device"]["state"], "enrolled", "{r}");
+ assert_eq!(r["device"]["phone"], false, "{r}");
+}
+
+fn relay_with(value: &str, extra: &[(&str, &str)]) -> std::process::Output {
+ let mut cmd = std::process::Command::new(env!("CARGO_BIN_EXE_cua-relay"));
+ cmd.arg("--listen")
+ .arg("127.0.0.1:0")
+ .env_clear()
+ .env("CUA_RELAY_TOKENS", "test-only-token")
+ .env("CUA_RELAY_DEVICE_REQUIRE_APPROVAL", value);
+ // Windows cannot start its network stack without SYSTEMROOT (os error
+ // 10106); keep it through the cleared environment.
+ for key in ["SYSTEMROOT", "SystemRoot"] {
+ if let Some(v) = std::env::var_os(key) {
+ cmd.env(key, v);
+ }
+ }
+ for (k, v) in extra {
+ cmd.env(k, v);
+ }
+ cmd.output().expect("run cua-relay")
+}
+
+/// The binary refuses `phones` when no phone client can exist (push off, so
+/// phone support off) and refuses a value it does not know, instead of
+/// silently approving nothing.
+#[test]
+fn the_binary_refuses_phones_without_phone_clients_and_unknown_values() {
+ let out = relay_with("phones", &[]);
+ assert!(!out.status.success());
+ let err = String::from_utf8_lossy(&out.stderr);
+ assert!(
+ err.contains("CUA_RELAY_DEVICE_REQUIRE_APPROVAL=phones needs"),
+ "{err}"
+ );
+
+ let out = relay_with("phone", &[]);
+ assert!(!out.status.success());
+ let err = String::from_utf8_lossy(&out.stderr);
+ assert!(err.contains("use true, false or phones"), "{err}");
+}
+
+/// The bare flag and the old boolean values still parse.
+#[test]
+fn the_flag_keeps_its_boolean_forms() {
+ for args in [
+ vec!["--device-require-approval", "--help"],
+ vec!["--device-require-approval=phones", "--help"],
+ ] {
+ let out = std::process::Command::new(env!("CARGO_BIN_EXE_cua-relay"))
+ .args(&args)
+ .env_clear()
+ .output()
+ .unwrap();
+ assert!(out.status.success(), "{args:?}");
+ }
+}