Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 20 additions & 9 deletions apps/desktop/src-tauri/src/machines.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -1932,14 +1933,26 @@ pub fn machines_cancel(
pub async fn machines_remove(
machines: tauri::State<'_, Arc<Machines>>,
id: String,
) -> Result<(), String> {
) -> Result<String, String> {
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)
Expand All @@ -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
Expand Down
8 changes: 4 additions & 4 deletions apps/desktop/src/state/machines.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string | null>("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?.();
},
Expand Down
10 changes: 10 additions & 0 deletions docs/remote-protocol/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions docs/remote-protocol/v1/golden/handshake/requests/unpair.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"type": "unpair"
}
13 changes: 13 additions & 0 deletions docs/remote-protocol/v1/handshake-request.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
12 changes: 8 additions & 4 deletions docs/remote-security.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,11 +207,15 @@ Revocation, from the quickest to the widest:
1. Settings › Remote access › *Revoke*, or `rc remote revoke <device>`:
the device's connections close in the same step with `revoked`, and its
token is forgotten.
2. `rc remote devices deny <id>`: 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 <id>`: 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,
Expand Down
6 changes: 3 additions & 3 deletions docs/remote.md
Original file line number Diff line number Diff line change
Expand Up @@ -521,7 +521,7 @@ fills in the same saved machines.
| `rc machines add <address> [--name <name>] [--code <digits>]` | 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 <name-or-id>` | Forget a machine and delete its token. It still lists this computer until it is revoked there. |
| `rc machines remove <name-or-id> [--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 <n>] [--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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
11 changes: 9 additions & 2 deletions rustcode/cli/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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());
Expand Down
31 changes: 23 additions & 8 deletions rustcode/cli/src/machines.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -1033,20 +1033,35 @@ 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:#}",
machine.name
),
}
println!(
"Removed {}. The machine still lists this computer until you revoke it there.",
machine.name
"{}",
rustcode_client::removal_message(&machine.name, unpaired)
);
Ok(())
}
Expand Down
2 changes: 2 additions & 0 deletions rustcode/client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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};
6 changes: 6 additions & 0 deletions rustcode/client/src/machine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1740,6 +1740,12 @@ impl Session {
pub async fn hub_join(self, access: &str, ask: bool) -> Result<AcpChannel> {
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<bool> {
self.connection.unpair(timeout).await
}
}

/// The titles of the machine's threads, newest first as `session/list` lists
Expand Down
3 changes: 3 additions & 0 deletions rustcode/client/src/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
);
Expand Down
26 changes: 25 additions & 1 deletion rustcode/client/src/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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<bool> {
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()))
Expand Down
Loading
Loading