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): default Space settings and detach-not-delete for removed computers (CUA-3413) (#6504)

cua-agents[bot]7e86b3ea5441
diff --git a/libs/cua-spacesd/crates/cua-relay/README.md b/libs/cua-spacesd/crates/cua-relay/README.md
index b52e3c6ba8..b13bef15b3 100644
--- a/libs/cua-spacesd/crates/cua-relay/README.md
+++ b/libs/cua-spacesd/crates/cua-relay/README.md
@@ -206,6 +206,20 @@ without printing proxy credentials, relay URL queries or response bodies.
(`GET /v1/pairing-codes`, never the code) and revokes
(`DELETE /v1/pairing-codes/{id}`) them. See `src/pairing.rs`.
+Removing a computer (`DELETE /v1/machines/{id}`) keeps the Spaces it provided
+(records whose `host` is that id) but detaches them: they are not listed and
+connections are refused (403, "its computer was removed from the account")
+until the computer registers again with the same id.
+`DELETE /v1/machines/{id}?spaces=delete` (owner) forgets them too and cuts
+their connections; deleting their files is the client's job, through the
+computer, before it removes it.
+
+Each account has a default Space and a fallback order, so the apps, CLI,
+phone and agents agree where to work: `GET`/`PUT /v1/spaces/settings` and
+`GET /v1/spaces/default?here=<machine-id>`, which resolves the default, then
+the fallback (or every online computer, oldest first), then `here` (see
+`src/spaces.rs`).
+
The API: `/v1/machines` (directory, see `src/api.rs`), `/v1/pairing-codes`, `/v1/devices` and
`/v1/audit` (see `src/device_api.rs`), `/v1/info`, `/healthz`, and
`/relay/v1/machines` (connected machines, admin token only).
@@ -542,6 +556,7 @@ Everything the relay keeps lives next to the state file, on one volume:
| Mesh registry | `<state>.mesh.json` | Compact JSON, one coalesced write per burst of changes (off the async workers), retried with backoff on failure. A new node waits for the write that covers it; a pairing is confirmed only once saved. Soft state: nodes register again on reconnect. Endpoint addresses nodes report are never written to it. |
| Pools | `<state>.pool/<account>/` | `log.jsonl` and `terminal.txt` appended (fsynced) per append; `lease.json`, `keys.json`, `snapshot.bin` replaced whole. A failed append is cut back (no torn line) and answered `500 storage`. |
| Pairing codes | `<state>.pairing.json` | Compact JSON, rewritten (streamed) per mint, spend or revoke. A failed write refuses the mint or spend (`500`); the code stays as it was. |
+| Space settings | `<state>.spaces.json` | Compact JSON of each account's default Space and fallback, rewritten (streamed) per change. A failed write refuses the change (`500`). |
| Grants | `<state>.grants.json` | Compact JSON of who reached each machine and whose access was revoked, rewritten (streamed) on a change. A failed write is not rolled back (a revoke holds in memory, so old tickets stay refused) and is retried with the next authorization. |
Every replaced file goes through a temp file (`.<name>.<uuid>.tmp`); startup
diff --git a/libs/cua-spacesd/crates/cua-relay/src/account_erase.rs b/libs/cua-spacesd/crates/cua-relay/src/account_erase.rs
index 5cf7140a89..355bd8f58f 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/account_erase.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/account_erase.rs
@@ -15,8 +15,9 @@
//! accounts' chains are separate and still verify), pairing codes;
//! - **teams** (leave, delete the ones solely owned, scrub invites and the
//! audit log), who-reached-what rows (`grants`), usage and queued
-//! analytics events, the cached plan, cached team-access answers, mesh
-//! nodes and pairings, and the account's pool.
+//! analytics events, the account's default Space settings, the cached
+//! plan, cached team-access answers, mesh nodes and pairings, and the
+//! account's pool.
//!
//! It needs the internal token (like every `/internal/v1/*` route), is
//! idempotent (a second call, or an unknown account, answers 200 with zero
@@ -230,6 +231,10 @@ fn run(relay: &Relay, sub: &str, given: &[String]) -> Result<serde_json::Value,
.erase_account(sub, &machine_ids)
.map_err(|e| failed("mesh", e))?;
relay.mesh.changed();
+ let spaces_settings = relay
+ .spaces
+ .erase_account(sub)
+ .map_err(|e| failed("spaces", e))?;
let pool = relay
.pool
.erase_account(sub)
@@ -245,6 +250,7 @@ fn run(relay: &Relay, sub: &str, given: &[String]) -> Result<serde_json::Value,
"usage": usage,
"plan_cache": plan_cache,
"pool": pool,
+ "spaces_settings": spaces_settings,
"teams": teams,
"grants": grants,
"posthog_distinct_id": crate::meter::posthog_distinct_id(sub),
diff --git a/libs/cua-spacesd/crates/cua-relay/src/api.rs b/libs/cua-spacesd/crates/cua-relay/src/api.rs
index ab508ede82..8e62eddeae 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/api.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/api.rs
@@ -7,13 +7,21 @@
//! - `GET /v1/info`
//! - `POST /v1/machines` (account): register a machine, get its token.
//! - `GET /v1/machines` (account): owned + shared machines.
-//! - `GET | PATCH | DELETE /v1/machines/{id}`
+//! - `GET | PATCH | DELETE /v1/machines/{id}`: removing a computer detaches
+//! the Spaces it provided (records whose `host` it is): they are kept, not
+//! listed and refused (403, "its computer was removed from the account")
+//! until the computer registers again with the same id.
+//! `DELETE ...?spaces=delete` (owner, not a computer token) also removes
+//! them and cuts their connections.
//! - `POST /v1/machines/{id}/stop-sharing` | `start-sharing` (owner or the
//! machine itself): cut every client and refuse new ones, or resume.
//! - `POST /v1/machines/{id}/leave` (anyone it is shared with, never the
//! owner): take yourself off it. A direct share is removed from the
//! allowlist or viewers; a team machine is hidden from your listing.
//!
+//! Default Space settings and their resolution live in [`crate::spaces`]:
+//! `GET | PUT /v1/spaces/settings` and `GET /v1/spaces/default?here=`.
+//!
//! Account callers other than registration need an enrolled client device
//! (see [`crate::devices`]). A machine token only serves its own machine:
//! it reads its own record, stops sharing, undoes a stop it made itself and
@@ -25,7 +33,7 @@
use std::collections::BTreeMap;
-use axum::extract::{Path, State};
+use axum::extract::{Path, Query, State};
use axum::http::{header, HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
@@ -222,14 +230,14 @@ pub(crate) async fn caller(relay: &Relay, headers: &HeaderMap) -> Result<Caller,
let machine_token = bearer(headers, header::AUTHORIZATION.as_str())
.filter(|t| t.starts_with(MACHINE_TOKEN_PREFIX));
if let Some(token) = machine_token {
- return relay
- .directory
- .machine_for_token(token)
- .map(Caller::Machine)
- .ok_or_else(|| {
- auth_log::rejected(headers, Route::Machines, Reason::UnknownMachineToken, None);
- error(StatusCode::UNAUTHORIZED, "invalid computer token")
- });
+ let record = relay.directory.machine_for_token(token).ok_or_else(|| {
+ auth_log::rejected(headers, Route::Machines, Reason::UnknownMachineToken, None);
+ error(StatusCode::UNAUTHORIZED, "invalid computer token")
+ })?;
+ if relay.directory.is_detached(&record) {
+ return Err(error(StatusCode::FORBIDDEN, DETACHED_MESSAGE));
+ }
+ return Ok(Caller::Machine(record));
}
let Some(oidc) = &relay.config.oidc else {
return Err(error(
@@ -708,83 +716,10 @@ async fn list(State(relay): State<Relay>, headers: HeaderMap) -> Response {
.teams
.accept_email_invites(&crate::teams::Actor { who, device }, &name);
}
- // The account's own and shared machines, then its teams'.
- let mut visible: Vec<(MachineRecord, Role, Option<String>)> = relay
- .directory
- .visible_to(who)
- .into_iter()
- .map(|(r, role)| (r, role, None))
- .collect();
- // Organizations (shadow / org): each org's machine list from
- // the Spaces API. Listing is not access: opening one still asks
- // the API (member, device approval).
- let mut org_listed: Vec<(MachineRecord, String)> = Vec::new();
- if source.evaluates_orgs() {
- for org in &who.orgs {
- let Ok(ids) = relay.org.org_machines(org.key()).await else {
- continue;
- };
- for machine in ids {
- if visible.iter().any(|(r, ..)| r.id == machine)
- || org_listed.iter().any(|(r, _)| r.id == machine)
- {
- continue;
- }
- let Some(r) = relay.directory.get(&machine) else {
- continue;
- };
- // Listed only while the record's owner is a member
- // of the same org (a binding takes any id).
- let owner_in_org = relay
- .org
- .access(&r.owner.id, org.key(), &machine, None)
- .await
- .is_ok_and(|a| a.member);
- if owner_in_org {
- org_listed.push((r, org.key().to_owned()));
- }
- }
- }
- }
- if source == crate::org_access::TeamsSource::Org {
- for (r, org) in org_listed {
- visible.push((r, Role::Shared, Some(org)));
- }
- } else {
- let own = visible.len();
- for (machine, team) in relay.teams.machines_for(&who.account) {
- if visible.iter().any(|(r, ..)| r.id == machine) {
- continue;
- }
- // Only while the team's grant on it still holds.
- if let Some(r) = relay.directory.get(&machine) {
- if relay
- .machine_role(&r, who)
- .is_some_and(|(_, t)| t.contains(&team))
- {
- visible.push((r, Role::Shared, Some(team)));
- }
- }
- }
- if source == crate::org_access::TeamsSource::Shadow {
- let file: std::collections::BTreeSet<&str> =
- visible[own..].iter().map(|(r, ..)| r.id.as_str()).collect();
- let org: std::collections::BTreeSet<&str> =
- org_listed.iter().map(|(r, _)| r.id.as_str()).collect();
- for m in file.symmetric_difference(&org) {
- let decision = if org.contains(m) {
- crate::org_access::OrgDecision::Granted { org: String::new() }
- } else {
- crate::org_access::OrgDecision::NotShared
- };
- relay
- .org
- .shadow("list", &who.user, m, file.contains(m), &decision);
- }
- }
- }
- // A team machine the caller left stays out of their listing.
- visible.retain(|(r, _, team)| team.is_none() || !r.hidden_from(&who.account));
+ let mut visible = visible_machines(&relay, who, source).await;
+ // A Space whose computer was removed from the account stays
+ // stored but is not listed (see [`Directory::is_detached`]).
+ visible.retain(|(r, ..)| !relay.directory.is_detached(r));
visible
.into_iter()
.map(|(r, role, team)| {
@@ -810,6 +745,95 @@ async fn list(State(relay): State<Relay>, headers: HeaderMap) -> Response {
finish(&relay, &caller, response)
}
+/// Every machine `who` can see, with the role and the team (or org) it
+/// reaches it through: their own and directly shared ones, then their
+/// teams' (or organizations'), minus team machines they left. Detached
+/// Spaces are included; callers that list drop them.
+pub(crate) async fn visible_machines(
+ relay: &Relay,
+ who: &Identity,
+ source: crate::org_access::TeamsSource,
+) -> Vec<(MachineRecord, Role, Option<String>)> {
+ // The account's own and shared machines, then its teams'.
+ let mut visible: Vec<(MachineRecord, Role, Option<String>)> = relay
+ .directory
+ .visible_to(who)
+ .into_iter()
+ .map(|(r, role)| (r, role, None))
+ .collect();
+ // Organizations (shadow / org): each org's machine list from
+ // the Spaces API. Listing is not access: opening one still asks
+ // the API (member, device approval).
+ let mut org_listed: Vec<(MachineRecord, String)> = Vec::new();
+ if source.evaluates_orgs() {
+ for org in &who.orgs {
+ let Ok(ids) = relay.org.org_machines(org.key()).await else {
+ continue;
+ };
+ for machine in ids {
+ if visible.iter().any(|(r, ..)| r.id == machine)
+ || org_listed.iter().any(|(r, _)| r.id == machine)
+ {
+ continue;
+ }
+ let Some(r) = relay.directory.get(&machine) else {
+ continue;
+ };
+ // Listed only while the record's owner is a member
+ // of the same org (a binding takes any id).
+ let owner_in_org = relay
+ .org
+ .access(&r.owner.id, org.key(), &machine, None)
+ .await
+ .is_ok_and(|a| a.member);
+ if owner_in_org {
+ org_listed.push((r, org.key().to_owned()));
+ }
+ }
+ }
+ }
+ if source == crate::org_access::TeamsSource::Org {
+ for (r, org) in org_listed {
+ visible.push((r, Role::Shared, Some(org)));
+ }
+ } else {
+ let own = visible.len();
+ for (machine, team) in relay.teams.machines_for(&who.account) {
+ if visible.iter().any(|(r, ..)| r.id == machine) {
+ continue;
+ }
+ // Only while the team's grant on it still holds.
+ if let Some(r) = relay.directory.get(&machine) {
+ if relay
+ .machine_role(&r, who)
+ .is_some_and(|(_, t)| t.contains(&team))
+ {
+ visible.push((r, Role::Shared, Some(team)));
+ }
+ }
+ }
+ if source == crate::org_access::TeamsSource::Shadow {
+ let file: std::collections::BTreeSet<&str> =
+ visible[own..].iter().map(|(r, ..)| r.id.as_str()).collect();
+ let org: std::collections::BTreeSet<&str> =
+ org_listed.iter().map(|(r, _)| r.id.as_str()).collect();
+ for m in file.symmetric_difference(&org) {
+ let decision = if org.contains(m) {
+ crate::org_access::OrgDecision::Granted { org: String::new() }
+ } else {
+ crate::org_access::OrgDecision::NotShared
+ };
+ relay
+ .org
+ .shadow("list", &who.user, m, file.contains(m), &decision);
+ }
+ }
+ }
+ // A team machine the caller left stays out of their listing.
+ visible.retain(|(r, _, team)| team.is_none() || !r.hidden_from(&who.account));
+ visible
+}
+
/// `x-cua-device-enrollment` on a listing for a device that is not
/// enrolled: the machines are listed by name only and cannot be reached.
pub const NOT_ENROLLED_FLAG: &str = "not-enrolled";
@@ -944,11 +968,26 @@ async fn patch_one(
}
}
+/// The message for a Space whose computer was removed from the account.
+pub const DETACHED_MESSAGE: &str = "its computer was removed from the account";
+
+/// `DELETE /v1/machines/{id}`: removes the computer. Spaces it provided
+/// (records whose `host` is this id) are kept but detached: not listed, not
+/// reachable, back unchanged when the computer registers again with the
+/// same id. `?spaces=delete` also removes those records (the computer's
+/// owner only) and cuts their connections; deleting their files is the
+/// client's job, through the computer, before it removes it.
async fn delete_one(
State(relay): State<Relay>,
Path(id): Path<String>,
+ Query(query): Query<std::collections::HashMap<String, String>>,
headers: HeaderMap,
) -> Response {
+ let delete_spaces = match query.get("spaces").map(String::as_str) {
+ None => false,
+ Some("delete") => true,
+ Some(_) => return error(StatusCode::BAD_REQUEST, "spaces: delete"),
+ };
let caller = match caller(&relay, &headers).await {
Ok(c) => c,
Err(r) => return r,
@@ -966,10 +1005,37 @@ async fn delete_one(
if let Err(r) = require_owner(role) {
return r;
}
+ if delete_spaces && matches!(caller, Caller::Machine(_)) {
+ return error(
+ StatusCode::FORBIDDEN,
+ "a computer token cannot delete its Spaces; use your account",
+ );
+ }
match relay.directory.remove(&id) {
Ok(removed) => {
relay.drop_machine(&id);
relay.teams.forget_machine(&id);
+ // Its Spaces lose their computer: cut them either way, then
+ // forget them only when asked to.
+ for child in relay.directory.children_of(&id) {
+ relay.drop_machine(&child.id);
+ if !delete_spaces {
+ continue;
+ }
+ match relay.directory.remove(&child.id) {
+ Ok(_) | Err(DirectoryError::NotFound) => {
+ relay.teams.forget_machine(&child.id);
+ relay.devices.audit(
+ &child.owner.id,
+ AuditEvent::new("machine_removed")
+ .device(caller.actor().as_deref())
+ .machine(&child.id)
+ .detail(format!("Space of removed computer {id}")),
+ );
+ }
+ Err(e) => return directory_error(e),
+ }
+ }
tracing::info!(machine = %id, "machine removed");
relay.devices.audit(
&removed.owner.id,
diff --git a/libs/cua-spacesd/crates/cua-relay/src/directory.rs b/libs/cua-spacesd/crates/cua-relay/src/directory.rs
index 61ea40ccdf..f7e5e4a181 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/directory.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/directory.rs
@@ -519,6 +519,28 @@ impl Directory {
.collect()
}
+ /// Whether `record` is a Space whose computer (its `host`) has no record:
+ /// the computer was removed from the account but its Spaces were kept.
+ /// A detached Space is not listed and cannot be reached; registering
+ /// the computer again with the same id brings it back unchanged.
+ pub fn is_detached(&self, record: &MachineRecord) -> bool {
+ match record.host.as_deref() {
+ Some(host) => !self.records.lock().expect("directory").contains_key(host),
+ None => false,
+ }
+ }
+
+ /// The records that name `host` as their computer.
+ pub fn children_of(&self, host: &str) -> Vec<MachineRecord> {
+ self.records
+ .lock()
+ .expect("directory")
+ .values()
+ .filter(|r| r.host.as_deref() == Some(host))
+ .cloned()
+ .collect()
+ }
+
/// Every record `who` owns or is allowlisted on, with the role.
pub fn visible_to(&self, who: &Identity) -> Vec<(MachineRecord, Role)> {
self.records
diff --git a/libs/cua-spacesd/crates/cua-relay/src/hosted.rs b/libs/cua-spacesd/crates/cua-relay/src/hosted.rs
index f6ffd43cb0..aebd356ee3 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/hosted.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/hosted.rs
@@ -556,7 +556,10 @@ pub(crate) fn shared_with(
};
let mut shared = Vec::new();
for (record, role) in relay.directory.visible_to(&who) {
- if role == crate::directory::Role::Owner || !record.sharing {
+ if role == crate::directory::Role::Owner
+ || !record.sharing
+ || relay.directory.is_detached(&record)
+ {
continue;
}
let host = record.host.as_deref().and_then(|h| relay.directory.get(h));
diff --git a/libs/cua-spacesd/crates/cua-relay/src/lib.rs b/libs/cua-spacesd/crates/cua-relay/src/lib.rs
index cde949eda8..9733d341a7 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/lib.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/lib.rs
@@ -56,6 +56,7 @@ pub mod push_api;
pub mod route_marker;
pub mod server;
pub mod share_web;
+pub mod spaces;
pub mod storage;
pub mod tcp_shares;
mod transport;
diff --git a/libs/cua-spacesd/crates/cua-relay/src/server.rs b/libs/cua-spacesd/crates/cua-relay/src/server.rs
index 65e8249d77..a199c69d8a 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/server.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/server.rs
@@ -409,6 +409,8 @@ pub struct Relay {
pub(crate) grants: Arc<crate::grants::Grants>,
/// Pairing codes ("add a machine" by link or QR).
pub(crate) pairing: Arc<crate::pairing::PairingStore>,
+ /// Each account's default Space and fallback order.
+ pub(crate) spaces: Arc<crate::spaces::SpacesSettings>,
pub(crate) key: Arc<RelayKey>,
/// Open client streams across every machine (S7): the global memory
/// budget's live counter.
@@ -529,6 +531,13 @@ impl Relay {
)?,
None => crate::pairing::PairingStore::in_memory(),
};
+ let spaces = match &config.state_file {
+ Some(path) => crate::spaces::SpacesSettings::open_with(
+ path.with_extension("spaces.json"),
+ storage.clone(),
+ )?,
+ None => crate::spaces::SpacesSettings::in_memory(),
+ };
let key = config
.signing_key
.clone()
@@ -583,6 +592,7 @@ impl Relay {
plans,
grants: Arc::new(grants),
pairing: Arc::new(pairing),
+ spaces: Arc::new(spaces),
key,
global_streams: Arc::default(),
mesh,
@@ -639,6 +649,7 @@ impl Relay {
.merge(crate::meter::routes())
.merge(self.hosted_routes())
.merge(crate::pairing::routes())
+ .merge(crate::spaces::routes())
.merge(crate::tcp_shares::routes())
.merge(if self.share_web_enabled() {
crate::share_web::routes()
@@ -1397,6 +1408,9 @@ async fn machine_connect_inner(
.filter(|t| t.starts_with(MACHINE_TOKEN_PREFIX))
.and_then(|t| relay.directory.machine_for_token(t));
match record {
+ Some(record) if record.id == id && relay.directory.is_detached(&record) => {
+ return text(StatusCode::FORBIDDEN, crate::api::DETACHED_MESSAGE)
+ }
Some(record) if record.id == id => Registrant::Account(record.owner.id),
Some(_) => {
return text(
@@ -2109,6 +2123,21 @@ async fn authorize_account_client(
"the host stopped sharing this computer",
));
}
+ // A Space whose computer was removed from the account is kept but
+ // refused. Someone it is not shared with gets the usual refusal below,
+ // so this does not tell them it exists.
+ if relay.directory.is_detached(&record)
+ && identity
+ .as_ref()
+ .is_none_or(|who| relay.machine_role(&record, who).is_some())
+ {
+ return Err(refuse(
+ headers,
+ StatusCode::FORBIDDEN,
+ GrpcCode::PermissionDenied,
+ crate::api::DETACHED_MESSAGE,
+ ));
+ }
let mut phone_call = false;
let mut ticket_phone = false;
let mut gate = None;
diff --git a/libs/cua-spacesd/crates/cua-relay/src/spaces.rs b/libs/cua-spacesd/crates/cua-relay/src/spaces.rs
new file mode 100644
index 0000000000..871833465a
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-relay/src/spaces.rs
@@ -0,0 +1,468 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Each account's default Space (account mode), kept here so the apps, CLI,
+//! phone and agents share one answer:
+//!
+//! - `GET /v1/spaces/settings`: `{default_space, fallback, fallback_on,
+//! updated_at}` (defaults for an account that never set any).
+//! - `PUT /v1/spaces/settings`: replaces the whole object. 400 for a bad id,
+//! a duplicate in `fallback` or more than [`MAX_FALLBACK`] entries; 403 for
+//! a computer the caller cannot see.
+//! - `GET /v1/spaces/default?here=<machine-id>`: where a client should work
+//! now: the default if it is online, else the fallback list (or, when it
+//! is empty, every online computer the account can use, oldest first),
+//! else `here` (the caller's own computer).
+//!
+//! A Space id is `relay:<machine-id>` (a computer, or a Space with its own
+//! record) or `relay:<machine-id>/<name>`. Ids that are no longer visible,
+//! or whose computer was removed (detached, see [`crate::api`]), are skipped
+//! but stay stored: they count again when they come back.
+//!
+//! Every call carries the account token (a computer token is refused) from
+//! an enrolled device. The settings persist per account in
+//! `<state>.spaces.json` (atomic replace, private file mode) and are erased
+//! with the account ([`crate::account_erase`]).
+
+// Handlers short-circuit with ready-made responses.
+#![allow(clippy::result_large_err)]
+
+use std::collections::{BTreeMap, HashMap};
+use std::path::PathBuf;
+use std::sync::{Arc, Mutex};
+
+use axum::extract::{DefaultBodyLimit, Query, State};
+use axum::http::{HeaderMap, StatusCode};
+use axum::response::{IntoResponse, Response};
+use axum::routing::get;
+use axum::{Json, Router};
+use serde::{Deserialize, Serialize};
+
+use crate::api::{account_caller, error, visible_machines, LIVE_HEARTBEAT_SECS};
+use crate::assertion::{now_secs, remove_stale_temps, write_private_with};
+use crate::device_api::{flag_grace, Gate};
+use crate::directory::{MachineRecord, Role};
+use crate::server::{Registrant, Relay};
+use crate::storage::{store, Storage};
+
+/// Most entries in `fallback`.
+pub const MAX_FALLBACK: usize = 16;
+/// Request bodies here are tiny.
+const BODY_LIMIT: usize = 8 * 1024;
+
+/// An account's default Space settings.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Settings {
+ /// The Space to work in; `null` when unset.
+ pub default_space: Option<String>,
+ /// Where to go when the default is offline; empty means automatic.
+ pub fallback: Vec<String>,
+ /// False: only the default, then this device.
+ pub fallback_on: bool,
+ /// Unix seconds of the last change (0 for settings never set).
+ pub updated_at: u64,
+}
+
+impl Default for Settings {
+ fn default() -> Self {
+ Settings {
+ default_space: None,
+ fallback: Vec::new(),
+ fallback_on: true,
+ updated_at: 0,
+ }
+ }
+}
+
+/// What a client may send to replace the settings; absent fields reset to
+/// their defaults.
+#[derive(Debug, Deserialize)]
+struct Put {
+ #[serde(default)]
+ default_space: Option<String>,
+ #[serde(default)]
+ fallback: Vec<String>,
+ #[serde(default = "yes")]
+ fallback_on: bool,
+}
+
+fn yes() -> bool {
+ true
+}
+
+/// The settings of every account, persisted as JSON (atomic replace) when a
+/// file is configured.
+#[derive(Debug, Default)]
+pub struct SpacesSettings {
+ path: Option<PathBuf>,
+ accounts: Mutex<BTreeMap<String, Settings>>,
+ storage: Arc<Storage>,
+}
+
+impl SpacesSettings {
+ /// In memory only.
+ pub fn in_memory() -> Self {
+ Self::default()
+ }
+
+ /// Loads (or starts) the store persisted at `path`, reporting writes to
+ /// `storage`.
+ pub fn open_with(path: PathBuf, storage: Arc<Storage>) -> std::io::Result<Self> {
+ remove_stale_temps(&path)?;
+ let accounts = match std::fs::read(&path) {
+ Ok(raw) => serde_json::from_slice(&raw)
+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => BTreeMap::new(),
+ Err(e) => return Err(e),
+ };
+ Ok(Self {
+ path: Some(path),
+ accounts: Mutex::new(accounts),
+ storage,
+ })
+ }
+
+ /// The account's settings (the defaults if it never set any).
+ pub fn get(&self, account: &str) -> Settings {
+ self.accounts
+ .lock()
+ .expect("spaces")
+ .get(account)
+ .cloned()
+ .unwrap_or_default()
+ }
+
+ /// Writes `next` and swaps it in; on a failed write the settings stay as
+ /// they were.
+ fn commit(
+ &self,
+ accounts: &mut BTreeMap<String, Settings>,
+ next: BTreeMap<String, Settings>,
+ ) -> Result<(), String> {
+ if let Some(path) = &self.path {
+ let written = (|| {
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ write_private_with(path, |out| {
+ serde_json::to_writer(&mut *out, &next).map_err(std::io::Error::other)
+ })
+ })();
+ self.storage.record(store::SPACES, &written);
+ written.map_err(|e| e.to_string())?;
+ }
+ *accounts = next;
+ Ok(())
+ }
+
+ /// Replaces the account's settings.
+ fn set(&self, account: &str, put: Put) -> Result<Settings, String> {
+ let mut accounts = self.accounts.lock().expect("spaces");
+ let mut next = accounts.clone();
+ let settings = Settings {
+ default_space: put.default_space,
+ fallback: put.fallback,
+ fallback_on: put.fallback_on,
+ updated_at: now_secs(),
+ };
+ next.insert(account.to_owned(), settings.clone());
+ self.commit(&mut accounts, next)?;
+ Ok(settings)
+ }
+
+ /// Account deletion: forgets the account's settings. Returns whether
+ /// there were any. The file is rewritten every call, so a retry after a
+ /// failed write finishes the job.
+ pub fn erase_account(&self, account: &str) -> Result<bool, String> {
+ let mut accounts = self.accounts.lock().expect("spaces");
+ let mut next = accounts.clone();
+ let had = next.remove(account).is_some();
+ self.commit(&mut accounts, next)?;
+ Ok(had)
+ }
+}
+
+pub(crate) fn routes() -> Router<Relay> {
+ Router::new()
+ .route("/v1/spaces/settings", get(get_settings).put(put_settings))
+ .route("/v1/spaces/default", get(resolve))
+ .layer(DefaultBodyLimit::max(BODY_LIMIT))
+}
+
+/// `relay:<machine-id>` or `relay:<machine-id>/<name>` as (machine id, name).
+pub fn parse_space(id: &str) -> Option<(&str, Option<&str>)> {
+ let rest = id.strip_prefix("relay:")?;
+ let (machine, name) = match rest.split_once('/') {
+ Some((m, n)) => (m, Some(n)),
+ None => (rest, None),
+ };
+ if !crate::valid_machine_id(machine) {
+ return None;
+ }
+ if let Some(n) = name {
+ let ok = (1..=63).contains(&n.len())
+ && n.bytes()
+ .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
+ if !ok {
+ return None;
+ }
+ }
+ Some((machine, name))
+}
+
+/// The account behind the request, from an enrolled device.
+async fn account(
+ relay: &Relay,
+ headers: &HeaderMap,
+) -> Result<(crate::oidc::Identity, Result<Gate, String>), Response> {
+ let (who, gate) = account_caller(relay, headers).await?;
+ if let Err(m) = &gate {
+ return Err(error(StatusCode::FORBIDDEN, m.clone()));
+ }
+ Ok((who, gate))
+}
+
+fn finish(relay: &Relay, gate: &Result<Gate, String>, mut response: Response) -> Response {
+ if matches!(gate, Ok(Gate::Grace)) {
+ flag_grace(relay, response.headers_mut());
+ }
+ response
+}
+
+async fn get_settings(State(relay): State<Relay>, headers: HeaderMap) -> Response {
+ let (who, gate) = match account(&relay, &headers).await {
+ Ok(v) => v,
+ Err(r) => return r,
+ };
+ finish(
+ &relay,
+ &gate,
+ Json(relay.spaces.get(&who.account)).into_response(),
+ )
+}
+
+async fn put_settings(
+ State(relay): State<Relay>,
+ headers: HeaderMap,
+ Json(put): Json<Put>,
+) -> Response {
+ let (who, gate) = match account(&relay, &headers).await {
+ Ok(v) => v,
+ Err(r) => return r,
+ };
+ if put.fallback.len() > MAX_FALLBACK {
+ return error(
+ StatusCode::BAD_REQUEST,
+ format!("at most {MAX_FALLBACK} fallback Spaces"),
+ );
+ }
+ let mut seen = std::collections::BTreeSet::new();
+ for id in &put.fallback {
+ if !seen.insert(id.as_str()) {
+ return error(StatusCode::BAD_REQUEST, format!("duplicate Space id: {id}"));
+ }
+ }
+ for id in put.default_space.iter().chain(put.fallback.iter()) {
+ let Some((machine, _)) = parse_space(id) else {
+ return error(StatusCode::BAD_REQUEST, format!("invalid Space id: {id}"));
+ };
+ let usable = relay
+ .directory
+ .get(machine)
+ .is_some_and(|r| relay.machine_role(&r, &who).is_some());
+ if !usable {
+ return error(
+ StatusCode::FORBIDDEN,
+ format!("{id} is not a computer you can use"),
+ );
+ }
+ }
+ match relay.spaces.set(&who.account, put) {
+ Ok(settings) => finish(&relay, &gate, Json(settings).into_response()),
+ Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e),
+ }
+}
+
+/// A computer is online when it is connected for its owner with a live
+/// heartbeat and is sharing.
+fn online(relay: &Relay, record: &MachineRecord) -> bool {
+ record.sharing
+ && relay
+ .machine(&record.id)
+ .filter(|m| matches!(&m.registrant, Registrant::Account(o) if o == &record.owner.id))
+ .is_some_and(|m| m.heartbeat_age().as_secs() <= LIVE_HEARTBEAT_SECS)
+}
+
+#[derive(Serialize)]
+struct Entry {
+ space: String,
+ name: String,
+ online: bool,
+ role: &'static str,
+}
+
+async fn resolve(
+ State(relay): State<Relay>,
+ headers: HeaderMap,
+ Query(query): Query<HashMap<String, String>>,
+) -> Response {
+ let (who, gate) = match account(&relay, &headers).await {
+ Ok(v) => v,
+ Err(r) => return r,
+ };
+ let settings = relay.spaces.get(&who.account);
+ // What the caller can use now: detached Spaces are out.
+ let usable: Vec<(MachineRecord, Role)> = visible_machines(&relay, &who, relay.org.source())
+ .await
+ .into_iter()
+ .filter(|(r, ..)| !relay.directory.is_detached(r))
+ .map(|(r, role, _)| (r, role))
+ .collect();
+ let find = |machine: &str| usable.iter().find(|(r, _)| r.id == machine);
+ // An id as an order entry, if it can be used now.
+ let entry = |space: &str, role: &'static str| -> Option<Entry> {
+ let (machine, child) = parse_space(space)?;
+ let (record, _) = find(machine)?;
+ Some(Entry {
+ space: space.to_owned(),
+ name: match child {
+ Some(n) => format!("{} / {n}", record.name),
+ None => record.name.clone(),
+ },
+ online: online(&relay, record),
+ role,
+ })
+ };
+
+ let here = query
+ .get("here")
+ .map(|h| h.trim())
+ .filter(|h| !h.is_empty())
+ .map(|h| format!("relay:{h}"))
+ .and_then(|s| entry(&s, "here"));
+
+ let Some(default) = settings.default_space.as_deref() else {
+ let space = here.as_ref().map(|e| e.space.clone());
+ return finish(
+ &relay,
+ &gate,
+ Json(serde_json::json!({
+ "space": space,
+ "reason": "unset",
+ "default_space": null,
+ "default_online": false,
+ "order": here.into_iter().collect::<Vec<_>>(),
+ }))
+ .into_response(),
+ );
+ };
+
+ let mut order: Vec<Entry> = Vec::new();
+ let default_entry = entry(default, "default");
+ let default_online = default_entry.as_ref().is_some_and(|e| e.online);
+ order.extend(default_entry);
+ if settings.fallback_on {
+ let here_id = here.as_ref().map(|e| e.space.as_str());
+ let skip = |space: &str| space == default || Some(space) == here_id;
+ if settings.fallback.is_empty() {
+ let mut auto: Vec<&MachineRecord> = usable
+ .iter()
+ .filter(|(r, role)| r.host.is_none() && *role != Role::Viewer && online(&relay, r))
+ .map(|(r, _)| r)
+ .filter(|r| !skip(&format!("relay:{}", r.id)))
+ .collect();
+ auto.sort_by(|a, b| (a.created_at, &a.id).cmp(&(b.created_at, &b.id)));
+ order.extend(auto.into_iter().map(|r| Entry {
+ space: format!("relay:{}", r.id),
+ name: r.name.clone(),
+ online: true,
+ role: "fallback",
+ }));
+ } else {
+ order.extend(
+ settings
+ .fallback
+ .iter()
+ .filter(|s| !skip(s))
+ .filter_map(|s| entry(s, "fallback")),
+ );
+ }
+ }
+ let first = order.iter().find(|e| e.online);
+ let (space, reason) = match first {
+ Some(e) if e.role == "default" => (Some(e.space.clone()), "default"),
+ Some(e) => (Some(e.space.clone()), "fallback"),
+ None => (here.as_ref().map(|e| e.space.clone()), "here"),
+ };
+ order.extend(here);
+ finish(
+ &relay,
+ &gate,
+ Json(serde_json::json!({
+ "space": space,
+ "reason": reason,
+ "default_space": default,
+ "default_online": default_online,
+ "order": order,
+ }))
+ .into_response(),
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn space_ids() {
+ assert_eq!(parse_space("relay:abcd1234"), Some(("abcd1234", None)));
+ assert_eq!(
+ parse_space("relay:abcd1234/dev-1"),
+ Some(("abcd1234", Some("dev-1")))
+ );
+ for bad in [
+ "abcd1234",
+ "relay:",
+ "relay:short",
+ "relay:abcd1234/",
+ "relay:abcd1234/UP",
+ "relay:abcd1234/a/b",
+ "relay:ABCD1234",
+ "local:abcd1234",
+ ] {
+ assert_eq!(parse_space(bad), None, "{bad}");
+ }
+ assert_eq!(
+ parse_space(&format!("relay:abcd1234/{}", "a".repeat(64))),
+ None
+ );
+ }
+
+ #[test]
+ fn settings_persist_and_erase() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("state.spaces.json");
+ let store = SpacesSettings::open_with(path.clone(), Default::default()).unwrap();
+ assert_eq!(store.get("ada"), Settings::default());
+ store
+ .set(
+ "ada",
+ Put {
+ default_space: Some("relay:abcd1234".into()),
+ fallback: vec![],
+ fallback_on: false,
+ },
+ )
+ .unwrap();
+ let again = SpacesSettings::open_with(path.clone(), Default::default()).unwrap();
+ assert_eq!(
+ again.get("ada").default_space.as_deref(),
+ Some("relay:abcd1234")
+ );
+ assert!(!again.get("ada").fallback_on);
+ assert!(again.erase_account("ada").unwrap());
+ assert!(!again.erase_account("ada").unwrap());
+ let last = SpacesSettings::open_with(path, Default::default()).unwrap();
+ assert_eq!(last.get("ada"), Settings::default());
+ }
+}
diff --git a/libs/cua-spacesd/crates/cua-relay/src/storage.rs b/libs/cua-spacesd/crates/cua-relay/src/storage.rs
index 0be3a527fc..586475deb2 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/storage.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/storage.rs
@@ -4,7 +4,7 @@
//! The health of the relay's state volume (CUA-1297).
//!
//! Every state store (devices, audit log, device sessions, machine
-//! directory, mesh registry, pool, usage, teams, pairing codes, grants)
+//! directory, mesh registry, pool, usage, teams, pairing codes, grants, Space settings)
//! reports each write here. A failed write
//! is counted, logged with a stable line (`state persist failed`, field
//! `alert = "state_persist_failed"`) and remembered as the store's last
@@ -69,9 +69,11 @@ pub mod store {
/// `<state>.grants.json`: who reached each machine and whose access was
/// revoked (old tickets refused).
pub const GRANTS: &str = "grants";
+ /// `<state>.spaces.json`: each account's default Space settings.
+ pub const SPACES: &str = "spaces";
/// Every store, in report order.
- pub const ALL: [&str; 10] = [
- DEVICES, AUDIT, SESSIONS, DIRECTORY, MESH, POOL, USAGE, TEAMS, PAIRING, GRANTS,
+ pub const ALL: [&str; 11] = [
+ DEVICES, AUDIT, SESSIONS, DIRECTORY, MESH, POOL, USAGE, TEAMS, PAIRING, GRANTS, SPACES,
];
}
diff --git a/libs/cua-spacesd/crates/cua-relay/src/tcp_shares.rs b/libs/cua-spacesd/crates/cua-relay/src/tcp_shares.rs
index 8742122c93..2458afbd5a 100644
--- a/libs/cua-spacesd/crates/cua-relay/src/tcp_shares.rs
+++ b/libs/cua-spacesd/crates/cua-relay/src/tcp_shares.rs
@@ -706,6 +706,7 @@ pub async fn reconcile(relay: &Relay, tcp: &Arc<TcpShares>) {
match relay.directory.get(&a.machine) {
None => Some("machine_removed"),
Some(r) if r.owner.id != a.owner => Some("machine_changed_owner"),
+ Some(r) if relay.directory.is_detached(&r) => Some("machine_removed"),
Some(r) if !r.sharing => Some("sharing_stopped"),
Some(_) => None,
}
diff --git a/libs/cua-spacesd/crates/cua-relay/tests/account_erase.rs b/libs/cua-spacesd/crates/cua-relay/tests/account_erase.rs
index 0c413f4078..85b10a68b8 100644
--- a/libs/cua-spacesd/crates/cua-relay/tests/account_erase.rs
+++ b/libs/cua-spacesd/crates/cua-relay/tests/account_erase.rs
@@ -304,6 +304,19 @@ impl Acct {
(status, r.json().await.unwrap_or(Value::Null))
}
+ async fn put(&self, base: &str, path: &str, body: Value) -> (StatusCode, Value) {
+ let r = reqwest::Client::new()
+ .put(format!("{base}{path}"))
+ .bearer_auth(&self.token)
+ .header(SESSION, &self.session)
+ .json(&body)
+ .send()
+ .await
+ .unwrap();
+ let status = r.status();
+ (status, r.json().await.unwrap_or(Value::Null))
+ }
+
async fn machines(&self, base: &str) -> Vec<Value> {
let (s, v) = self.get(base, "/v1/machines").await;
assert_eq!(s, StatusCode::OK, "{v}");
@@ -419,7 +432,7 @@ async fn an_unknown_account_is_a_200_with_zero_counts() {
] {
assert_eq!(v[k], 0, "{k}: {v}");
}
- for k in ["usage", "plan_cache", "pool"] {
+ for k in ["usage", "plan_cache", "pool", "spaces_settings"] {
assert_eq!(v[k], false, "{k}: {v}");
}
assert_eq!(
@@ -530,6 +543,17 @@ async fn it_erases_one_account_everywhere_and_nobody_elses_and_survives_a_restar
"ada's pool directory exists"
);
+ // Her default Space.
+ let (s, set) = ada
+ .put(
+ &env.base,
+ "/v1/spaces/settings",
+ json!({"default_space": format!("relay:{a}")}),
+ )
+ .await;
+ assert_eq!(s, StatusCode::OK, "{set}");
+ assert!(!files_with(env.dir.path(), ADA).is_empty());
+
// Mesh: Ada's host and laptop, Bob's host.
let m_a = mesh_node(
&env.base,
@@ -590,6 +614,7 @@ async fn it_erases_one_account_everywhere_and_nobody_elses_and_survives_a_restar
assert!(v["mesh_nodes"].as_u64().unwrap() >= 2, "{v}");
assert_eq!(v["usage"], true, "{v}");
assert_eq!(v["pool"], true, "{v}");
+ assert_eq!(v["spaces_settings"], true, "{v}");
assert_eq!(
v["teams"], 4,
"T1 passed on, T2 left, T3 invite scrubbed, T4 deleted: {v}"
@@ -694,7 +719,7 @@ async fn it_erases_one_account_everywhere_and_nobody_elses_and_survives_a_restar
] {
assert_eq!(again[k], 0, "{k}: {again}");
}
- for k in ["usage", "plan_cache", "pool"] {
+ for k in ["usage", "plan_cache", "pool", "spaces_settings"] {
assert_eq!(again[k], false, "{k}: {again}");
}
diff --git a/libs/cua-spacesd/crates/cua-relay/tests/spaces_settings.rs b/libs/cua-spacesd/crates/cua-relay/tests/spaces_settings.rs
new file mode 100644
index 0000000000..8bb796c453
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-relay/tests/spaces_settings.rs
@@ -0,0 +1,704 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Default Space settings (`GET | PUT /v1/spaces/settings`), their
+//! resolution (`GET /v1/spaces/default`), and detach-not-delete for a
+//! removed computer's Spaces (`DELETE /v1/machines/{id}`).
+
+use std::path::Path;
+use std::sync::Arc;
+use std::time::Duration;
+
+use cua_relay::devices::DevicePolicy;
+use cua_relay::oidc::testing::FakeIssuer;
+use cua_relay::oidc::{OidcConfig, OidcValidator};
+use cua_relay::server::{Relay, RelayConfig};
+use reqwest::{Method, StatusCode};
+use serde_json::{json, Value};
+use tokio_util::sync::CancellationToken;
+
+const ISSUER: &str = "https://auth.test/realms/cua";
+const GONE: &str = "its computer was removed from the account";
+
+fn config(issuer: &FakeIssuer, dir: &Path) -> RelayConfig {
+ RelayConfig {
+ oidc: Some(Arc::new(OidcValidator::with_jwks(
+ OidcConfig::new(ISSUER),
+ issuer.jwks(),
+ ))),
+ device_policy: DevicePolicy {
+ grace_secs: 14 * 86_400,
+ ..DevicePolicy::default()
+ },
+ state_file: Some(dir.join("machines.json")),
+ ..RelayConfig::default()
+ }
+}
+
+async fn serve(relay: &Relay) -> String {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}", listener.local_addr().unwrap());
+ let relay = relay.clone();
+ tokio::spawn(async move {
+ let _ = relay.serve(listener, std::future::pending()).await;
+ });
+ base
+}
+
+struct Env {
+ relay: Relay,
+ base: String,
+ issuer: FakeIssuer,
+ dir: tempfile::TempDir,
+ ada: String,
+ bob: String,
+}
+
+impl Env {
+ async fn start() -> Env {
+ let issuer = FakeIssuer::new(ISSUER);
+ let dir = tempfile::tempdir().unwrap();
+ let relay = Relay::new(config(&issuer, dir.path()));
+ let base = serve(&relay).await;
+ let ada = issuer.token("ada-sub", Some("[email protected]"), "cua-relay", 3000);
+ let bob = issuer.token("bob-sub", Some("[email protected]"), "cua-relay", 3000);
+ Env {
+ relay,
+ base,
+ issuer,
+ dir,
+ ada,
+ bob,
+ }
+ }
+
+ async fn call(
+ &self,
+ method: Method,
+ path: &str,
+ token: &str,
+ body: Option<Value>,
+ ) -> (StatusCode, Value) {
+ let mut r = reqwest::Client::new()
+ .request(method, format!("{}{path}", self.base))
+ .bearer_auth(token);
+ if let Some(b) = body {
+ r = r.json(&b);
+ }
+ let r = r.send().await.unwrap();
+ let status = r.status();
+ let text = r.text().await.unwrap_or_default();
+ (
+ status,
+ serde_json::from_str(&text).unwrap_or(Value::String(text)),
+ )
+ }
+
+ /// Registers a computer (or, with `host`, a Space on it); returns its
+ /// id and machine token.
+ async fn register(
+ &self,
+ token: &str,
+ id: &str,
+ host: Option<&str>,
+ allow: &[&str],
+ ) -> (String, String) {
+ let (s, v) = self
+ .call(
+ Method::POST,
+ "/v1/machines",
+ token,
+ Some(json!({"id": id, "name": id, "host": host, "allow": allow})),
+ )
+ .await;
+ assert!(s.is_success(), "register {id}: {s} {v}");
+ (
+ id.to_owned(),
+ v["machine_token"].as_str().unwrap().to_owned(),
+ )
+ }
+
+ async fn new_id(&self) -> String {
+ format!("m{}", uuid::Uuid::new_v4().simple())
+ }
+
+ /// Connects `id` and returns once the relay sees it.
+ async fn connect(&self, id: &str, token: &str) -> CancellationToken {
+ let unused = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let local = unused.local_addr().unwrap();
+ drop(unused);
+ let mut join = cua_relay::client::JoinConfig::new(
+ self.base.replace("http://", "ws://"),
+ token.to_owned(),
+ id.to_owned(),
+ local,
+ );
+ join.heartbeat = Duration::from_secs(1);
+ let stop = CancellationToken::new();
+ tokio::spawn(cua_relay::client::run(join, stop.clone()));
+ for _ in 0..200 {
+ if self.relay.machine_ids().contains(&id.to_owned()) {
+ return stop;
+ }
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+ panic!("{id} did not connect");
+ }
+
+ async fn listed(&self, token: &str) -> Vec<String> {
+ let (s, v) = self.call(Method::GET, "/v1/machines", token, None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ v["machines"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|m| m["id"].as_str().unwrap().to_owned())
+ .collect()
+ }
+
+ async fn put(&self, token: &str, body: Value) -> (StatusCode, Value) {
+ self.call(Method::PUT, "/v1/spaces/settings", token, Some(body))
+ .await
+ }
+
+ async fn resolve(&self, token: &str, here: Option<&str>) -> Value {
+ let q = here.map(|h| format!("?here={h}")).unwrap_or_default();
+ let (s, v) = self
+ .call(Method::GET, &format!("/v1/spaces/default{q}"), token, None)
+ .await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ v
+ }
+}
+
+fn space(id: &str) -> String {
+ format!("relay:{id}")
+}
+
+fn orders(v: &Value) -> Vec<(String, bool, String)> {
+ v["order"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|e| {
+ (
+ e["space"].as_str().unwrap().to_owned(),
+ e["online"].as_bool().unwrap(),
+ e["role"].as_str().unwrap().to_owned(),
+ )
+ })
+ .collect()
+}
+
+#[tokio::test]
+async fn settings_start_unset_and_round_trip() {
+ let env = Env::start().await;
+ let (a, _) = env.register(&env.ada, &env.new_id().await, None, &[]).await;
+ let (b, _) = env.register(&env.ada, &env.new_id().await, None, &[]).await;
+
+ let (s, v) = env
+ .call(Method::GET, "/v1/spaces/settings", &env.ada, None)
+ .await;
+ assert_eq!(s, StatusCode::OK);
+ assert_eq!(
+ v,
+ json!({"default_space": null, "fallback": [], "fallback_on": true, "updated_at": 0})
+ );
+
+ let body = json!({
+ "default_space": space(&a),
+ "fallback": [format!("{}/dev-1", space(&b))],
+ "fallback_on": false,
+ });
+ let (s, v) = env.put(&env.ada, body.clone()).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert!(v["updated_at"].as_u64().unwrap() > 0);
+ let (_, got) = env
+ .call(Method::GET, "/v1/spaces/settings", &env.ada, None)
+ .await;
+ assert_eq!(got, v);
+ assert_eq!(got["default_space"], body["default_space"]);
+ assert_eq!(got["fallback_on"], false);
+
+ // PUT replaces the whole object: what is not sent goes back to its default.
+ let (s, v) = env.put(&env.ada, json!({"default_space": space(&b)})).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(v["fallback"], json!([]));
+ assert_eq!(v["fallback_on"], true);
+
+ // Settings are per account.
+ let (_, bobs) = env
+ .call(Method::GET, "/v1/spaces/settings", &env.bob, None)
+ .await;
+ assert_eq!(bobs["default_space"], Value::Null);
+}
+
+#[tokio::test]
+async fn bad_settings_are_refused_with_the_reason() {
+ let env = Env::start().await;
+ let (a, a_token) = env.register(&env.ada, &env.new_id().await, None, &[]).await;
+ let (bob_box, _) = env.register(&env.bob, &env.new_id().await, None, &[]).await;
+
+ for bad in [
+ "abcdefgh12",
+ "relay:short",
+ "relay:",
+ "relay:ABCDEFGH12",
+ "relay:abcdefgh12/UP",
+ ] {
+ let (s, v) = env.put(&env.ada, json!({"default_space": bad})).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST, "{bad}");
+ assert_eq!(v["error"], format!("invalid Space id: {bad}"));
+ }
+ let (s, v) = env
+ .put(&env.ada, json!({"fallback": [space(&a), space(&a)]}))
+ .await;
+ assert_eq!(s, StatusCode::BAD_REQUEST);
+ assert_eq!(v["error"], format!("duplicate Space id: {}", space(&a)));
+
+ let many: Vec<String> = (0..17).map(|i| format!("{}/s-{i}", space(&a))).collect();
+ let (s, v) = env.put(&env.ada, json!({"fallback": many})).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST);
+ assert_eq!(v["error"], "at most 16 fallback Spaces");
+ let sixteen: Vec<String> = (0..16).map(|i| format!("{}/s-{i}", space(&a))).collect();
+ let (s, v) = env.put(&env.ada, json!({"fallback": sixteen})).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+
+ // Someone else's computer, and one that does not exist, look the same.
+ for other in [space(&bob_box), space("doesnotexist1")] {
+ let (s, v) = env.put(&env.ada, json!({"default_space": other})).await;
+ assert_eq!(s, StatusCode::FORBIDDEN, "{other}");
+ assert_eq!(v["error"], format!("{other} is not a computer you can use"));
+ let (s, _) = env.put(&env.ada, json!({"fallback": [other]})).await;
+ assert_eq!(s, StatusCode::FORBIDDEN);
+ }
+ // A refused change leaves the settings as they were.
+ let (_, got) = env
+ .call(Method::GET, "/v1/spaces/settings", &env.ada, None)
+ .await;
+ assert_eq!(got["fallback"].as_array().unwrap().len(), 16);
+
+ // Shared with Bob: now he can use it.
+ let (shared, _) = env
+ .register(&env.ada, &env.new_id().await, None, &["[email protected]"])
+ .await;
+ let (s, v) = env
+ .put(&env.bob, json!({"default_space": space(&shared)}))
+ .await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+
+ // A computer token is refused, on both routes.
+ for (method, path, body) in [
+ (Method::GET, "/v1/spaces/settings", None),
+ (Method::PUT, "/v1/spaces/settings", Some(json!({}))),
+ (Method::GET, "/v1/spaces/default", None),
+ ] {
+ let (s, v) = env.call(method, path, &a_token, body).await;
+ assert_eq!(s, StatusCode::FORBIDDEN, "{path}");
+ assert_eq!(v["error"], "a machine token cannot do this");
+ }
+}
+
+#[tokio::test]
+async fn settings_survive_a_restart() {
+ let env = Env::start().await;
+ let (a, _) = env.register(&env.ada, &env.new_id().await, None, &[]).await;
+ let (s, v) = env
+ .put(
+ &env.ada,
+ json!({"default_space": space(&a), "fallback": [space(&a)], "fallback_on": false}),
+ )
+ .await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ let file = env.dir.path().join("machines.spaces.json");
+ assert!(file.exists());
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt as _;
+ let mode = std::fs::metadata(&file).unwrap().permissions().mode() & 0o777;
+ assert_eq!(mode, 0o600, "private file mode");
+ }
+
+ let relay2 = Relay::new(config(&env.issuer, env.dir.path()));
+ let base2 = serve(&relay2).await;
+ let r = reqwest::Client::new()
+ .get(format!("{base2}/v1/spaces/settings"))
+ .bearer_auth(&env.ada)
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(r.status(), StatusCode::OK);
+ let got: Value = r.json().await.unwrap();
+ assert_eq!(got, v);
+}
+
+#[tokio::test]
+async fn the_default_resolves_to_the_first_online_place() {
+ let env = Env::start().await;
+ // Created oldest first: old, then new. The ids sort the other way round,
+ // so "oldest first" is not just id order.
+ let (old, old_token) = env
+ .register(
+ &env.ada,
+ &format!("mzzzz{}", uuid::Uuid::new_v4().simple()),
+ None,
+ &[],
+ )
+ .await;
+ tokio::time::sleep(Duration::from_millis(1100)).await;
+ let (new, new_token) = env
+ .register(
+ &env.ada,
+ &format!("maaaa{}", uuid::Uuid::new_v4().simple()),
+ None,
+ &[],
+ )
+ .await;
+ let (dflt, dflt_token) = env.register(&env.ada, &env.new_id().await, None, &[]).await;
+ let (here, here_token) = env.register(&env.ada, &env.new_id().await, None, &[]).await;
+
+ // Nothing set.
+ let v = env.resolve(&env.ada, Some(&here)).await;
+ assert_eq!(v["reason"], "unset");
+ assert_eq!(v["space"], space(&here));
+ assert_eq!(v["default_space"], Value::Null);
+ let v = env.resolve(&env.ada, None).await;
+ assert_eq!(
+ (v["reason"].as_str(), v["space"].clone()),
+ (Some("unset"), Value::Null)
+ );
+
+ let (s, v) = env
+ .put(&env.ada, json!({"default_space": space(&dflt)}))
+ .await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+
+ // Nothing online: use this device. With no `here` (or one not on the
+ // relay) the answer is null and the client uses this device.
+ let v = env.resolve(&env.ada, Some(&here)).await;
+ assert_eq!(
+ (v["reason"].as_str(), v["space"].clone()),
+ (Some("here"), json!(space(&here)))
+ );
+ assert_eq!(v["default_online"], false);
+ assert_eq!(v["default_space"], space(&dflt));
+ assert_eq!(
+ orders(&v),
+ vec![
+ (space(&dflt), false, "default".into()),
+ (space(&here), false, "here".into()),
+ ]
+ );
+ let v = env.resolve(&env.ada, None).await;
+ assert_eq!(
+ (v["reason"].as_str(), v["space"].clone()),
+ (Some("here"), Value::Null)
+ );
+ let v = env.resolve(&env.ada, Some("notonrelay1")).await;
+ assert_eq!(v["space"], Value::Null);
+
+ // The newer computer comes online first, then the older: automatic
+ // order is oldest first.
+ let _s1 = env.connect(&new, &new_token).await;
+ let v = env.resolve(&env.ada, Some(&here)).await;
+ assert_eq!(
+ (v["reason"].as_str(), v["space"].clone()),
+ (Some("fallback"), json!(space(&new)))
+ );
+ let _s2 = env.connect(&old, &old_token).await;
+ let v = env.resolve(&env.ada, Some(&here)).await;
+ assert_eq!(v["space"], space(&old));
+ assert_eq!(
+ orders(&v),
+ vec![
+ (space(&dflt), false, "default".into()),
+ (space(&old), true, "fallback".into()),
+ (space(&new), true, "fallback".into()),
+ (space(&here), false, "here".into()),
+ ]
+ );
+
+ // An explicit fallback list is used in its order, offline entries shown.
+ let (s, v) = env
+ .put(
+ &env.ada,
+ json!({"default_space": space(&dflt), "fallback": [space(&new), space(&here), space(&old)]}),
+ )
+ .await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ let v = env.resolve(&env.ada, Some(&here)).await;
+ assert_eq!(v["space"], space(&new));
+ assert_eq!(
+ orders(&v),
+ vec![
+ (space(&dflt), false, "default".into()),
+ (space(&new), true, "fallback".into()),
+ (space(&old), true, "fallback".into()),
+ (space(&here), false, "here".into()),
+ ],
+ "here is skipped inside the list and always last"
+ );
+
+ // Fallback off: only the default, then this device.
+ let (s, _) = env
+ .put(
+ &env.ada,
+ json!({"default_space": space(&dflt), "fallback_on": false}),
+ )
+ .await;
+ assert_eq!(s, StatusCode::OK);
+ let v = env.resolve(&env.ada, Some(&here)).await;
+ assert_eq!(
+ (v["reason"].as_str(), v["space"].clone()),
+ (Some("here"), json!(space(&here)))
+ );
+ assert_eq!(orders(&v).len(), 2);
+
+ // The default comes online: it wins.
+ let (s, _) = env
+ .put(&env.ada, json!({"default_space": space(&dflt)}))
+ .await;
+ assert_eq!(s, StatusCode::OK);
+ let _s3 = env.connect(&dflt, &dflt_token).await;
+ let v = env.resolve(&env.ada, Some(&here)).await;
+ assert_eq!(
+ (v["reason"].as_str(), v["space"].clone()),
+ (Some("default"), json!(space(&dflt)))
+ );
+ assert_eq!(v["default_online"], true);
+ // A Space of the default computer counts as online with it.
+ let child = format!("{}/dev-1", space(&dflt));
+ let (s, _) = env.put(&env.ada, json!({"default_space": child})).await;
+ assert_eq!(s, StatusCode::OK);
+ let v = env.resolve(&env.ada, Some(&here)).await;
+ assert_eq!(
+ (v["reason"].as_str(), v["space"].clone()),
+ (Some("default"), json!(child))
+ );
+ let _ = here_token;
+}
+
+#[tokio::test]
+async fn a_default_that_is_no_longer_visible_is_skipped_but_kept() {
+ let env = Env::start().await;
+ let (shared, shared_token) = env
+ .register(&env.ada, &env.new_id().await, None, &["[email protected]"])
+ .await;
+ let (mine, mine_token) = env.register(&env.bob, &env.new_id().await, None, &[]).await;
+ let _s1 = env.connect(&shared, &shared_token).await;
+ let _s2 = env.connect(&mine, &mine_token).await;
+
+ let (s, v) = env
+ .put(&env.bob, json!({"default_space": space(&shared)}))
+ .await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(
+ env.resolve(&env.bob, Some(&mine)).await["space"],
+ space(&shared)
+ );
+
+ // Ada stops sharing it with Bob: skipped, Bob's own computer is used,
+ // and the stored default is still there.
+ let (s, v) = env
+ .call(
+ Method::PATCH,
+ &format!("/v1/machines/{shared}"),
+ &env.ada,
+ Some(json!({"allow": []})),
+ )
+ .await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ let v = env.resolve(&env.bob, Some(&mine)).await;
+ assert_eq!(v["default_space"], space(&shared));
+ assert_eq!(v["default_online"], false);
+ assert_eq!(
+ (v["reason"].as_str(), v["space"].clone()),
+ (Some("here"), json!(space(&mine)))
+ );
+ assert!(!orders(&v).iter().any(|(s, ..)| s == &space(&shared)));
+
+ // Shared again: it is back.
+ let (s, _) = env
+ .call(
+ Method::PATCH,
+ &format!("/v1/machines/{shared}"),
+ &env.ada,
+ Some(json!({"allow": ["[email protected]"]})),
+ )
+ .await;
+ assert_eq!(s, StatusCode::OK);
+ assert_eq!(
+ env.resolve(&env.bob, Some(&mine)).await["space"],
+ space(&shared)
+ );
+}
+
+#[tokio::test]
+async fn removing_a_computer_detaches_its_spaces_and_registering_it_again_restores_them() {
+ let env = Env::start().await;
+ let host = env.new_id().await;
+ let (_, host_token) = env.register(&env.ada, &host, None, &[]).await;
+ let (kid, kid_token) = env
+ .register(&env.ada, &env.new_id().await, Some(&host), &[])
+ .await;
+ let _live = env.connect(&kid, &kid_token).await;
+ let probe = |token: &str| {
+ let url = format!("{}/m/{kid}/probe", env.base);
+ let token = token.to_owned();
+ async move {
+ let r = reqwest::Client::new()
+ .get(url)
+ .bearer_auth(token)
+ .send()
+ .await
+ .unwrap();
+ (r.status(), r.text().await.unwrap_or_default())
+ }
+ };
+ assert_eq!(env.listed(&env.ada).await.len(), 2);
+ let (s, body) = probe(&env.ada).await;
+ assert_ne!(s, StatusCode::FORBIDDEN, "{body}");
+
+ // The computer's own token removes it.
+ let (s, v) = env
+ .call(
+ Method::DELETE,
+ &format!("/v1/machines/{host}"),
+ &host_token,
+ None,
+ )
+ .await;
+ assert_eq!(s, StatusCode::NO_CONTENT, "{v}");
+ assert!(env.listed(&env.ada).await.is_empty(), "the Space is hidden");
+ let (s, body) = probe(&env.ada).await;
+ assert_eq!(s, StatusCode::FORBIDDEN);
+ assert!(body.contains(GONE), "{body}");
+ // Its live connection was cut, and its token is refused too.
+ for _ in 0..100 {
+ if !env.relay.machine_ids().contains(&kid) {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+ assert!(!env.relay.machine_ids().contains(&kid));
+ let (s, v) = env
+ .call(Method::GET, "/v1/machines", &kid_token, None)
+ .await;
+ assert_eq!(s, StatusCode::FORBIDDEN, "{v}");
+ assert_eq!(v["error"], GONE);
+ // Not something to default to while it is detached.
+ let (s, _) = env
+ .put(&env.ada, json!({"default_space": space(&kid)}))
+ .await;
+ assert_eq!(s, StatusCode::OK, "it is still the account's own record");
+ let v = env.resolve(&env.ada, None).await;
+ assert_eq!(v["default_space"], space(&kid));
+ assert!(orders(&v).is_empty(), "{v}");
+
+ // The computer registers again with the same id: the Space is back.
+ env.register(&env.ada, &host, None, &[]).await;
+ let ids = env.listed(&env.ada).await;
+ assert!(ids.contains(&kid) && ids.contains(&host), "{ids:?}");
+ let (s, body) = probe(&env.ada).await;
+ assert_ne!(s, StatusCode::FORBIDDEN, "{body}");
+ let (s, v) = env
+ .call(Method::GET, "/v1/machines", &kid_token, None)
+ .await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(
+ orders(&env.resolve(&env.ada, None).await).len(),
+ 1,
+ "the default is usable again"
+ );
+}
+
+#[tokio::test]
+async fn deleting_a_computer_with_its_spaces_forgets_them() {
+ let env = Env::start().await;
+ let host = env.new_id().await;
+ let (_, host_token) = env.register(&env.ada, &host, None, &[]).await;
+ let (kid, kid_token) = env
+ .register(&env.ada, &env.new_id().await, Some(&host), &[])
+ .await;
+ let (kid2, _) = env
+ .register(&env.ada, &env.new_id().await, Some(&host), &[])
+ .await;
+ let (other_host, _) = env.register(&env.ada, &env.new_id().await, None, &[]).await;
+ let (other_kid, _) = env
+ .register(&env.ada, &env.new_id().await, Some(&other_host), &[])
+ .await;
+ let _live = env.connect(&kid, &kid_token).await;
+
+ let (s, v) = env
+ .call(
+ Method::DELETE,
+ &format!("/v1/machines/{host}?spaces=maybe"),
+ &env.ada,
+ None,
+ )
+ .await;
+ assert_eq!(
+ (s, v["error"].clone()),
+ (StatusCode::BAD_REQUEST, json!("spaces: delete"))
+ );
+ // A computer token cannot ask for it, and nothing was removed.
+ let (s, v) = env
+ .call(
+ Method::DELETE,
+ &format!("/v1/machines/{host}?spaces=delete"),
+ &host_token,
+ None,
+ )
+ .await;
+ assert_eq!(s, StatusCode::FORBIDDEN, "{v}");
+ assert_eq!(env.listed(&env.ada).await.len(), 5);
+ // Someone it is not shared with cannot see it at all.
+ let (s, _) = env
+ .call(
+ Method::DELETE,
+ &format!("/v1/machines/{host}?spaces=delete"),
+ &env.bob,
+ None,
+ )
+ .await;
+ assert_eq!(s, StatusCode::NOT_FOUND);
+
+ let (s, v) = env
+ .call(
+ Method::DELETE,
+ &format!("/v1/machines/{host}?spaces=delete"),
+ &env.ada,
+ None,
+ )
+ .await;
+ assert_eq!(s, StatusCode::NO_CONTENT, "{v}");
+ assert_eq!(
+ env.listed(&env.ada).await.len(),
+ 2,
+ "only the other computer and its Space remain"
+ );
+ for _ in 0..100 {
+ if !env.relay.machine_ids().contains(&kid) {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+ assert!(
+ !env.relay.machine_ids().contains(&kid),
+ "connection dropped"
+ );
+ let (s, _) = env
+ .call(Method::GET, &format!("/v1/machines/{kid2}"), &env.ada, None)
+ .await;
+ assert_eq!(s, StatusCode::NOT_FOUND);
+ let (s, _) = env
+ .call(Method::GET, "/v1/machines", &kid_token, None)
+ .await;
+ assert_eq!(s, StatusCode::UNAUTHORIZED, "its token is gone");
+
+ // Registering the computer again does not bring them back.
+ env.register(&env.ada, &host, None, &[]).await;
+ let ids = env.listed(&env.ada).await;
+ assert_eq!(ids.len(), 3, "{ids:?}");
+ assert!(!ids.contains(&kid) && !ids.contains(&kid2) && ids.contains(&other_kid));
+}