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(spaces): signing in as another account recovers the daemon session, host registration and mesh key (CUA-2295) (#5961)

cua-agents[bot]3c0c26456d17
diff --git a/apps/cua-spaces-desktop/src/model/host.ts b/apps/cua-spaces-desktop/src/model/host.ts
index 9e27002215..4d1ce46ed2 100644
--- a/apps/cua-spaces-desktop/src/model/host.ts
+++ b/apps/cua-spaces-desktop/src/model/host.ts
@@ -337,6 +337,10 @@ export class HostModel {
this.error = words(error);
this.actionFailure = presentHostFailure(words(error), this.platform);
this.failedAction = this.native.AppHostActionId.ResumeSharing;
+ // What the failure left behind: a switch of account pauses the old
+ // registration first, so Retry goes through the sign-in check again,
+ // never straight to starting the old one.
+ await this.refresh();
}
} finally {
this.reconciling = false;
diff --git a/apps/cua-spaces-desktop/test/host-bridge.test.ts b/apps/cua-spaces-desktop/test/host-bridge.test.ts
index e679661723..d23a7e96ef 100644
--- a/apps/cua-spaces-desktop/test/host-bridge.test.ts
+++ b/apps/cua-spaces-desktop/test/host-bridge.test.ts
@@ -398,6 +398,39 @@ describe.skipIf(!built)("This machine, Devices and Settings on the app core", ()
expect(s.pausedSignedOut).toBe(false);
});
+ it("moves the host to another account that signs in, with no manual step", async () => {
+ const account = new FakeAccountTokens();
+ account.token = "tok";
+ account.wire(model.host);
+ model.host.currentAccount = () => ({ id: "user-1", email: "[email protected]", display: "Ada" });
+ await call("host.setUp", { request: { mode: "relay" } });
+ account.token = null;
+ await model.host.reconcileAccount();
+ expect(host.calls).toContain("pause");
+ account.signInGives = "tok-bob";
+ model.host.currentAccount = () => ({ id: "user-2", email: "[email protected]", display: "Bob" });
+ const s = (await call("host.action", { action: "sign-in" })) as Record<string, unknown>;
+ expect(host.calls.at(-1)).toBe("resume:user-2");
+ expect(s.pausedSignedOut).toBe(false);
+ expect(s.owner).toBe("user-2");
+ });
+
+ it("a failed switch leaves the host paused, and Retry never starts the old registration", async () => {
+ const account = new FakeAccountTokens();
+ account.token = "tok";
+ account.wire(model.host);
+ model.host.currentAccount = () => ({ id: "user-1", email: "[email protected]", display: "Ada" });
+ await call("host.setUp", { request: { mode: "relay" } });
+ host.failResume = "this computer still runs 1 Space for the account that was signed in before";
+ model.host.currentAccount = () => ({ id: "user-2", email: "[email protected]", display: "Bob" });
+ await model.host.reconcileAccount();
+ const s = (await call("host.status")) as Record<string, unknown>;
+ expect(s.pausedSignedOut).toBe(true);
+ await model.host.retryFailedAction();
+ expect(host.calls).not.toContain("start");
+ expect(host.calls.at(-1)).toBe("resume:user-2");
+ });
+
it("without an account wired, Sign In leaves the status as it is", async () => {
await make({ account: null });
await call("host.status");
diff --git a/apps/cua-spaces-desktop/test/host-fixtures.ts b/apps/cua-spaces-desktop/test/host-fixtures.ts
index f965de75ef..173861282e 100644
--- a/apps/cua-spaces-desktop/test/host-fixtures.ts
+++ b/apps/cua-spaces-desktop/test/host-fixtures.ts
@@ -28,6 +28,8 @@ export class FixtureHost {
script: Error[] = [];
/** The next `configure` fails with this (once). */
failConfigure: string | null = null;
+ /** The next resume for another account fails with this (once), after pausing the host as the real one does. */
+ failResume: string | null = null;
owner = "user-1";
ownerEmail = "[email protected]";
@@ -103,10 +105,20 @@ export class FixtureHost {
async resumeSignedIn(account: string) {
this.calls.push(`resume:${account}`);
- if (!this.current.pausedSignedOut) return this.current;
- if (account !== this.owner && account.toLowerCase() !== this.ownerEmail.toLowerCase()) {
- throw sdkError("InvalidArgument", "this machine is shared with another Cua account");
+ const isOwner = account === this.owner || account.toLowerCase() === this.ownerEmail.toLowerCase();
+ // Another account: the host registers again for it, paused or not.
+ if (!isOwner && this.failResume) {
+ const why = this.failResume;
+ this.failResume = null;
+ this.current = { ...this.current, pausedSignedOut: true, sharing: false, online: false, serviceRunning: false };
+ throw sdkError("InvalidArgument", why);
}
+ if (!isOwner) {
+ this.owner = account;
+ this.ownerEmail = "";
+ this.current = { ...this.current, owner: account, ownerEmail: undefined };
+ }
+ if (!this.current.pausedSignedOut && isOwner) return this.current;
this.current = { ...this.current, pausedSignedOut: false, sharing: true, online: true, serviceInstalled: true, serviceRunning: true };
return this.current;
}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostModel.swift
index 5c673a87fd..ed2f804b8a 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostModel.swift
@@ -47,6 +47,9 @@ public final class FixtureHost: HostRunning, @unchecked Sendable {
public var failSetup: String?
/// The next `configure` fails with this (once).
public var failConfigure: String?
+ /// The next `resumeSignedIn` for another account fails with this (once),
+ /// after pausing the host as the real one does.
+ public var failResume: String?
/// What `migrateService` answers (nil: moved, needing permissions).
public var migration: HostServiceMigration?
@@ -136,10 +139,24 @@ public final class FixtureHost: HostRunning, @unchecked Sendable {
public func resumeSignedIn(account: String) async throws -> HostStatus {
calls.append("resume:\(account)")
- guard current.pausedSignedOut else { return current }
- guard account == owner || account.caseInsensitiveCompare(ownerEmail) == .orderedSame else {
- throw CuaError.InvalidArgument(message: "this computer is shared with another Cua account")
+ let isOwner = account == owner || account.caseInsensitiveCompare(ownerEmail) == .orderedSame
+ // Another account: the host registers again for it (as the real
+ // one does), paused or not.
+ if !isOwner, let why = failResume {
+ failResume = nil
+ current.pausedSignedOut = true
+ current.sharing = false
+ current.online = false
+ current.serviceRunning = false
+ throw CuaError.InvalidArgument(message: why)
+ }
+ if !isOwner {
+ owner = account
+ ownerEmail = ""
+ current.owner = account
+ current.ownerEmail = nil
}
+ guard current.pausedSignedOut || !isOwner else { return current }
current.pausedSignedOut = false
current.sharing = true
current.online = true
@@ -505,6 +522,10 @@ public final class HostModel {
} catch {
actionFailure = HostSetupFailure.presenting(LiveSpacesBackend.words(error))
failedAction = .resumeSharing
+ // What the failure left behind: a switch of account pauses the
+ // old registration first, so Retry goes through the sign-in
+ // check again, never straight to starting the old one.
+ await refreshStatusOnly()
}
}
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostSignInSharingTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostSignInSharingTests.swift
index e7696794d3..8bdf65a6f7 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostSignInSharingTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostSignInSharingTests.swift
@@ -9,7 +9,7 @@ import Testing
/// Relay sharing follows the sign-in: signed out pauses it (the host leaves
/// the relay, its setup stays), the owner signing in again resumes it, and
-/// another account is never handed the old account's registration.
+/// another account signing in moves the Mac over to it.
@MainActor
@Suite("Relay sharing and the sign-in")
struct HostSignInSharingTests {
@@ -97,7 +97,9 @@ struct HostSignInSharingTests {
#expect(!host.calls.contains { $0.hasPrefix("resume") || $0 == "start" })
}
- @Test func anotherAccountIsNotHandedTheOldRegistration() async {
+ /// Signing in as another account registers this Mac again for it with
+ /// no manual step (the host keeps its name and settings).
+ @Test func anotherAccountSignInMovesTheHostOver() async {
let host = FixtureHost()
let (m, account, who) = await sharing(host)
account.token = nil
@@ -106,21 +108,46 @@ struct HostSignInSharingTests {
account.signInGives = "tok-bob"
who.value = Self.bob
await m.run(.signIn)
- #expect(!host.calls.contains { $0.hasPrefix("resume") })
- #expect(host.current.pausedSignedOut)
+ #expect(host.calls.last == "resume:user-2")
+ #expect(host.owner == "user-2")
+ #expect(!host.current.pausedSignedOut)
+ #expect(host.current.sharing && host.current.serviceRunning)
let panel = m.panel
- #expect(panel.notice?.contains("another Cua account") == true)
- #expect(panel.noticeAction == nil)
- #expect(panel.actions.map(\.id) == [.remove])
+ #expect(panel.notice == nil)
+ #expect(panel.actions.first?.id == .stopSharing)
}
- @Test func anotherAccountSignedInWhileSharingPausesIt() async {
+ @Test func anotherAccountSignedInWhileSharingMovesTheHostOver() async {
let host = FixtureHost()
let (m, account, who) = await sharing(host)
account.token = "tok-bob"
who.value = Self.bob
await m.reconcileAccount()
- #expect(host.calls.last == "pause")
+ #expect(!host.calls.contains("pause"))
+ #expect(host.calls.last == "resume:user-2")
+ #expect(host.owner == "user-2")
+ #expect(host.current.sharing)
+ }
+
+ /// A switch that fails (Spaces still run for the old account) leaves the
+ /// host paused, and the page shows that: Retry goes through the sign-in
+ /// check, never straight to starting the old registration.
+ @Test func aFailedSwitchLeavesTheHostPausedAndRetryNeverStartsTheOldOne() async {
+ let host = FixtureHost()
+ let (m, account, who) = await sharing(host)
+ host.failResume = "this computer still runs 1 Space for the account that was signed in before"
+ account.token = "tok-bob"
+ who.value = Self.bob
+ await m.reconcileAccount()
+ #expect(host.current.pausedSignedOut)
+ #expect(m.state?.pausedSignedOut == true, "the page reads what the failure left")
+ #expect(m.actionFailure != nil)
+ // Retry: the sign-in check again (which switches now), not `start`.
+ await m.retryFailedAction()
+ #expect(!host.calls.contains("start"))
+ #expect(host.calls.last == "resume:user-2")
+ #expect(host.owner == "user-2")
+ #expect(!host.current.pausedSignedOut && host.current.sharing)
}
@Test func offlineIsNotSignedOut() async {
diff --git a/libs/cua/crates/cua-host/src/device.rs b/libs/cua/crates/cua-host/src/device.rs
index 119f70e9cd..9a6b1ad5a6 100644
--- a/libs/cua/crates/cua-host/src/device.rs
+++ b/libs/cua/crates/cua-host/src/device.rs
@@ -236,9 +236,37 @@ pub struct DeviceAuth {
name: String,
machine_id: std::sync::OnceLock<Option<String>>,
session: tokio::sync::Mutex<Option<(String, u64)>>,
+ /// A hash of the key the cached session was opened with (0: none), when
+ /// the slot was last looked at again (unix milliseconds) and how often
+ /// to (milliseconds); see [`DeviceAuth::key_changed`]. Flat atomics:
+ /// this struct sits inside the SDK's deep futures, whose layout check
+ /// has a fixed depth budget.
+ session_key: std::sync::atomic::AtomicU64,
+ key_checked_ms: std::sync::atomic::AtomicU64,
+ key_recheck_ms: u64,
pending_file: Option<PathBuf>,
}
+/// How often a long-lived [`DeviceAuth`] (the daemon's) looks at its key
+/// slot again while it holds a session.
+const KEY_RECHECK: std::time::Duration = std::time::Duration::from_secs(5);
+
+fn now_ms() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_millis() as u64)
+ .unwrap_or(0)
+}
+
+/// A nonzero hash of a key id, to tell one key from another in this
+/// process.
+fn key_hash(id: &str) -> u64 {
+ use std::hash::{Hash as _, Hasher as _};
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ id.hash(&mut h);
+ h.finish() | 1
+}
+
/// The one-time code this device last showed, remembered (in
/// `~/.cua/device-pending.json`) so `cua devices status` can show it again
/// and `cua devices enroll` reuses it instead of re-registering: a new
@@ -264,13 +292,29 @@ const CODE_REUSE_MARGIN_SECS: u64 = 60;
/// relay's default bootstrap window).
const FRESH_SIGN_IN_SECS: u64 = 600;
-/// The unverified `auth_time` claim of a JWT access token (display and
-/// local decisions only; the relay verifies).
-fn token_auth_time(token: &str) -> Option<u64> {
+/// The unverified claims of a JWT access token (display and local
+/// decisions only; the relay verifies).
+fn token_claims(token: &str) -> Option<serde_json::Value> {
let payload = token.split('.').nth(1)?;
let bytes = b64().decode(payload.trim_end_matches('=')).ok()?;
- let claims: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
- claims.get("auth_time")?.as_u64()
+ serde_json::from_slice(&bytes).ok()
+}
+
+/// The unverified `auth_time` claim of a JWT access token.
+fn token_auth_time(token: &str) -> Option<u64> {
+ token_claims(token)?.get("auth_time")?.as_u64()
+}
+
+/// The unverified `sub` claim of a JWT access token: which account it is
+/// for. A long-running process compares it to the account it started
+/// state for (a mesh node, a pool agent) to notice a sign-in as another
+/// account; the relay still verifies every token.
+pub fn token_subject(token: &str) -> Option<String> {
+ token_claims(token)?
+ .get("sub")?
+ .as_str()
+ .map(str::to_owned)
+ .filter(|s| !s.is_empty())
}
impl std::fmt::Debug for DeviceAuth {
@@ -300,10 +344,44 @@ impl DeviceAuth {
name: name.into(),
machine_id: std::sync::OnceLock::new(),
session: tokio::sync::Mutex::new(None),
+ session_key: std::sync::atomic::AtomicU64::new(0),
+ key_checked_ms: std::sync::atomic::AtomicU64::new(0),
+ key_recheck_ms: KEY_RECHECK.as_millis() as u64,
pending_file: None,
})
}
+ /// Looks at the key slot again at most every `every` while a session
+ /// is held (default a few seconds).
+ pub fn with_key_recheck(mut self, every: std::time::Duration) -> Self {
+ self.key_recheck_ms = every.as_millis() as u64;
+ self
+ }
+
+ /// Whether the key in the slot is no longer the one the cached session
+ /// was opened with: another process (the app, the CLI) enrolled this
+ /// device again, for instance after a sign-in as another account. The
+ /// relay refuses the old key's session, so the cached one must not be
+ /// used. Looked at most every `key_recheck`.
+ fn key_changed(&self) -> bool {
+ use std::sync::atomic::Ordering::Relaxed;
+ let known = self.session_key.load(Relaxed);
+ if known == 0 {
+ return false;
+ }
+ let now = now_ms();
+ if now.saturating_sub(self.key_checked_ms.load(Relaxed)) < self.key_recheck_ms {
+ return false;
+ }
+ self.key_checked_ms.store(now, Relaxed);
+ match self.key() {
+ Ok(Some(k)) => key_hash(&k.id()) != known,
+ Ok(None) => true,
+ // Unreadable now (a locked vault): keep what works.
+ Err(_) => false,
+ }
+ }
+
/// Remembers this device's pending code in `path` (see
/// [`PendingCode`]).
pub fn with_pending_file(mut self, path: impl Into<PathBuf>) -> Self {
@@ -551,6 +629,7 @@ impl DeviceAuth {
let mut cached = self.session.lock().await;
if let Some((token, expires)) = cached.as_ref()
&& *expires > now_secs() + SESSION_MARGIN_SECS
+ && !self.key_changed()
{
return Ok(token.clone());
}
@@ -562,6 +641,10 @@ impl DeviceAuth {
})?;
let token = self.tokens.access_token().await?;
let session = self.open_session(&token, &key).await?;
+ self.session_key
+ .store(key_hash(&key.id()), std::sync::atomic::Ordering::Relaxed);
+ self.key_checked_ms
+ .store(now_ms(), std::sync::atomic::Ordering::Relaxed);
*cached = Some(session.clone());
Ok(session.0)
}
diff --git a/libs/cua/crates/cua-host/src/host.rs b/libs/cua/crates/cua-host/src/host.rs
index 48c42a6d53..0b66cf2535 100644
--- a/libs/cua/crates/cua-host/src/host.rs
+++ b/libs/cua/crates/cua-host/src/host.rs
@@ -59,6 +59,21 @@ pub enum HostMode {
},
}
+/// The file under `<home>/host` that keeps this computer's registrations
+/// under other accounts than the signed-in one.
+const REGISTRATIONS_FILE: &str = "registrations.json";
+
+/// A relay registration of this computer under one account.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+struct StoredRegistration {
+ machine_id: String,
+ machine_token: String,
+}
+
+/// Account id -> the registration of this computer under it, for accounts
+/// that signed in here before and are not signed in now.
+type Registrations = std::collections::BTreeMap<String, StoredRegistration>;
+
/// Options for [`Host::setup`].
#[derive(Clone, Debug)]
pub struct SetupOptions {
@@ -1928,8 +1943,9 @@ impl Host {
/// Undoes [`Host::pause_signed_out`] once the owner is signed in again:
/// `account` is the signed-in account's id (or email). Another account
/// is refused: it cannot use this registration, and sharing the old
- /// account's machine under it would be wrong; remove the host setup and
- /// set it up again for that account. Sharing comes back as the owner
+ /// account's machine under it would be wrong
+ /// ([`Host::resume_or_switch_account`] registers it again for that
+ /// account instead). Sharing comes back as the owner
/// left it (stopped stays stopped, but online).
pub async fn resume_signed_in(&self, account: &str) -> Result<HostStatus> {
let mut config = self.require_config()?;
@@ -1941,8 +1957,8 @@ impl Host {
&& !owned_by(p, account)
{
return Err(Error::InvalidArgument(
- "this computer is shared with another Cua account; remove the host setup \
- and set it up again to share it with this one"
+ "this computer was set up for another Cua account; sign in to that \
+ account, or register this computer again for this one"
.into(),
));
}
@@ -1950,11 +1966,28 @@ impl Host {
p.sharing = config.sharing;
write_json(&self.paths.policy(), &p)?;
}
+ // Stopped stays stopped, but online: a registration made while the
+ // owner had stopped sharing starts as sharing on the relay, so the
+ // stop is sent again (it changes nothing when the relay has it).
+ if !config.sharing
+ && let (Some(url), Some(id)) = (&config.relay_url, &config.machine_id)
+ && let Ok(token) = read_secret(&self.paths.machine_token())
+ {
+ RelayClient::new(url)?.stop_sharing(&token, id).await?;
+ }
+ let manager = self.manager_for_config(&config);
+ if let Err(e) = manager
+ .install(&self.service_spec(&config))
+ .and_then(|()| manager.start())
+ {
+ // Still paused (and refusing clients), so the next sign-in
+ // check tries again instead of finding a sharing host that is
+ // not running.
+ self.set_policy_sharing(false)?;
+ return Err(e);
+ }
config.paused_signed_out = false;
write_json(&self.paths.config(), &config)?;
- let manager = self.manager_for_config(&config);
- manager.install(&self.service_spec(&config))?;
- manager.start()?;
let _ = crate::provided::audit(
&self.paths.dir,
"config",
@@ -1965,6 +1998,203 @@ impl Host {
self.status().await
}
+ /// [`Host::resume_signed_in`] that also follows a switch of account:
+ /// when `account` is not the machine's owner, this computer is
+ /// registered again for the signed-in account (behind `tokens`), so
+ /// signing in as someone else needs no manual remove and set up. The
+ /// relay still decides: it only accepts the registration of the account
+ /// that signed in. Direct mode is left alone.
+ pub async fn resume_or_switch_account(
+ &self,
+ account: &str,
+ tokens: &dyn AccountTokens,
+ ) -> Result<HostStatus> {
+ let config = self.require_config()?;
+ if config.mode == "relay"
+ && let Some(p) = self.policy()?
+ && !owned_by(&p, account)
+ {
+ return self.switch_account(tokens).await;
+ }
+ self.resume_signed_in(account).await
+ }
+
+ /// Registers this computer again for the account behind `tokens`, which
+ /// is not the one it was set up for. The old registration belongs to
+ /// the previous account (the relay refuses its id, and the machine's
+ /// mesh key was bound to it), so this computer registers under a machine
+ /// id of the new account and takes a new mesh key; its name, what it
+ /// shares and the Provide Spaces setting stay. The previous account's
+ /// allowlist is not carried over. While it still runs Spaces for the
+ /// previous account it stays paused instead (they are not handed to
+ /// another account). The registration it leaves is kept
+ /// (see [`Registrations`]) for when that account signs in again, so
+ /// switching back reuses it: no machines pile up on the relay, and what
+ /// is tied to the machine (its provided Spaces) stays with it.
+ async fn switch_account(&self, tokens: &dyn AccountTokens) -> Result<HostStatus> {
+ let mut config = self.require_config()?;
+ if config.relay_url.is_none() || self.policy()?.is_none() {
+ return Err(Error::InvalidArgument(
+ "this computer is not set up on a relay".into(),
+ ));
+ }
+ // Off the relay first, as when signing out: if the new registration
+ // fails, the previous account's access stays closed and the next
+ // reconcile tries again (paused, with another account signed in).
+ if !config.paused_signed_out {
+ self.pause_signed_out().await?;
+ config = self.require_config()?;
+ }
+ let (Some(url), Some(mut policy)) = (config.relay_url.clone(), self.policy()?) else {
+ return Err(Error::InvalidArgument(
+ "this computer is not set up on a relay".into(),
+ ));
+ };
+ // The Spaces it provides were made for the previous account's
+ // devices and are tied to its registration: they are not handed to
+ // another account. It stays paused until they are deleted (or that
+ // account signs in again).
+ let provided = crate::provided::load_provided(&self.paths.dir)?;
+ if !provided.is_empty() {
+ return Err(Error::InvalidArgument(format!(
+ "this computer still runs {} Space{} for the account that was signed in \
+ before; delete {} (or sign in to that account again) to share this \
+ computer with the account you are signed in to now",
+ provided.len(),
+ if provided.len() == 1 { "" } else { "s" },
+ if provided.len() == 1 { "it" } else { "them" },
+ )));
+ }
+ let relay = RelayClient::new(&url)?;
+ let token = tokens.access_token().await?;
+ let mut kept = self.registrations();
+ // The registration being left, kept for its account.
+ if !policy.owner.is_empty()
+ && let (Some(id), Ok(machine_token)) = (
+ config.machine_id.clone(),
+ read_secret(&self.paths.machine_token()),
+ )
+ {
+ kept.insert(
+ policy.owner.clone(),
+ StoredRegistration {
+ machine_id: id,
+ machine_token,
+ },
+ );
+ }
+ let request = |id: String| RegisterRequest {
+ id,
+ name: config.name.clone(),
+ allow: vec![],
+ host: None,
+ meta: host_meta(config.provide_spaces),
+ };
+ // This account's earlier registration of this computer, if any (the
+ // token says whose it is); else, or when the relay no longer takes
+ // it, a new machine id. Another account's id is never tried: if its
+ // record is gone from the relay it would register here and clash
+ // with the saved one.
+ let earlier: Vec<StoredRegistration> = crate::device::token_subject(&token)
+ .and_then(|sub| kept.get(&sub).cloned())
+ .into_iter()
+ .collect();
+ let mut reg = None;
+ for r in earlier {
+ match relay
+ .register_as_machine(&token, Some(&r.machine_token), &request(r.machine_id))
+ .await
+ {
+ Ok(r) => {
+ reg = Some(r);
+ break;
+ }
+ Err(
+ Error::Unauthenticated(_)
+ | Error::PermissionDenied(_)
+ | Error::NotFound(_)
+ | Error::Conflict(_),
+ ) => {}
+ Err(e) => return Err(e),
+ }
+ }
+ let reg = match reg {
+ Some(r) => r,
+ None => {
+ relay
+ .register_as_machine(&token, None, &request(random_hex(16)))
+ .await?
+ }
+ };
+ // The new registration is kept before anything else can fail, so a
+ // retry reuses it instead of making another machine.
+ kept.insert(
+ reg.machine.owner.id.clone(),
+ StoredRegistration {
+ machine_id: reg.machine.id.clone(),
+ machine_token: reg.machine_token.clone(),
+ },
+ );
+ self.save_registrations(&kept)?;
+ // The relay's sharing state follows this computer's own choice
+ // (a reused registration keeps whatever it had under its account;
+ // a new one starts as sharing). Before anything local changes, so a
+ // failure leaves this paused with the old owner and the next check
+ // tries it all again.
+ if config.sharing {
+ relay
+ .start_sharing(&reg.machine_token, &reg.machine.id)
+ .await?;
+ } else {
+ relay
+ .stop_sharing(&reg.machine_token, &reg.machine.id)
+ .await?;
+ }
+
+ write_secret(&self.paths.machine_id, &format!("{}\n", reg.machine.id))?;
+ write_secret(&self.paths.machine_token(), &reg.machine_token)?;
+ if reg.jwks.is_null() {
+ let _ = std::fs::remove_file(self.paths.relay_jwks());
+ } else {
+ write_json(&self.paths.relay_jwks(), &reg.jwks)?;
+ }
+ // The old machine's mesh key is bound to its machine id: a new
+ // machine takes a new one, which the service makes on its start.
+ let _ = std::fs::remove_file(self.paths.driver_data.join("mesh").join("identity.json"));
+ policy.owner = reg.machine.owner.id.clone();
+ policy.owner_email = reg.machine.owner.email.clone();
+ policy.allow = vec![];
+ policy.viewers = vec![];
+ // Still paused (not sharing) until the service is up.
+ policy.sharing = false;
+ write_json(&self.paths.policy(), &policy)?;
+ config.machine_id = Some(reg.machine.id.clone());
+ write_json(&self.paths.config(), &config)?;
+ // Committed: the active registration is not kept; the others are
+ // (until here it stays kept, so a crash or a failed write retries
+ // with it instead of making another machine).
+ kept.remove(&reg.machine.owner.id);
+ self.save_registrations(&kept)?;
+ // Registered for the new account and paused: resuming installs and
+ // starts the service with the new registration (and keeps a stopped
+ // host stopped on the relay), and is what a retry does if that fails.
+ self.resume_signed_in(&reg.machine.owner.id).await
+ }
+
+ /// The registrations of this computer under accounts that are not the
+ /// signed-in one (`<home>/host/registrations.json`, 0600).
+ fn registrations(&self) -> Registrations {
+ read_secret(&self.paths.dir.join(REGISTRATIONS_FILE))
+ .ok()
+ .and_then(|t| serde_json::from_str(&t).ok())
+ .unwrap_or_default()
+ }
+
+ fn save_registrations(&self, kept: &Registrations) -> Result<()> {
+ let text = serde_json::to_string(kept).map_err(|e| Error::Internal(e.to_string()))?;
+ write_secret(&self.paths.dir.join(REGISTRATIONS_FILE), &text)
+ }
+
/// Renames the machine and/or replaces its allowlist (relay mode; the
/// account must own it).
pub async fn update(
@@ -2351,6 +2581,18 @@ impl Host {
{
note(e);
}
+ // Its registrations under other accounts go too: nothing of this
+ // computer stays listed anywhere.
+ if let Some(url) = &config.relay_url {
+ for r in self.registrations().values() {
+ if let Err(e) = RelayClient::new(url)?
+ .delete(&r.machine_token, &r.machine_id)
+ .await
+ {
+ note(e);
+ }
+ }
+ }
self.manager_for_config(&config).uninstall()?;
if config.runner == RunnerKind::AppHelper.as_str() {
// Whatever an interrupted move left of the old agent.
diff --git a/libs/cua/crates/cua-host/src/lib.rs b/libs/cua/crates/cua-host/src/lib.rs
index 5836748f63..29d6c61496 100644
--- a/libs/cua/crates/cua-host/src/lib.rs
+++ b/libs/cua/crates/cua-host/src/lib.rs
@@ -54,7 +54,9 @@ pub mod testing;
mod tests;
pub mod uv;
-pub use device::{DeviceAuth, DeviceKey, FileKeySlot, KeySlot, MemoryKeySlot, PendingCode};
+pub use device::{
+ DeviceAuth, DeviceKey, FileKeySlot, KeySlot, MemoryKeySlot, PendingCode, token_subject,
+};
pub use helper_migration::{ServiceMigration, VerifyTiming};
pub use host::SetupStage;
pub use host::{
diff --git a/libs/cua/crates/cua-host/src/service.rs b/libs/cua/crates/cua-host/src/service.rs
index 5189d6c213..e0bcf3fc37 100644
--- a/libs/cua/crates/cua-host/src/service.rs
+++ b/libs/cua/crates/cua-host/src/service.rs
@@ -1748,6 +1748,8 @@ pub struct FakeServiceManager {
/// The last installed spec.
pub spec: Mutex<Option<ServiceSpec>>,
running: Mutex<bool>,
+ /// `start` fails while this is set.
+ pub fail_start: Mutex<bool>,
}
impl ServiceManager for FakeServiceManager {
@@ -1761,6 +1763,9 @@ impl ServiceManager for FakeServiceManager {
}
fn start(&self) -> Result<()> {
self.calls.lock().unwrap().push("start".into());
+ if *self.fail_start.lock().unwrap() {
+ return Err(Error::Service("the service would not start".into()));
+ }
*self.running.lock().unwrap() = true;
Ok(())
}
diff --git a/libs/cua/crates/cua-host/src/tests.rs b/libs/cua/crates/cua-host/src/tests.rs
index 6c13f6bc71..8f6e60e8cc 100644
--- a/libs/cua/crates/cua-host/src/tests.rs
+++ b/libs/cua/crates/cua-host/src/tests.rs
@@ -1332,6 +1332,61 @@ async fn sign_in_as_another_account_replaces_the_key_of_the_previous_one() {
assert!(as_b.session().await.is_ok());
}
+/// An account token that changes while the process lives (the daemon's
+/// session, read per call).
+struct SwitchableToken(std::sync::Mutex<String>);
+
+#[async_trait::async_trait]
+impl AccountTokens for SwitchableToken {
+ async fn access_token(&self) -> Result<String> {
+ Ok(self.0.lock().unwrap().clone())
+ }
+
+ async fn signed_in(&self) -> bool {
+ true
+ }
+}
+
+/// A long-running process (the daemon) holds a device session for the key
+/// it started with. When the app enrolls this computer again for another
+/// account with a new key, the daemon picks the new key up without a
+/// restart instead of sending the old session.
+#[tokio::test]
+async fn a_running_daemon_follows_a_new_device_key_after_an_account_switch() {
+ let relay = FakeRelay::start().await;
+ relay.add_account("acct-a", "user-a", Some("[email protected]"));
+ relay.add_account("acct-b", "user-b", Some("[email protected]"));
+ relay.require_devices(true);
+ relay.fresh_sign_in("user-a");
+ relay.fresh_sign_in("user-b");
+ let slot = Arc::new(MemoryKeySlot::default());
+ let tokens = Arc::new(SwitchableToken(std::sync::Mutex::new("acct-a".into())));
+ let device = |tokens: Arc<dyn AccountTokens>| {
+ DeviceAuth::new(&relay.url, tokens, slot.clone(), "Mac")
+ .unwrap()
+ .with_machine_id(Some("mac-1".into()))
+ };
+ // The daemon started signed in as A, with a session open.
+ let daemon = device(tokens.clone()).with_key_recheck(std::time::Duration::ZERO);
+ daemon.enroll_after_sign_in().await.unwrap();
+ let old_session = daemon.session().await.unwrap();
+ let old_id = daemon.device_id().unwrap().unwrap();
+
+ // The app signs in as B and enrolls with a new key (another process).
+ let app = device(Arc::new(StaticToken("acct-b".into())));
+ let enrolled = app.enroll_after_sign_in().await.unwrap();
+ assert_ne!(enrolled.device.id, old_id);
+ // The daemon's own session now reads as B.
+ *tokens.0.lock().unwrap() = "acct-b".into();
+
+ let session = daemon.session().await.unwrap();
+ assert_ne!(session, old_session, "the old key's session is not reused");
+ let listing = daemon.listing().await.unwrap();
+ let current = listing.devices.iter().find(|d| d.current).unwrap();
+ assert_eq!(current.id, enrolled.device.id);
+ assert_eq!(daemon.device_id().unwrap().unwrap(), enrolled.device.id);
+}
+
/// Two builds on one machine that each made a key end up with one: the key
/// the relay enrolled wins, the other's record is retired.
#[tokio::test]
@@ -1742,6 +1797,261 @@ async fn signing_out_pauses_relay_sharing_until_the_owner_signs_in() {
assert!(spec.args.join(" ").starts_with("join --relay"));
}
+/// A JWT-shaped account token whose `sub` is `user` (the host reads whose
+/// token it is from it).
+fn jwt(user: &str) -> String {
+ use base64::Engine as _;
+ let b = |v: &str| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(v);
+ format!("{}.{}.sig", b("{}"), b(&format!(r#"{{"sub":"{user}"}}"#)))
+}
+
+/// Signing in as another account re-registers this computer for it: a new
+/// machine id and mesh key, while the name and the Provide Spaces setting
+/// stay.
+#[tokio::test]
+async fn signing_in_as_another_account_registers_the_host_again() {
+ let relay = FakeRelay::start().await;
+ relay.add_account(&jwt("user-1"), "user-1", Some("[email protected]"));
+ relay.add_account(&jwt("user-2"), "user-2", Some("[email protected]"));
+ let f = fixture();
+ let host = f.host();
+ let mut opts = f.relay_opts(&relay.url);
+ opts.provide_spaces = true;
+ let before = host.setup(opts, &StaticToken(jwt("user-1"))).await.unwrap();
+ let old_id = before.machine_id.clone().unwrap();
+ let old_token = std::fs::read_to_string(host.paths().machine_token()).unwrap();
+ let mesh = host.paths().driver_data.join("mesh");
+ std::fs::create_dir_all(&mesh).unwrap();
+ std::fs::write(mesh.join("identity.json"), "{}").unwrap();
+ host.pause_signed_out().await.unwrap();
+
+ // The account that signed out is resumed as before.
+ let same = host
+ .resume_or_switch_account("user-1", &StaticToken(jwt("user-1")))
+ .await
+ .unwrap();
+ assert_eq!(same.machine_id.as_deref(), Some(old_id.as_str()));
+ host.pause_signed_out().await.unwrap();
+
+ // Another account's sign-in moves it over, with no manual step.
+ f.manager.calls.lock().unwrap().clear();
+ let switched = host
+ .resume_or_switch_account("user-2", &StaticToken(jwt("user-2")))
+ .await
+ .unwrap();
+ assert!(!switched.paused_signed_out);
+ assert!(switched.service.installed && switched.service.running);
+ assert!(switched.sharing);
+ assert_ne!(switched.machine_id.as_deref(), Some(old_id.as_str()));
+ assert_eq!(switched.owner.as_deref(), Some("user-2"));
+ assert_eq!(switched.name.as_deref(), Some("mini"));
+ assert!(switched.provide_spaces, "the Provide Spaces setting stays");
+ assert!(host.policy().unwrap().unwrap().provide_spaces);
+ assert!(host.policy().unwrap().unwrap().allow.is_empty());
+ assert_ne!(
+ std::fs::read_to_string(host.paths().machine_token()).unwrap(),
+ old_token
+ );
+ assert!(
+ !mesh.join("identity.json").exists(),
+ "the mesh key bound to the old account is dropped"
+ );
+ // The relay registered the new id to the new account.
+ let on_relay = relay
+ .machine(switched.machine_id.as_deref().unwrap())
+ .expect("registered");
+ assert_eq!(on_relay.owner.id, "user-2");
+
+ // The previous account's record of this computer is kept for it.
+ assert_eq!(
+ relay.machine(&old_id).expect("kept").owner.id,
+ "user-1",
+ "the first account's registration stays"
+ );
+
+ // Signed in as the new owner again: a plain resume, no new machine.
+ host.pause_signed_out().await.unwrap();
+ let again = host
+ .resume_or_switch_account("user-2", &StaticToken(jwt("user-2")))
+ .await
+ .unwrap();
+ assert_eq!(again.machine_id, switched.machine_id);
+
+ // Back to the first account: its own registration is reused (same
+ // machine id, so what is tied to it stays), not a third machine.
+ let back = host
+ .resume_or_switch_account("user-1", &StaticToken(jwt("user-1")))
+ .await
+ .unwrap();
+ assert_eq!(back.machine_id.as_deref(), Some(old_id.as_str()));
+ assert_eq!(back.owner.as_deref(), Some("user-1"));
+ assert_eq!(back.name.as_deref(), Some("mini"));
+ assert!(back.provide_spaces && back.service.running);
+ assert_eq!(
+ relay
+ .machine(switched.machine_id.as_deref().unwrap())
+ .expect("the second account's is kept")
+ .owner
+ .id,
+ "user-2"
+ );
+
+ // Removing the host unregisters every registration of this computer.
+ host.remove().await.unwrap();
+ assert!(relay.machine(&old_id).is_none());
+ assert!(
+ relay
+ .machine(switched.machine_id.as_deref().unwrap())
+ .is_none()
+ );
+}
+
+/// A computer that still runs Spaces for the account that was signed in does
+/// not hand them to another account: it stays paused (and says why) until
+/// they are deleted, and then moves over.
+#[tokio::test]
+async fn a_switch_waits_while_spaces_run_for_the_previous_account() {
+ let relay = FakeRelay::start().await;
+ relay.add_account(&jwt("user-1"), "user-1", Some("[email protected]"));
+ relay.add_account(&jwt("user-2"), "user-2", Some("[email protected]"));
+ let f = fixture();
+ let host = f.host();
+ let before = host
+ .setup(f.relay_opts(&relay.url), &StaticToken(jwt("user-1")))
+ .await
+ .unwrap();
+ let space = crate::provided::ProvidedSpace {
+ relay_machine: "space-1".into(),
+ local_space: "local:one".into(),
+ name: "one".into(),
+ created_by_account: "user-1".into(),
+ ..Default::default()
+ };
+ crate::provided::save_provided(&host.paths().dir, &[space]).unwrap();
+ let as_b = StaticToken(jwt("user-2"));
+
+ let err = host
+ .resume_or_switch_account("user-2", &as_b)
+ .await
+ .unwrap_err();
+ assert!(err.to_string().contains("still runs 1 Space"), "{err}");
+ let s = host.status().await.unwrap();
+ assert!(
+ s.paused_signed_out && !s.sharing,
+ "the old account's access is closed"
+ );
+ assert_eq!(s.machine_id, before.machine_id, "nothing was re-registered");
+ assert_eq!(host.provided_spaces().unwrap().len(), 1);
+
+ crate::provided::save_provided(&host.paths().dir, &[]).unwrap();
+ let s = host
+ .resume_or_switch_account("user-2", &as_b)
+ .await
+ .unwrap();
+ assert!(!s.paused_signed_out && s.sharing);
+ assert_eq!(s.owner.as_deref(), Some("user-2"));
+}
+
+/// What the owner chose for sharing follows the host across accounts: it is
+/// sent to the relay for the registration that takes over.
+#[tokio::test]
+async fn sharing_follows_the_hosts_choice_when_the_account_changes_back() {
+ let relay = FakeRelay::start().await;
+ relay.add_account(&jwt("user-1"), "user-1", Some("[email protected]"));
+ relay.add_account(&jwt("user-2"), "user-2", Some("[email protected]"));
+ let f = fixture();
+ let host = f.host();
+ let first = host
+ .setup(f.relay_opts(&relay.url), &StaticToken(jwt("user-1")))
+ .await
+ .unwrap();
+ host.stop_sharing().await.unwrap();
+ let as_b = StaticToken(jwt("user-2"));
+ host.resume_or_switch_account("user-2", &as_b)
+ .await
+ .unwrap();
+ // As the second account sharing is turned on again.
+ let started = host.start_sharing().await.unwrap();
+ assert!(started.sharing);
+ // Back to the first account: sharing is on there too (the host's
+ // choice), not left stopped on its old registration.
+ let back = host
+ .resume_or_switch_account("user-1", &StaticToken(jwt("user-1")))
+ .await
+ .unwrap();
+ assert_eq!(back.machine_id, first.machine_id);
+ assert!(back.sharing);
+ assert!(
+ relay
+ .machine(first.machine_id.as_deref().unwrap())
+ .unwrap()
+ .sharing
+ );
+}
+
+/// A host the owner had stopped sharing stays stopped (on the relay too)
+/// after a switch of account.
+#[tokio::test]
+async fn a_stopped_host_stays_stopped_after_an_account_switch() {
+ let relay = FakeRelay::start().await;
+ relay.add_account(&jwt("user-1"), "user-1", Some("[email protected]"));
+ relay.add_account(&jwt("user-2"), "user-2", Some("[email protected]"));
+ let f = fixture();
+ let host = f.host();
+ host.setup(f.relay_opts(&relay.url), &StaticToken(jwt("user-1")))
+ .await
+ .unwrap();
+ host.stop_sharing().await.unwrap();
+ let switched = host
+ .resume_or_switch_account("user-2", &StaticToken(jwt("user-2")))
+ .await
+ .unwrap();
+ assert!(!switched.sharing, "still stopped here");
+ assert!(switched.service.running, "but online");
+ let on_relay = relay
+ .machine(switched.machine_id.as_deref().unwrap())
+ .unwrap();
+ assert!(!on_relay.sharing, "and on the relay");
+}
+
+/// A switch of account that fails leaves the previous account's sharing
+/// closed and retries on the next check, instead of leaving it open or the
+/// host offline for good.
+#[tokio::test]
+async fn a_failed_account_switch_stays_paused_and_retries() {
+ let relay = FakeRelay::start().await;
+ relay.add_account(&jwt("user-1"), "user-1", Some("[email protected]"));
+ relay.add_account(&jwt("user-2"), "user-2", Some("[email protected]"));
+ let f = fixture();
+ let host = f.host();
+ let before = host
+ .setup(f.relay_opts(&relay.url), &StaticToken(jwt("user-1")))
+ .await
+ .unwrap();
+ let b = StaticToken(jwt("user-2"));
+
+ // The relay refuses the new registration while the host is sharing: the
+ // old account's sharing is closed first, and stays closed.
+ relay.fail_registrations(&[400]);
+ assert!(host.resume_or_switch_account("user-2", &b).await.is_err());
+ let s = host.status().await.unwrap();
+ assert!(s.paused_signed_out && !s.sharing && !s.service.running);
+ assert_eq!(s.machine_id, before.machine_id);
+ assert!(!host.policy().unwrap().unwrap().sharing);
+
+ // The service fails to start after registering: still paused, with the
+ // new owner, so the next check resumes it as the owner.
+ *f.manager.fail_start.lock().unwrap() = true;
+ assert!(host.resume_or_switch_account("user-2", &b).await.is_err());
+ let s = host.status().await.unwrap();
+ assert!(s.paused_signed_out && !s.sharing);
+ assert_eq!(s.owner.as_deref(), Some("user-2"));
+ assert_ne!(s.machine_id, before.machine_id);
+ *f.manager.fail_start.lock().unwrap() = false;
+ let s = host.resume_or_switch_account("user-2", &b).await.unwrap();
+ assert!(!s.paused_signed_out && s.sharing && s.service.running);
+}
+
/// Stopped sharing stays stopped across a pause, and direct mode (no
/// account involved) is never paused.
#[tokio::test]
diff --git a/libs/cua/crates/cua-mesh/src/coord.rs b/libs/cua/crates/cua-mesh/src/coord.rs
index 24a0a9e2ad..cdce06b1ff 100644
--- a/libs/cua/crates/cua-mesh/src/coord.rs
+++ b/libs/cua/crates/cua-mesh/src/coord.rs
@@ -240,12 +240,21 @@ fn tls_connector() -> tokio_tungstenite::Connector {
tokio_tungstenite::Connector::Rustls(Arc::new(cfg))
}
+/// What the coordinator says when a node key is registered to another
+/// owner (the account that was signed in before).
+pub const KEY_OWNED_BY_ANOTHER: &str = "this node key belongs to another owner";
+
/// The reason, when `e` is the coordinator refusing this node's
-/// credentials (HTTP 401 or 403) rather than a transient failure (a
-/// restarting relay answers 502 or 503 and is retried as before).
+/// credentials (HTTP 401 or 403) or its key (bound to another owner, for
+/// life) rather than a transient failure (a restarting relay answers 502
+/// or 503 and is retried as before).
fn denial(e: &Error) -> Option<String> {
match e {
- Error::Refused(m) if m.starts_with("HTTP 401") || m.starts_with("HTTP 403") => {
+ Error::Refused(m)
+ if m.starts_with("HTTP 401")
+ || m.starts_with("HTTP 403")
+ || m.contains(KEY_OWNED_BY_ANOTHER) =>
+ {
Some(m.clone())
}
_ => None,
diff --git a/libs/cua/crates/cua-mesh/src/testing.rs b/libs/cua/crates/cua-mesh/src/testing.rs
index 477ca71718..d795634232 100644
--- a/libs/cua/crates/cua-mesh/src/testing.rs
+++ b/libs/cua/crates/cua-mesh/src/testing.rs
@@ -52,6 +52,10 @@ struct State {
close_after_welcome: Mutex<Option<(u16, String)>>,
/// Nodes welcomed since start.
welcomes: AtomicU64,
+ /// The account credential (`x-cua-relay-authorization`) each client node
+ /// key was first seen with: a key belongs to one owner for life, as in
+ /// `cua-relay`.
+ key_owners: Mutex<HashMap<PublicKey, String>>,
}
/// See the module docs.
@@ -327,6 +331,7 @@ fn may_relay(state: &State, mode: Mode, a: &PublicKey, b: &PublicKey) -> bool {
#[allow(clippy::result_large_err)]
async fn serve(state: Arc<State>, mode: Mode, tcp: tokio::net::TcpStream) {
let mut machine_id = None::<String>;
+ let mut account = None::<String>;
let denied = state.denied.lock().expect("denied").clone();
let mesh_off = state.mesh_off.load(Ordering::SeqCst);
let ws = tokio_tungstenite::accept_hdr_async(tcp, |req: &Request, resp: Response| {
@@ -335,6 +340,11 @@ async fn serve(state: Arc<State>, mode: Mode, tcp: tokio::net::TcpStream) {
.get(proto::MACHINE_ID_HEADER)
.and_then(|v| v.to_str().ok())
.map(str::to_owned);
+ account = req
+ .headers()
+ .get("x-cua-relay-authorization")
+ .and_then(|v| v.to_str().ok())
+ .map(str::to_owned);
let refused = denied.iter().any(|(k, v)| {
req.headers()
.get(k.as_str())
@@ -405,6 +415,27 @@ async fn serve(state: Arc<State>, mode: Mode, tcp: tokio::net::TcpStream) {
.await;
return;
}
+ let owned_by_another = match &account {
+ Some(owner) if kind == NodeKind::Client => {
+ let mut owners = state.key_owners.lock().expect("owners");
+ owners.entry(node_key).or_insert_with(|| owner.clone()) != owner
+ }
+ _ => false,
+ };
+ {
+ if owned_by_another {
+ let _ = sink
+ .send(WsMessage::Text(
+ serde_json::to_string(&ServerMsg::Error {
+ message: crate::coord::KEY_OWNED_BY_ANOTHER.into(),
+ })
+ .expect("json")
+ .into(),
+ ))
+ .await;
+ return;
+ }
+ }
let info = PeerInfo {
node_key,
disco_key,
diff --git a/libs/cua/crates/cua-sdk/src/native/host.rs b/libs/cua/crates/cua-sdk/src/native/host.rs
index f21de4200f..4461666ea3 100644
--- a/libs/cua/crates/cua-sdk/src/native/host.rs
+++ b/libs/cua/crates/cua-sdk/src/native/host.rs
@@ -796,10 +796,15 @@ impl Host {
pub async fn resume_signed_in(&self, account: String) -> Result<HostStatus> {
let home = self.home.clone();
run(async move {
- Ok(cua_host::Host::new(home)
- .resume_signed_in(&account)
- .await?
- .into())
+ // Another account is not refused here: the host registers again
+ // for it (same name and Provide Spaces setting), so a different
+ // sign-in needs no manual remove and set up.
+ let tokens = SessionTokens(Arc::new(cua_auth::Session::from_env()));
+ Ok(
+ Box::pin(cua_host::Host::new(home).resume_or_switch_account(&account, &tokens))
+ .await?
+ .into(),
+ )
})
.await
}
diff --git a/libs/cua/crates/cua-spaces-app-core/src/host.rs b/libs/cua/crates/cua-spaces-app-core/src/host.rs
index ed3fbe56af..3c8a073780 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/host.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/host.rs
@@ -535,8 +535,9 @@ pub enum HostAccountStep {
Resume,
}
-/// Relay sharing follows the sign-in: nobody signed in (or another
-/// account) pauses it, the owner signing in again resumes it. `account` is
+/// Relay sharing follows the sign-in: nobody signed in pauses it, the owner
+/// signing in again resumes it, and another account signing in moves this
+/// computer over to it (the host registers again). `account` is
/// `None` only when the app knows nobody is signed in (not when it could
/// not tell, offline). Direct mode does not use the account.
pub fn account_step(state: &HostState, account: Option<&HostAccount>) -> HostAccountStep {
@@ -545,7 +546,11 @@ pub fn account_step(state: &HostState, account: Option<&HostAccount>) -> HostAcc
}
let owner = account.map(|a| owned_by(state, a).unwrap_or(true));
match (state.paused_signed_out, owner) {
- (false, None | Some(false)) => HostAccountStep::Pause,
+ (false, None) => HostAccountStep::Pause,
+ // Another account signed in: `Resume` makes the host register again
+ // for it (name and Provide Spaces stay), paused or not, so there
+ // is no manual remove and set up.
+ (_, Some(false)) => HostAccountStep::Resume,
(true, Some(true)) => HostAccountStep::Resume,
_ => HostAccountStep::Keep,
}
@@ -1302,10 +1307,19 @@ pub fn panel(state: Option<&HostState>) -> HostPanelView {
};
if relay && s.paused_signed_out {
match s.account.as_ref().map(|a| owned_by(s, a)) {
- // Signed in to another account: this registration is not
- // theirs to share. Removing it, then setting up again, is.
+ // Signed in to another account: the app moves this computer
+ // over by itself (see [`account_step`]); this is the button
+ // when that failed.
Some(Some(false)) => {
v.notice = Some(OTHER_ACCOUNT_NOTICE.into());
+ v.notice_action = Some(HostAction {
+ id: HostActionId::ResumeSharing,
+ label: "Share With This Account".into(),
+ destructive: false,
+ confirm: None,
+ enabled: true,
+ help: None,
+ });
v.actions = vec![remove];
}
// The owner is signed in again (the app resumes on its own;
@@ -1371,9 +1385,9 @@ pub const NOTHING_TO_SHARE_HELP: &str =
/// The page's line while another account is signed in and this machine's
/// relay sharing (registered to the account that signed out) is paused.
-pub const OTHER_ACCOUNT_NOTICE: &str = "This Mac is shared with another Cua \
-account, so sharing stays paused. Remove the host setup, then set it up again \
-to share it with yours.";
+pub const OTHER_ACCOUNT_NOTICE: &str = "This Mac was set up with another Cua \
+account, so sharing is paused. Share it with the account you are signed in to \
+now; its name and settings stay.";
/// "Up to 4 Spaces · 2 macOS VMs". The macOS part is for a Mac: a shell on
/// another system drops it (the web UI's `limitsFor`).
@@ -2490,16 +2504,26 @@ mod tests {
HostActionId::ResumeSharing
);
- // Another account: never re-share the old one's registration.
+ // Another account signs in: the host registers again for it, with
+ // no manual step, whether sharing was paused or not.
let s = owned(true, Some(bob.clone()));
- assert_eq!(account_step(&s, s.account.as_ref()), HostAccountStep::Keep);
+ assert_eq!(
+ account_step(&s, s.account.as_ref()),
+ HostAccountStep::Resume
+ );
+ // The button, if that failed.
let v = panel(Some(&s));
assert_eq!(v.notice.as_deref(), Some(OTHER_ACCOUNT_NOTICE));
- assert!(v.notice_action.is_none());
+ assert_eq!(
+ v.notice_action.as_ref().unwrap().id,
+ HostActionId::ResumeSharing
+ );
assert_eq!(v.actions[0].id, HostActionId::Remove);
- // ...and one signed in while it shares pauses it.
let s = owned(false, Some(bob));
- assert_eq!(account_step(&s, s.account.as_ref()), HostAccountStep::Pause);
+ assert_eq!(
+ account_step(&s, s.account.as_ref()),
+ HostAccountStep::Resume
+ );
// Direct mode and a machine that is not set up never follow it.
let direct = HostState {
diff --git a/libs/cua/crates/cua-spaces-cli/src/pool_ext.rs b/libs/cua/crates/cua-spaces-cli/src/pool_ext.rs
index 70152f7a6c..ea411c331f 100644
--- a/libs/cua/crates/cua-spaces-cli/src/pool_ext.rs
+++ b/libs/cua/crates/cua-spaces-cli/src/pool_ext.rs
@@ -227,7 +227,7 @@ struct DaemonHost {
home: PathBuf,
runtime_host: Option<Arc<cua_spaces::host_spaces::HostSpacesServer>>,
/// The pool per relay URL, once its account is known.
- relays: Mutex<HashMap<String, RelayPool>>,
+ relays: Mutex<HashMap<String, (Option<String>, RelayPool)>>,
/// Each machine's OS, once it answered.
os: Arc<Mutex<HashMap<String, String>>>,
/// Whether a machine whose setup said otherwise provides Spaces now,
@@ -240,7 +240,12 @@ struct DaemonHost {
}
/// A relay URL, when its device key was read, and the key.
-type CachedSigner = (String, std::time::Instant, Arc<dyn DeviceSigner>);
+type CachedSigner = (
+ String,
+ std::time::Instant,
+ Option<String>,
+ Arc<dyn DeviceSigner>,
+);
/// The name of this device's pool key in the credential store (the OS
/// vault for Cua-signed builds, else a 0600 file), next to its device key.
@@ -332,7 +337,12 @@ impl DaemonHost {
impl Host for DaemonHost {
async fn relay(&self) -> Option<RelayPool> {
let account = self.spaces.relay_account()?;
- if let Some(p) = self.relays.lock().expect("relays").get(&account.url) {
+ // Which account this is: the pool is the account's, so another
+ // sign-in needs its own (the relay says its id below).
+ let who = account.account_subject().await;
+ if let Some((started, p)) = self.relays.lock().expect("relays").get(&account.url)
+ && !cua_spaces::relay::account_changed(started, &who)
+ {
return Some(p.clone());
}
let auth: Arc<dyn PoolAuth> = Arc::new(AccountAuth(account.clone()));
@@ -347,7 +357,7 @@ impl Host for DaemonHost {
self.relays
.lock()
.expect("relays")
- .insert(account.url.clone(), pool.clone());
+ .insert(account.url.clone(), (who, pool.clone()));
Some(pool)
}
@@ -438,15 +448,18 @@ impl Host for DaemonHost {
if url != relay.base() {
return None;
}
- if let Some((u, at, s)) = self.signer.lock().expect("signer").as_ref()
+ let who = account.account_subject().await;
+ if let Some((u, at, started, s)) = self.signer.lock().expect("signer").as_ref()
&& *u == url
&& at.elapsed() < std::time::Duration::from_secs(60)
+ && !cua_spaces::relay::account_changed(started, &who)
{
return Some(s.clone());
}
let key = account.device.as_ref()?.key().ok()??;
let s: Arc<dyn DeviceSigner> = Arc::new(DeviceKeySigner(key));
- *self.signer.lock().expect("signer") = Some((url, std::time::Instant::now(), s.clone()));
+ *self.signer.lock().expect("signer") =
+ Some((url, std::time::Instant::now(), who, s.clone()));
Some(s)
}
diff --git a/libs/cua/crates/cua-spaces-cluster/src/pool/mod.rs b/libs/cua/crates/cua-spaces-cluster/src/pool/mod.rs
index ca471c7dea..123343db38 100644
--- a/libs/cua/crates/cua-spaces-cluster/src/pool/mod.rs
+++ b/libs/cua/crates/cua-spaces-cluster/src/pool/mod.rs
@@ -600,6 +600,7 @@ impl PoolAgent {
self.drop_holding("signed out", false).await;
continue;
};
+ self.drop_holding_of_another_account(&relay).await;
if self.no_relay_pool.load(Ordering::SeqCst) {
continue;
}
@@ -838,6 +839,24 @@ impl PoolAgent {
}
}
+ /// Another account signed in than the one this machine coordinates
+ /// the pool of: its coordinator and job state are the old account's, so
+ /// it stops at once (the lease is not released: `relay` is the new
+ /// account's pool, and the old lease ends by itself). Returns whether
+ /// it did.
+ async fn drop_holding_of_another_account(&self, relay: &RelayPool) -> bool {
+ let other = self
+ .holding
+ .lock()
+ .await
+ .as_ref()
+ .is_some_and(|h| h.relay.key() != relay.key());
+ if other {
+ self.drop_holding("another account signed in", false).await;
+ }
+ other
+ }
+
async fn drop_holding(&self, why: &str, release: bool) {
let h = self.holding.lock().await.take();
if let Some(h) = h {
@@ -1223,6 +1242,80 @@ mod tests {
}
}
+ struct NoHost;
+
+ #[async_trait]
+ impl Host for NoHost {
+ async fn relay(&self) -> Option<RelayPool> {
+ None
+ }
+ fn name(&self) -> String {
+ "mini".into()
+ }
+ fn machine_id(&self) -> String {
+ String::new()
+ }
+ fn provides_spaces(&self) -> bool {
+ false
+ }
+ async fn account_machines(&self) -> Result<Vec<PoolMachine>, String> {
+ Ok(vec![])
+ }
+ async fn direct_machines(&self) -> Vec<PoolMachine> {
+ vec![]
+ }
+ async fn local_runner(&self) -> Option<Arc<dyn NodeLink>> {
+ None
+ }
+ fn elastic(&self) -> Option<(NodeRow, LinkFactory)> {
+ None
+ }
+ }
+
+ struct NoAuth;
+
+ #[async_trait]
+ impl relay::PoolAuth for NoAuth {
+ async fn headers(&self) -> Result<Vec<(String, String)>, String> {
+ Err("not used".into())
+ }
+ }
+
+ /// A machine that coordinates the pool of the account that was signed
+ /// in stops when another account signs in, even if the new pool grants
+ /// the same epoch number; the same account keeps it.
+ #[tokio::test]
+ async fn the_coordinator_of_the_previous_account_stops_when_another_signs_in() {
+ let dir = tempfile::tempdir().unwrap();
+ let agent = PoolAgent::start(
+ dir.path().join("pool"),
+ Arc::new(NoHost),
+ AgentConfig::default(),
+ )
+ .await
+ .unwrap();
+ let auth: Arc<dyn relay::PoolAuth> = Arc::new(NoAuth);
+ let pool_a = RelayPool::new("http://relay", "acct-a", auth.clone());
+ let pool_b = RelayPool::new("http://relay", "acct-b", auth);
+ let coord = Coordinator::start(crate::coordinator::Config::new(dir.path().join("c")), None)
+ .await
+ .unwrap();
+ *agent.holding.lock().await = Some(Holding {
+ epoch: 1,
+ relay: pool_a.clone(),
+ coord,
+ stop: CancellationToken::new(),
+ });
+ assert!(!agent.drop_holding_of_another_account(&pool_a).await);
+ assert!(agent.holder().await.is_some(), "the same account keeps it");
+ assert!(agent.drop_holding_of_another_account(&pool_b).await);
+ assert!(
+ agent.holder().await.is_none(),
+ "the other account's is gone"
+ );
+ agent.shutdown().await;
+ }
+
/// A machine removed from the account is drained at the first listing
/// without it and leaves the pool at the next, so its name is free for
/// a new machine (`cua cloud add aws --down`, then `cua cloud add aws`).
diff --git a/libs/cua/crates/cua-spaces/src/mesh.rs b/libs/cua/crates/cua-spaces/src/mesh.rs
index 14e3e9dce6..81bff621e3 100644
--- a/libs/cua/crates/cua-spaces/src/mesh.rs
+++ b/libs/cua/crates/cua-spaces/src/mesh.rs
@@ -85,14 +85,33 @@ enum Slot {
dialer: Arc<Dialer>,
/// Held while the node lives: one persistent identity per home.
_lock: Option<std::fs::File>,
+ /// The account the node connected for (an account node).
+ account: Option<String>,
},
/// The mesh cannot be used (the relay has none, or refused this
- /// device), and why; checked again after a while.
- Unsupported(Instant, String),
+ /// device), and why; checked again after a while (or at once when
+ /// another account signs in).
+ Unsupported(Instant, String, Option<String>, Duration),
}
+use crate::relay::account_changed;
+
const RECHECK: Duration = Duration::from_secs(600);
+/// A node the relay refused (not enrolled yet, a key it did not take) is
+/// tried again soon: the cause is often a sign-in whose device enrollment
+/// has not finished, not a relay without a mesh.
+const RECHECK_REFUSED: Duration = Duration::from_secs(5);
+
+/// When to try a node that could not start again.
+fn recheck_after(why: &str) -> Duration {
+ if why.contains("mesh refused") {
+ RECHECK_REFUSED
+ } else {
+ RECHECK
+ }
+}
+
/// Per-runtime mesh nodes, started on first use.
#[derive(Default)]
pub(crate) struct MeshClients {
@@ -100,7 +119,10 @@ pub(crate) struct MeshClients {
/// Spaces connected over the mesh, through which node, and whether one
/// of your own hosts provides the Space (it then prefers the mesh
/// without `CUA_MESH`, [`policy_for_provided`]).
- routed: std::sync::Mutex<HashMap<String, (Key, bool)>>,
+ routed: std::sync::Mutex<HashMap<String, (Key, bool, u64)>>,
+ /// How many nodes each key has had: a Space routed through an earlier
+ /// node holds forwards that ended with it.
+ generations: std::sync::Mutex<HashMap<Key, u64>>,
/// Spaces that took the relay's HTTPS path although they prefer the
/// mesh, because their machine was not on it yet (a Space whose driver
/// joins a moment after its relay connection): its node, machine id and
@@ -215,10 +237,21 @@ fn key_of(via: &Via<'_>) -> Key {
impl MeshClients {
/// Records that Space `space` (its id) connected over `via`'s mesh.
pub(crate) fn note_routed(&self, space: &str, via: &Via<'_>, provided: bool) {
+ let key = key_of(via);
+ let generation = self.generation(&key);
self.routed
.lock()
.expect("routed")
- .insert(space.to_owned(), (key_of(via), provided));
+ .insert(space.to_owned(), (key, provided, generation));
+ }
+
+ fn generation(&self, key: &Key) -> u64 {
+ self.generations
+ .lock()
+ .expect("generations")
+ .get(key)
+ .copied()
+ .unwrap_or(0)
}
/// Records that Space `space` (its id) took the relay's HTTPS path
@@ -265,9 +298,14 @@ impl MeshClients {
space: &str,
policy: impl FnOnce(bool) -> MeshPolicy,
) -> Option<String> {
- let (key, provided) = self.routed.lock().expect("routed").get(space).cloned()?;
+ let (key, provided, generation) =
+ self.routed.lock().expect("routed").get(space).cloned()?;
let reason = if !policy(provided).uses_mesh() {
Some("the mesh was turned off".into())
+ } else if self.generation(&key) != generation {
+ // Another account signed in and the node started again: this
+ // Space's forwards ended with the old node.
+ Some("its mesh node was replaced".into())
} else {
None
};
@@ -285,9 +323,12 @@ impl MeshClients {
/// by the relay fails a moment before the relay's refusal arrives.
/// Leaves the Space marked, so its next use reconnects.
pub(crate) async fn cut_reason(&self, space: &str, wait: Duration) -> Option<String> {
- let (key, _) = self.routed.lock().expect("routed").get(space).cloned()?;
+ let (key, _, generation) = self.routed.lock().expect("routed").get(space).cloned()?;
let deadline = Instant::now() + wait;
loop {
+ if self.generation(&key) != generation {
+ return Some("its mesh node was replaced".into());
+ }
if let Some(reason) = self.unusable(&key).await {
return Some(reason);
}
@@ -307,7 +348,28 @@ impl MeshClients {
}
async fn dialer(&self, via: &Via<'_>) -> Result<Arc<Dialer>, String> {
- let key = key_of(via);
+ let account = match via {
+ Via::Account(a) => a.account_subject().await,
+ Via::Static { .. } => None,
+ };
+ self.dialer_with(key_of(via), account, || start(via)).await
+ }
+
+ /// The node for `key`, started by `start` when there is none, it can
+ /// no longer be used, or another account is signed in than the one it
+ /// connected for (its connection to the relay is that account's until
+ /// it reconnects, so Spaces of the new account would not be on its
+ /// map and would take the relay's HTTPS path).
+ async fn dialer_with<F, Fut>(
+ &self,
+ key: Key,
+ account: Option<String>,
+ start: F,
+ ) -> Result<Arc<Dialer>, String>
+ where
+ F: FnOnce() -> Fut,
+ Fut: std::future::Future<Output = Result<(Dialer, Option<std::fs::File>), String>>,
+ {
let mut nodes = self.nodes.lock().await;
match nodes.get(&key) {
// A node the relay no longer coordinates (mesh turned off, or
@@ -318,26 +380,48 @@ impl MeshClients {
dialer.mesh().shutdown();
nodes.remove(&key);
}
+ Some(Slot::Ready {
+ dialer,
+ account: started,
+ ..
+ }) if account_changed(started, &account) => {
+ tracing::info!("another account signed in: starting the mesh node again for it");
+ dialer.mesh().shutdown();
+ nodes.remove(&key);
+ }
Some(Slot::Ready { dialer, .. }) => return Ok(dialer.clone()),
- Some(Slot::Unsupported(at, why)) if at.elapsed() < RECHECK => {
+ Some(Slot::Unsupported(at, why, started, every))
+ if at.elapsed() < *every && !account_changed(started, &account) =>
+ {
return Err(why.clone());
}
_ => {}
}
- match start(via).await {
+ match start().await {
Ok((d, lock)) => {
let d = Arc::new(d);
+ *self
+ .generations
+ .lock()
+ .expect("generations")
+ .entry(key.clone())
+ .or_default() += 1;
nodes.insert(
key,
Slot::Ready {
dialer: d.clone(),
_lock: lock,
+ account,
},
);
Ok(d)
}
Err(e) => {
- nodes.insert(key, Slot::Unsupported(Instant::now(), e.clone()));
+ let every = recheck_after(&e);
+ nodes.insert(
+ key,
+ Slot::Unsupported(Instant::now(), e.clone(), account, every),
+ );
Err(e)
}
}
@@ -421,12 +505,48 @@ async fn start(via: &Via<'_>) -> Result<(Dialer, Option<std::fs::File>), String>
Some(lock) => (Some(dir.join(format!("{name}.json"))), Some(lock)),
None => (None, None),
};
- let dialer = Dialer::start(&url, auth, identity, Duration::from_secs(10))
- .await
- .map_err(|e| e.to_string())?;
+ let dialer = start_dialer(&url, auth, identity).await?;
Ok((dialer, lock))
}
+/// Starts the client node. The relay binds a node key to the account that
+/// first used it, for life. After signing in as another account on this
+/// computer the saved key is the previous account's, and the relay refuses
+/// it: the key is rotated (the identity file is replaced by a new one) and
+/// the node starts again, so Spaces keep their mesh path instead of
+/// silently falling back to the relay's HTTPS path. The relay still decides
+/// whether the new key is accepted.
+async fn start_dialer(
+ url: &str,
+ auth: cua_mesh::AuthProvider,
+ identity: Option<std::path::PathBuf>,
+) -> Result<Dialer, String> {
+ let wait = Duration::from_secs(10);
+ // Boxed: the SDK's futures nest deeply, and their layout check has a
+ // fixed depth budget.
+ match Box::pin(Dialer::start(url, auth.clone(), identity.clone(), wait)).await {
+ Err(cua_mesh::Error::Refused(why))
+ if why.contains(cua_mesh::coord::KEY_OWNED_BY_ANOTHER) && identity.is_some() =>
+ {
+ let path = identity.clone().expect("checked");
+ tracing::info!(
+ relay = %url,
+ "this computer's mesh key belongs to the account that was signed in before; making a new one"
+ );
+ std::fs::remove_file(&path)
+ .or_else(|e| match e.kind() {
+ std::io::ErrorKind::NotFound => Ok(()),
+ _ => Err(e),
+ })
+ .map_err(|e| format!("could not replace the mesh key: {e}"))?;
+ Box::pin(Dialer::start(url, auth, identity, wait))
+ .await
+ .map_err(|e| e.to_string())
+ }
+ other => other.map_err(|e| e.to_string()),
+ }
+}
+
fn lock_identity(dir: &std::path::Path, name: &str) -> Option<std::fs::File> {
std::fs::create_dir_all(dir).ok()?;
let f = std::fs::OpenOptions::new()
@@ -617,13 +737,14 @@ mod tests {
Slot::Ready {
dialer: Arc::new(dialer),
_lock: None,
+ account: None,
},
);
clients
.routed
.lock()
.unwrap()
- .insert("relay:m1".into(), (key, false));
+ .insert("relay:m1".into(), (key, false, 0));
assert!(
clients
.stale("relay:m1", |_| MeshPolicy::Prefer)
@@ -666,6 +787,136 @@ mod tests {
);
}
+ fn as_account(token: &'static str) -> cua_mesh::AuthProvider {
+ cua_mesh::static_auth(vec![(
+ "x-cua-relay-authorization".into(),
+ format!("Bearer {token}"),
+ )])
+ }
+
+ /// The daemon's node is connected as the account that was signed in
+ /// when it started. When another account signs in, the node is started
+ /// again for it (with a new key), instead of staying on the previous
+ /// account's map where the new account's computers are missing.
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn a_running_node_is_replaced_when_another_account_signs_in() {
+ let coord = cua_mesh::testing::FakeCoordinator::start(cua_mesh::Mode::Account).await;
+ let dir = tempfile::tempdir().unwrap();
+ let identity = dir.path().join("client.json");
+ let clients = MeshClients::default();
+ let key = Key::Account(coord.url.clone());
+ let starter = |token: &'static str| {
+ let (url, identity) = (coord.url.clone(), identity.clone());
+ move || async move {
+ let d = start_dialer(&url, as_account(token), Some(identity)).await?;
+ Ok::<_, String>((d, None))
+ }
+ };
+ let a = clients
+ .dialer_with(key.clone(), Some("sub-a".into()), starter("a"))
+ .await
+ .unwrap();
+ let key_a = a.mesh().node_key();
+ // The same account again: the same node.
+ let again = clients
+ .dialer_with(key.clone(), Some("sub-a".into()), starter("a"))
+ .await
+ .unwrap();
+ assert!(Arc::ptr_eq(&a, &again));
+ // A session that does not say who it is never restarts the node.
+ let unknown = clients
+ .dialer_with(key.clone(), None, starter("a"))
+ .await
+ .unwrap();
+ assert!(Arc::ptr_eq(&a, &unknown));
+
+ // Another account signs in.
+ let b = clients
+ .dialer_with(key.clone(), Some("sub-b".into()), starter("b"))
+ .await
+ .unwrap();
+ assert!(!Arc::ptr_eq(&a, &b), "a new node for the new account");
+ assert_ne!(b.mesh().node_key(), key_a, "with a new key");
+ assert!(b.mesh().unusable().is_none());
+
+ // A Space connected through A's node lost its forwards with it:
+ // it reconnects (once), through B's node.
+ clients.routed.lock().unwrap().insert(
+ "relay:m1".into(),
+ (key.clone(), false, 1), // the first node's generation
+ );
+ let why = clients.stale("relay:m1", |_| MeshPolicy::Prefer).await;
+ assert_eq!(why.as_deref(), Some("its mesh node was replaced"));
+ assert!(
+ clients
+ .stale("relay:m1", |_| MeshPolicy::Prefer)
+ .await
+ .is_none()
+ );
+ // A Space routed through B's node is fine, until A signs in again.
+ clients.routed.lock().unwrap().insert(
+ "relay:m2".into(),
+ (key.clone(), false, clients.generation(&key)),
+ );
+ assert!(
+ clients
+ .stale("relay:m2", |_| MeshPolicy::Prefer)
+ .await
+ .is_none()
+ );
+ let a_again = clients
+ .dialer_with(key.clone(), Some("sub-a".into()), starter("a"))
+ .await
+ .unwrap();
+ assert!(!Arc::ptr_eq(&a_again, &b));
+ assert_eq!(
+ clients
+ .stale("relay:m2", |_| MeshPolicy::Prefer)
+ .await
+ .as_deref(),
+ Some("its mesh node was replaced")
+ );
+ a_again.mesh().shutdown();
+ }
+
+ /// Signing in as another account on this computer: the saved node key
+ /// belongs to the previous account, so it is rotated and the node joins
+ /// the mesh as the new account.
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn a_node_key_of_the_previous_account_is_rotated() {
+ let coord = cua_mesh::testing::FakeCoordinator::start(cua_mesh::Mode::Account).await;
+ let dir = tempfile::tempdir().unwrap();
+ let identity = dir.path().join("client.json");
+ // Signed in as A: the node registers its key.
+ let a = start_dialer(&coord.url, as_account("a"), Some(identity.clone()))
+ .await
+ .unwrap();
+ let key_a = a.mesh().node_key();
+ a.mesh().shutdown();
+
+ // The same key as B is refused by the coordinator.
+ let refused = Dialer::start(
+ &coord.url,
+ as_account("b"),
+ Some(identity.clone()),
+ Duration::from_secs(10),
+ )
+ .await;
+ assert!(
+ matches!(&refused, Err(cua_mesh::Error::Refused(m)) if m.contains("another owner")),
+ "{:?}",
+ refused.err()
+ );
+
+ // Starting the way Spaces does rotates the key and joins.
+ let b = start_dialer(&coord.url, as_account("b"), Some(identity.clone()))
+ .await
+ .unwrap();
+ assert_ne!(b.mesh().node_key(), key_a, "a new node key");
+ assert!(b.mesh().unusable().is_none());
+ b.mesh().shutdown();
+ }
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_space_that_fell_back_moves_to_the_mesh_once_its_machine_joins() {
let coord = cua_mesh::testing::FakeCoordinator::start(cua_mesh::Mode::Account).await;
@@ -684,6 +935,7 @@ mod tests {
Slot::Ready {
dialer: Arc::new(dialer),
_lock: None,
+ account: None,
},
);
clients.note_fallback("relay:late", &Via::Account(&a), "late");
@@ -743,7 +995,7 @@ mod tests {
let clients = MeshClients::default();
clients.routed.lock().unwrap().insert(
"relay:m1".into(),
- (Key::Account("http://relay".into()), false),
+ (Key::Account("http://relay".into()), false, 0),
);
// Off now (CUA_MESH=off, or the app left the channel that uses it):
// the cached connection is dropped and reconnects over HTTPS.
@@ -764,6 +1016,12 @@ mod tests {
);
}
+ #[test]
+ fn a_refused_node_is_tried_again_sooner_than_a_relay_without_a_mesh() {
+ assert!(recheck_after("mesh refused: HTTP 403: not enrolled") < RECHECK);
+ assert_eq!(recheck_after("the relay has no mesh coordinator"), RECHECK);
+ }
+
#[test]
fn the_policy_reads_cua_mesh() {
assert_eq!(MeshPolicy::parse("off"), Some(MeshPolicy::Off));
diff --git a/libs/cua/crates/cua-spaces/src/relay.rs b/libs/cua/crates/cua-spaces/src/relay.rs
index 66e0ec35df..69c513feb2 100644
--- a/libs/cua/crates/cua-spaces/src/relay.rs
+++ b/libs/cua/crates/cua-spaces/src/relay.rs
@@ -73,12 +73,27 @@ impl RelayAccount {
}
}
+ /// Which account is signed in now (the access token's `sub`), when the
+ /// session says. A long-running node compares it with the account it
+ /// started for.
+ pub async fn account_subject(&self) -> Option<String> {
+ let token = self.tokens.access_token().await.ok()?;
+ cua_host::token_subject(&token)
+ }
+
/// A directory client carrying the device session.
pub async fn client(&self) -> cua_host::Result<cua_host::RelayClient> {
Ok(cua_host::RelayClient::new(&self.url)?.with_device_session(self.device_session().await))
}
}
+/// Another account is signed in now than the one state was started for
+/// (`started`; each as [`RelayAccount::account_subject`]). Unknown on either
+/// side is never a change: only a known switch restarts anything.
+pub fn account_changed(started: &Option<String>, now: &Option<String>) -> bool {
+ matches!((started, now), (Some(a), Some(b)) if a != b)
+}
+
/// The gateway bearer of `relay:<id>` connections: the account token in
/// `authorization` plus the device session header, both fetched per call.
pub(crate) struct RelayBearer {
@@ -223,3 +238,40 @@ impl crate::Spaces {
self.forget_attached_machine(machine_id);
}
}
+
+#[cfg(test)]
+mod account_tests {
+ use super::*;
+ use base64::Engine as _;
+
+ fn token(sub: &str) -> String {
+ let b = |v: &str| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(v);
+ format!("{}.{}.sig", b("{}"), b(&format!(r#"{{"sub":"{sub}"}}"#)))
+ }
+
+ #[tokio::test]
+ async fn the_signed_in_account_is_the_tokens_subject() {
+ let a = RelayAccount::new(
+ "http://relay",
+ Arc::new(cua_host::StaticToken(token("user-a"))),
+ );
+ assert_eq!(a.account_subject().await.as_deref(), Some("user-a"));
+ // Not a JWT, or not signed in: unknown, never a different account.
+ let opaque = RelayAccount::new("http://relay", Arc::new(cua_host::StaticToken("x".into())));
+ assert_eq!(opaque.account_subject().await, None);
+ let out = RelayAccount::new(
+ "http://relay",
+ Arc::new(cua_host::StaticToken(String::new())),
+ );
+ assert_eq!(out.account_subject().await, None);
+ }
+
+ #[test]
+ fn only_a_known_switch_of_account_counts() {
+ let s = |v: &str| Some(v.to_string());
+ assert!(account_changed(&s("a"), &s("b")));
+ assert!(!account_changed(&s("a"), &s("a")));
+ assert!(!account_changed(&None, &s("b")));
+ assert!(!account_changed(&s("a"), &None));
+ }
+}