diff --git a/apps/desktop/src-tauri/src/machines.rs b/apps/desktop/src-tauri/src/machines.rs index 5d0139564..9c27cfe92 100644 --- a/apps/desktop/src-tauri/src/machines.rs +++ b/apps/desktop/src-tauri/src/machines.rs @@ -1922,8 +1922,9 @@ pub fn machines_cancel( Ok(()) } -/// Forget a machine and its token. It still lists this computer until it is -/// revoked there. +/// Forget a machine and its token, after asking the machine to end this +/// computer's pairing there. Answers what to tell the owner, which says when +/// the machine could not be asked and still lists this computer. /// /// The credential goes first: a machine whose token could not be deleted stays /// listed, with a plain reason, instead of becoming a row that can never pair @@ -1932,14 +1933,26 @@ pub fn machines_cancel( pub async fn machines_remove( machines: tauri::State<'_, Arc>, id: String, -) -> Result<(), String> { +) -> Result { let config_dir = config_dir()?; let mut registry = MachineRegistry::load(&config_dir).map_err(chain)?; let machine = registry .get(&id) .ok_or("That machine is no longer saved.")? .clone(); + if let Some(mut entry) = machines.live.lock().unwrap().remove(&machine.host_id) { + if let Some(task) = entry.task.take() { + task.abort(); + } + } let tokens = machines.tokens(&config_dir).await?; + let unpaired = rustcode_client::unpair_machine( + &Machines::connector(&config_dir)?, + &machine, + &tokens, + rustcode_client::UNPAIR_TIMEOUT, + ) + .await; let host_id = machine.host_id.clone(); token_store::bounded("deleting the pairing token", STORE_TIMEOUT, move || { tokens.remove(&host_id) @@ -1960,12 +1973,10 @@ pub async fn machines_remove( machine.name )); } - if let Some(mut entry) = machines.live.lock().unwrap().remove(&machine.host_id) { - if let Some(task) = entry.task.take() { - task.abort(); - } - } - Ok(()) + Ok(rustcode_client::removal_message( + machine.display_name.as_deref().unwrap_or(&machine.name), + Some(unpaired), + )) } /// Rename a machine. The name is stamped with the time, so the machine diff --git a/apps/desktop/src/state/machines.ts b/apps/desktop/src/state/machines.ts index ef40b749e..ed4b984d0 100644 --- a/apps/desktop/src/state/machines.ts +++ b/apps/desktop/src/state/machines.ts @@ -1341,15 +1341,15 @@ export function removeMachine(machine: Machine, onRemoved?: () => void): void { title: `Remove ${name}?`, message: `${name} is forgotten on this computer: its pairing token and routes are deleted, and its threads are no longer listed here. ` + - "It keeps listing this computer until you revoke it there.", + "This computer's access there ends too when it can be reached; otherwise revoke it there.", action: "Remove", destructive: true, run: () => { - void shellCall("machines_remove", { id: machine.id }).then( - async () => { + void shellCall("machines_remove", { id: machine.id }).then( + async (message) => { detach(machine.id); void import("./settingsFollow").then((follow) => follow.forgetFollower(machine.id)); - toast(`Removed ${name}.`, "success"); + toast(message || `Removed ${name}.`, "success"); await refreshMachines(); onRemoved?.(); }, diff --git a/docs/remote-protocol/README.md b/docs/remote-protocol/README.md index d0fcc439c..8c6a09936 100644 --- a/docs/remote-protocol/README.md +++ b/docs/remote-protocol/README.md @@ -245,6 +245,16 @@ used again, and a signature cannot, because it is good for one socket only. have not registered a key. An older gateway ignores `public_key`, sends no `challenge`, and a device keeps its token there. +### Ending a pairing from the device + +An authenticated device may send `{"type": "unpair"}` to end its own pairing. +The gateway revokes the device record the socket signed in as (the frame names +no device, so a device can end only its own), closes every connection of that +record with the bare `error` frame `revoked`, and refuses its tokens and key +from then on. As a first frame it is refused with `invalid_frame`. A gateway +older than `unpair` does not answer it with `revoked`; a client that sees no +`revoked` within its timeout must assume the pairing still stands. + ### Rotating tokens, no expiry A device that names `"capabilities": ["token_rotation"]` in `pair` gets no diff --git a/docs/remote-protocol/v1/golden/handshake/requests/unpair.json b/docs/remote-protocol/v1/golden/handshake/requests/unpair.json new file mode 100644 index 000000000..2bbc52250 --- /dev/null +++ b/docs/remote-protocol/v1/golden/handshake/requests/unpair.json @@ -0,0 +1,3 @@ +{ + "type": "unpair" +} diff --git a/docs/remote-protocol/v1/handshake-request.schema.json b/docs/remote-protocol/v1/handshake-request.schema.json index dd9e523f8..4b22dacd2 100644 --- a/docs/remote-protocol/v1/handshake-request.schema.json +++ b/docs/remote-protocol/v1/handshake-request.schema.json @@ -294,6 +294,19 @@ "type" ], "type": "object" + }, + { + "description": "End this device's own pairing, after authenticating: the host revokes the record the socket signed in as and closes it with `revoked`.", + "properties": { + "type": { + "const": "unpair", + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object" } ], "title": "HandshakeRequest" diff --git a/docs/remote-security.md b/docs/remote-security.md index 74e587fdf..7444d5c57 100644 --- a/docs/remote-security.md +++ b/docs/remote-security.md @@ -207,11 +207,15 @@ Revocation, from the quickest to the widest: 1. Settings › Remote access › *Revoke*, or `rc remote revoke `: the device's connections close in the same step with `revoked`, and its token is forgotten. -2. `rc remote devices deny `: removes the ACP grant and disconnects. -3. `/remote off` or `rc remote stop`: nobody reaches the gateway; +2. Remove on the device's side (Settings › Machines › *Remove*, or + `rc machines remove`): the device sends `unpair` and the host revokes the + record it signed in as, as in 1. A host that cannot be reached keeps the + record, and the device says so. +3. `rc remote devices deny `: removes the ACP grant and disconnects. +4. `/remote off` or `rc remote stop`: nobody reaches the gateway; pairings are kept. -4. Replay of a retired refresh token: the whole pairing is revoked by the host. -5. Expiry: a static token ends after 30 days; a rotating pairing lasts until +5. Replay of a retired refresh token: the whole pairing is revoked by the host. +6. Expiry: a static token ends after 30 days; a rotating pairing lasts until revoked. A revoked device is refused with `unauthorized` or `revoked` when it returns, diff --git a/docs/remote.md b/docs/remote.md index 93ea5307c..e40d4befa 100644 --- a/docs/remote.md +++ b/docs/remote.md @@ -521,7 +521,7 @@ fills in the same saved machines. | `rc machines add
[--name ] [--code ]` | Ask the machine to let this one in; the code is exactly the eight digits it shows (spaces and dashes are ignored). It shows *‹name› wants to connect* on that machine; accept it there, then type the eight-digit code it shows (or pass `--code`). Prints `Waiting for … to accept…` while the request is open. Pairs, stores the token and saves the machine. | | `rc machines add --discover` | The same, choosing the machine from Bonjour when exactly one answers. | | `rc machines list [--threads] [--json]` | Name, platform, the route in use, the network it runs over with whether that is encrypted (`LAN (not encrypted)`, `NetBird (encrypted by the tunnel)`; `—` while the machine is not connected) and whether the machine answers now. Under a machine that is reachable one way and not another, it prints the hint: e.g. `Not reachable over NetBird (100.90.16.237:17879). On that machine, check that NetBird allows inbound connections and that an access policy allows TCP 17879 between the two machines.` The platform comes from the gateway (`macos`, `windows` or `linux`) and is refreshed whenever the machine is reached; a gateway older than that reports none, and the row keeps `unknown`. With `--threads`, each connected machine's thread titles over ACP (`session/list`), printed under the machine's row and after its hint. `--json` for scripts, with the same hint under `hint` and the network under `network` (`path`, `provider`, `encrypted`, `label`). | -| `rc machines remove ` | Forget a machine and delete its token. It still lists this computer until it is revoked there. | +| `rc machines remove [--local]` | Forget a machine and delete its token, after asking the machine to end this computer's pairing there (`unpair`, within ten seconds). When the machine cannot be reached or runs a RustCode without `unpair`, it is forgotten here anyway and the command says the machine still lists this computer, to revoke there. `--local` only forgets it here. | | `rc machines discover [--secs ] [--json]` | Machines on this network whose record lists `caps=desktops`: name, address and machine id. | The desktop app writes every connect and drop of a paired machine to @@ -936,7 +936,7 @@ same. computer (under Settings › Remote access › Paired devices and `rc remote devices`). Ending one never ends the other: *Forget* on the machine (or `rc machines remove`) ends this computer's access to - `box`; *Revoke* on the device (or `rc remote revoke`) ends `box`'s + `box`, on both sides when `box` can be reached; *Revoke* on the device (or `rc remote revoke`) ends `box`'s access to this computer. Settings › Machines › ‹box› › **Access** shows both with their own button; a device counts as `box` when its `hostId` is the machine's id. @@ -979,7 +979,7 @@ are all visible at once. | **Checking the code** | The code is being checked with that machine, which answers within ten seconds. After half a minute the page stops waiting and says so — *‹host› did not answer* — with **Ask again** and **Cancel**: a machine that accepted the code but could not store the token still lists this computer as a device, so it is removed there and the pairing started again. No stage of the flow is a spinner without a way out. | | A machine row | Its name and platform, the state chip at the row's top right — *Connected*, *Connecting*, *Reconnecting…* (a machine that is away while the app retries it on its own), *Offline*, what a machine that answered and would not serve said — *Server not running*, *Version mismatch*, *Not allowed*, *Busy*, *Refused* — and *Needs pairing* — the route **in use** (else the one it answered on last) under the name as `LAN · Unencrypted` or `NetBird`/`Tailscale`/`VPN · Encrypted`, then when it was last reached and how many threads it has. **Remove** sits in a row of its own below. Under the route, the hint for one kind of route that answers while another does not (see [Machines](#machines)), and a version skew line when that machine runs another RustCode: *RustCode 0.96.0 on that machine — update it there: Settings › About › Check for updates, or `brew upgrade rustcode`* (the platform's own way, from [install](install.md#updating); a development build never shows the line), or *update RustCode here* when that machine is newer. | | **This computer · RustCode server** | Whether the RustCode server is installed as a background service: *Server: Installed · Running*, or *Not installed* with **Install server**. Installed, that engine stays up when the app closes and starts when you log in; the threads this app starts still run in its own engine and end with it. What `rc server status` reports, including a running version that differs from the app's, is on the same line. | -| **Remove** | Forgets it here: token, routes and its threads' rows go. The machine keeps listing this computer until it is revoked there. | +| **Remove** | Asks the machine to end this computer's pairing there, then forgets it here: token, routes and its threads' rows go. The notice says *Removed Studio and ended this computer's access there*, or that the machine still lists this computer when it could not be reached or runs an older RustCode. | | **Pair again** | On a machine whose pairing it ended (*Needs pairing*): asks it again, so a new code can be typed. | The app keeps one connection per machine, retried with jittered backoff from a diff --git a/rustcode/cli/src/cli.rs b/rustcode/cli/src/cli.rs index 1ea3bb224..a5de9449b 100644 --- a/rustcode/cli/src/cli.rs +++ b/rustcode/cli/src/cli.rs @@ -816,10 +816,13 @@ pub enum MachineCommands { #[arg(long, default_value_t = 4, value_name = "SECONDS")] discover_secs: u64, }, - /// Forget a machine and its token + /// Forget a machine and its token, and end this computer's access there Remove { /// Name, host id or a prefix of one machine: String, + /// Only forget it here; the machine keeps listing this computer + #[arg(long)] + local: bool, }, /// Create a connect code here, for another computer to pair with this /// one: valid ten minutes, once, no accept step. Anyone who has it can see @@ -2118,7 +2121,11 @@ mod tests { assert!(machines(&["add", "10.0.0.2", "--discover"]).is_err()); assert!(matches!( machines(&["remove", "Studio"]).unwrap(), - MachineCommands::Remove { ref machine } if machine == "Studio" + MachineCommands::Remove { ref machine, local: false } if machine == "Studio" + )); + assert!(matches!( + machines(&["remove", "Studio", "--local"]).unwrap(), + MachineCommands::Remove { local: true, .. } )); assert!(machines(&["discover", "--json", "--secs", "2"]).is_ok()); assert!(machines(&["remove"]).is_err()); diff --git a/rustcode/cli/src/machines.rs b/rustcode/cli/src/machines.rs index 35d54017e..44de3d4f3 100644 --- a/rustcode/cli/src/machines.rs +++ b/rustcode/cli/src/machines.rs @@ -123,7 +123,7 @@ pub async fn run(command: &MachineCommands) -> Result<()> { ) .await } - MachineCommands::Remove { machine } => remove(&config_dir, machine), + MachineCommands::Remove { machine, local } => remove(&config_dir, machine, *local).await, MachineCommands::Discover { secs, json } => { discover(Duration::from_secs(*secs), *json).await } @@ -1033,11 +1033,26 @@ fn discovered_table(found: &[DiscoveredMachine]) -> String { columns(&table) } -fn remove(config_dir: &std::path::Path, selector: &str) -> Result<()> { - let mut registry = MachineRegistry::load(config_dir)?; - let machine = registry.select(selector)?.clone(); - registry.remove(&machine.host_id)?; - match TokenStore::open(config_dir).and_then(|tokens| tokens.remove(&machine.host_id)) { +async fn remove(config_dir: &std::path::Path, selector: &str, local: bool) -> Result<()> { + let machine = MachineRegistry::load(config_dir)?.select(selector)?.clone(); + let tokens = TokenStore::open(config_dir); + let unpaired = match (&tokens, local) { + (Ok(tokens), false) => { + let connector = Connector::new(config_dir, ClientKind::Desktop)?; + Some( + rustcode_client::unpair_machine( + &connector, + &machine, + tokens, + rustcode_client::UNPAIR_TIMEOUT, + ) + .await, + ) + } + _ => None, + }; + MachineRegistry::load(config_dir)?.remove(&machine.host_id)?; + match tokens.and_then(|tokens| tokens.remove(&machine.host_id)) { Ok(()) => {} Err(error) => eprintln!( "warning: {} was removed but its token could not be deleted: {error:#}", @@ -1045,8 +1060,8 @@ fn remove(config_dir: &std::path::Path, selector: &str) -> Result<()> { ), } println!( - "Removed {}. The machine still lists this computer until you revoke it there.", - machine.name + "{}", + rustcode_client::removal_message(&machine.name, unpaired) ); Ok(()) } diff --git a/rustcode/client/src/lib.rs b/rustcode/client/src/lib.rs index 3ab2ba25d..93120f6ec 100644 --- a/rustcode/client/src/lib.rs +++ b/rustcode/client/src/lib.rs @@ -46,6 +46,7 @@ pub mod ssh; pub mod tokens; pub mod transport; pub mod tunnel; +pub mod unpair; pub use connect_code::ConnectCode; pub use discovery::{DiscoveredMachine, SERVICE_TYPE, browse, browse_async}; @@ -73,3 +74,4 @@ pub use routes::{ }; pub use tokens::{Access, TokenStore}; pub use transport::{AcpChannel, DEFAULT_PORT, MAX_FRAME_BYTES}; +pub use unpair::{UNPAIR_TIMEOUT, Unpaired, removal_message, unpair_machine}; diff --git a/rustcode/client/src/machine.rs b/rustcode/client/src/machine.rs index 0a3ed5109..1d906b3a0 100644 --- a/rustcode/client/src/machine.rs +++ b/rustcode/client/src/machine.rs @@ -1740,6 +1740,12 @@ impl Session { pub async fn hub_join(self, access: &str, ask: bool) -> Result { self.connection.hub_open(access, ask).await } + + /// End this computer's pairing on the machine; see + /// [`crate::transport::Connection::unpair`]. + pub async fn unpair(self, timeout: std::time::Duration) -> Result { + self.connection.unpair(timeout).await + } } /// The titles of the machine's threads, newest first as `session/list` lists diff --git a/rustcode/client/src/protocol.rs b/rustcode/client/src/protocol.rs index b99a8e721..cc62116a0 100644 --- a/rustcode/client/src/protocol.rs +++ b/rustcode/client/src/protocol.rs @@ -172,6 +172,8 @@ pub enum HandshakeRequest { /// named `rotation_id`, so the machine may retire the token before it. A /// session-path frame after authentication, never a first frame. TokenAck { rotation_id: String }, + /// End this device's own pairing on the machine, after authenticating. + Unpair, } /// An address the host answers on, as a handshake reports it. The kind is the @@ -473,6 +475,7 @@ mod tests { "pair_credential.json".to_owned(), "pair_machine.json".to_owned(), "token_ack.json".to_owned(), + "unpair.json".to_owned(), ]), "a golden request was added or removed: update this mirror and this list" ); diff --git a/rustcode/client/src/transport.rs b/rustcode/client/src/transport.rs index 36369d8da..5f4ad61b9 100644 --- a/rustcode/client/src/transport.rs +++ b/rustcode/client/src/transport.rs @@ -16,7 +16,8 @@ //! tunnel's edge, verified against the operating system's trust store. use crate::protocol::{ - AcpClientFrame, AcpServerFrame, HandshakeRequest, HandshakeResponse, MAX_HANDSHAKE_FRAME_BYTES, + AcpClientFrame, AcpServerFrame, ErrorCode, HandshakeRequest, HandshakeResponse, + MAX_HANDSHAKE_FRAME_BYTES, }; use anyhow::{Context, Result, bail, ensure}; use futures_util::{SinkExt, StreamExt}; @@ -428,6 +429,29 @@ impl Connection { } } + /// Ask the machine to end this device's pairing (`unpair`). `true` once + /// it answers `revoked`; `false` when it does not within `timeout`, as a + /// machine older than `unpair` never does. + pub async fn unpair(self, timeout: Duration) -> Result { + let mut connection = self; + let unpair = serde_json::to_value(HandshakeRequest::Unpair)?; + connection.send_json(&unpair).await.context("send unpair")?; + let deadline = tokio::time::Instant::now() + timeout; + while let Ok(Some(text)) = connection + .next_text_or_close(Some((deadline, timeout))) + .await + { + if let Ok(HandshakeResponse::Error { + code: ErrorCode::Revoked, + .. + }) = serde_json::from_str(&text) + { + return Ok(true); + } + } + Ok(false) + } + async fn send_json(&mut self, frame: &Value) -> Result<()> { self.socket .send(Message::text(frame.to_string())) diff --git a/rustcode/client/src/unpair.rs b/rustcode/client/src/unpair.rs new file mode 100644 index 000000000..d982e974a --- /dev/null +++ b/rustcode/client/src/unpair.rs @@ -0,0 +1,84 @@ +//! Ending this computer's pairing on a machine it is about to forget, so that +//! Remove also takes back the access the machine granted this computer. + +use crate::{Connector, Machine, TokenStore, needs_new_pairing}; +use std::time::Duration; + +/// How long Remove waits for the machine before forgetting it here anyway. +pub const UNPAIR_TIMEOUT: Duration = Duration::from_secs(10); + +/// What became of this computer's access on the machine. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Unpaired { + /// The machine revoked this computer's device record. + Ended, + /// The machine no longer knew this computer: nothing was left to end. + AlreadyEnded, + /// No route answered as the machine within the time allowed. + Unreachable, + /// The machine answered but did not end the pairing: an older RustCode. + Unsupported, +} + +/// Sign in to `machine` and ask it to end this computer's pairing, within +/// `timeout` for the whole attempt. +pub async fn unpair_machine( + connector: &Connector, + machine: &Machine, + tokens: &TokenStore, + timeout: Duration, +) -> Unpaired { + let attempt = async { + match connector.connect_raced(machine, tokens).await { + Ok(connected) => match connected.session.unpair(timeout).await { + Ok(true) => Unpaired::Ended, + _ => Unpaired::Unsupported, + }, + Err(error) if needs_new_pairing(&error) => Unpaired::AlreadyEnded, + Err(_) => Unpaired::Unreachable, + } + }; + tokio::time::timeout(timeout, attempt) + .await + .unwrap_or(Unpaired::Unreachable) +} + +/// What to tell the owner after removing `name`; `None` when the machine was +/// not asked (`--local`). +pub fn removal_message(name: &str, unpaired: Option) -> String { + match unpaired { + Some(Unpaired::Ended | Unpaired::AlreadyEnded) => { + format!("Removed {name} and ended this computer's access there.") + } + Some(Unpaired::Unreachable) => format!( + "Removed {name} here. {name} was not reachable, so it still lists this computer: run `rc remote revoke` there." + ), + Some(Unpaired::Unsupported) => format!( + "Removed {name} here. {name} runs a RustCode that cannot end the pairing from here, so it still lists this computer: run `rc remote revoke` there." + ), + None => format!( + "Removed {name}. The machine still lists this computer until you revoke it there." + ), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_message_says_whether_the_machine_still_lists_this_computer() { + assert!(removal_message("Studio", Some(Unpaired::Ended)).contains("ended")); + assert!(removal_message("Studio", Some(Unpaired::AlreadyEnded)).contains("ended")); + for outcome in [ + Some(Unpaired::Unreachable), + Some(Unpaired::Unsupported), + None, + ] { + assert!( + removal_message("Studio", outcome).contains("still lists this computer"), + "{outcome:?}" + ); + } + } +} diff --git a/rustcode/client/tests/gateway_round_trip.rs b/rustcode/client/tests/gateway_round_trip.rs index 9cbeea98e..082e5c268 100644 --- a/rustcode/client/tests/gateway_round_trip.rs +++ b/rustcode/client/tests/gateway_round_trip.rs @@ -1290,3 +1290,39 @@ async fn a_pinned_machine_is_never_dialled_in_the_clear() { .unwrap() .expect("the client never fell back to plain"); } + +/// Removing a machine ends this computer's pairing there: the machine +/// forgets the device record, and its token no longer signs in (#4391). +#[tokio::test] +async fn removing_a_machine_ends_this_computers_pairing_there() { + let host = Host::start().await; + let config = tempfile::tempdir_in("/tmp").unwrap(); + let connector = Connector::new(config.path(), ClientKind::Desktop).unwrap(); + let (machine, tokens, paired) = pair(&host, &connector, config.path()).await; + drop(paired); + assert_eq!( + rustcode_client::unpair_machine( + &connector, + &machine, + &tokens, + rustcode_client::UNPAIR_TIMEOUT + ) + .await, + rustcode_client::Unpaired::Ended + ); + let error = connector + .connect(&machine, &tokens) + .await + .expect_err("the pairing is over"); + assert!(rustcode_client::needs_new_pairing(&error), "{error:#}"); + assert_eq!( + rustcode_client::unpair_machine( + &connector, + &machine, + &tokens, + rustcode_client::UNPAIR_TIMEOUT + ) + .await, + rustcode_client::Unpaired::AlreadyEnded + ); +} diff --git a/rustcode/engine/src/remote/contract.rs b/rustcode/engine/src/remote/contract.rs index 96a7ef55a..28b598597 100644 --- a/rustcode/engine/src/remote/contract.rs +++ b/rustcode/engine/src/remote/contract.rs @@ -283,6 +283,7 @@ pub fn golden_handshake_requests() -> Vec<(&'static str, HandshakeRequest)> { rotation_id: "5be1c4a07d2e9f63".to_owned(), }), ), + ("unpair", HandshakeRequest::Unpair), ] } diff --git a/rustcode/engine/src/remote_gateway/e2e_tests.rs b/rustcode/engine/src/remote_gateway/e2e_tests.rs index cc0e9bd04..c24729fb3 100644 --- a/rustcode/engine/src/remote_gateway/e2e_tests.rs +++ b/rustcode/engine/src/remote_gateway/e2e_tests.rs @@ -1675,6 +1675,28 @@ async fn a_rotating_device_keeps_its_pairing_until_it_is_revoked() { drop(host.dir); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_device_ends_its_own_pairing_with_unpair() { + let host = Host::start().await; + let (mut phone, paired) = pair_rotating(&host).await; + assert_eq!(paired["type"], "paired", "{paired}"); + let (mut other, welcome) = + authenticate_with(&host, &paired, ("access_token", &paired["access_token"])).await; + assert_eq!(welcome["type"], "authenticated", "{welcome}"); + + phone.send(json!({"type": "unpair"})).await; + let revoked = phone.frame(|frame| frame["type"] == "error").await; + assert_eq!(revoked["code"], "revoked", "{revoked}"); + assert!(phone.read().await.is_none()); + assert!(host.lifecycle.devices().unwrap().is_empty()); + let revoked = other.frame(|frame| frame["type"] == "error").await; + assert_eq!(revoked["code"], "revoked", "{revoked}"); + let (_, gone) = + authenticate_with(&host, &paired, ("access_token", &paired["access_token"])).await; + assert_eq!(gone["code"], "unauthorized", "{gone}"); + drop(host.dir); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_rotating_device_recovers_from_a_dropped_authenticated_frame() { let host = Host::start().await; diff --git a/rustcode/engine/src/remote_gateway/gateway.rs b/rustcode/engine/src/remote_gateway/gateway.rs index 183aa7fd2..eba864f11 100644 --- a/rustcode/engine/src/remote_gateway/gateway.rs +++ b/rustcode/engine/src/remote_gateway/gateway.rs @@ -628,6 +628,10 @@ impl Shared { ErrorCode::InvalidFrame, "token_ack is only valid after authenticating", )), + HandshakeRequest::Unpair => Err(HandshakeResponse::error( + ErrorCode::InvalidFrame, + "unpair is only valid after authenticating", + )), } } @@ -1302,6 +1306,14 @@ impl Shared { /// Forget a device and close its live connections in one step. The store /// is written first: if that fails nothing changes and the caller is told. + /// End the pairing of the device signed in as `device_id`, at its own + /// request: the same revocation the owner's `rc remote revoke` makes. + pub(super) fn unpair(&self, device_id: &str) -> Result<()> { + let record = self.state().devices.select(device_id)?.clone(); + anyhow::ensure!(record.id == device_id, "no device record {device_id}"); + self.revoke(&record.id).map(drop) + } + fn revoke(&self, selector: &str) -> Result<(DeviceRecord, usize)> { let mut state = self.state(); let record = state.devices.select(selector)?.clone(); diff --git a/rustcode/engine/src/remote_gateway/handshake.rs b/rustcode/engine/src/remote_gateway/handshake.rs index 5538c8fff..12b4245e6 100644 --- a/rustcode/engine/src/remote_gateway/handshake.rs +++ b/rustcode/engine/src/remote_gateway/handshake.rs @@ -221,6 +221,8 @@ pub enum HandshakeRequest { /// just received, so the host may retire the token before it. Only valid /// on an authenticated connection, never as a first frame. TokenAck(TokenAck), + /// End this device's own pairing, after authenticating: the host revokes the record the socket signed in as and closes it with `revoked`. + Unpair, } /// The body of a `token_ack` frame: which rotation the device stored. @@ -247,6 +249,8 @@ pub enum SessionControl { NotAControl, /// The device acknowledged a rotation. TokenAck(TokenAck), + /// The device asked to end its own pairing. + Unpair, /// A frame tagged `token_ack` that does not carry what one must. Malformed, } @@ -254,6 +258,14 @@ pub enum SessionControl { /// Read a frame that may be a `token_ack`. Only a frame whose tag says so is /// parsed, so the session path stays a pass-through. pub fn session_control(text: &str) -> SessionControl { + if text.contains("\"unpair\"") + && matches!( + serde_json::from_str::(text), + Ok(HandshakeRequest::Unpair) + ) + { + return SessionControl::Unpair; + } if !text.contains("\"token_ack\"") { return SessionControl::NotAControl; } @@ -317,7 +329,10 @@ impl HandshakeRequest { Self::Pair { wire_names, .. } | Self::Authenticate { wire_names, .. } => { wire_names.as_deref() == Some(WIRE_NAMES_THREAD) } - Self::Describe { .. } | Self::ConnectRequest { .. } | Self::TokenAck(_) => false, + Self::Describe { .. } + | Self::ConnectRequest { .. } + | Self::TokenAck(_) + | Self::Unpair => false, } } @@ -327,7 +342,10 @@ impl HandshakeRequest { Self::Pair { capabilities, .. } | Self::Authenticate { capabilities, .. } => { capabilities } - Self::Describe { .. } | Self::ConnectRequest { .. } | Self::TokenAck(_) => { + Self::Describe { .. } + | Self::ConnectRequest { .. } + | Self::TokenAck(_) + | Self::Unpair => { return false; } }; @@ -404,9 +422,10 @@ impl HandshakeRequest { ), // Neither says what the device is: an authenticated device was // recorded when it paired, and an acknowledgement says nothing. - Self::Describe { .. } | Self::Authenticate { .. } | Self::TokenAck(_) => { - DeviceProfile::default() - } + Self::Describe { .. } + | Self::Authenticate { .. } + | Self::TokenAck(_) + | Self::Unpair => DeviceProfile::default(), } } @@ -935,6 +954,26 @@ mod tests { ); } + #[test] + fn an_unpair_is_a_session_control_frame_and_nothing_else_is() { + assert_eq!( + session_control(r#"{"type":"unpair"}"#), + SessionControl::Unpair + ); + assert_eq!( + session_control(r#"{"type":"unpair","request_id":"r1"}"#), + SessionControl::Unpair + ); + assert_eq!( + session_control(r#"{"type":"submit_prompt","text":"say \"unpair\""}"#), + SessionControl::NotAControl + ); + assert_eq!( + serde_json::to_string(&HandshakeRequest::Unpair).unwrap(), + r#"{"type":"unpair"}"# + ); + } + #[test] fn response_wire_shapes_are_stable() { let paired = HandshakeResponse::Paired { diff --git a/rustcode/engine/src/remote_gateway/transport.rs b/rustcode/engine/src/remote_gateway/transport.rs index 5c751c5af..8e1edb5ae 100644 --- a/rustcode/engine/src/remote_gateway/transport.rs +++ b/rustcode/engine/src/remote_gateway/transport.rs @@ -603,6 +603,15 @@ async fn pump( ); continue; } + SessionControl::Unpair => { + return match shared.unpair(&connection.context.device_id) { + Ok(()) => Some(ErrorCode::Revoked), + Err(error) => { + crate::dbg_log!("remote gateway: unpair failed: {error:#}"); + Some(ErrorCode::Internal) + } + }; + } SessionControl::Malformed => return Some(ErrorCode::InvalidFrame), } if let Some((access, ask)) = super::hub_link::MemberFrame::parse_join(&text) {