Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua): support host-only sign-in from a remote machine (#4675)

injaneityea763a110ff9
diff --git a/docs/content/docs/cua-cli/reference/cli/host.mdx b/docs/content/docs/cua-cli/reference/cli/host.mdx
index a6bfb9395d..22bf280b72 100644
--- a/docs/content/docs/cua-cli/reference/cli/host.mdx
+++ b/docs/content/docs/cua-cli/reference/cli/host.mdx
@@ -49,6 +49,7 @@ cua host setup [OPTIONS]
| <span id="cua-host-setup--runner"></span>`--runner` | string | `auto` | auto \| systemd \| launchd \| windows-task \| process. |
| <span id="cua-host-setup--profile"></span>`--profile` | `desktop` \| `spare` | `desktop` | What this machine is for: `desktop` (share this desktop; the default) or `spare` (do not share the desktop; provide Spaces). |
| <span id="cua-host-setup--max-spaces"></span>`--max-spaces` | integer | | Provided Spaces at once (default 4; 0: no limit). |
+| <span id="cua-host-setup--remote"></span>`--remote` | boolean | `false` | When sign-in is needed, use a device code to approve it in a browser on another machine. The account session is not saved. |
| <span id="cua-host-setup--desktop"></span>`--desktop` | boolean | `false` | Share this machine's own desktop as a Space. |
| <span id="cua-host-setup--no-desktop"></span>`--no-desktop` | boolean | `false` | Do not share this machine's own desktop (screen, input, shell, files): relayed callers reach only the Spaces it provides. |
| <span id="cua-host-setup--provide-spaces"></span>`--provide-spaces` | boolean | `false` | Create Spaces for your enrolled devices on this machine's runtimes (Lume macOS VMs, Docker Linux containers). |
diff --git a/docs/content/docs/spaces/guides/unattended-access.mdx b/docs/content/docs/spaces/guides/unattended-access.mdx
index 72109c9613..cf2855acc3 100644
--- a/docs/content/docs/spaces/guides/unattended-access.mdx
+++ b/docs/content/docs/spaces/guides/unattended-access.mdx
@@ -23,6 +23,7 @@ machine is shared with, or enroll devices.
| Option | Effect |
|--------|--------|
+| `--remote` | When sign-in is needed, print a device code to approve in a browser on another machine (for example over SSH). The account session is not saved. Cannot be combined with `--direct`. |
| `--direct ip:port` | Serve on your LAN (or a forwarded port) with a local env token instead of the relay. No account needed. |
| `--relay URL` | Another relay (`CUA_RELAY_URL`, default `https://relay.cua.ai`); any self-hosted `cua-relay` works. |
| `--name NAME` | Display name (default: host name). |
diff --git a/docs/content/docs/start-here/host-spaces-on-your-spare-mac.mdx b/docs/content/docs/start-here/host-spaces-on-your-spare-mac.mdx
index f4a7a6207d..dbe08c0e1d 100644
--- a/docs/content/docs/start-here/host-spaces-on-your-spare-mac.mdx
+++ b/docs/content/docs/start-here/host-spaces-on-your-spare-mac.mdx
@@ -62,20 +62,17 @@ curl -fsSL https://cua.ai/install.sh | sh -s -- -y --select spaces,host --no-onb
`-y` accepts the install without the interactive checklist, `--select
spaces,host` picks the Cua Spaces app and hosting, and `--no-onboarding`
skips the automatic `cua auth login` (there is no browser or tty to sign in
-with yet). Then sign in with a device code instead of a browser:
-
-```bash skip="no-runner"
-cua auth login --remote
-```
-
-This prints a URL and a short code. Show both to the user and have them
-approve the code on another signed-in device or at the URL. Once signed in,
-set the mini up as a spare host:
+with yet). Then set up the host with a device code:
```bash test="cli-shape" id="cua-host-setup-spare-ssh"
-cua host setup --profile spare --name "Mac mini (spare)"
+cua host setup --remote --profile spare --name "Mac mini (spare)"
```
+If the mini has no saved account session, this prints a URL and a short code
+that you can approve in a browser on another device. The sign-in is held only
+for setup: the mini keeps its machine token, without saving an account session
+or enrolling it as a controller. An existing account session is reused.
+
<Callout type="warn">
The mini needs an active GUI login session: `cua-spacesd` runs as a
LaunchAgent in the logged-in (Aqua) session, so it starts only after
diff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rs
index 472878d5a3..8c59eb8a31 100644
--- a/libs/cua/crates/cua-cli/src/host.rs
+++ b/libs/cua/crates/cua-cli/src/host.rs
@@ -34,6 +34,10 @@ pub enum HostCmd {
/// Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai).
#[arg(long, conflicts_with = "direct")]
relay: Option<String>,
+ /// When sign-in is needed, use a device code to approve it in a
+ /// browser on another machine. The account session is not saved.
+ #[arg(long, conflicts_with = "direct")]
+ remote: bool,
/// Serve directly on ip:port with a local env token (LAN /
/// port-forwarded) instead of joining a relay.
#[arg(long)]
@@ -846,8 +850,10 @@ impl SetupTokens {
}
/// The stored session, else an interactive sign-in that is not saved.
- pub fn session_or_sign_in() -> Self {
- Self::new(Arc::new(SessionTokens), || Box::pin(sign_in_for_setup()))
+ pub fn session_or_sign_in(flow: cua_auth::Flow) -> Self {
+ Self::new(Arc::new(SessionTokens), move || {
+ Box::pin(sign_in_for_setup(flow))
+ })
}
/// Whether the sign-in was held in memory only.
@@ -878,12 +884,9 @@ impl AccountTokens for SetupTokens {
}
/// Signs in for `cua host setup` without storing the session.
-async fn sign_in_for_setup() -> cua_host::Result<String> {
+async fn sign_in_for_setup(flow: cua_auth::Flow) -> cua_host::Result<String> {
let unauth = |e: cua_auth::Error| cua_host::Error::Unauthenticated(e.to_string());
- let pending = auth::session()
- .begin_login(cua_auth::Flow::Auto)
- .await
- .map_err(unauth)?;
+ let pending = auth::session().begin_login(flow).await.map_err(unauth)?;
eprintln!("Sign in to cua.ai to register this machine (the session is not stored here):");
eprintln!(" {}", pending.url);
if let Some(code) = &pending.user_code {
@@ -910,8 +913,12 @@ impl AccountTokens for SessionTokens {
}
pub fn host_err(e: cua_host::Error) -> CuaError {
+ let message = e.to_string();
+ host_error(e, message)
+}
+
+fn host_error(e: cua_host::Error, m: String) -> CuaError {
use cua_host::Error as E;
- let m = e.to_string();
match e {
E::InvalidArgument(_) | E::Conflict(_) => CuaError::InvalidArgument(m),
E::Unauthenticated(_) => CuaError::Unauthenticated(m),
@@ -1196,6 +1203,7 @@ pub async fn run_host(
match cmd {
HostCmd::Setup {
relay,
+ remote: _, // Selected by the command's SetupTokens.
direct,
name,
allow,
@@ -1234,7 +1242,13 @@ pub async fn run_host(
}
opts.max_spaces = max_spaces;
opts.allow_any_address = allow_any_address;
- let s = host.setup(opts, tokens).await.map_err(host_err)?;
+ let s = host
+ .setup_staged(opts, tokens)
+ .await
+ .map_err(|(stage, e)| {
+ let message = format!("host setup failed at {}: {e}", stage.as_str());
+ host_error(e, message)
+ })?;
emit(&s, json, out)?;
if allow_any_address && s.provide_spaces {
eprintln!(
@@ -2133,6 +2147,96 @@ mod tests {
assert!(!stored.used_ephemeral());
}
+ /// The CLI keeps the core's failure stage without changing its error
+ /// category or exit status. No real OS service is called.
+ #[tokio::test]
+ async fn setup_errors_keep_the_stage_and_error_category() {
+ struct RefuseInstall;
+ impl ServiceManager for RefuseInstall {
+ fn kind(&self) -> RunnerKind {
+ RunnerKind::Process
+ }
+ fn install(&self, _: &cua_host::ServiceSpec) -> cua_host::Result<()> {
+ Err(cua_host::Error::Service("fixture install refused".into()))
+ }
+ fn start(&self) -> cua_host::Result<()> {
+ panic!("must not start")
+ }
+ fn stop(&self) -> cua_host::Result<()> {
+ panic!("must not stop")
+ }
+ fn uninstall(&self) -> cua_host::Result<()> {
+ panic!("must not uninstall")
+ }
+ fn state(&self) -> cua_host::ServiceState {
+ panic!("must not read service state")
+ }
+ }
+ let relay = FakeRelay::start().await;
+ let dir = tempfile::tempdir().unwrap();
+ let driver = dir.path().join("fixture-spacesd");
+ std::fs::write(&driver, b"fixture only").unwrap();
+ let missing = dir.path().join("missing-spacesd");
+ for (stage, code, message) in [
+ ("preflight", 2, "there is nothing to share"),
+ ("token", 6, "fixture sign-in refused"),
+ ("register", 6, "account token required"),
+ ("download", 2, "does not exist"),
+ ("service", 1, "fixture install refused"),
+ ] {
+ let tokens = SetupTokens::new(Arc::new(cua_host::NoAccount), move || {
+ Box::pin(async move {
+ if stage == "token" {
+ Err(cua_host::Error::Unauthenticated(
+ "fixture sign-in refused".into(),
+ ))
+ } else {
+ Ok("unrecognized-account".into())
+ }
+ })
+ });
+ let mut args = vec!["setup", "--driver-bin", driver.to_str().unwrap()];
+ if matches!(stage, "token" | "register") {
+ args.extend(["--relay", &relay.url]);
+ } else {
+ args.extend(["--direct", "127.0.0.1:3211"]);
+ }
+ if stage == "preflight" {
+ args.extend(["--no-desktop", "--no-provide-spaces"]);
+ }
+ if stage == "download" {
+ args[2] = missing.to_str().unwrap();
+ }
+ let mut out = Vec::new();
+ let error = run_host(
+ parse(&args),
+ &dir.path().join(stage),
+ &tokens,
+ None,
+ Some(Arc::new(RefuseInstall)),
+ true,
+ &mut out,
+ )
+ .await
+ .unwrap_err();
+ assert!(out.is_empty());
+ assert_eq!(crate::exit_code(&error), code, "{stage}: {error}");
+ match stage {
+ "preflight" | "download" => assert!(matches!(&error, CuaError::InvalidArgument(_))),
+ "token" | "register" => assert!(matches!(&error, CuaError::Unauthenticated(_))),
+ "service" => assert!(matches!(&error, CuaError::Runtime(_))),
+ _ => unreachable!(),
+ }
+ let text = error.to_string();
+ assert!(
+ text.contains(&format!("host setup failed at {stage}:")),
+ "{text}"
+ );
+ assert!(text.contains(message), "{text}");
+ }
+ assert_eq!(relay.register_calls(), 1);
+ }
+
/// `--allow` sharing stays, is confirmed before it widens access, and is
/// revocable with `unshare`; the driver policy follows.
#[tokio::test]
diff --git a/libs/cua/crates/cua-cli/src/lib.rs b/libs/cua/crates/cua-cli/src/lib.rs
index 1e7db9562c..7873546409 100644
--- a/libs/cua/crates/cua-cli/src/lib.rs
+++ b/libs/cua/crates/cua-cli/src/lib.rs
@@ -1615,7 +1615,12 @@ async fn run(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {
match cli.command {
Command::Host(cmd) => {
let home = util::cua_home();
- let tokens = host::SetupTokens::session_or_sign_in();
+ let flow = if matches!(&cmd, host::HostCmd::Setup { remote: true, .. }) {
+ cua_auth::Flow::Device
+ } else {
+ cua_auth::Flow::Auto
+ };
+ let tokens = host::SetupTokens::session_or_sign_in(flow);
let device = devices_cmd::device_auth(&host::relay_url(None, &home)).ok();
let code =
host::run_host(cmd, &home, &tokens, device.as_deref(), None, json, out).await?;
diff --git a/libs/cua/crates/cua-cli/tests/host_setup.rs b/libs/cua/crates/cua-cli/tests/host_setup.rs
new file mode 100644
index 0000000000..9789f91fe0
--- /dev/null
+++ b/libs/cua/crates/cua-cli/tests/host_setup.rs
@@ -0,0 +1,247 @@
+//! Host-only sign-in through the real CLI, with loopback OIDC/relay servers.
+//! Stop at a missing explicit driver, before any service can be installed.
+mod common;
+use common::*;
+use serde_json::json;
+use std::sync::{Arc, Mutex};
+
+const ACCESS: &str = "ephemeral-account-access";
+const REFRESH: &str = "ephemeral-account-refresh";
+
+async fn issuer(refusal: Option<&'static str>) -> FakeHttp {
+ FakeHttp::start(move |r| {
+ let base = format!("http://{}", r.headers["host"]);
+ match (r.method.as_str(), r.path.split('?').next().unwrap()) {
+ ("GET", "/.well-known/openid-configuration") => (
+ 200,
+ json!({
+ "authorization_endpoint": format!("{base}/authorize"),
+ "token_endpoint": format!("{base}/token"),
+ "device_authorization_endpoint": format!("{base}/device")
+ }),
+ ),
+ // Auto really chooses PKCE: do not mask a regression with a
+ // missing endpoint or a refused redirect preflight.
+ ("GET", "/authorize") => (200, json!({})),
+ ("POST", "/device") => (
+ 200,
+ json!({
+ "device_code": "fixture-device-code", "user_code": "ABCD-EFGH",
+ "verification_uri": format!("{base}/verify"),
+ "expires_in": 60, "interval": 1
+ }),
+ ),
+ ("POST", "/token") => {
+ assert_eq!(
+ r.form("grant_type").as_deref(),
+ Some("urn:ietf:params:oauth:grant-type:device_code")
+ );
+ assert_eq!(
+ r.form("device_code").as_deref(),
+ Some("fixture-device-code")
+ );
+ match refusal {
+ Some(error) => (400, json!({"error": error})),
+ None => (
+ 200,
+ json!({"access_token": ACCESS,
+ "refresh_token": REFRESH, "expires_in": 3600}),
+ ),
+ }
+ }
+ _ => (404, json!({"error": "unexpected request"})),
+ }
+ })
+ .await
+}
+
+fn home(issuer: &FakeHttp, relay: &FakeHttp) -> Home {
+ let mut h = Home::new();
+ h.set("CUA_OIDC_ISSUER", &issuer.url)
+ .set("CUA_RELAY_URL", &relay.url)
+ .set("CUA_OIDC_REDIRECT_PORT", "0")
+ .set("CUA_OIDC_LOGIN_TIMEOUT_SECS", "1")
+ .set("CUA_OIDC_POLL_UNIT_MS", "1");
+ h
+}
+
+async fn setup(h: &Home, extra: &[&str]) -> Out {
+ let missing = h.dir.path().join("missing-spacesd");
+ let mut args = vec![
+ "host",
+ "setup",
+ "--runner",
+ "process",
+ "--driver-bin",
+ missing.to_str().unwrap(),
+ ];
+ args.extend_from_slice(extra);
+ h.run(&args).await
+}
+
+fn no_account_state(h: &Home) {
+ assert!(!h.cua_home().join("credentials.json").exists());
+ let mut dirs = vec![h.dir.path().to_path_buf()];
+ while let Some(dir) = dirs.pop() {
+ for entry in std::fs::read_dir(dir).unwrap() {
+ let path = entry.unwrap().path();
+ if path.is_dir() {
+ dirs.push(path);
+ } else {
+ let name = path.file_name().unwrap().to_string_lossy();
+ assert!(
+ !name.contains("device") && !name.contains("session"),
+ "{path:?}"
+ );
+ let bytes = std::fs::read(&path).unwrap();
+ let text = String::from_utf8_lossy(&bytes);
+ assert!(
+ !text.contains(ACCESS) && !text.contains(REFRESH),
+ "{path:?}"
+ );
+ }
+ }
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn remote_sign_in_and_retry_keep_only_the_machine_credentials() {
+ let oidc = issuer(None).await;
+ let registered = Arc::new(Mutex::new(None::<String>));
+ let state = registered.clone();
+ let relay = FakeHttp::start(move |r| {
+ assert_eq!(
+ (r.method.as_str(), r.path.as_str()),
+ ("POST", "/v1/machines")
+ );
+ assert_eq!(r.headers["authorization"], format!("Bearer {ACCESS}"));
+ let body: serde_json::Value = serde_json::from_str(&r.body).unwrap();
+ let id = body["id"].as_str().unwrap().to_string();
+ let mut previous = state.lock().unwrap();
+ if let Some(old) = previous.as_ref() {
+ assert_eq!(&id, old, "retry must not create a second identity");
+ assert_eq!(
+ r.headers["x-cua-machine-authorization"],
+ "Bearer machine-token-1"
+ );
+ } else {
+ assert!(!r.headers.contains_key("x-cua-machine-authorization"));
+ }
+ let token = if previous.is_some() {
+ "machine-token-2"
+ } else {
+ "machine-token-1"
+ };
+ *previous = Some(id.clone());
+ (200, json!({"machine": {"id": id}, "machine_token": token}))
+ })
+ .await;
+ let h = home(&oidc, &relay);
+ for (args, token) in [
+ (vec!["--remote"], "machine-token-1"),
+ (vec!["--remote", "--json"], "machine-token-2"),
+ ] {
+ let o = setup(&h, &args).await;
+ assert_eq!(o.code, 2, "{o:?}");
+ assert!(
+ o.stdout.is_empty(),
+ "errors stay on stderr even with --json: {o:?}"
+ );
+ assert!(o.stderr.contains("host setup failed at download:"), "{o:?}");
+ assert!(o.stderr.contains("does not exist"), "{o:?}");
+ assert!(o.stderr.contains(&format!("{}/verify", oidc.url)), "{o:?}");
+ assert!(o.stderr.contains("ABCD-EFGH"), "{o:?}");
+ assert!(
+ !o.stderr.contains(ACCESS) && !o.stderr.contains(REFRESH),
+ "{o:?}"
+ );
+ assert_eq!(
+ std::fs::read_to_string(h.cua_home().join("host/machine-token"))
+ .unwrap()
+ .trim(),
+ token
+ );
+ no_account_state(&h);
+ }
+ assert_eq!(relay.requests().len(), 2);
+ let requests = oidc.requests();
+ assert_eq!(requests.iter().filter(|r| r.path == "/device").count(), 2);
+ assert_eq!(requests.iter().filter(|r| r.path == "/token").count(), 2);
+ assert!(!requests.iter().any(|r| r.path.starts_with("/authorize")));
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn remote_refusals_stop_at_token_without_registering() {
+ for refusal in ["access_denied", "expired_token"] {
+ let oidc = issuer(Some(refusal)).await;
+ let relay = FakeHttp::start(|_| (500, json!({"error": "must not register"}))).await;
+ let h = home(&oidc, &relay);
+ let o = setup(&h, &["--remote", "--json"]).await;
+ assert_eq!(o.code, 6, "{o:?}");
+ assert!(o.stdout.is_empty(), "{o:?}");
+ assert!(o.stderr.contains("host setup failed at token:"), "{o:?}");
+ assert!(o.stderr.contains(refusal), "{o:?}");
+ assert!(relay.requests().is_empty());
+ no_account_state(&h);
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn default_uses_pkce_and_remote_reuses_an_existing_session() {
+ let oidc = issuer(None).await;
+ let relay = FakeHttp::start(|r| {
+ assert_eq!(r.path, "/v1/machines");
+ assert_eq!(r.headers["authorization"], "Bearer existing-account");
+ (401, json!({"error": "fixture account refused"}))
+ })
+ .await;
+ let h = home(&oidc, &relay);
+ let o = setup(&h, &[]).await;
+ assert_eq!(o.code, 6, "{o:?}");
+ assert!(o.stderr.contains("host setup failed at token:"), "{o:?}");
+ assert!(
+ oidc.requests()
+ .iter()
+ .any(|r| r.path.starts_with("/authorize?"))
+ );
+ assert!(!oidc.requests().iter().any(|r| r.path == "/device"));
+ assert!(relay.requests().is_empty());
+ no_account_state(&h);
+
+ let path = h.cua_home().join("credentials.json");
+ let credentials =
+ json!({"access_token": "existing-account", "refresh_token": "existing-refresh",
+ "expires_at": "2099-01-01T00:00:00+00:00", "token_type": "Bearer"})
+ .to_string();
+ std::fs::write(&path, &credentials).unwrap();
+ let before = oidc.requests().len();
+ let o = setup(&h, &["--remote"]).await;
+ assert_eq!(o.code, 6, "{o:?}");
+ assert!(o.stderr.contains("host setup failed at register:"), "{o:?}");
+ assert!(o.stderr.contains("fixture account refused"), "{o:?}");
+ assert_eq!(
+ oidc.requests().len(),
+ before,
+ "stored session takes precedence"
+ );
+ assert_eq!(relay.requests().len(), 1);
+ assert_eq!(std::fs::read_to_string(path).unwrap(), credentials);
+}
+
+#[tokio::test]
+async fn remote_is_documented_and_conflicts_with_direct() {
+ let h = Home::new();
+ let help = h.run(&["host", "setup", "--help"]).await;
+ help.ok();
+ assert!(help.stdout.contains("--remote"), "{help:?}");
+ let o = h
+ .run(&["host", "setup", "--remote", "--direct", "127.0.0.1:3211"])
+ .await;
+ assert_eq!(o.code, 2, "{o:?}");
+ assert!(o.stderr.contains("cannot be used with"), "{o:?}");
+ assert!(
+ o.stderr.contains("--direct") && o.stderr.contains("--remote"),
+ "{o:?}"
+ );
+ assert!(!h.cua_home().join("host").exists());
+}
diff --git a/libs/cua/crates/cua-host/src/testing.rs b/libs/cua/crates/cua-host/src/testing.rs
index d8efa8bfce..09eb3a232c 100644
--- a/libs/cua/crates/cua-host/src/testing.rs
+++ b/libs/cua/crates/cua-host/src/testing.rs
@@ -613,6 +613,9 @@ async fn device_session(
{
return err(StatusCode::UNAUTHORIZED, "invalid device signature");
}
+ if device.state == crate::relay::DeviceState::Revoked {
+ return err(StatusCode::FORBIDDEN, "this device was revoked");
+ }
if device.state != crate::relay::DeviceState::Enrolled {
return err(
StatusCode::FORBIDDEN,
diff --git a/scripts/docs-generators/cli-specs/cua.json b/scripts/docs-generators/cli-specs/cua.json
index b0c264e1b9..5d24e854af 100644
--- a/scripts/docs-generators/cli-specs/cua.json
+++ b/scripts/docs-generators/cli-specs/cua.json
@@ -9134,6 +9134,17 @@
"aliases": [],
"arguments": [],
"flags": [
+ {
+ "aliases": [],
+ "default_value": false,
+ "env": null,
+ "help": "When sign-in is needed, use a device code to approve it in a browser on another machine. The account session is not saved",
+ "hidden": false,
+ "name": "remote",
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": false
+ },
{
"aliases": [],
"default_value": false,