diff --git a/changes/pair-over-ssh.md b/changes/pair-over-ssh.md new file mode 100644 index 00000000..d0438b54 --- /dev/null +++ b/changes/pair-over-ssh.md @@ -0,0 +1,14 @@ +--- +type: new +link: docs/README.md +--- + +## Pair two machines over SSH, with nobody at either screen + +From a machine that reaches the other over SSH, `localify machines pair +--over-ssh ` starts the other side through `ssh`, compares both codes +itself, and confirms both only when they match. An agent you gave SSH access to both +machines can now pair them. It needs OpenSSH 8.7 or later on the machine you run it on. +A pairing cut short after a confirm now says what each machine saved, instead of claiming +nothing was, and pairing again completes it. A machine on 1.7.0 or earlier can't say +whether it saved, so a pairing with it reports only what this machine saved. diff --git a/desktop-ui/src/components/app/remote/remote-pairing-dialogs.tsx b/desktop-ui/src/components/app/remote/remote-pairing-dialogs.tsx index 9d51ebc3..35adac77 100644 --- a/desktop-ui/src/components/app/remote/remote-pairing-dialogs.tsx +++ b/desktop-ui/src/components/app/remote/remote-pairing-dialogs.tsx @@ -136,6 +136,20 @@ function OutgoingPairingDialog() { ) : null} + + {outgoing.step === "partial" ? ( + <> + + Pairing with {name} did not finish + {outgoing.message} + + + + + + ) : null} ); @@ -218,6 +232,20 @@ function IncomingPairingDialog() { ) : null} + + {incoming.step === "partial" ? ( + <> + + Pairing with {incoming.name} did not finish + {incoming.message} + + + + + + ) : null} ); diff --git a/desktop-ui/src/lib/util.remote-controls.test.ts b/desktop-ui/src/lib/util.remote-controls.test.ts index 093c9e47..a98e3771 100644 --- a/desktop-ui/src/lib/util.remote-controls.test.ts +++ b/desktop-ui/src/lib/util.remote-controls.test.ts @@ -128,6 +128,15 @@ test("with controls off, an action that runs in the background asks for backgrou }); }); +test("a target of a later protocol asks and relaunches as on protocol 2", () => { + assert.deepEqual(quickAction(item(), "start", 3, "B", true), { kind: "ask", wants: "control" }); + const relaunch = legacy({ start: allowed, stop: allowed, restart: allowed }); + assert.deepEqual(quickAction(relaunch, "restart", 3, "B", true), { + kind: "relaunch", + access: null, + }); +}); + test("a target of protocol 1 only gets the command to run there", () => { assert.deepEqual(quickAction(item(), "start", 1, "B", true), { kind: "command", diff --git a/desktop-ui/src/lib/util.remote-controls.ts b/desktop-ui/src/lib/util.remote-controls.ts index a9a9af16..8c7b8c35 100644 --- a/desktop-ui/src/lib/util.remote-controls.ts +++ b/desktop-ui/src/lib/util.remote-controls.ts @@ -89,7 +89,7 @@ export function quickAction( const control = item.controls[action]; const legacyId = item.run?.legacyId; if (legacyId && (action === "restart" || control.code === "legacy_run")) { - if (proto !== 2) return { kind: "message", text: `Update Localify on ${machine}.` }; + if (!asksAccess(proto)) return { kind: "message", text: `Update Localify on ${machine}.` }; // A relaunch is a restart: the restart's checks decide. const restart = item.controls.restart; if (restart.allowed) return { kind: "relaunch", access: null }; @@ -100,10 +100,15 @@ export function quickAction( if (control.allowed) return { kind: "run" }; if (control.code === "legacy_run") return { kind: "message", text: `Relaunch it on ${machine}.` }; const wants = accessWants(control.code, runsInBackground(item, action, appRunning)); - if (wants) return proto === 2 ? { kind: "ask", wants } : { kind: "command", wants }; + if (wants) return asksAccess(proto) ? { kind: "ask", wants } : { kind: "command", wants }; return { kind: "message", text: refusalText(control.code, machine) }; } +/** Protocol 2 and later carry access requests and relaunches. */ +function asksAccess(proto: number | null): boolean { + return proto !== null && proto >= 2; +} + function refusalText(code: string | undefined, machine: string): string { return remoteErrorMessage(code ?? "", machine, `Not available on ${machine}.`); } diff --git a/desktop-ui/src/lib/util.remote.test.ts b/desktop-ui/src/lib/util.remote.test.ts index c7bc7242..b213ca92 100644 --- a/desktop-ui/src/lib/util.remote.test.ts +++ b/desktop-ui/src/lib/util.remote.test.ts @@ -17,6 +17,7 @@ import { ownerLabel, PAIRING_CANCELLED, pairingCancelledMessage, + pairingPartialMessage, remoteErrorMessage, remoteHost, serviceChips, @@ -136,6 +137,22 @@ test("a pairing nobody can confirm says how to fix it", () => { ); }); +test("a pairing that stopped after a confirm says what each side saved", () => { + assert.equal( + pairingPartialMessage("B", "pinned", "unknown", "timeout"), + "Pairing did not finish on both machines. This Mac saved B's key; B may or may not have saved this Mac's key. Pair them again to complete it.", + ); + assert.equal( + pairingPartialMessage("B", "not_pinned", "pinned", "done"), + "Pairing did not finish on both machines. This Mac did not save B's key; B saved this Mac's key. Pair them again to complete it.", + ); + // A peer on 1.7.0 or earlier never says it saved: pairing again ends the same way. + assert.equal( + pairingPartialMessage("B", "pinned", "unknown", "unconfirmed"), + "This Mac saved B's key. B runs an older version of Localify, which doesn't say whether it saved this Mac's key: check on B, or update Localify there and pair again.", + ); +}); + test("a running service whose port does not answer yet is starting", () => { const chips = serviceChips(item({ process: "running", owner: "background" })); assert.deepEqual( diff --git a/desktop-ui/src/lib/util.remote.ts b/desktop-ui/src/lib/util.remote.ts index 609f273e..c970ecba 100644 --- a/desktop-ui/src/lib/util.remote.ts +++ b/desktop-ui/src/lib/util.remote.ts @@ -2,6 +2,7 @@ import type { RemoteInventoryItemDto, RemoteMachineDto, RemoteOwner, + RemotePinState, RemoteStatusDto, } from "@/types/localify"; @@ -177,6 +178,30 @@ export function remoteErrorMessage(code: string, machine: string, fallback: stri export const PAIRING_CANCELLED = "Pairing cancelled. Nothing was saved."; +/** What each side saved when a pairing stopped after a confirm (docs/remote-machines.md, "Partial results"). */ +export function pairingPartialMessage( + machine: string, + local: RemotePinState, + peer: RemotePinState, + reason: string, +): string { + const here = + local === "pinned" + ? `This Mac saved ${machine}'s key` + : `This Mac did not save ${machine}'s key`; + // Pairing again would end the same way. + if (reason === "unconfirmed") { + return `${here}. ${machine} runs an older version of Localify, which doesn't say whether it saved this Mac's key: check on ${machine}, or update Localify there and pair again.`; + } + const there = + peer === "pinned" + ? `${machine} saved this Mac's key` + : peer === "not_pinned" + ? `${machine} did not save this Mac's key` + : `${machine} may or may not have saved this Mac's key`; + return `Pairing did not finish on both machines. ${here}; ${there}. Pair them again to complete it.`; +} + /** Why a pairing this Mac asked for did not happen (docs/remote-machines.md, "Pairing"). */ export function pairingCancelledMessage(reason: string, message: string, machine: string): string { switch (reason) { diff --git a/desktop-ui/src/providers/remote-provider.tsx b/desktop-ui/src/providers/remote-provider.tsx index 782e3727..1ca4cb85 100644 --- a/desktop-ui/src/providers/remote-provider.tsx +++ b/desktop-ui/src/providers/remote-provider.tsx @@ -30,7 +30,7 @@ import { RemotePairingDialogs } from "@/components/app/remote/remote-pairing-dia import { remoteQueries } from "@/lib/queries"; import { openRemoteStream } from "@/lib/remote-stream"; import { tauriClient } from "@/lib/tauri-client"; -import { pairingCancelledMessage } from "@/lib/util.remote"; +import { pairingCancelledMessage, pairingPartialMessage } from "@/lib/util.remote"; import { type AccessPrompt, accessPromptAdded, @@ -48,7 +48,9 @@ export type OutgoingPairing = | { step: "asking"; machine: RemoteMachineDto } | { step: "code"; machine: RemoteMachineDto; pairingId: string; code: string; answered: boolean } | { step: "paired"; machine: RemoteMachineDto } - | { step: "cancelled"; machine: RemoteMachineDto; message: string }; + | { step: "cancelled"; machine: RemoteMachineDto; message: string } + /** It stopped after a confirm: one side may hold a pin the other lacks. */ + | { step: "partial"; machine: RemoteMachineDto; message: string }; /** A pairing another machine asked for, with this Mac as the target. */ export type IncomingPairing = @@ -61,7 +63,8 @@ export type IncomingPairing = answered: boolean; } | { step: "paired"; pairingId: string; name: string } - | { step: "cancelled"; pairingId: string; name: string }; + | { step: "cancelled"; pairingId: string; name: string } + | { step: "partial"; pairingId: string; name: string; message: string }; /** Another machine asks this Mac to turn on remote controls (docs/remote-machines.md). */ export interface IncomingAccess { @@ -140,6 +143,19 @@ export function RemoteProvider({ children }: PropsWithChildren) { : current, ); return; + case "pair_partial": + setIncoming((current) => + current && current.pairingId === event.pairingId + ? { + step: "partial", + pairingId: event.pairingId, + name: event.name, + message: pairingPartialMessage(event.name, event.local, event.peer, event.reason), + } + : current, + ); + refreshMachines(); + return; case "access_request": { const { event: _, expiresAt: __, ...request } = event; setAccessQueue((queue) => accessPromptAdded(queue, request)); @@ -219,6 +235,14 @@ export function RemoteProvider({ children }: PropsWithChildren) { message: pairingCancelledMessage(event.reason, event.message, machine.name), }); return; + case "partial": + setOutgoing({ + step: "partial", + machine, + message: pairingPartialMessage(machine.name, event.local, event.peer, event.reason), + }); + refreshMachines(); + return; } }; void openRemoteStream( diff --git a/desktop-ui/src/types/localify.ts b/desktop-ui/src/types/localify.ts index 943988af..5508a4b1 100644 --- a/desktop-ui/src/types/localify.ts +++ b/desktop-ui/src/types/localify.ts @@ -1275,6 +1275,17 @@ export type RemoteEventDto = | { event: "pair_request"; pairingId: string; machineId: string; name: string; code: string } | { event: "paired"; pairingId: string; machineId: string; name: string } | { event: "pair_cancelled"; pairingId: string; machineId: string; reason: string } + /** The pairing ended after a confirm with only one side known to hold a pin. */ + | { + event: "pair_partial"; + pairingId: string; + machineId: string; + name: string; + local: RemotePinState; + peer: RemotePinState; + /** `unconfirmed`: the peer runs a version that cannot say it saved. */ + reason: string; + } | { event: "presence"; machineId: string; state: "online" | "offline" } | { event: "revoked"; machineId: string } | { event: "unpaired"; machineId: string } @@ -1318,11 +1329,24 @@ export interface RemoteAccessSuppressedDto { since: string; } +/** A side's pin after a pairing: its own as it verified it, the other's as it said. */ +export type RemotePinState = "pinned" | "not_pinned" | "unknown"; + /** What `remote_pair` says to the machine that asked. */ export type RemotePairEventDto = | { event: "code"; pairingId: string; machineId: string; name: string; code: string } | { event: "paired"; machineId: string; name: string } - | { event: "cancelled"; reason: string; message: string }; + | { event: "cancelled"; reason: string; message: string } + /** After a confirm, only one side may hold a pin (docs/remote-machines.md, "Partial results"). */ + | { + event: "partial"; + machineId: string; + name: string; + local: RemotePinState; + peer: RemotePinState; + reason: string; + message: string; + }; export interface RemoteMachineSummaryDto { machineId: string; diff --git a/docs/README.md b/docs/README.md index 8025180c..dc15333e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -481,8 +481,17 @@ localify machines pair --accept # or wait for a request on the other one Both machines show the same 6-digit code, and you confirm it on each. What the machines say to each other is end-to-end encrypted, so Localify Cloud relays it without reading -it. Pairing and removing a machine need a person at a terminal or in the app; agents -can't do it. `localify machines unpair ` forgets a paired machine, and +it. Pairing needs a person at a terminal or in the app, with one exception: from a +machine that can reach the other over SSH, `localify machines pair teo-desktop +--over-ssh teo@teo-desktop.local` starts the other side through `ssh`, compares both +codes itself, and confirms both only when they match. So an agent you gave SSH access to +both machines can pair them. It needs OpenSSH 8.7 or later on the machine you run it +on, and the host key must already be trusted; when ssh's shell doesn't find `localify` +there, pass its path with `--remote-localify`. It exits 0 once both machines saved each +other, 2 when nothing was saved, and 4 when only one may have: pairing again completes +it. A machine on Localify 1.7.0 or earlier can't say whether it saved, so pairing with it +always exits 4 until you update it. Removing a machine always needs a person. +`localify machines unpair ` forgets a paired machine, and `localify machines remove ` signs it out of the account. **Choose what others may see and do here.** Each machine decides for itself, in Settings diff --git a/docs/adr/0035-a-machine-reached-over-ssh-pairs-without-a-person.md b/docs/adr/0035-a-machine-reached-over-ssh-pairs-without-a-person.md new file mode 100644 index 00000000..bfb7879e --- /dev/null +++ b/docs/adr/0035-a-machine-reached-over-ssh-pairs-without-a-person.md @@ -0,0 +1,18 @@ +# A Machine Reached Over SSH Pairs Without a Person + +`localify machines pair` used to need a person at a terminal on both machines. The founder wants an agent that already has trusted access to both machines to pair them itself, as one did for him over SSH with a script that typed `yes`. + +The short code exists to catch a relay that sits in the middle: it makes both sides derive different codes. What matters is that someone compares the two codes, not that the someone is a person. Someone who can run commands on both machines can already read both codes, so a person adds nothing there. The weak point of the script was elsewhere. It typed `yes` on each side without comparing, so a relay in the middle would have passed. + +So `localify machines pair B --over-ssh ` runs the whole pairing from A: +- It starts `localify machines pair --accept --for-ssh` on B through `ssh `. +- It reads both codes and compares them in Localify's own code. +- It confirms both sides only when they match, and cancels both otherwise. + +The trust comes from the SSH access the caller already has, which is exactly the access a person would use, so that access must itself be authenticated. The SSH host key must already be trusted: an unknown or changed key fails, since an attacker who could answer for B over SSH and sit in the relay would otherwise pass the comparison. B's daemon must also report the machine id and the account A expects. Without `--over-ssh`, a person still confirms at a terminal or in the app, as before. + +`--for-ssh` is a machine-readable interface for whoever runs it as a user that can reach B's daemon. It is not a check of its own: someone with access to B alone could feed it back its own code, which authorizes B's side only, never A's. The comparison that protects the pairing is A's. It refuses a terminal, which only keeps a person from using it by mistake. + +The MCP server still has no pairing tool. An agent pairs through the CLI and its own SSH access, which a person granted. Removing a machine from the account stays a person's decision. + +A lost connection after the confirmations started can leave one side pinned. That was already true of every pairing. The contract now says so: the CLI reports what each side did, and pairing the same machines again completes it. diff --git a/docs/remote-machines.md b/docs/remote-machines.md index 7a53e1d8..3eaa5972 100644 --- a/docs/remote-machines.md +++ b/docs/remote-machines.md @@ -1,6 +1,6 @@ # Remote machines -The contract for remote machines: what the cloud, the relay, the daemon, the desktop app, the CLI and the MCP server each do, and the messages between them. The decisions behind it are ADRs 0028 to 0033; ADRs 0030 and 0031 amend ADR 0012. It builds on [public-urls.md](public-urls.md) for accounts, machines, plans and the Worker, and on the entitlement model of PR #56. +The contract for remote machines: what the cloud, the relay, the daemon, the desktop app, the CLI and the MCP server each do, and the messages between them. The decisions behind it are ADRs 0028 to 0033 and 0035; ADRs 0030 and 0031 amend ADR 0012. It builds on [public-urls.md](public-urls.md) for accounts, machines, plans and the Worker, and on the entitlement model of PR #56. ## What it does @@ -63,7 +63,7 @@ Turning `share` off also turns the others off. Turning a switch off ends what de ### Asking for access -A viewer on session protocol 2 can ask a target to turn on `control`, or `control` and `backgroundStarts`, with `access.request`. The request changes nothing by itself: a person on the target decides, in the app (ADR 0033). +A viewer on session protocol 2 or later can ask a target to turn on `control`, or `control` and `backgroundStarts`, with `access.request`. The request changes nothing by itself: a person on the target decides, in the app (ADR 0033). 1. **Requires `share`.** An `access.request` to a target whose `share` is off is answered `not_shared`. Access never turns `share` on. 2. **Limits, in this order:** `granted` at once when the switches asked for are already on; `too_many` with `retryAfter` when a request from this pinned peer showed a dialog less than 10 minutes ago (a request answered at once, `nobody` included, does not count, so the peer can ask again as soon as someone opens the app), or less than an hour ago and was refused, or when the target has shown 5 dialogs in the last hour, counted on the daemon's monotonic clock across sessions while it runs; `busy` when another request is waiting on this target. A person who ticks "Don't ask again from A" in the dialog suppresses A's requests until they turn it back on in Settings → Remote access; those get `declined` at once. @@ -92,11 +92,11 @@ The roster's keys are never the root of trust. They tell a viewer which machines ### Pairing -Pairing runs over the relay as a Noise session with purpose `pair` (see "Sessions"), followed by a commit and reveal that makes the short code safe against a relay in the middle. Without the commitment, a relay running two handshakes could try ephemeral keys until both codes match. With it, the responder is bound to its nonce before it sees the initiator's, both nonces and the final handshake hash go into the code, and each attempt succeeds with probability 10⁻⁶ and costs a person's click. +Pairing runs over the relay as a Noise session with purpose `pair` (see "Sessions"), followed by a commit and reveal that makes the short code safe against a relay in the middle. Without the commitment, a relay running two handshakes could try ephemeral keys until both codes match. With it, the responder is bound to its nonce before it sees the initiator's, both nonces and the final handshake hash go into the code, and each attempt succeeds with probability 10⁻⁶ and counts against the target's limit of 5 attempts an hour. 1. On the viewer A, the switcher lists B as "Not paired" with a `Pair` button. `localify machines pair ` does the same. 2. A sends a pairing request: the three Noise XX handshake messages, the first one's envelope carrying purpose `pair`. Both now hold the other's static key and the final handshake hash `h`. -3. B's daemon checks that a person can answer: the desktop app is subscribed to its events, or `localify machines pair --accept` is waiting. Otherwise it answers `pair.declined` with `nobody_to_confirm`, and A shows: "Nobody can confirm on B. Open Localify on B, or run `localify machines pair --accept` there, then try again." +3. B's daemon checks that someone can answer: the desktop app is subscribed to its events, or `localify machines pair --accept` is waiting (with or without `--for-ssh`). Otherwise it answers `pair.declined` with `nobody_to_confirm`, and A shows: "Nobody can confirm on B. Open Localify on B, or run `localify machines pair --accept` there, then try again." 4. B picks a random 32-byte `nB` and sends `pair.commit` with `c = BLAKE2s("localify-pair-commit" ‖ h ‖ nB)`. 5. A picks a random 32-byte `nA` and sends `pair.nonce` with it. 6. B sends `pair.reveal` with `nB`. A checks it against `c`, and abandons the pairing on a mismatch. @@ -105,10 +105,31 @@ Pairing runs over the relay as a Noise session with purpose `pair` (see "Session - A: title "Pair with B", body "Check that B shows this code: **482 913**", buttons `Codes match` and `Cancel`. - B: title "A wants to pair with this Mac" (or "this computer" on Linux), body "Pair only if A shows the same code: **482 913**. A will then see this Mac's name. It sees projects and output, or controls services, only after you turn that on in Settings → Remote access.", buttons `Codes match, pair` and `Cancel`. - CLI: `A wants to pair. Code: 482 913. Type yes if A shows the same code:`. -9. Each side sends `pair.confirm` with `accept` once its person answers. A side writes its pin only when its own person accepted and the peer's `accept: true` arrived. A cancel, a mismatch, a message out of order or repeated, a closed session or 2 minutes without both answers pins nothing, and both show "Pairing cancelled. Nothing was saved." + - Over SSH (ADR 0035), see "Pairing over SSH" below. +9. Each side sends `pair.confirm` with `accept` once its person answers. A side writes its pin only when its own person accepted and the peer's `accept: true` arrived. Before either side has sent `pair.confirm`, a cancel, a mismatch, a message out of order or repeated, a closed session or 2 minutes without both answers pins nothing, and both show "Pairing cancelled. Nothing was saved." After that, see "Partial results" below. 10. After pairing, B shows "Paired with A" and a link to Settings → Remote access, with the three switches still off. A shows B as "Paired · not sharing" until B turns `share` on. -The pairing messages come in exactly that order, each once: commit, nonce, reveal, then the two confirms. Anything else abandons the pairing. A target accepts one pairing at a time and at most 5 pairing attempts an hour; more answer `busy` with `retryAfter`. Pairing is symmetric: both machines pin each other, and each one's own settings decide what the other may see or do. +**Partial results.** Before either side sends `pair.confirm`, nothing writes a new pin. After the first `pair.confirm`, a lost session can leave one side pinned and not the other. Each side then reports its own state as it verified it on disk, `pinned` or `not_pinned`, and the peer's as `pinned` (its `pair.saved` arrived), `not_pinned` (it cancelled before confirming), or `unknown`. In a session of protocol 3 or later, a side sends `pair.saved` only once its pin is durably written, and then waits up to 30 seconds for the peer's before it ends with `bye` `done`; nothing else, `bye` `done` included, says the peer saved. A peer of protocol 2 (1.7.0 and earlier) has no `pair.saved`, and ends with `bye` `done` whether it saved, failed to save, or timed out, so a side paired with it ends as soon as it wrote its own pin and reports the peer `unknown`: the CLI exits 4 and says to check on that machine or update it, since pairing again would end the same way. Nothing was written when this side wrote no pin, and either never sent `accept: true` or got the peer's `accept: false`: the peer writes its pin only once this side's `accept: true` arrived, and only if it accepted too. The CLI exits 4 unless both sides are known to be pinned (0) or nothing was written (2). Pairing again with the same machine ids and keys completes it. A different key for an existing pin never replaces it silently: that is a key mismatch, and the pairing stops right after the handshake, before any code, with `key_mismatch`. The pin write checks again under the pins' lock, so when another pairing pinned another key for the same machine in the meantime, this one writes nothing and ends `partial` with `key_mismatch`. + +### Pairing over SSH + +`localify machines pair --over-ssh [--remote-localify ]` lets someone who can run commands on both machines, such as an agent a person gave SSH access, pair them without a person at either screen (ADR 0035). Either machine can be the initiator, macOS or Linux, with or without the desktop app. Pairing changes no setting on either side. + +- **SSH:** A runs `ssh` directly, with no local shell, as `ssh -T -o BatchMode=yes -o StrictHostKeyChecking=yes -o StdinNull=no -o ForkAfterAuthentication=no -o ForwardAgent=no -o ForwardX11=no -o ClearAllForwardings=yes -o ControlMaster=no -o ControlPath=none -o ConnectTimeout=15 -- `. The host key must already be trusted (`known_hosts` or a host CA); an unknown or changed key fails before anything else. `` must be one operand that does not start with `-`. The remote command is the executable path and fixed arguments, each quoted for a POSIX shell. `--remote-localify` is one absolute path, refused if it holds a newline or NUL. `StdinNull` and `ForkAfterAuthentication` need OpenSSH 8.7 or later, so A runs `ssh -V` first and, for any other ssh or an older version, refuses with exit 2 and a message that names the version needed, before `ssh` connects. Without `--remote-localify`, the command is `localify` as the remote non-interactive environment finds it, and a missing one fails with a message that names `--remote-localify`. Nothing is installed or updated on B, and nothing switches users or uses `sudo`. +- **The accepting side:** `localify machines pair --accept --for-ssh --from --account ` is a machine-readable interface for an authorized local caller. Refusing a terminal on stdin or stdout only prevents accidental interactive use. It is not authentication and it proves nothing about SSH. The comparison is A's, and processes of the daemon's own user are inside the trust boundary, as everywhere in this contract. It opens no listener. It talks to its own daemon over the management socket as the user SSH logged in as; when that user cannot reach the daemon, or the daemon's account or machine id differ from what A expects, it fails before pairing. +- **Protocol:** stdout carries JSON lines only, each under 4 KiB, with `"v": 1`. stderr is diagnostics, read and logged by A but never parsed. Both are drained at once. The lines, in order: + 1. `{"v": 1, "event": "ready", "machineId", "account", "attempt"}`. It is sent only once B's daemon holds a one-shot acceptor for that account and that initiating machine id; a pairing request from another machine id cannot consume it. `attempt` is a fresh id B picks, which A passes to its daemon (`remote_pair {machineId, attempt}`) and which tags the `code` and `result` lines, so A never mixes two attempts. It is a correlation id, not a check: a relay that answers in A's name is caught by the code comparison, which is what protects the pairing. + 2. `{"v": 1, "event": "code", "attempt", "code"}`. + 3. `{"v": 1, "event": "result", "attempt", "outcome": "paired" | "cancelled" | "partial", "local", "peer", "detail"}`, with the states of "Partial results". + + A cancel or an expiry before any code ends with `ready` then `result`. A failure before `ready` (no daemon, a daemon that does not answer within 15 s, a stdin that closes or a line that comes first, wrong account, a pairing already active, over the limit) writes nothing to stdout, explains on stderr and exits non-zero; B watches its stdin from the start. + + A starts its pairing request only after a `ready` whose `machineId` is the B it resolved and whose `account` is its own. A malformed, repeated, out-of-order or foreign line ends the attempt, even after the confirms: from then on A reads no line of B's, not even an earlier `result`, never reports B `pinned`, and exits 2 or 4 with that line as the reason. After `code`, A compares it with its own code. On a match, it writes `{"v": 1, "confirm": ""}` to B's stdin and confirms its own side, and keeps stdin open until B's `result`. On a mismatch, it writes `{"v": 1, "cancel": true}` and cancels its side. A closed stdin before a confirm cancels B. B confirms only when the line's code equals its own. +- **Deadlines:** 15 s for SSH to connect and 15 s more for `ready`, on A. B starts the pairing's 2 minutes on its monotonic clock when it registers the acceptor, just before it writes `ready`; A starts its own 2 minutes when it receives a valid `ready`. Neither is extended by progress, and B's expiry decides. On any failure, A cancels its side and closes B's stdin. A reaps the `ssh` child, and B's acceptor expires on its own deadline if cleanup can't reach it. +- **Limits:** the same as any pairing. One active pairing per target, and 5 attempts an hour per target, counted by B's daemon on `ready`, mismatches and cancels included; a new helper or a reconnect doesn't reset the count. There is no automatic retry after a mismatch. +- **Exit codes:** 0 paired on both sides; 2 refused or cancelled with nothing saved; 4 partial, with both sides' states. + +The pairing messages come in exactly that order, each once: commit, nonce, reveal, then the two confirms, then, in a session of protocol 3 or later, each side's `pair.saved` (see "Partial results"). Anything else abandons the pairing. A target accepts one pairing at a time and at most 5 pairing attempts an hour; more answer `busy` with `retryAfter`. Pairing is symmetric: both machines pin each other, and each one's own settings decide what the other may see or do. ### Sessions @@ -300,7 +321,7 @@ JSON objects inside Noise transport messages, at most 32 KiB before encryption. ```ts // Both ways, first. type Hello = { - t: "hello"; proto: { min: 1; max: 2 }; version: string; + t: "hello"; proto: { min: 1; max: 3 }; version: string; now: string; // RFC 3339, the sender's clock role: "viewer" | "target"; // Target only. @@ -379,6 +400,7 @@ type PairCommit = { t: "pair.commit"; c: string }; // base64url type PairNonce = { t: "pair.nonce"; n: string }; type PairReveal = { t: "pair.reveal"; n: string }; type PairConfirm = { t: "pair.confirm"; accept: boolean }; +type PairSaved = { t: "pair.saved" }; // protocol 3: after both accepted, once this side's pin is written type PairDeclined = { t: "pair.declined"; reason: "nobody_to_confirm" | "busy" | "cancelled" }; ``` @@ -414,7 +436,7 @@ The `code` of a `SessionError`, or of a `ControlResult` that is not `done`: ### Versioning -Two versions move separately. The relay protocol is the WebSocket subprotocol, `localify-remote.1`; a Worker that drops one closes its sockets with `4002`. The session protocol is `proto` in `hello` and in `presence`. The session's version is the highest one in both `hello` ranges, and each side computes it from the two authenticated `hello`s, never from `presence`, which the relay could alter: `presence` and `X-Localify-Proto` only let the viewer say "Update needed" before it opens a session. The prologue's label, `localify-remote/1`, names the handshake's format and does not change with the session protocol. When the `hello` ranges do not overlap, the session ends with `unsupported`. Version 2 adds `access.request`, `access.cancel`, `access.result` and `expect.legacyId`. A sender never sends them in a session whose version is 1, and a receiver treats them there as an unknown `t`. A new optional field is added without a new version, and a receiver ignores fields it does not know, except in `control`, where an unknown field is refused so that no argument is ever silently dropped. A new message type, or a change in meaning, takes a new version, and a sender never sends a type the peer's version lacks. +Two versions move separately. The relay protocol is the WebSocket subprotocol, `localify-remote.1`; a Worker that drops one closes its sockets with `4002`. The session protocol is `proto` in `hello` and in `presence`. The session's version is the highest one in both `hello` ranges, and each side computes it from the two authenticated `hello`s, never from `presence`, which the relay could alter: `presence` and `X-Localify-Proto` only let the viewer say "Update needed" before it opens a session. The prologue's label, `localify-remote/1`, names the handshake's format and does not change with the session protocol. When the `hello` ranges do not overlap, the session ends with `unsupported`. Version 2 adds `access.request`, `access.cancel`, `access.result` and `expect.legacyId`. Version 3 adds `pair.saved`. A sender never sends them in a session of an earlier version, and a receiver treats them there as an unknown `t`. So a pairing with a 1.7.0 peer, which speaks 1 to 2, agrees on 2 and never carries `pair.saved`. A new optional field is added without a new version, and a receiver ignores fields it does not know, except in `control`, where an unknown field is refused so that no argument is ever silently dropped. A new message type, or a change in meaning, takes a new version, and a sender never sends a type the peer's version lacks. ## Inventory @@ -740,11 +762,12 @@ New management socket commands. The streaming ones keep the connection open and | Command | Answer | |---|---| -| `remote_status` | `{relay: "off" \| "connecting" \| "connected" \| "reconnecting" \| "blocked", blocked: {code, message} \| null, retryAt, settings, fingerprint, shellEnvironmentError}`; `shellEnvironmentError` says why background starts run with the daemon's own environment, `null` otherwise | +| `remote_status` | `{relay: "off" \| "connecting" \| "connected" \| "reconnecting" \| "blocked", blocked: {code, message} \| null, retryAt, settings, fingerprint, shellEnvironmentError, machineId, account}`; `shellEnvironmentError` says why background starts run with the daemon's own environment, `null` otherwise; `machineId` and `account`, the account's user id, while connected, `null` otherwise | | `remote_reload_shell_environment` | `{shellEnvironmentError}`, once the daemon read the user's shell environment again for background starts; the app sends it on `Reload shell environment` | | `remote_machines` | the roster merged with pins, presence and sessions: `[{id, name, self, paired, state, version, fingerprint, proto}]`, `state` as in "Desktop app"; `proto` is the session version agreed from the authenticated `hello`s of the open session, `null` with no session | | `remote_settings {share?, control?, backgroundStarts?}` | the settings after the change | -| `remote_pair {machineId}` | streaming: `code`, then `paired` or `cancelled` | +| `remote_pair {machineId, attempt?}` | streaming: `code`, then `paired`, `cancelled`, or `partial` with `{local: "pinned" \| "not_pinned", peer: "pinned" \| "not_pinned" \| "unknown"}` (see "Partial results"); `attempt` only correlates the SSH helper's lines, and comes back on every event | +| `remote_pair_accept {machineId, account}` | streaming, for `--accept --for-ssh`: `{event: "ready", machineId, account, attempt}` once a one-shot acceptor for that account and that initiating machine id is registered (see "Pairing over SSH"), then `code` with its `pairingId`, answered with `remote_pair_answer`, then `paired`, `cancelled` or `partial`. A wrong account, this machine's own id, a pairing already active or the hour's limit is an error instead of `ready`. Closing the stream cancels the acceptor, or the pairing it started | | `remote_pair_answer {pairingId, accept}` | `{ok}` | | `remote_unpair {machineId}` | `{ok}` | | `remote_inventory {machineId}` | one snapshot, all pages | @@ -756,7 +779,7 @@ New management socket commands. The streaming ones keep the connection open and | `remote_access_suppressed` | target side: `[{machineId, name, since}]`, the peers whose requests are suppressed | | `remote_access_restore {machineId}` | target side: lets that peer ask again; `{ok}` | | `remote_access_answer {requestId, allow, suppress}` | target side, from the app's dialog: `{outcome}`, `granted` only when the request was still waiting and the settings unchanged (see "Asking for access") | -| `remote_events {access?}` | streaming: pairing requests, access requests (`access_request {requestId, machineId, name, fingerprint, wants, expiresAt}`) and their end (`access_closed {requestId}`), presence, revocations; the app subscribes while it runs. Access events go only to a client subscribed with `access: true`, one that shows the access dialog, and "no app is subscribed" in "Asking for access" means none of those. The app subscribes with it | +| `remote_events {access?}` | streaming: pairing requests and how they ended (`paired`, `pair_cancelled`, `pair_partial {local, peer, reason}`, `reason` `unconfirmed` when the peer runs a version without `pair.saved`), access requests (`access_request {requestId, machineId, name, fingerprint, wants, expiresAt}`) and their end (`access_closed {requestId}`), presence, revocations; the app subscribes while it runs. Access events go only to a client subscribed with `access: true`, one that shows the access dialog, and "no app is subscribed" in "Asking for access" means none of those. The app subscribes with it | One local command serves this machine's own inventory: `inventory {have?}` answers the snapshot the relay will page (`schema`, `epoch`, `rev`, `pages`, `truncated`, `items`), or `{unchanged: true, epoch, rev}` when `have` names its revision. One snapshot is built at a time; a request that arrives during a build shares its result. Its `controls` follow the switches and the app as the relay pages do: `machine.app`, like `app` in a target's `hello`, says whether the app's bridge answered the daemon's last `hello`, asked every 2 seconds. The local `inventory` command's `rev` counts its items only; the relay pages carry the revision of "Epoch and revision", which the summary moves too. The hidden `localify inventory [--have :]` prints it, for tests. @@ -782,8 +805,8 @@ The daemon opens a session only when one of these asks for it, carries every req - **A remote machine's view** is the Projects screen of that machine, drawn like this Mac's and read-only: no editor, no domain or profile editing, no terminal. A banner says "You're viewing B. Its .localify URLs open only on B." Each project is a card like this Mac's: the primary checkout's services as domain chips, and each worktree folded under one line with its count of services that answer. A chip holds a dot (green once the service answers, amber while it starts, red after a failed exit, grey when stopped), the domain, the port, the public URL's globe, the launch profile, Start or Stop, and a menu with `Show output`, `Open public URL`, `Copy URL` and `Restart`. The dot's tooltip gives the owner ("In the app", "In the background", "In a terminal", "Unknown process") and the four states: Process, Port, Output, Public URL. The Start, Stop and Restart buttons follow `controls`. A control in flight shows its progress, and `unknown` shows "Outcome unknown. Checking B…". - **Quick actions:** a control that is not allowed stays clickable and opens a small card that says why and what fixes it, instead of a disabled button: - - `control_disabled` or `background_disabled`, on a target whose session agreed on protocol 2 (`proto` in `remote_machines`): `Ask B`, which sends `access.request` and shows "Waiting for an answer on B…" with `Cancel`, then "B allowed remote controls.", "B didn't allow it.", "Nobody can answer on B: Localify isn't open there.", or the end's reason. `background_disabled` asks for `backgroundStarts`. So does `control_disabled` when the control would run in the background on B: a start while B's app is absent (`machine.app` is `absent`), or a restart of a background run. `backgroundStarts` turns `control` on too, so one request is enough; asking for `control` first would get `background_disabled` next, and a second request within 10 minutes gets `too_many`. Otherwise `control_disabled` asks for `control`. Below it, always, "Or run this on B:" with the command for the same switches, `localify machines settings --control on`, or `localify machines settings --control on --background-starts on`, and a copy button. On a target of protocol 1, only the command shows, under "Update Localify on B to ask from here." - - `legacy_run` on a run with `legacyId`, on protocol 2, Output's "Relaunch to share" for the same run, and `Restart` of a run with `legacyId` even when `controls.restart` allows it: `Relaunch on B`, always after a confirmation: "web started before this version of Localify on B. Relaunch it so its output and controls work here? It restarts with its configured command." When controls are off, the card asks for access first, and shows "Or run this on B:" with the command, as `Ask B` does; once granted, it relaunches only if the snapshot still shows the same `legacyId` and `configRev` the person confirmed, and asks again otherwise. A request that ends without access (`nobody`, `declined`, an error) leaves its reason on screen with the same command, until the person closes it. + - `control_disabled` or `background_disabled`, on a target whose session agreed on protocol 2 or later (`proto` in `remote_machines`): `Ask B`, which sends `access.request` and shows "Waiting for an answer on B…" with `Cancel`, then "B allowed remote controls.", "B didn't allow it.", "Nobody can answer on B: Localify isn't open there.", or the end's reason. `background_disabled` asks for `backgroundStarts`. So does `control_disabled` when the control would run in the background on B: a start while B's app is absent (`machine.app` is `absent`), or a restart of a background run. `backgroundStarts` turns `control` on too, so one request is enough; asking for `control` first would get `background_disabled` next, and a second request within 10 minutes gets `too_many`. Otherwise `control_disabled` asks for `control`. Below it, always, "Or run this on B:" with the command for the same switches, `localify machines settings --control on`, or `localify machines settings --control on --background-starts on`, and a copy button. On a target of protocol 1, only the command shows, under "Update Localify on B to ask from here." + - `legacy_run` on a run with `legacyId`, on protocol 2 or later, Output's "Relaunch to share" for the same run, and `Restart` of a run with `legacyId` even when `controls.restart` allows it: `Relaunch on B`, always after a confirmation: "web started before this version of Localify on B. Relaunch it so its output and controls work here? It restarts with its configured command." When controls are off, the card asks for access first, and shows "Or run this on B:" with the command, as `Ask B` does; once granted, it relaunches only if the snapshot still shows the same `legacyId` and `configRev` the person confirmed, and asks again otherwise. A request that ends without access (`nobody`, `declined`, an error) leaves its reason on screen with the same command, until the person closes it. - `legacy_run` with no `legacyId`, or on protocol 1: "Relaunch it on B." (or "Update Localify on B."), with no action. So are `not_owned`, `owner_gone`, `refused_profile` and the others: the message, with no action. - **URLs:** a remote `.localify` URL is copied, never opened. Clicking the domain opens the output when it is shared, and copies the URL otherwise. When the service has a public URL that serves, its globe and `Open public URL` open it. - **Output** opens in a panel docked at the bottom, sized, coloured and resized like the terminal panel, titled with the project and service, "on B", with search, Follow / Pause and selectable text (see "Output"). The terminal panel holds this Mac's PTYs only, so remote output stays out of it; opening one closes the other. @@ -798,6 +821,7 @@ All of it goes through `DesktopApi` and the management socket. The UI does no ne ```bash localify machines # the roster: name, id, state, paired, sharing, version localify machines pair # pairs with another machine: a code to confirm on both +localify machines pair --over-ssh [--remote-localify ] # pairs over SSH, comparing both codes itself localify machines pair --accept # waits on this machine for a pairing request localify machines unpair localify machines remove [--yes] # signs it out of the account @@ -814,7 +838,7 @@ localify restart --machine [--project ] [--env ] - **What `--machine` refuses:** with `dev`, every option but `--project`, `--env` and `--profile`: no command after `--`, no `--detach`, `--in-app`, `--env-file`, `--confirm-profile` or `--domain`. The target decides where the service runs. - **Launch flags:** `--launch-id`, `--launch-expires`, `--remote-launch`, `--expect-rev`, `--request` and `--replace-legacy` are hidden flags for dispatchers, documented here and not in `--help`. - **Output:** human on a terminal, JSON otherwise, as everywhere. A control prints its progress, then its result; an outcome it could not learn (`lost`) prints the fresh status and exits with code 3. A refusal prints the message of "Errors" and exits with code 2; a `conflict` prints "B changed in the meantime." with the service's fresh state, and the control is never sent again. `unknown` is progress, "Outcome unknown. Checking B…", never where a control stops. A control the snapshot already refuses (its `controls`, or a live legacy run, which the app relaunches after a confirmation) is refused the same way without being sent. A run that failed exits with code 1. With JSON, progress goes to stderr, so stdout holds one document: `{outcome, code, message, …}`. `logs` prints plain lines, as without `--machine`, and its next cursor on stderr. When the service restarts during a read or `--follow` (`gone`), it reads the service's current run from offset 0. -- `pair` and `remove` need a terminal: an agent cannot pair or remove machines. +- `pair` needs a terminal, or `--over-ssh` on the initiator and `--accept --for-ssh` on the side it starts (see "Pairing over SSH" and ADR 0035), which lets an agent with SSH access to both machines pair them. `remove` needs a terminal: an agent cannot remove a machine. ## MCP @@ -822,7 +846,7 @@ localify restart --machine [--project ] [--env ] - An optional `machine` argument on `list_services`, `service_status`, `service_logs`, `service_start`, `service_stop` and `service_restart`, and on no other tool. With it, a tool ignores `cwd`. Any other tool given `machine` fails before it runs anything, rather than acting on this machine. - With `machine`, `service_start` takes only `service`, `project`, `env` and `profile`. `background`, `env_files`, `confirm_profile`, `command` and `domain` make it fail with an error that says the target decides how its services start. It never creates a project. - `service_logs` with `machine` returns a cursor `:`. `list_services` and `service_status` with `machine` both give the target's snapshot (`services status --machine`). -- Pairing, unpairing, settings and removal have no tool. Like signing in (ADR 0018), they stay a person's decision. +- Pairing, unpairing, settings and removal have no tool. Like signing in (ADR 0018), they stay a person's decision, except that an agent a person gave SSH access to both machines may pair them with `localify machines pair --over-ssh` (ADR 0035). - An error from a target reaches the agent with its code and message, so `control_disabled` tells it to ask the user to allow controls on that machine, and an outcome it could not learn (`lost`) tells it to check `service_status` before trying again. ## Failure modes @@ -926,7 +950,7 @@ Against a real daemon, a real app process where it says so, and the relay in `wr **PR 2, trust and relay:** -- Pairing: a nonce sent before the commit, a duplicated commit, a reveal that does not match the commit, a handshake hash altered by a test relay that substitutes a key, a cancel on either side, and a 2-minute timeout each pin nothing. A test relay running two handshakes cannot make both codes match except by chance. +- Pairing: a nonce sent before the commit, a duplicated commit, a reveal that does not match the commit, a handshake hash altered by a test relay that substitutes a key, a cancel on either side, and a 2-minute timeout each pin nothing when they happen before either `pair.confirm`; a session cut after one is reported `partial` with each side's verified state. The peer counts as pinned only once its `pair.saved` arrives: a 1.7.0 peer's `bye` `done`, after its timeout or a failed pin write, leaves it `unknown`. A pin of another key written during a pairing is never replaced. A test relay running two handshakes cannot make both codes match except by chance. - Replay: a recorded session's frames replayed into a new session fail; a duplicated or reordered transport message ends the session; a forced nonce reuse is rejected. - Identity substitution: a relay that rewrites `from`, a roster key that differs from the pin, a purpose rewritten in the envelope, and a same-name sign-in all fail to open a session. - Handshakes: an incomplete one is dropped after 30 s; more than 4 at once get `busy`. diff --git a/src/cli/machines.rs b/src/cli/machines.rs index 2a60e947..8336aa95 100644 --- a/src/cli/machines.rs +++ b/src/cli/machines.rs @@ -1,7 +1,8 @@ //! `localify machines`: the other machines of this Localify Cloud account, //! pairing with them, and what they may see and do here //! (`docs/remote-machines.md`, "CLI"). Pairing and removal need a person at -//! a terminal: an agent cannot pair or remove machines. +//! a terminal, except that someone who can run commands on both machines +//! may pair them over SSH (ADR 0035, `pair_ssh`). use std::io::{self, BufRead, Write}; @@ -11,6 +12,7 @@ use serde::Deserialize; use serde_json::{Value, json}; use super::output::{can_prompt, print_json, wants_json}; +use super::pair_ssh; use crate::application::ports::DaemonConnectionError; use crate::branding::BRANDING; use crate::cli::context::AppContext; @@ -19,6 +21,8 @@ use crate::infrastructure::cloud::api::CloudClient; use crate::infrastructure::cloud::credentials::CredentialsStore; use crate::infrastructure::cloud::http::{CloudHttp, block_on}; use crate::infrastructure::mgmt_client::MgmtSocketClient; +use crate::infrastructure::remote::pairing::{Outcome, PinState}; +use crate::infrastructure::remote::ssh_pair; #[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] pub enum Switch { @@ -243,7 +247,9 @@ fn typed_yes(prompt: &str) -> Result { } /// `localify machines pair `, as the viewer. -pub fn pair(query: &str, ctx: &AppContext) -> Result<()> { +/// Returns the exit code: 0 paired, 2 nothing saved, 4 partial (see +/// docs/remote-machines.md, "Partial results"). +pub fn pair(query: &str, ctx: &AppContext) -> Result { require_person("Pair")?; let target = resolve(&candidates(&machines(&ctx.mgmt_client, false)?), query)?; if target.is_self { @@ -271,15 +277,23 @@ pub fn pair(query: &str, ctx: &AppContext) -> Result<()> { "Paired with {}. It shows this machine's name; it shares projects and output, or allows controls, only once its owner turns that on.", target.name ); - return Ok(()); + return Ok(0); } Some("cancelled") => { - bail!("{}", cancelled_message(&event)); + eprintln!("{}", cancelled_message(&event)); + return Ok(2); + } + Some("partial") => { + eprintln!("{}", event["message"].as_str().unwrap_or_default()); + return Ok(4); } _ => {} } } - bail!("Pairing cancelled. Nothing was saved.") + bail!( + "The daemon stopped answering about the pairing; run `{} machines` to see where it stands.", + BRANDING.cli_command() + ) } fn answer(ctx: &AppContext, pairing_id: &str, accept: bool) -> Result<()> { @@ -300,7 +314,8 @@ fn cancelled_message(event: &Value) -> String { /// `localify machines pair --accept`: waits here for another machine's /// request, and asks the person to confirm its code. -pub fn accept(ctx: &AppContext) -> Result<()> { +/// Returns the exit code, as [`pair`] does. +pub fn accept(ctx: &AppContext) -> Result { require_person("Pair --accept")?; let mut stream = ctx .mgmt_client @@ -331,10 +346,33 @@ pub fn accept(ctx: &AppContext) -> Result<()> { "Paired with {name}. It sees this machine's name only, until you turn on sharing: {} machines settings --share on", BRANDING.cli_command() ); - return Ok(()); + return Ok(0); } Some("pair_cancelled") if waiting_for.as_deref() == Some(pairing_id.as_str()) => { - bail!("Pairing cancelled. Nothing was saved.") + eprintln!("Pairing cancelled. Nothing was saved."); + return Ok(2); + } + Some("pair_partial") if waiting_for.as_deref() == Some(pairing_id.as_str()) => { + let here = if event["local"] == "pinned" { + "saved" + } else { + "did not save" + }; + // Pairing again would end the same way. + if event["reason"] == "unconfirmed" { + eprintln!( + "This machine {here} {name}'s key. {name} runs an older version of Localify, which does not say whether it saved this machine's key: check on {name}, or update Localify there and pair again." + ); + return Ok(4); + } + eprintln!( + "Pairing did not finish on both machines: this machine {here} {name}'s key, and {name}'s side is {}. Pair them again to complete it.", + event["peer"] + .as_str() + .unwrap_or("unknown") + .replace('_', " ") + ); + return Ok(4); } _ => {} } @@ -342,6 +380,136 @@ pub fn accept(ctx: &AppContext) -> Result<()> { bail!("The daemon stopped waiting for a pairing request.") } +/// `localify machines pair --over-ssh `: pairs +/// with no person at either screen, comparing both codes here. Prints how +/// it ended, and returns the exit code: 0 paired, 2 nothing saved, 4 +/// partial. +pub fn pair_over_ssh( + query: &str, + destination: &str, + remote_localify: Option<&str>, + json_flag: bool, + ctx: &AppContext, +) -> i32 { + let ready = ssh_target(query, ctx).and_then(|target| { + require_openssh()?; + Ok(target) + }); + let report = match ready { + Ok(target) => match ssh_command(destination, remote_localify, &target) { + Ok(args) => { + let started = std::time::Instant::now(); + let mut ssh = std::process::Command::new("ssh"); + ssh.args(&args); + match pair_ssh::Peer::spawn(ssh, &target.name) { + Ok(peer) => pair_ssh::drive(&ctx.mgmt_client, &target, peer, started), + Err(error) => pair_ssh::Report::refused( + Some(&target), + format!("Could not run ssh: {error}"), + ), + } + } + Err(error) => pair_ssh::Report::refused(Some(&target), format!("{error:#}")), + }, + Err(error) => pair_ssh::Report::refused(None, format!("{error:#}")), + }; + print_report(&report, wants_json(json_flag)); + report.exit_code() +} + +/// The machine to pair with, and this machine's account, from its daemon. +fn ssh_target(query: &str, ctx: &AppContext) -> Result { + let status = ctx.mgmt_client.remote_status().map_err(daemon_error)?; + let (Some(self_id), Some(account)) = (status["machineId"].as_str(), status["account"].as_str()) + else { + bail!( + "Remote access is not available on this machine: it is not connected to Localify Cloud right now. Check `{} machines`.", + BRANDING.cli_command() + ); + }; + let target = resolve(&candidates(&machines(&ctx.mgmt_client, false)?), query)?; + if target.is_self || target.id == self_id { + bail!("{} is this machine: pair it from another one.", target.name); + } + Ok(pair_ssh::Target { + machine_id: target.id, + name: target.name, + own_id: self_id.to_string(), + account: account.to_string(), + }) +} + +/// Fails before `ssh` runs when it is not OpenSSH 8.7 or newer, rather +/// than letting it refuse the contract's options. +fn require_openssh() -> Result<()> { + let output = std::process::Command::new("ssh") + .arg("-V") + .stdin(std::process::Stdio::null()) + .output() + .map_err(|error| anyhow!("Could not run ssh: {error}"))?; + // `ssh -V` writes its version to stderr. + let mut said = String::from_utf8_lossy(&output.stderr).into_owned(); + said.push_str(&String::from_utf8_lossy(&output.stdout)); + Ok(ssh_pair::require_openssh(&said)?) +} + +/// `ssh`'s arguments, with the helper's command for the remote shell. +fn ssh_command( + destination: &str, + remote_localify: Option<&str>, + target: &pair_ssh::Target, +) -> Result> { + let executable = match remote_localify { + Some(path) => ssh_pair::remote_executable(path)?, + None => BRANDING.cli_command(), + }; + let command = ssh_pair::remote_command(executable, &target.own_id, &target.account)?; + Ok(ssh_pair::ssh_args(destination, &command)?) +} + +fn print_report(report: &pair_ssh::Report, json: bool) { + if json { + let _ = print_json(report); + return; + } + let name = report.name.as_deref().unwrap_or("the other machine"); + match report.outcome { + Outcome::Paired => println!( + "Paired with {name} over SSH: both machines saved each other's key. {name} sees this machine's name; it shares projects and output, or allows controls, only once that is turned on there." + ), + Outcome::Cancelled if report.detail.is_empty() => { + eprintln!("Pairing cancelled. Nothing was saved."); + } + Outcome::Cancelled => eprintln!("Pairing cancelled. Nothing was saved. {}", report.detail), + Outcome::Partial => { + let here = match report.local { + PinState::Pinned => "saved", + PinState::NotPinned => "did not save", + PinState::Unknown => "may or may not have saved", + }; + let there = match report.peer { + PinState::Pinned => "saved this machine's key", + PinState::NotPinned => "did not save this machine's key", + PinState::Unknown => "may or may not have saved this machine's key", + }; + eprintln!( + "Pairing did not finish on both machines: this machine {here} {name}'s key, and {name} {there}. Pair them again to complete it. {}", + report.detail + ); + } + } +} + +/// `localify machines pair --accept --for-ssh`, on the machine +/// `--over-ssh` reaches. Returns the exit code. +pub fn accept_for_ssh(from: &str, account: &str, ctx: &AppContext) -> Result { + let args = pair_ssh::HelperArgs { + from: from.to_string(), + account: account.to_string(), + }; + pair_ssh::accept_for_ssh(&ctx.mgmt_client, &args) +} + /// `localify machines unpair `: deletes the pin, and tells the /// machine when a session is open. pub fn unpair(query: &str, json_flag: bool, ctx: &AppContext) -> Result<()> { diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 43280dcc..2c621f71 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -15,6 +15,7 @@ pub mod logs; pub mod machines; pub mod mcp; pub mod output; +pub mod pair_ssh; pub mod profile_init; pub mod project; pub mod project_env; diff --git a/src/cli/pair_ssh.rs b/src/cli/pair_ssh.rs new file mode 100644 index 00000000..55af400b --- /dev/null +++ b/src/cli/pair_ssh.rs @@ -0,0 +1,937 @@ +//! Pairing over SSH (`docs/remote-machines.md`, "Pairing over SSH"; ADR +//! 0035): `localify machines pair --over-ssh ` on the +//! initiator, and the helper it starts on B, `localify machines pair +//! --accept --for-ssh`. +//! +//! The initiator runs `ssh` itself, reads both codes, compares them here, +//! and confirms both sides only when they match. The trust comes from the +//! SSH access the caller already has; the helper's refusal of a terminal +//! only keeps a person from using it by mistake. + +use std::io::{self, BufRead, BufReader, Read, Write}; +use std::net::Shutdown; +use std::os::unix::net::UnixStream; +use std::process::{Child, Command, ExitStatus, Stdio}; +use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; +use std::thread; +use std::time::{Duration, Instant}; + +use anyhow::{Result, anyhow, bail}; +use serde::Serialize; +use serde_json::{Value, json}; + +use crate::branding::BRANDING; +use crate::infrastructure::mgmt_client::{MgmtSocketClient, MgmtStream}; +use crate::infrastructure::remote::pairing::{Outcome, PinState}; +use crate::infrastructure::remote::ssh_pair::{ + self, ControlLine, HelperLine, HelperLines, ProtocolError, +}; + +/// 15 s for `ssh` to connect, its own `ConnectTimeout`, then 15 s more for +/// `ready`. +const READY_WAIT: Duration = Duration::from_secs(30); +/// The helper's wait for its daemon to register the acceptor. +const REGISTER_WAIT: Duration = Duration::from_secs(15); +/// The pairing's 2 minutes, from a valid `ready`. +const PAIRING_WAIT: Duration = Duration::from_secs(120); +/// Once the attempt is decided, how long the other side gets to say how it +/// ended, and `ssh` to exit. +const WIND_DOWN: Duration = Duration::from_secs(10); + +/// What reaches the one loop of either side. +enum Input { + /// A line from the other side: B's stdout on A, A's lines on B. + Line(Result, ProtocolError>), + /// The other side closed its end. + LineEnd, + /// An answer of this machine's daemon. + Daemon(Value), + /// The daemon ended its stream, with the error it sent, if any. + DaemonEnd(Option), +} + +/// How a pairing ended, for a person or a program. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Report { + pub outcome: Outcome, + pub machine_id: Option, + pub name: Option, + /// This machine's pin, as its daemon verified it. + pub local: PinState, + /// The other machine's pin, as it said. + pub peer: PinState, + pub detail: String, +} + +impl Report { + /// Refused or cancelled before anything could be written. + pub fn refused(target: Option<&Target>, detail: impl Into) -> Self { + Self { + outcome: Outcome::Cancelled, + machine_id: target.map(|target| target.machine_id.clone()), + name: target.map(|target| target.name.clone()), + local: PinState::NotPinned, + peer: PinState::NotPinned, + detail: detail.into(), + } + } + + /// 0 paired on both sides, 2 nothing saved, 4 partial. + pub fn exit_code(&self) -> i32 { + exit_code(self.outcome) + } +} + +fn exit_code(outcome: Outcome) -> i32 { + match outcome { + Outcome::Paired => 0, + Outcome::Cancelled => 2, + Outcome::Partial => 4, + } +} + +/// Reads lines from the other side until it closes, as they come. After a +/// line that breaks the protocol, the rest is drained and dropped. +fn read_lines(input: impl Read + Send + 'static, tx: Sender) { + thread::spawn(move || { + let mut reader = BufReader::new(input); + let mut broken = false; + loop { + match ssh_pair::read_line(&mut reader) { + Ok(Some(line)) if !broken => { + broken = line.is_err(); + if tx.send(Input::Line(line)).is_err() { + return; + } + } + Ok(Some(_)) => {} + Ok(None) | Err(_) => { + let _ = tx.send(Input::LineEnd); + return; + } + } + } + }); +} + +/// Forwards the daemon's answers until it closes the stream. +fn read_daemon(mut stream: MgmtStream, tx: Sender) { + thread::spawn(move || { + loop { + match stream.next_answer() { + Ok(Some(answer)) => { + if tx.send(Input::Daemon(answer)).is_err() { + return; + } + } + Ok(None) => { + let _ = tx.send(Input::DaemonEnd(None)); + return; + } + Err(error) => { + let error = super::machines::daemon_error(error).to_string(); + let _ = tx.send(Input::DaemonEnd(Some(error))); + return; + } + } + } + }); +} + +/// `text`, or `fallback` when it is empty. +fn or_else(text: String, fallback: &str) -> String { + if text.is_empty() { + fallback.to_string() + } else { + text + } +} + +/// The time left until `deadline`. +fn left(deadline: Instant) -> Duration { + deadline.saturating_duration_since(Instant::now()) +} + +/// A pin state the daemon sent, `unknown` when it sent none this version +/// reads. +fn pin_state(value: &Value) -> PinState { + serde_json::from_value(value.clone()).unwrap_or(PinState::Unknown) +} + +/// The states and detail of a daemon's last pairing event: `paired`, +/// `cancelled` or `partial`. +fn ended(event: &Value) -> Option<(PinState, PinState, String)> { + let message = event["message"].as_str().unwrap_or_default().to_string(); + match event["event"].as_str()? { + "paired" => Some((PinState::Pinned, PinState::Pinned, String::new())), + "cancelled" => Some((PinState::NotPinned, PinState::NotPinned, message)), + "partial" => Some(( + pin_state(&event["local"]), + pin_state(&event["peer"]), + message, + )), + _ => None, + } +} + +// --- The accepting side -------------------------------------------------------- + +/// What A passed on B's command line. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HelperArgs { + /// A's machine id: only its pairing request may consume the acceptor. + pub from: String, + /// The account A is signed in to. + pub account: String, +} + +/// The helper is for a program at the other end of a pipe. A terminal on +/// either end means a person ran it by mistake. +pub fn refuse_terminal(stdin_is_terminal: bool, stdout_is_terminal: bool) -> Result<()> { + if stdin_is_terminal || stdout_is_terminal { + bail!( + "--for-ssh is what `{0} machines pair --over-ssh` starts on this machine, not something to run at a terminal. To pair by hand, run `{0} machines pair --accept`.", + BRANDING.cli_command() + ); + } + Ok(()) +} + +/// `localify machines pair --accept --for-ssh`: registers a one-shot +/// acceptor with this machine's daemon, then speaks the line protocol on +/// stdin and stdout. A failure before `ready` writes nothing to stdout. +/// Returns the exit code. +pub fn accept_for_ssh(client: &MgmtSocketClient, args: &HelperArgs) -> Result { + use std::io::IsTerminal; + refuse_terminal(io::stdin().is_terminal(), io::stdout().is_terminal())?; + run_helper(client, args, io::stdin(), &mut io::stdout()) +} + +/// The helper once the terminal check passed: `input` is what A writes, +/// `out` carries the protocol's lines only. +pub fn run_helper( + client: &MgmtSocketClient, + args: &HelperArgs, + input: impl Read + Send + 'static, + out: &mut impl Write, +) -> Result { + run_helper_within(client, args, input, out, REGISTER_WAIT) +} + +/// [`run_helper`], with `register_wait` for the daemon's first answer. +pub fn run_helper_within( + client: &MgmtSocketClient, + args: &HelperArgs, + input: impl Read + Send + 'static, + out: &mut impl Write, + register_wait: Duration, +) -> Result { + let command = json!({ + "cmd": "remote_pair_accept", "machineId": args.from, "account": args.account, + }); + let stream = client + .remote_stream(&command) + .map_err(super::machines::daemon_error)?; + let closer = stream.closer()?; + // A's stdin is watched from the start: closing it, or any line before + // `ready`, stops the registration. + let (tx, rx) = mpsc::channel(); + read_lines(input, tx.clone()); + read_daemon(stream, tx); + let ready = registered(&rx, register_wait).and_then(|ready| ready_line(&ready, args)); + let ready = match ready { + Ok(ready) => ready, + Err(error) => { + // Closing the stream cancels the acceptor, if it was made. + let _ = closer.shutdown(Shutdown::Both); + return Err(error); + } + }; + let HelperLine::Ready { attempt, .. } = &ready else { + bail!("The daemon's answer is not ready."); + }; + let attempt = attempt.clone(); + write_line(out, &ready.to_line())?; + let mut helper = Helper { + client, + closer, + code: None, + answered: false, + accepted: false, + }; + let (outcome, local, peer, detail) = helper.run(&rx, out, &attempt)?; + let result = HelperLine::Result { + attempt, + outcome, + local, + peer, + detail, + }; + write_line(out, &result.to_line())?; + Ok(exit_code(outcome)) +} + +/// The daemon's first answer, within `wait`, unless A gives up first. +fn registered(rx: &Receiver, wait: Duration) -> Result { + match rx.recv_timeout(wait) { + Ok(Input::Daemon(answer)) => Ok(answer), + Ok(Input::DaemonEnd(error)) => Err(anyhow!(error.unwrap_or_else(|| { + "The daemon closed the connection before it was ready.".into() + }))), + Ok(Input::Line(_) | Input::LineEnd) => { + bail!("The initiator gave up before this machine was ready.") + } + Err(_) => bail!( + "This machine's daemon did not answer within {} s.", + wait.as_secs_f32() + ), + } +} + +/// The daemon's `ready`, checked against what A expects. +fn ready_line(ready: &Value, args: &HelperArgs) -> Result { + let field = |name: &str| ready[name].as_str().unwrap_or_default().to_string(); + if ready["event"] != "ready" { + bail!("The daemon did not register the acceptor."); + } + let (machine_id, account) = (field("machineId"), field("account")); + if account != args.account { + bail!( + "This machine is signed in to another Localify Cloud account than the one asked for." + ); + } + if machine_id.is_empty() || machine_id == args.from { + bail!("This machine's daemon reports no machine id of its own, or the initiator's."); + } + Ok(HelperLine::Ready { + machine_id, + account, + attempt: field("attempt"), + }) +} + +fn write_line(out: &mut impl Write, line: &str) -> Result<()> { + out.write_all(line.as_bytes())?; + out.flush()?; + Ok(()) +} + +struct Helper<'a> { + client: &'a MgmtSocketClient, + /// Closes the daemon stream: before the code, that cancels the acceptor. + closer: UnixStream, + /// The pairing id and the code, once the daemon showed it. + code: Option<(String, String)>, + /// A's confirm or cancel was acted on; later lines change nothing. + answered: bool, + /// This side sent its acceptance to the daemon. + accepted: bool, +} + +impl Helper<'_> { + /// Until the daemon says how the pairing ended. + fn run( + &mut self, + rx: &Receiver, + out: &mut impl Write, + attempt: &str, + ) -> Result<(Outcome, PinState, PinState, String)> { + // The daemon's 2 minutes decide; this only bounds a stuck daemon. + let deadline = Instant::now() + PAIRING_WAIT + WIND_DOWN; + loop { + match rx.recv_timeout(left(deadline)) { + Ok(Input::Daemon(event)) if event["event"] == "code" => { + let code = event["code"].as_str().unwrap_or_default().to_string(); + let pairing_id = event["pairingId"].as_str().unwrap_or_default(); + self.code = Some((pairing_id.to_string(), code.clone())); + let line = HelperLine::Code { + attempt: attempt.to_string(), + code, + }; + write_line(out, &line.to_line())?; + } + Ok(Input::Daemon(event)) => { + if let Some((local, peer, detail)) = ended(&event) { + return Ok((Outcome::of(local, peer), local, peer, detail)); + } + } + Ok(Input::DaemonEnd(error)) => return Ok(self.lost(error)), + Ok(Input::Line(Ok(line))) => match ssh_pair::parse_control_line(&line) { + Ok(ControlLine::Confirm(code)) => self.confirm(&code), + Ok(ControlLine::Cancel) => self.cancel("The initiator cancelled."), + Err(error) => self.cancel(&format!("The initiator sent {error}.")), + }, + Ok(Input::Line(Err(error))) => { + self.cancel(&format!("The initiator sent {error}.")); + } + Ok(Input::LineEnd) => { + self.cancel("The initiator closed stdin before it confirmed.") + } + Err(RecvTimeoutError::Timeout | RecvTimeoutError::Disconnected) => { + self.cancel("The daemon did not say how the pairing ended."); + return Ok(self.lost(None)); + } + } + } + } + + /// Confirms only on this side's own code, exactly; anything else + /// cancels. + fn confirm(&mut self, code: &str) { + let pairing_id = match &self.code { + Some((pairing_id, mine)) if mine == code => pairing_id.clone(), + Some(_) => return self.cancel("The initiator confirmed another code."), + None => return self.cancel("The initiator confirmed before the code."), + }; + if self.answered { + return; + } + self.answered = true; + // Even without a reply, the daemon may have taken it. + self.accepted = true; + if let Err(error) = self.client.remote_pair_answer(&pairing_id, true) { + eprintln!("Could not confirm the pairing: {error}"); + } + } + + fn cancel(&mut self, why: &str) { + if self.answered { + return; + } + self.answered = true; + eprintln!("{why}"); + match &self.code { + Some((pairing_id, _)) => { + if let Err(error) = self.client.remote_pair_answer(pairing_id, false) { + eprintln!("Could not cancel the pairing: {error}"); + } + } + // Closing the stream cancels the acceptor. + None => { + let _ = self.closer.shutdown(Shutdown::Both); + } + } + } + + /// The daemon's stream ended without a last event. + fn lost(&self, error: Option) -> (Outcome, PinState, PinState, String) { + let detail = error.unwrap_or_else(|| "The pairing ended before it started.".into()); + if self.accepted { + ( + Outcome::Partial, + PinState::Unknown, + PinState::Unknown, + detail, + ) + } else { + // This side never accepted, so neither side could write a pin. + ( + Outcome::Cancelled, + PinState::NotPinned, + PinState::NotPinned, + detail, + ) + } + } +} + +// --- The initiating side ------------------------------------------------------- + +/// The machine to pair with, and the account both must share. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Target { + pub machine_id: String, + pub name: String, + /// This machine's id: the only one B's acceptor takes a request from. + pub own_id: String, + /// This machine's account: B's daemon must report the same. + pub account: String, +} + +/// The other end: B's helper through `ssh`, or in tests, a helper run +/// here on pipes. +pub struct Peer { + stdin: Option>, + child: Option, + tx: Sender, + rx: Receiver, +} + +impl Peer { + /// Runs `command` directly, without a local shell, with all three + /// streams piped: `ssh`, or in tests the helper itself. + pub fn spawn(mut command: Command, name: &str) -> io::Result { + let mut child = command + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn()?; + let (Some(stdin), Some(stdout), Some(stderr)) = + (child.stdin.take(), child.stdout.take(), child.stderr.take()) + else { + let _ = child.kill(); + let _ = child.wait(); + return Err(io::Error::other("ssh started without its pipes")); + }; + let mut peer = Self::from_pipes(stdin, stdout, stderr, name); + peer.child = Some(child); + Ok(peer) + } + + /// The other end on these pipes. Its stdout and stderr are drained at + /// once, so neither can block it. + pub fn from_pipes( + stdin: impl Write + Send + 'static, + stdout: impl Read + Send + 'static, + stderr: impl Read + Send + 'static, + name: &str, + ) -> Self { + let (tx, rx) = mpsc::channel(); + read_lines(stdout, tx.clone()); + log_diagnostics(stderr, name.to_string()); + Self { + stdin: Some(Box::new(stdin)), + child: None, + tx, + rx, + } + } + + fn send(&mut self, line: &ControlLine) -> bool { + let Some(stdin) = &mut self.stdin else { + return false; + }; + stdin.write_all(line.to_line().as_bytes()).is_ok() && stdin.flush().is_ok() + } + + fn close_stdin(&mut self) { + self.stdin = None; + } + + /// Waits up to `wait` for the child to exit, then kills it; reaps it + /// either way. + fn reap(&mut self, wait: Duration) -> Option { + let mut child = self.child.take()?; + let deadline = Instant::now() + wait; + loop { + match child.try_wait() { + Ok(Some(status)) => return Some(status), + Ok(None) if Instant::now() < deadline => thread::sleep(Duration::from_millis(50)), + _ => { + let _ = child.kill(); + return child.wait().ok(); + } + } + } + } +} + +impl Drop for Peer { + fn drop(&mut self) { + self.close_stdin(); + self.reap(Duration::ZERO); + } +} + +/// B's stderr goes to this machine's, line by line, without control +/// characters; it is never parsed. +fn log_diagnostics(stderr: impl Read + Send + 'static, name: String) { + thread::spawn(move || { + let mut reader = BufReader::new(stderr); + let mut chunk = Vec::new(); + loop { + chunk.clear(); + let read = (&mut reader) + .take(ssh_pair::MAX_LINE as u64) + .read_until(b'\n', &mut chunk); + match read { + Ok(0) | Err(_) => return, + Ok(_) => { + let text: String = String::from_utf8_lossy(&chunk) + .chars() + .filter(|c| !c.is_control() || *c == '\t') + .collect(); + eprintln!("{name}: {text}"); + } + } + } + }); +} + +/// Runs a pairing with the helper on `peer`, from its `ready` on, through +/// this machine's daemon. `started` is when `ssh` started. +pub fn drive(own: &MgmtSocketClient, target: &Target, peer: Peer, started: Instant) -> Report { + let mut run = Run { + own, + target, + peer, + lines: HelperLines::default(), + ours: None, + theirs: None, + decided: None, + own_closer: None, + own_end: None, + own_closed: false, + peer_result: None, + peer_done: false, + peer_eof: false, + broke: None, + failure: None, + }; + let attempt = match run.await_ready(started + READY_WAIT) { + Ok(attempt) => attempt, + Err(why) => { + run.peer.send(&ControlLine::Cancel); + run.peer.close_stdin(); + run.peer.reap(Duration::from_secs(2)); + return Report::refused(Some(target), why); + } + }; + run.pair(&attempt); + run.wind_down(); + run.report() +} + +struct Run<'a> { + own: &'a MgmtSocketClient, + target: &'a Target, + peer: Peer, + lines: HelperLines, + /// This machine's pairing id and code, once its daemon showed them. + ours: Option<(String, String)>, + /// B's code. + theirs: Option, + /// `Some(true)` once both sides were told to confirm, `Some(false)` + /// once they were told to cancel. + decided: Option, + own_closer: Option, + /// This machine's last pairing event. + own_end: Option, + own_closed: bool, + /// B's `result`: outcome, its own pin, its view of this machine's. + peer_result: Option<(PinState, String)>, + /// B said how it ended, closed its stdout, or broke the protocol. + peer_done: bool, + /// B's stdout closed. Its lines are checked until then, so a line after + /// its `result` still breaks the protocol and undoes that result. + peer_eof: bool, + /// How B's stdout broke the protocol. From then on, none of its lines + /// is trusted, not even an earlier `result`. + broke: Option, + /// Why the attempt ended early, for the report. + failure: Option, +} + +impl Run<'_> { + /// The first line must be `ready`, for the machine and account + /// expected. Returns its attempt. + fn await_ready(&mut self, deadline: Instant) -> Result { + let name = self.target.name.clone(); + loop { + match self.peer.rx.recv_timeout(left(deadline)) { + Ok(Input::Line(Ok(line))) => { + return match self.lines.take(&line) { + Ok(HelperLine::Ready { + machine_id, + account, + attempt, + }) => self.check_ready(&machine_id, &account).map(|()| attempt), + Ok(_) => Err(format!("{name} did not start with ready.")), + Err(error) => Err(format!( + "{name} sent a line this version cannot take: {error}." + )), + }; + } + Ok(Input::Line(Err(error))) => { + return Err(format!( + "{name} sent a line this version cannot take: {error}." + )); + } + Ok(Input::LineEnd) => return Err(self.ended_early()), + Ok(Input::Daemon(_) | Input::DaemonEnd(_)) => {} + Err(_) => { + return Err(format!( + "{name} was not ready within {} s: ssh could not connect, or Localify there did not answer.", + READY_WAIT.as_secs() + )); + } + } + } + } + + fn check_ready(&self, machine_id: &str, account: &str) -> Result<(), String> { + let target = self.target; + if machine_id != target.machine_id { + return Err(format!( + "The machine reached over SSH is {machine_id}, not {} ({}). Check the destination.", + target.name, target.machine_id + )); + } + if account != target.account { + return Err(format!( + "{} is signed in to another Localify Cloud account than this machine.", + target.name + )); + } + Ok(()) + } + + /// B's stdout closed before `ready`: say why, from its exit status. + fn ended_early(&mut self) -> String { + let status = self.peer.reap(Duration::from_secs(2)); + let name = &self.target.name; + match status.and_then(|status| status.code()) { + Some(127) => format!( + "Localify was not found on {name} by the non-interactive shell ssh runs. Pass its absolute path with --remote-localify." + ), + Some(255) => format!( + "ssh could not reach {name}; its message is above. Its host key must already be trusted, and no password prompt is possible." + ), + Some(code) => format!( + "The accepting side on {name} stopped before it was ready (exit {code}); its message is above." + ), + None => format!("The accepting side on {name} stopped before it was ready."), + } + } + + /// From a valid `ready` to both sides' ends, within 2 minutes. + fn pair(&mut self, attempt: &str) { + let deadline = Instant::now() + PAIRING_WAIT; + let command = json!({ + "cmd": "remote_pair", "machineId": self.target.machine_id, "attempt": attempt, + }); + match self.own.remote_stream(&command) { + Ok(stream) => { + self.own_closer = stream.closer().ok(); + read_daemon(stream, self.peer.tx.clone()); + } + Err(error) => { + self.own_closed = true; + self.abandon(format!( + "This machine's daemon could not start the pairing: {error}" + )); + } + } + while !(self.own_done() && self.peer_done) { + match self.peer.rx.recv_timeout(left(deadline)) { + Ok(input) => self.take(input), + Err(_) => { + let name = &self.target.name; + self.abandon(format!( + "The pairing with {name} did not finish within 2 minutes." + )); + return; + } + } + } + } + + fn own_done(&self) -> bool { + self.own_end.is_some() || self.own_closed + } + + fn take(&mut self, input: Input) { + match input { + Input::Daemon(event) if event["event"] == "code" => { + let code = event["code"].as_str().unwrap_or_default().to_string(); + let pairing_id = event["pairingId"].as_str().unwrap_or_default().to_string(); + self.ours = Some((pairing_id, code)); + self.decide(); + } + Input::Daemon(event) => { + if let Some((_, _, detail)) = ended(&event) { + self.own_end = Some(event); + self.abandon(or_else( + detail, + "This machine's side of the pairing ended first.", + )); + } + } + Input::DaemonEnd(error) => { + self.own_closed = true; + let why = + error.unwrap_or_else(|| "This machine's daemon ended the pairing.".into()); + self.abandon(why); + } + Input::Line(Ok(line)) => self.take_line(&line), + Input::Line(Err(error)) => self.broken(&error), + Input::LineEnd if self.broke.is_some() => self.peer_eof = true, + Input::LineEnd => { + self.peer_eof = true; + self.peer_done = true; + let name = &self.target.name; + self.abandon(format!( + "The accepting side on {name} stopped before it answered." + )); + } + } + } + + fn take_line(&mut self, line: &[u8]) { + if self.broke.is_some() { + return; + } + match self.lines.take(line) { + Ok(HelperLine::Code { code, .. }) => { + self.theirs = Some(code); + self.decide(); + } + Ok(HelperLine::Result { local, detail, .. }) => { + let name = &self.target.name; + let why = or_else( + detail.clone(), + &format!("{name}'s side of the pairing ended first."), + ); + self.peer_result = Some((local, detail)); + self.peer_done = true; + self.abandon(why); + } + Ok(HelperLine::Ready { .. }) => {} + Err(error) => self.broken(&error), + } + } + + /// A line that breaks the protocol ends the attempt: nothing from B's + /// stdout is trusted any more, and the report says why, even after + /// both sides were told to confirm. + fn broken(&mut self, error: &ProtocolError) { + if self.broke.is_some() { + return; + } + let name = &self.target.name; + let why = format!("{name} sent a line this version cannot take: {error}."); + self.broke = Some(why.clone()); + self.peer_result = None; + self.peer_done = true; + self.abandon(why); + self.peer.close_stdin(); + } + + /// Once both codes are in: confirm both sides on a match, cancel both + /// otherwise. + fn decide(&mut self) { + let (Some((pairing_id, ours)), Some(theirs), None) = + (&self.ours, &self.theirs, self.decided) + else { + return; + }; + let pairing_id = pairing_id.clone(); + if ours != theirs { + let message = format!( + "The codes differ: {} shows {theirs}, this machine {ours}. Something between the machines changed the pairing.", + self.target.name + ); + return self.abandon(message); + } + let code = ours.clone(); + if !self.peer.send(&ControlLine::Confirm(code)) { + let name = &self.target.name; + return self.abandon(format!("Could not confirm on {name}: its stdin closed.")); + } + self.decided = Some(true); + if let Err(error) = self.own.remote_pair_answer(&pairing_id, true) { + self.failure + .get_or_insert(format!("Could not confirm on this machine: {error}")); + } + } + + /// Cancels both sides, unless they were already told to confirm or + /// cancel. + fn abandon(&mut self, why: String) { + if self.decided.is_some() { + return; + } + self.decided = Some(false); + self.failure.get_or_insert(why); + self.peer.send(&ControlLine::Cancel); + match &self.ours { + Some((pairing_id, _)) if !self.own_done() => { + let _ = self.own.remote_pair_answer(pairing_id, false); + } + // Before the code, closing the stream cancels the pairing. + _ => self.close_own(), + } + } + + fn close_own(&mut self) { + if let Some(closer) = self.own_closer.take() { + let _ = closer.shutdown(Shutdown::Both); + } + } + + /// Both sides get a little time to say how they ended; then B's stdin + /// closes, and `ssh` is reaped. + fn wind_down(&mut self) { + let deadline = Instant::now() + WIND_DOWN; + // B ends once its stdin closes. Everything it still writes is checked + // until its stdout closes: a line after its `result` breaks the + // protocol, and that result is no longer trusted. + self.peer.close_stdin(); + while !(self.own_done() && self.peer_eof) { + match self.peer.rx.recv_timeout(left(deadline)) { + Ok(Input::Daemon(event)) if ended(&event).is_some() => self.own_end = Some(event), + Ok(Input::DaemonEnd(_)) => self.own_closed = true, + Ok(Input::Line(Ok(line))) => self.take_line(&line), + Ok(Input::Line(Err(error))) => self.broken(&error), + Ok(Input::LineEnd) => { + self.peer_eof = true; + self.peer_done = true; + } + Ok(_) => {} + Err(_) => break, + } + } + self.close_own(); + self.peer.reap(WIND_DOWN); + } + + /// Both sides' states: this one's from its daemon, B's from its own + /// `result`, else from what this daemon heard. + fn report(&self) -> Report { + let accepted = self.decided == Some(true); + let (local, heard, own_detail) = match self.own_end.as_ref().and_then(ended) { + Some(states) => states, + None if accepted => (PinState::Unknown, PinState::Unknown, String::new()), + None => (PinState::NotPinned, PinState::NotPinned, String::new()), + }; + // B accepts only on this machine's confirm line. + let (peer, peer_detail) = match &self.peer_result { + Some((state, detail)) => (*state, detail.clone()), + // After a break, B is never reported pinned: the attempt failed, + // and it exits 2 or 4. + None if accepted && self.broke.is_some() && heard == PinState::Pinned => { + (PinState::Unknown, String::new()) + } + None if accepted => (heard, String::new()), + None => (PinState::NotPinned, String::new()), + }; + let outcome = Outcome::of(local, peer); + let nonempty = |detail: String| Some(detail).filter(|detail| !detail.is_empty()); + let detail = match outcome { + // The break is the first thing to know, whatever the states. + _ if self.broke.is_some() => self.broke.clone(), + Outcome::Paired => None, + // Why it stopped; the states already say what each side saved. + Outcome::Partial => self.failure.clone().or_else(|| { + let reason = self.own_end.as_ref()?["reason"].as_str()?; + Some(format!("This machine's side ended with {reason}.")) + }), + Outcome::Cancelled => self + .failure + .clone() + .filter(|_| !accepted) + .or_else(|| nonempty(own_detail)) + .or_else(|| nonempty(peer_detail)), + } + .unwrap_or_default(); + Report { + outcome, + machine_id: Some(self.target.machine_id.clone()), + name: Some(self.target.name.clone()), + local, + peer, + detail, + } + } +} diff --git a/src/daemon/mgmt_socket.rs b/src/daemon/mgmt_socket.rs index 74012d82..1f4c3aa8 100644 --- a/src/daemon/mgmt_socket.rs +++ b/src/daemon/mgmt_socket.rs @@ -13,8 +13,8 @@ use super::lifecycle::ShutdownHandle; use super::public_tunnel::PublicTunnel; use super::remote::local::build_snapshot; use super::remote::{ - AccessEvent, Asking, ControlAsk, ControlEvent, Failure, FollowEvent, Following, PairEvent, - RemoteLink, + Accepted, AccessEvent, Asking, ControlAsk, ControlEvent, Failure, FollowEvent, Following, + PairEvent, RemoteLink, }; use super::router::SharedState; use crate::application::inventory::Have; @@ -82,9 +82,20 @@ enum MgmtCommand { #[serde(flatten)] change: SettingsChange, }, - /// Streaming: the code, then `paired` or `cancelled`. + /// Streaming: the code, then `paired`, `cancelled` or `partial`. + /// `attempt` only tags the events, for the SSH helper's lines. #[serde(rename = "remote_pair", rename_all = "camelCase")] - RemotePair { machine_id: String }, + RemotePair { + machine_id: String, + #[serde(default)] + attempt: Option, + }, + /// Streaming, for `localify machines pair --accept --for-ssh`: `ready` + /// once a one-shot acceptor for that account and that initiating + /// machine is registered, then the code and how the pairing ended. + /// Closing the connection cancels it. + #[serde(rename = "remote_pair_accept", rename_all = "camelCase")] + RemotePairAccept { machine_id: String, account: String }, #[serde(rename = "remote_pair_answer", rename_all = "camelCase")] RemotePairAnswer { pairing_id: String, accept: bool }, #[serde(rename = "remote_unpair", rename_all = "camelCase")] @@ -324,8 +335,22 @@ pub async fn serve( let command = parse_command(&line); match command { - Some(MgmtCommand::RemotePair { machine_id }) => { - return stream_pairing(&remote, &machine_id, reader, writer).await; + Some(MgmtCommand::RemotePair { + machine_id, + attempt, + }) => { + let events = remote.pair(&machine_id).await; + return stream_pairing(events, attempt, None, reader, writer).await; + } + Some(MgmtCommand::RemotePairAccept { + machine_id, + account, + }) => { + let (ready, events) = match remote.accept(&machine_id, &account).await { + Ok((accepted, events)) => (Some(accepted), Ok(events)), + Err(error) => (None, Err(error)), + }; + return stream_pairing(events, None, ready, reader, writer).await; } Some(MgmtCommand::RemoteEvents { access }) => { return stream_events(&remote, access, reader, writer).await; @@ -578,28 +603,42 @@ async fn client_gone(reader: &mut BufReader) { } } -/// `remote_pair`: one line per event until the pairing ends. Closing the -/// connection cancels the pairing. +/// `remote_pair` and `remote_pair_accept`: `ready` first for an acceptor, +/// then one line per event until the pairing ends. Closing the connection +/// cancels the pairing. async fn stream_pairing( - remote: &RemoteLink, - machine_id: &str, + events: anyhow::Result>, + attempt: Option, + ready: Option, mut reader: BufReader, mut writer: OwnedWriteHalf, ) { - let mut events = match remote.pair(machine_id).await { + let mut events = match events { Ok(events) => events, Err(error) => { write_line(&mut writer, &MgmtResponse::error(format!("{error:#}"))).await; return; } }; + if let Some(ready) = ready { + let Ok(mut data) = serde_json::to_value(&ready) else { + return; + }; + data["event"] = "ready".into(); + if !write_line(&mut writer, &MgmtResponse::success(data)).await { + return; + } + } loop { tokio::select! { _ = client_gone(&mut reader) => return, event = events.recv() => { let Some(event) = event else { return }; let last = !matches!(event, PairEvent::Code { .. }); - let Ok(data) = serde_json::to_value(&event) else { return }; + let Ok(mut data) = serde_json::to_value(&event) else { return }; + if let Some(attempt) = &attempt { + data["attempt"] = attempt.clone().into(); + } if !write_line(&mut writer, &MgmtResponse::success(data)).await || last { return; } diff --git a/src/daemon/remote/actor.rs b/src/daemon/remote/actor.rs index a1fa40f5..a1573dae 100644 --- a/src/daemon/remote/actor.rs +++ b/src/daemon/remote/actor.rs @@ -45,15 +45,16 @@ use super::socket::RelaySocket; use super::{Shared, View}; use crate::daemon::public_tunnel::Clocks; use crate::infrastructure::cloud::api::CloudClient; +use crate::infrastructure::launch_rev::random_bytes; use crate::infrastructure::remote::noise::{ HASH_LEN, Handshake, KEY_LEN, SessionContext, SessionId, StaticKeys, Transport, decode_key, encode_key, }; -use crate::infrastructure::remote::pairing::{Pairing, Step}; +use crate::infrastructure::remote::pairing::{Outcome, Pairing, PinState, Step}; use crate::infrastructure::remote::store::{Pin, now_rfc3339}; use crate::infrastructure::remote::wire::{ - AccessOutcome, AccessWants, ByeReason, DeclineReason, FrameKind, Hello, PresenceState, Purpose, - RelayFrame, Role, Send, SessionMessage, unknown_control_field, + AccessOutcome, AccessWants, ByeReason, DeclineReason, FrameKind, Hello, PROTO_PAIR_SAVED, + PresenceState, Purpose, RelayFrame, Role, Send, SessionMessage, unknown_control_field, }; /// A target handles at most this many handshakes at once. @@ -102,6 +103,30 @@ pub enum PairEvent { reason: String, message: String, }, + /// The session ended after a `pair.confirm`, and the two sides are not + /// both known to hold the other's pin (`docs/remote-machines.md`, + /// "Partial results"). + Partial { + machine_id: String, + name: String, + local: PinState, + peer: PinState, + reason: String, + message: String, + }, +} + +/// What the `--for-ssh` helper's acceptor answers once it is registered. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Accepted { + /// This machine's id, which the initiator checks against the one it + /// resolved. + pub machine_id: String, + pub account: String, + /// A fresh id that tags the helper's lines; a correlation id, not a + /// check. + pub attempt: String, } /// What `remote_events` clients hear. @@ -130,6 +155,16 @@ pub enum Event { machine_id: String, reason: String, }, + /// The pairing ended with only one side known to hold a pin. + PairPartial { + pairing_id: String, + machine_id: String, + name: String, + local: PinState, + peer: PinState, + /// Why; `unconfirmed` when the peer's version cannot say it saved. + reason: String, + }, Presence { machine_id: String, state: PresenceState, @@ -181,6 +216,14 @@ pub enum Command { accept: bool, reply: oneshot::Sender, }, + /// Registers the one-shot acceptor of `localify machines pair --accept + /// --for-ssh`: only a pairing request from `from` consumes it. + Accept { + from: String, + account: String, + events: mpsc::Sender, + reply: oneshot::Sender>, + }, Unpair { peer: String, }, @@ -302,7 +345,16 @@ struct Session { not_responding: bool, pairing: Option, code_shown: bool, + /// This side wrote its pin in this pairing. paired: bool, + /// The pairing ends at this time; by default its 2 minutes from the + /// first handshake message, or the acceptor's own deadline. + pair_deadline: Option, + /// After writing its pin and sending `pair.saved`, the side waits + /// until then for the peer's. + settle_until: Option, + /// The peer sent `pair.saved`: it durably wrote its pin. + peer_saved: bool, holder: Holder, /// Target: what the viewer asked for. served: target::Served, @@ -342,6 +394,9 @@ impl Session { pairing: None, code_shown: false, paired: false, + pair_deadline: None, + settle_until: None, + peer_saved: false, holder: Holder::None, served: target::Served::default(), taps: HashMap::new(), @@ -412,6 +467,17 @@ struct Actor { /// Target: cancels the controls of each peer not dispatched yet, once /// it is unpaired or paired again. control_cancels: HashMap, + /// Target: the `--for-ssh` helper's acceptor, until a pairing request + /// from its machine consumes it or it expires. + acceptor: Option, +} + +/// A one-shot acceptor, bound to the account and one initiating machine. +struct Acceptor { + from: String, + /// The pairing's 2 minutes, from registration. + deadline: Instant, + events: mpsc::Sender, } pub async fn run( @@ -453,6 +519,7 @@ pub async fn run( taps_made: 0, access_ended: VecDeque::new(), control_cancels: HashMap::new(), + acceptor: None, }; let mut tick = tokio::time::interval(timings.tick); tick.set_missed_tick_behavior(MissedTickBehavior::Delay); @@ -1034,6 +1101,16 @@ impl Actor { if role == Role::Viewer && purpose == Purpose::Pair { session.pairing = Some(Pairing::initiator(hash)); } + // A different key for an existing pin never replaces it silently. + if purpose == Purpose::Pair + && let Some(failure) = self.pin_conflict(&key.0, remote) + { + self.send_message( + key, + &SessionMessage::error("key_mismatch", failure.message.clone()), + ); + return self.end(key, End::Close, &failure); + } if role == Role::Target && purpose == Purpose::Session { if let Err(failure) = self.peer_check(&key.0, remote) { let code = if failure.code == "key_mismatch" { @@ -1099,6 +1176,35 @@ impl Actor { result } + /// A pin for `peer` with another key than the one the pairing + /// handshake gave. + fn pin_conflict(&self, peer: &str, remote: Option<[u8; KEY_LEN]>) -> Option { + let pins = self.shared.store.pins().unwrap_or_default(); + let pin = pins.get(peer)?; + if remote.is_some() && decode_key(&pin.public_key).ok() == remote { + return None; + } + Some(self.key_mismatch(peer)) + } + + /// A pairing met a pin of another key for `peer`: it never replaces it. + fn key_mismatch(&self, peer: &str) -> Failure { + self.view() + .failures + .insert(peer.to_string(), "key_mismatch".into()); + Failure::new( + "key_mismatch", + "This machine already holds another key for it. Don't trust it until you know why: unpair it, then pair again.", + ) + } + + /// Whether the pins on disk hold `peer` with the key the handshake gave. + fn holds_pin(&self, peer: &str, remote: Option<[u8; KEY_LEN]>) -> bool { + let pins = self.shared.store.pins().unwrap_or_default(); + pins.get(peer) + .is_some_and(|pin| remote.is_some() && decode_key(&pin.public_key).ok() == remote) + } + fn hello(&self, role: Role, purpose: Purpose) -> Hello { // A pairing peer is not trusted yet: it learns no settings. let settings = (role == Role::Target && purpose == Purpose::Session).then(|| { @@ -1314,6 +1420,7 @@ impl Actor { | SessionMessage::PairNonce { .. } | SessionMessage::PairReveal { .. } | SessionMessage::PairConfirm { .. }) => self.on_pairing(key, &message), + SessionMessage::PairSaved => self.on_saved(key), _ => self.end( key, End::Error("bad_request", "Unexpected message.".into()), @@ -1397,21 +1504,28 @@ impl Actor { /// On the target, once both hellos are in: decline, or commit. fn start_pairing(&mut self, key: &Key) { let now = Instant::now(); - // Kept by the link, so a new connection does not reset the count. - let mut attempts = self.shared.pair_attempts(); - while attempts - .front() - .is_some_and(|at| now.duration_since(*at) >= HOUR) - { - attempts.pop_front(); - } - let oldest = attempts.front().copied(); - let full = attempts.len() >= PAIRINGS_PER_HOUR; - drop(attempts); let decline = |reason, retry_after| SessionMessage::PairDeclined { reason, retry_after, }; + // The `--for-ssh` helper's acceptor: only its machine consumes it, + // and its attempt was counted when it was registered. + let mine = |acceptor: &mut Acceptor| acceptor.from == key.0 && now < acceptor.deadline; + if let Some(acceptor) = self.acceptor.take_if(mine) { + if let Some(session) = self.sessions.get_mut(key) { + session.holder = Holder::Pair(acceptor.events); + session.pair_deadline = Some(acceptor.deadline); + } + return self.commit(key); + } + if self.acceptor.is_some() { + self.send_message(key, &decline(DeclineReason::Busy, Some(60))); + return self.end( + key, + End::Bye(ByeReason::Done), + &Failure::new("busy", "Busy."), + ); + } if self.shared.subscribers.load(Ordering::SeqCst) == 0 { self.send_message(key, &decline(DeclineReason::NobodyToConfirm, None)); return self.end( @@ -1420,22 +1534,12 @@ impl Actor { &Failure::new("nobody_to_confirm", "Nobody could confirm."), ); } - let another = self.sessions.iter().any(|(other, session)| { - other != key - && session.role == Role::Target - && session - .pairing - .as_ref() - .is_some_and(|pairing| !pairing.is_finished()) - }); - if another || full { - let retry_after = match oldest { - Some(oldest) if !another => HOUR - .saturating_sub(now.duration_since(oldest)) - .as_secs() - .max(1), - _ => 60, - }; + let busy = if self.pairing_active(Some(key)) { + Some(60) + } else { + self.pairing_room(now).err() + }; + if let Some(retry_after) = busy { self.send_message(key, &decline(DeclineReason::Busy, Some(retry_after))); return self.end( key, @@ -1444,6 +1548,43 @@ impl Actor { ); } self.shared.pair_attempts().push_back(now); + self.commit(key); + } + + /// Whether a pairing other than `except` is going on as the target. + fn pairing_active(&self, except: Option<&Key>) -> bool { + self.sessions.iter().any(|(other, session)| { + Some(other) != except + && session.role == Role::Target + && session + .pairing + .as_ref() + .is_some_and(|pairing| !pairing.is_finished()) + }) + } + + /// Whether the last hour leaves room for one more pairing attempt, or + /// how many seconds until it does. The link keeps the attempts, so a + /// new connection does not reset the count. + fn pairing_room(&self, now: Instant) -> Result<(), u64> { + let mut attempts = self.shared.pair_attempts(); + while attempts + .front() + .is_some_and(|at| now.duration_since(*at) >= HOUR) + { + attempts.pop_front(); + } + match attempts.front() { + Some(oldest) if attempts.len() >= PAIRINGS_PER_HOUR => Err(HOUR + .saturating_sub(now.duration_since(*oldest)) + .as_secs() + .max(1)), + _ => Ok(()), + } + } + + /// The responder's commitment, which starts the pairing. + fn commit(&mut self, key: &Key) { let Some(hash) = self.sessions.get(key).and_then(|session| session.hash) else { return; }; @@ -1462,6 +1603,79 @@ impl Actor { } } + /// `remote_pair_accept`: registers the helper's acceptor. Counted + /// against the hour's attempts now, as it is about to write `ready`, + /// and its 2 minutes start now. + fn register_acceptor( + &mut self, + from: String, + account: &str, + events: mpsc::Sender, + ) -> Result { + if account != self.ctx.account { + return Err(Failure::new( + "wrong_account", + "This machine is signed in to another Localify Cloud account than the one asked for.", + )); + } + if from == self.ctx.self_id { + return Err(Failure::new( + "bad_request", + "A machine cannot pair with itself.", + )); + } + if self + .acceptor + .as_ref() + .is_some_and(|acceptor| acceptor.events.is_closed()) + { + self.acceptor = None; + } + let now = Instant::now(); + if self.acceptor.is_some() || self.pairing_active(None) { + return Err(Failure::new( + "busy", + "Another pairing is going on on this machine. Try again in a minute.", + )); + } + if let Err(seconds) = self.pairing_room(now) { + return Err(Failure::new( + "busy", + format!( + "This machine took 5 pairing attempts in the last hour. Try again in {} min.", + seconds.div_ceil(60) + ), + )); + } + let mut bytes = [0_u8; 16]; + random_bytes(&mut bytes).map_err(|error| Failure::new("internal", format!("{error:#}")))?; + self.shared.pair_attempts().push_back(now); + self.acceptor = Some(Acceptor { + from, + deadline: now + self.shared.timings.pairing_timeout, + events, + }); + Ok(Accepted { + machine_id: self.ctx.self_id.clone(), + account: self.ctx.account.clone(), + attempt: URL_SAFE_NO_PAD.encode(bytes), + }) + } + + /// An acceptor whose 2 minutes ran out, or whose helper left, before a + /// request consumed it. Nothing was saved. + fn expire_acceptor(&mut self, now: Instant) { + let gone = + |acceptor: &mut Acceptor| now >= acceptor.deadline || acceptor.events.is_closed(); + if let Some(acceptor) = self.acceptor.take_if(gone) { + let failure = Failure::new( + "timeout", + "No pairing request came from that machine in time.", + ); + notify_failure(Holder::Pair(acceptor.events), &failure); + } + } + fn on_pairing(&mut self, key: &Key, message: &SessionMessage) { let Some(pairing) = self .sessions @@ -1556,48 +1770,94 @@ impl Actor { } } - /// Both people accepted: pin the key the handshake gave. + /// Both people accepted: pin the key the handshake gave. With a peer + /// of protocol 3, say so with `pair.saved` and wait for the peer's; an + /// older peer never says, so the session ends as it always did. fn paired(&mut self, key: &Key) { - let name = self.view().name_of(&key.0); let Some(peer_key) = self.sessions.get(key).and_then(|session| session.peer_key) else { return; }; - let pin = Pin { - public_key: encode_key(&peer_key), - name: name.clone(), - paired_at: now_rfc3339(), - }; - if let Err(error) = self.shared.store.update_pins(&self.ctx.self_id, |pins| { - pins.insert(key.0.clone(), pin); - }) { - let message = format!("The pin could not be saved: {error:#}"); - return self.end( - key, - End::Bye(ByeReason::Done), - &Failure::new("cancelled", message), - ); + if let Err(failure) = self.write_pin(key, peer_key) { + let how = if failure.code == "key_mismatch" { + End::Error("key_mismatch", failure.message.clone()) + } else { + End::Bye(ByeReason::Done) + }; + return self.end(key, how, &failure); } info!(peer = %key.0, "Paired"); // A pin with a new key: nothing the old key asked for goes on. self.cancel_controls(&key.0); self.view().failures.remove(&key.0); + let settle = Instant::now() + self.shared.timings.pair_settle; let Some(session) = self.sessions.get_mut(key) else { return; }; session.paired = true; - match &session.holder { - Holder::Pair(events) => { - let _ = events.try_send(PairEvent::Paired { - machine_id: key.0.clone(), - name, + if session.proto.unwrap_or(1) < PROTO_PAIR_SAVED { + return self.end( + key, + End::Bye(ByeReason::Done), + &Failure::new( + "unconfirmed", + "The other machine does not say whether it saved.", + ), + ); + } + session.settle_until = Some(settle); + self.send_message(key, &SessionMessage::PairSaved); + } + + /// Writes the pin, checking under the pins' lock that no pin of + /// another key appeared since the handshake: two pairings for the same + /// machine id never overwrite each other. + fn write_pin(&self, key: &Key, peer_key: [u8; KEY_LEN]) -> Result<(), Failure> { + let pin = Pin { + public_key: encode_key(&peer_key), + name: self.view().name_of(&key.0), + paired_at: now_rfc3339(), + }; + let mut conflict = false; + let written = + self.shared + .store + .update_pins(&self.ctx.self_id, |pins| match pins.get(&key.0) { + Some(held) if decode_key(&held.public_key).ok() != Some(peer_key) => { + conflict = true; + } + _ => { + pins.insert(key.0.clone(), pin); + } }); - } - _ => self.shared.emit(Event::Paired { - pairing_id: key.1.encode(), - machine_id: key.0.clone(), - name, - }), + if conflict { + return Err(self.key_mismatch(&key.0)); + } + written.map(drop).map_err(|error| { + Failure::new( + "pin_failed", + format!("The pin could not be saved: {error:#}"), + ) + }) + } + + /// The peer's `pair.saved`: it comes once, after both accepted and + /// this side's own pin step. Anything else breaks the pairing. + fn on_saved(&mut self, key: &Key) { + let Some(session) = self.sessions.get_mut(key) else { + return; + }; + let both_accepted = session + .pairing + .as_ref() + .is_some_and(|pairing| pairing.mine() == Some(true) && pairing.theirs() == Some(true)); + if !both_accepted || !session.paired || session.peer_saved { + return self.end( + key, + End::Error("bad_request", "Unexpected pair.saved.".into()), + &bad_request(), + ); } + session.peer_saved = true; self.end( key, End::Bye(ByeReason::Done), @@ -1605,6 +1865,82 @@ impl Actor { ); } + /// What each side holds once a pairing session ended: nothing when + /// neither could have written a pin, otherwise this side's pin as the + /// disk has it and the peer's as it said. + fn pin_states(&self, key: &Key, session: &Session, pairing: &Pairing) -> (PinState, PinState) { + // The peer writes its pin only once this side's `accept: true` + // arrived. + let peer_may_have_pinned = pairing.mine() == Some(true) && pairing.theirs() != Some(false); + if !session.paired && !peer_may_have_pinned { + return (PinState::NotPinned, PinState::NotPinned); + } + let local = if self.holds_pin(&key.0, session.peer_key) { + PinState::Pinned + } else { + PinState::NotPinned + }; + let peer = if session.peer_saved { + PinState::Pinned + } else { + PinState::Unknown + }; + (local, peer) + } + + /// Tells whoever waits on a pairing session how it ended. + fn report_pairing(&mut self, key: &Key, session: Session, failure: &Failure) { + let name = self.view().name_of(&key.0); + let states = session + .pairing + .as_ref() + .map(|pairing| self.pin_states(key, &session, pairing)); + let outcome = states.map_or(Outcome::Cancelled, |(local, peer)| Outcome::of(local, peer)); + let machine_id = key.0.clone(); + match (session.holder, outcome, states) { + (Holder::Pair(events), Outcome::Paired, _) => { + let _ = events.try_send(PairEvent::Paired { machine_id, name }); + } + (Holder::Pair(events), Outcome::Partial, Some((local, peer))) => { + let _ = events.try_send(PairEvent::Partial { + message: partial_message(&name, local, peer, failure), + machine_id, + name, + local, + peer, + reason: failure.code.clone(), + }); + } + (Holder::None, outcome, states) + if session.role == Role::Target && session.code_shown => + { + let pairing_id = key.1.encode(); + let event = match (outcome, states) { + (Outcome::Paired, _) => Event::Paired { + pairing_id, + machine_id, + name, + }, + (Outcome::Partial, Some((local, peer))) => Event::PairPartial { + pairing_id, + machine_id, + name, + local, + peer, + reason: failure.code.clone(), + }, + _ => Event::PairCancelled { + pairing_id, + machine_id, + reason: failure.code.clone(), + }, + }; + self.shared.emit(event); + } + (holder, _, _) => notify_failure(holder, failure), + } + } + fn forget_pin(&mut self, peer: &str) { let mut removed = false; if let Err(error) = self.shared.store.update_pins(&self.ctx.self_id, |pins| { @@ -1697,6 +2033,14 @@ impl Actor { } => { let _ = reply.send(self.on_answer(&pairing_id, accept)); } + Command::Accept { + from, + account, + events, + reply, + } => { + let _ = reply.send(self.register_acceptor(from, &account, events)); + } Command::Unpair { peer } => { self.cancel_controls(&peer); let keys: Vec = self @@ -1810,6 +2154,7 @@ impl Actor { self.check(&key, now); } self.expire_access(now); + self.expire_acceptor(now); self.serve_tick(now); } @@ -1846,11 +2191,21 @@ impl Actor { .pairing .as_ref() .is_some_and(|pairing| !pairing.is_finished()); - if pairing_open && now.duration_since(session.started) >= timings.pairing_timeout { + let deadline = session + .pair_deadline + .unwrap_or(session.started + timings.pairing_timeout); + if pairing_open && now >= deadline { return self.end( key, End::Bye(ByeReason::Done), - &Failure::new("timeout", "Pairing cancelled. Nothing was saved."), + &Failure::new("timeout", "The pairing timed out."), + ); + } + if session.settle_until.is_some_and(|until| now >= until) { + return self.end( + key, + End::Bye(ByeReason::Done), + &Failure::new("timeout", "The other machine did not say it saved its pin."), ); } let left = match &session.holder { @@ -1865,7 +2220,7 @@ impl Actor { self.end( key, End::Bye(ByeReason::Done), - &Failure::new("cancelled", "Pairing cancelled. Nothing was saved."), + &Failure::new("cancelled", "Nobody waits for this pairing any more."), ); } return; @@ -1989,15 +2344,8 @@ impl Actor { // The session is gone: the viewer hears nothing more. self.access_closed(&waiting.request_id, AccessOutcome::Cancelled); } - if session.paired { - return; - } - if session.role == Role::Target && session.code_shown { - self.shared.emit(Event::PairCancelled { - pairing_id: key.1.encode(), - machine_id: key.0.clone(), - reason: failure.code.clone(), - }); + if session.purpose == Purpose::Pair { + return self.report_pairing(key, session, failure); } notify_failure(session.holder, failure); } @@ -2038,6 +2386,9 @@ impl Actor { for key in keys { self.end(&key, End::Silent, failure); } + if let Some(acceptor) = self.acceptor.take() { + notify_failure(Holder::Pair(acceptor.events), failure); + } } } @@ -2063,6 +2414,29 @@ fn notify_failure(holder: Holder, failure: &Failure) { } } +/// What a person reads when only one side may hold a pin. +fn partial_message(name: &str, local: PinState, peer: PinState, failure: &Failure) -> String { + let here = match local { + PinState::Pinned => format!("This machine saved {name}'s key"), + _ => format!("This machine did not save {name}'s key"), + }; + let there = match peer { + PinState::Pinned => format!("{name} saved this machine's key"), + PinState::NotPinned => format!("{name} did not save this machine's key"), + PinState::Unknown => format!("{name} may or may not have saved this machine's key"), + }; + match failure.code.as_str() { + // Pairing again would end the same way. + "unconfirmed" => format!( + "{here}. {name} runs an older version of Localify, which does not say whether it saved this machine's key: check on {name}, or update Localify there and pair again." + ), + "key_mismatch" => format!("{} {here}; {there}.", failure.message), + _ => format!( + "Pairing did not finish on both machines. {here}; {there}. Pair them again to complete it." + ), + } +} + fn bad_request() -> Failure { Failure::new( "bad_request", diff --git a/src/daemon/remote/fake_relay.rs b/src/daemon/remote/fake_relay.rs index 8411db4b..50961829 100644 --- a/src/daemon/remote/fake_relay.rs +++ b/src/daemon/remote/fake_relay.rs @@ -33,10 +33,17 @@ use crate::infrastructure::app_bridge::{BridgeError, Handoff, LaunchRequest}; use crate::infrastructure::remote::control::{ ControlRunner, ControlTimings, DetachedLaunch, Expected, Host, Live, Look, Order, Spawned, }; -use crate::infrastructure::remote::noise::{Handshake, SessionContext, SessionId, StaticKeys}; +use crate::infrastructure::remote::noise::{ + HASH_LEN, Handshake, SessionContext, SessionId, StaticKeys, Transport, +}; +use crate::infrastructure::remote::pairing::{Pairing, Step}; use crate::infrastructure::remote::requests::{Report, RequestEntries}; +use crate::infrastructure::remote::store::now_rfc3339; use crate::infrastructure::remote::wire::ControlPhase; -use crate::infrastructure::remote::wire::{AppPresence, FrameKind, Purpose, Send}; +use crate::infrastructure::remote::wire::{ + AppPresence, ByeReason, FrameKind, Hello, ProtoRange, Purpose, Role as WireRole, Send, + SessionMessage, +}; use crate::infrastructure::running_services::ServiceKey; use crate::infrastructure::runs::RunId; use crate::infrastructure::runs::launches::{LaunchReport, RefusalCode, unix_ms_now}; @@ -75,6 +82,7 @@ struct State { sockets: HashMap>, hook: Option, mitm: Option, + legacy: Option, budgets: HashMap, refusals: u32, lease_requests: u32, @@ -216,6 +224,27 @@ impl FakeCloud { }); } + /// Plays `b` towards `a` in every pairing session as Localify 1.7.0 + /// does on the wire, and ends it as `ends` says. + pub fn play_legacy(&self, a: &str, b: &str, ends: LegacyEnd) { + self.state().legacy = Some(Legacy { + a: a.into(), + b: b.into(), + keys: StaticKeys::generate().unwrap(), + ends, + sessions: HashMap::new(), + heard: Vec::new(), + }); + } + + /// The messages `a` sent the legacy `b`, decrypted. + pub fn legacy_heard(&self) -> Vec { + self.state() + .legacy + .as_ref() + .map_or_else(Vec::new, |legacy| legacy.heard.clone()) + } + /// How many handshakes the relay completed with `b` as `a`. pub fn mitm_completed(&self) -> u32 { self.state() @@ -542,6 +571,14 @@ impl FakeCloud { return; } } + if let Some(replies) = self.as_legacy(&mut state, from, &frame) { + if let Some(socket) = state.sockets.get(from) { + for reply in replies { + let _ = socket.send(Message::text(reply.to_string())); + } + } + return; + } if let Some(handled) = self.in_the_middle(&mut state, from, &frame) { if let Some((to, value)) = handled && let Some(socket) = state.sockets.get(&to) @@ -670,6 +707,224 @@ impl FakeCloud { } } +/// How the 1.7.0 target the relay plays ends a pairing both sides accepted. +/// Either way, it says `bye` `done` and never `pair.saved`, which 1.7.0 +/// does not have, whether or not it saved its pin. +#[derive(Debug, Clone, Copy)] +pub enum LegacyEnd { + /// It took A's confirm, could not save its pin, and ended. + PinFailed, + /// Its 2 minutes ran out this long after its own confirm, before A's + /// confirm reached it. + Timeout(std::time::Duration), +} + +/// Localify 1.7.0 as a pairing target, on the wire: `hello` with versions +/// 1 to 2, the commitment and the reveal, its own `pair.confirm` with +/// `accept: true` once the code is out, then `bye` `done`. +struct Legacy { + a: String, + b: String, + keys: StaticKeys, + ends: LegacyEnd, + sessions: HashMap, + heard: Vec, +} + +enum LegacySession { + Handshake(Handshake), + Open { + transport: Transport, + hash: [u8; HASH_LEN], + pairing: Option, + }, +} + +impl FakeCloud { + /// A frame from `a` to the legacy `b`: what `b` answers, encrypted. + fn as_legacy(&self, state: &mut State, from: &str, frame: &Send) -> Option> { + let user = state.user_id.clone(); + let legacy = state.legacy.as_mut()?; + if from != legacy.a || frame.to != legacy.b { + return None; + } + let data = frame + .data + .as_deref() + .and_then(|data| URL_SAFE_NO_PAD.decode(data).ok()); + let (Some(data), Some(sid)) = (data, SessionId::parse(&frame.sid)) else { + return Some(Vec::new()); + }; + let b = legacy.b.clone(); + let reply = |data: &[u8], kind: &str| { + json!({"t": "recv", "from": b, "sid": frame.sid, "kind": kind, + "data": URL_SAFE_NO_PAD.encode(data)}) + }; + // Anything it cannot take, it drops, as the session would end. + Some( + self.legacy_reply(legacy, user, frame, sid, &data, reply) + .unwrap_or_default(), + ) + } + + fn legacy_reply( + &self, + legacy: &mut Legacy, + user: String, + frame: &Send, + sid: SessionId, + data: &[u8], + reply: impl Fn(&[u8], &str) -> Value, + ) -> Option> { + match (frame.kind, legacy.sessions.remove(&frame.sid)) { + (FrameKind::Hs, None) => { + let context = SessionContext { + purpose: frame.purpose?, + account: user, + initiator: legacy.a.clone(), + responder: legacy.b.clone(), + sid, + }; + let mut handshake = Handshake::responder(&legacy.keys, &context).ok()?; + handshake.read(data).ok()?; + let second = handshake.write().ok()?; + legacy + .sessions + .insert(frame.sid.clone(), LegacySession::Handshake(handshake)); + Some(vec![reply(&second, "hs")]) + } + (FrameKind::Hs, Some(LegacySession::Handshake(mut handshake))) => { + handshake.read(data).ok()?; + let (mut transport, hash) = handshake.finish().ok()?; + let hello = SessionMessage::Hello(Hello { + proto: ProtoRange { min: 1, max: 2 }, + version: "1.7.0".into(), + now: now_rfc3339(), + role: WireRole::Target, + settings: None, + app: None, + }); + let sealed = seal(&mut transport, &hello); + legacy.sessions.insert( + frame.sid.clone(), + LegacySession::Open { + transport, + hash, + pairing: None, + }, + ); + Some(vec![reply(&sealed, "msg")]) + } + ( + FrameKind::Msg, + Some(LegacySession::Open { + mut transport, + hash, + mut pairing, + }), + ) => { + let plaintext = transport.decrypt(data).ok()?; + let value: Value = serde_json::from_slice(&plaintext).ok()?; + legacy.heard.push(value.clone()); + let message: SessionMessage = serde_json::from_value(value).ok()?; + let (out, timer) = legacy_answer(legacy.ends, hash, &mut pairing, &message); + let sealed: Vec = out + .iter() + .map(|message| reply(&seal(&mut transport, message), "msg")) + .collect(); + legacy.sessions.insert( + frame.sid.clone(), + LegacySession::Open { + transport, + hash, + pairing, + }, + ); + if let Some(after) = timer { + self.legacy_timeout(frame.sid.clone(), after); + } + Some(sealed) + } + _ => None, + } + } + + /// The legacy `b`'s 2 minutes run out: `bye` `done`, nothing saved. + fn legacy_timeout(&self, sid: String, after: std::time::Duration) { + let cloud = self.clone(); + tokio::spawn(async move { + tokio::time::sleep(after).await; + let mut state = cloud.state(); + let Some(legacy) = state.legacy.as_mut() else { + return; + }; + let (a, b) = (legacy.a.clone(), legacy.b.clone()); + let Some(LegacySession::Open { transport, .. }) = legacy.sessions.get_mut(&sid) else { + return; + }; + let bye = seal(transport, &bye_done()); + let frame = json!({"t": "recv", "from": b, "sid": sid, "kind": "msg", + "data": URL_SAFE_NO_PAD.encode(bye)}); + if let Some(socket) = state.sockets.get(&a) { + let _ = socket.send(Message::text(frame.to_string())); + } + }); + } +} + +/// What the legacy `b` sends for `message`, and when its own timeout +/// fires, if it starts one. +fn legacy_answer( + ends: LegacyEnd, + hash: [u8; HASH_LEN], + pairing: &mut Option, + message: &SessionMessage, +) -> (Vec, Option) { + let sends = |steps: Vec| -> Vec { + steps + .into_iter() + .filter_map(|step| match step { + Step::Send(message) => Some(message), + _ => None, + }) + .collect() + }; + match (message, pairing.as_mut()) { + (SessionMessage::Hello(_), None) => { + let (started, commit) = Pairing::responder(hash).unwrap(); + *pairing = Some(started); + (vec![commit], None) + } + (SessionMessage::PairNonce { .. }, Some(pairing)) => { + // The code is out; its person accepts at once. + let mut out = sends(pairing.receive(message).unwrap()); + out.extend(sends(pairing.answer(true).unwrap())); + let timer = match ends { + LegacyEnd::Timeout(after) => Some(after), + LegacyEnd::PinFailed => None, + }; + (out, timer) + } + // Its pin could not be saved: 1.7.0 still ends with `bye` `done`. + (SessionMessage::PairConfirm { .. }, Some(_)) if matches!(ends, LegacyEnd::PinFailed) => { + (vec![bye_done()], None) + } + _ => (Vec::new(), None), + } +} + +fn bye_done() -> SessionMessage { + SessionMessage::Bye { + reason: ByeReason::Done, + } +} + +fn seal(transport: &mut Transport, message: &SessionMessage) -> Vec { + transport + .encrypt(&serde_json::to_vec(message).unwrap()) + .unwrap() +} + /// relay.ts's two budgets: 200 frames refilled at 50 a second, 5 MiB /// refilled at 512 KiB a second, and at most 32 frames or 512 KiB waiting /// behind the frame being handled. A refused frame takes nothing; the 50th diff --git a/src/daemon/remote/mod.rs b/src/daemon/remote/mod.rs index 11cf8a05..a09a6617 100644 --- a/src/daemon/remote/mod.rs +++ b/src/daemon/remote/mod.rs @@ -37,8 +37,8 @@ use tokio_util::sync::CancellationToken; use tracing::{info, warn}; pub use self::actor::Failure; +pub use self::actor::{Accepted, Event, PairEvent}; use self::actor::{Command, TapEvent, TapRequest}; -pub use self::actor::{Event, PairEvent}; use self::backoff::{Backoff, Ending, Next, Stop, random_fraction, up_to}; use self::lease::{LeaseError, LeaseKeeper}; use self::local::LocalSource; @@ -130,6 +130,9 @@ pub struct Timings { pub viewer_gives_up_after: Duration, pub target_gives_up_after: Duration, pub pairing_timeout: Duration, + /// After writing its pin, a side waits this long for the peer's `bye`, + /// which says the peer wrote its own. + pub pair_settle: Duration, pub idle_after: Duration, pub lifetime: Duration, pub tick: Duration, @@ -183,6 +186,7 @@ impl Default for Timings { viewer_gives_up_after: seconds(60), target_gives_up_after: seconds(90), pairing_timeout: seconds(120), + pair_settle: seconds(30), idle_after: seconds(120), lifetime: seconds(3600), tick: seconds(1), @@ -233,6 +237,10 @@ pub struct RemoteStatus { /// Why background starts run with the daemon's own environment: the /// user's shell environment could not be read. pub shell_environment_error: Option, + /// This machine's id and the account's user id, while connected: what + /// a pairing over SSH checks on both sides. + pub machine_id: Option, + pub account: Option, } /// What the link knows, for the management socket. @@ -301,6 +309,8 @@ struct Conn { lease: Arc, cloud: Arc, self_id: String, + /// The account's user id. + account: String, } struct Shared { @@ -562,6 +572,10 @@ impl RemoteLink { } pub fn status(&self) -> RemoteStatus { + let conn = self + .shared + .conn() + .filter(|_| self.shared.view().relay == RelayState::Connected); let view = self.shared.view(); let fingerprint = self .shared @@ -578,6 +592,8 @@ impl RemoteLink { settings: self.shared.store.settings().unwrap_or(DEFAULT_SETTINGS), fingerprint, shell_environment_error: self.shared.source.shell_environment_failure(), + machine_id: conn.as_ref().map(|conn| conn.self_id.clone()), + account: conn.map(|conn| conn.account), } } @@ -802,6 +818,32 @@ impl RemoteLink { Ok(receiver) } + /// Registers the one-shot acceptor of `localify machines pair --accept + /// --for-ssh`: only a pairing request from `from` consumes it, for the + /// account `account`. The events say the code, then how it ended. + pub async fn accept( + &self, + from: &str, + account: &str, + ) -> Result<(Accepted, mpsc::Receiver)> { + let conn = self.connected()?; + let (events, receiver) = mpsc::channel(16); + let (reply, accepted) = oneshot::channel(); + conn.commands + .send(Command::Accept { + from: from.to_string(), + account: account.to_string(), + events, + reply, + }) + .map_err(|_| anyhow!("The relay connection closed. Try again."))?; + match accepted.await { + Ok(Ok(accepted)) => Ok((accepted, receiver)), + Ok(Err(failure)) => bail!("{}", failure.message), + Err(_) => bail!("The relay connection closed. Try again."), + } + } + /// A person's answer to the code of a pairing, on either side. pub async fn answer(&self, pairing_id: &str, accept: bool) -> Result<()> { let conn = self.connected()?; @@ -1183,6 +1225,7 @@ async fn connect_and_serve( lease: Arc::clone(&lease), cloud: Arc::clone(&ready.cloud), self_id: ready.credentials.machine_id.clone(), + account: ready.account.user_id.clone(), }; shared.set_conn(Some(conn.clone())); // The names pins are saved with. diff --git a/src/daemon/remote/socket.rs b/src/daemon/remote/socket.rs index e1aa936b..998cf2c6 100644 --- a/src/daemon/remote/socket.rs +++ b/src/daemon/remote/socket.rs @@ -142,7 +142,7 @@ mod tests { assert_eq!(headers["Authorization"], "Bearer lfy_t"); assert_eq!(headers["Sec-WebSocket-Protocol"], "localify-remote.1"); assert_eq!(headers["X-Localify-Version"], env!("CARGO_PKG_VERSION")); - assert_eq!(headers["X-Localify-Proto"], "1-2"); + assert_eq!(headers["X-Localify-Proto"], "1-3"); } #[test] diff --git a/src/daemon/remote/tests.rs b/src/daemon/remote/tests.rs index 860a9b58..9bee4746 100644 --- a/src/daemon/remote/tests.rs +++ b/src/daemon/remote/tests.rs @@ -6,6 +6,7 @@ mod access; mod cli; mod control; mod convergence; +mod ssh_pairing; mod viewing; use std::sync::Arc; @@ -17,13 +18,15 @@ use tokio::sync::{broadcast, mpsc}; use tokio::time::Instant; use tokio_util::sync::CancellationToken; -use super::fake_relay::{FakeCloud, FakeSource, Route, is_message, opens}; +use super::fake_relay::{FakeCloud, FakeSource, LegacyEnd, Route, is_message, opens}; use super::local::LocalSource; use super::machines::{MachineState, RelayState, SessionState}; use super::{Event, PairEvent, RemoteLink, Timings, spawn}; use crate::infrastructure::cloud::credentials::{CloudCredentials, CredentialsStore}; use crate::infrastructure::remote::noise::{SessionId, StaticKeys, encode_key}; +use crate::infrastructure::remote::pairing::PinState; use crate::infrastructure::remote::store::RemoteStore; +use crate::infrastructure::remote::store::{Pin, now_rfc3339}; use crate::infrastructure::remote::wire::{FrameKind, Purpose}; fn fast() -> Timings { @@ -35,6 +38,7 @@ fn fast() -> Timings { viewer_gives_up_after: ms(2500), target_gives_up_after: ms(4000), pairing_timeout: ms(2500), + pair_settle: ms(1500), idle_after: ms(30_000), lifetime: ms(3_600_000), tick: ms(40), @@ -560,14 +564,26 @@ async fn a_pairing_nobody_answers_times_out_and_pins_nothing() { let cloud = FakeCloud::start().await; let (a, b) = two(&cloud).await; let mut subscription = b.link.subscribe(false); - let (mut events, id_a, _, _, _) = to_codes(&a, &b, &mut subscription.events).await; - // A accepts; B's person never answers. - a.link.answer(&id_a, true).await.unwrap(); + // Nobody answers on either side: nothing was saved. + let (mut events, _, _, _, _) = to_codes(&a, &b, &mut subscription.events).await; let PairEvent::Cancelled { reason, .. } = next_pair_event(&mut events).await else { panic!("not cancelled"); }; + // Whichever side's 2 minutes end first. assert!(reason == "timeout" || reason == "done", "{reason}"); assert!(!a.pinned("mB") && !b.pinned("mA")); + + // A accepts; B's person never answers. A cannot know B did not, so it + // reports a partial result, with its own state verified. + let (mut events, id_a, _, _, _) = to_codes(&a, &b, &mut subscription.events).await; + a.link.answer(&id_a, true).await.unwrap(); + let event = next_pair_event(&mut events).await; + let PairEvent::Partial { local, peer, .. } = &event else { + panic!("not partial: {event:?}"); + }; + assert_eq!((*local, *peer), (PinState::NotPinned, PinState::Unknown)); + tokio::time::sleep(Duration::from_millis(300)).await; + assert!(!a.pinned("mB") && !b.pinned("mA")); } #[tokio::test] @@ -664,6 +680,220 @@ async fn a_target_takes_one_pairing_at_a_time_and_five_an_hour() { assert_eq!(reason, "busy"); } +/// From B's `pair.confirm` with `accept: true` on, the relay swallows every +/// message B sends: the session is cut after the first confirm. The +/// confirm is the only message of its size, `{"t":"pair.confirm", +/// "accept":true}` and its 16-byte tag. +pub(super) fn cut_after_bs_confirm(cloud: &FakeCloud) { + let mut cut = false; + cloud.set_hook(Some(Box::new(move |from, frame| { + if from == "mB" && is_message(frame) { + let size = frame + .data + .as_deref() + .and_then(|data| { + base64::Engine::decode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, data) + .ok() + }) + .map_or(0, |bytes| bytes.len()); + cut |= size == 34 + 16; + if cut { + return Route::Swallow; + } + } + Route::Forward + }))); +} + +#[tokio::test] +async fn a_session_cut_after_a_confirm_is_partial_and_pairing_again_completes_it() { + let cloud = FakeCloud::start().await; + let (a, b) = two(&cloud).await; + let mut subscription = b.link.subscribe(false); + cut_after_bs_confirm(&cloud); + let (mut events, id_a, code_a, id_b, code_b) = to_codes(&a, &b, &mut subscription.events).await; + assert_eq!(code_a, code_b); + a.link.answer(&id_a, true).await.unwrap(); + b.link.answer(&id_b, true).await.unwrap(); + + // B had A's accept and saved; its confirm never reached A. + wait_until("B pins A", || b.pinned("mA")).await; + let event = next_pair_event(&mut events).await; + let PairEvent::Partial { local, peer, .. } = &event else { + panic!("not partial: {event:?}"); + }; + assert_eq!((*local, *peer), (PinState::NotPinned, PinState::Unknown)); + let Event::PairPartial { local, peer, .. } = next_event(&mut subscription.events, |event| { + matches!(event, Event::PairPartial { .. }) + }) + .await + else { + unreachable!() + }; + assert_eq!((local, peer), (PinState::Pinned, PinState::Unknown)); + assert!(!a.pinned("mB")); + + // The same machines and keys: pairing again completes it. + cloud.set_hook(None); + pair(&a, &b).await; +} + +#[tokio::test] +async fn pairing_never_replaces_a_pin_of_another_key() { + let cloud = FakeCloud::start().await; + let (a, b) = two(&cloud).await; + let other = pin_other_key(&a); + let _subscription = b.link.subscribe(false); + let mut events = a.link.pair("mB").await.unwrap(); + let event = next_pair_event(&mut events).await; + let PairEvent::Cancelled { reason, .. } = &event else { + panic!("not cancelled: {event:?}"); + }; + assert_eq!(reason, "key_mismatch"); + assert_eq!(a.store().pins().unwrap()["mB"].public_key, other); + assert!(!b.pinned("mA")); +} + +/// A pin for B with another key, written on A as another pairing would. +fn pin_other_key(a: &Daemon) -> String { + let other = encode_key(&StaticKeys::generate().unwrap().public); + a.store() + .update_pins("mA", |pins| { + pins.insert( + "mB".into(), + Pin { + public_key: other.clone(), + name: "teo-mini".into(), + paired_at: now_rfc3339(), + }, + ); + }) + .unwrap(); + other +} + +#[tokio::test] +async fn a_pin_of_another_key_written_during_a_pairing_is_never_replaced() { + let cloud = FakeCloud::start().await; + let (a, b) = two(&cloud).await; + let mut subscription = b.link.subscribe(false); + let (mut events, id_a, _, id_b, _) = to_codes(&a, &b, &mut subscription.events).await; + // Past the handshake's check: another pairing pins another key for B. + let other = pin_other_key(&a); + a.link.answer(&id_a, true).await.unwrap(); + b.link.answer(&id_b, true).await.unwrap(); + let event = next_pair_event(&mut events).await; + let PairEvent::Partial { + local, + reason, + message, + .. + } = &event + else { + panic!("not partial: {event:?}"); + }; + assert_eq!(reason, "key_mismatch"); + assert_eq!(*local, PinState::NotPinned); + assert!(message.contains("another key"), "{message}"); + assert_eq!(a.store().pins().unwrap()["mB"].public_key, other); + assert_eq!( + a.link.shared.view().failures.get("mB").map(String::as_str), + Some("key_mismatch") + ); +} + +#[tokio::test] +async fn the_peer_is_pinned_only_once_its_pair_saved_arrives() { + let cloud = FakeCloud::start().await; + let (a, b) = two(&cloud).await; + let mut subscription = b.link.subscribe(false); + // The relay swallows B's `pair.saved`, `{"t":"pair.saved"}` and its + // 16-byte tag; B's `bye` `done` still comes. + cloud.set_hook(Some(Box::new(|from, frame| { + let size = frame + .data + .as_deref() + .and_then(|data| { + base64::Engine::decode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, data).ok() + }) + .map_or(0, |bytes| bytes.len()); + if from == "mB" && is_message(frame) && size == 18 + 16 { + Route::Swallow + } else { + Route::Forward + } + }))); + let (mut events, id_a, _, id_b, _) = to_codes(&a, &b, &mut subscription.events).await; + a.link.answer(&id_a, true).await.unwrap(); + b.link.answer(&id_b, true).await.unwrap(); + let event = next_pair_event(&mut events).await; + let PairEvent::Partial { local, peer, .. } = &event else { + panic!("not partial: {event:?}"); + }; + assert_eq!((*local, *peer), (PinState::Pinned, PinState::Unknown)); + // B heard A's `pair.saved`. + next_event(&mut subscription.events, |event| { + matches!(event, Event::Paired { .. }) + }) + .await; + assert!(a.pinned("mB") && b.pinned("mA")); + + // Both acknowledgements through: paired on both sides. + cloud.set_hook(None); + pair(&a, &b).await; +} + +/// A pairing with a target that runs 1.7.0, which ends with `bye` `done` +/// as `ends` says. Both people accept; A saves its pin and cannot know +/// whether the target did. +async fn pair_with_legacy(ends: LegacyEnd) { + let cloud = FakeCloud::start().await; + let (a, _b) = two(&cloud).await; + cloud.play_legacy("mA", "mB", ends); + let mut events = a.link.pair("mB").await.unwrap(); + let event = next_pair_event(&mut events).await; + let PairEvent::Code { pairing_id, .. } = event else { + panic!("no code: {event:?}"); + }; + a.link.answer(&pairing_id, true).await.unwrap(); + let event = next_pair_event(&mut events).await; + let PairEvent::Partial { + local, + peer, + reason, + message, + .. + } = &event + else { + panic!("not partial: {event:?}"); + }; + assert_eq!((*local, *peer), (PinState::Pinned, PinState::Unknown)); + assert_eq!(reason, "unconfirmed"); + assert!(message.contains("older version"), "{message}"); + assert!(a.pinned("mB")); + // Nothing A sent is new to 1.7.0: no `pair.saved`, and a `hello` whose + // range holds version 2. + wait_until("the target hears A's bye", || { + cloud.legacy_heard().len() == 4 + }) + .await; + let heard = cloud.legacy_heard(); + let kinds: Vec<&str> = heard.iter().filter_map(|m| m["t"].as_str()).collect(); + assert_eq!(kinds, ["hello", "pair.nonce", "pair.confirm", "bye"]); + let proto = &heard[0]["proto"]; + assert!(proto["min"].as_u64() <= Some(2) && proto["max"].as_u64() >= Some(2)); +} + +#[tokio::test] +async fn a_bye_from_1_7_0_after_its_timeout_is_not_a_saved_pin() { + pair_with_legacy(LegacyEnd::Timeout(Duration::from_millis(400))).await; +} + +#[tokio::test] +async fn a_bye_from_1_7_0_after_its_pin_failed_is_not_a_saved_pin() { + pair_with_legacy(LegacyEnd::PinFailed).await; +} + // --- Identity ---------------------------------------------------------------- #[tokio::test] @@ -1216,10 +1446,12 @@ async fn signing_out_while_connected_closes_the_link_and_pins_nothing() { .unwrap(); a.link.refresh(); wait_until("A's socket closes", || !cloud.connected("mA")).await; - assert!(matches!( - next_pair_event(&mut events).await, - PairEvent::Cancelled { .. } - )); + // A accepted: B could have saved, as far as A knows. + let event = next_pair_event(&mut events).await; + let PairEvent::Partial { local, peer, .. } = &event else { + panic!("not partial: {event:?}"); + }; + assert_eq!((*local, *peer), (PinState::NotPinned, PinState::Unknown)); let _ = b.link.answer(&id_b, true).await; wait_until("A is off", || a.link.status().relay == RelayState::Off).await; @@ -1255,10 +1487,19 @@ async fn a_stale_pairing_writes_nothing_into_a_newer_sign_in() { .unwrap(); // B confirms: A's old actor gets the confirmation and tries to pin. b.link.answer(&id_b, true).await.unwrap(); - let PairEvent::Cancelled { message, .. } = next_pair_event(&mut events).await else { - panic!("A's pairing should not complete"); + // B saved; A could not, and says so. + let event = next_pair_event(&mut events).await; + let PairEvent::Partial { + local, + reason, + message, + .. + } = &event + else { + panic!("A's pairing should not complete: {event:?}"); }; - assert!(message.contains("pin could not be saved"), "{message}"); + assert_eq!(*local, PinState::NotPinned); + assert_eq!(reason, "pin_failed", "{message}"); let store = a.store(); assert!(store.pins().unwrap().is_empty()); assert!(!a.dir.path().join("remote/peers.json").exists()); diff --git a/src/daemon/remote/tests/access.rs b/src/daemon/remote/tests/access.rs index 70ddb417..f171bc22 100644 --- a/src/daemon/remote/tests/access.rs +++ b/src/daemon/remote/tests/access.rs @@ -14,7 +14,9 @@ use crate::daemon::remote::machines::SessionState; use crate::daemon::remote::{AccessEvent, Asking, Command, Event, Subscription, Timings}; use crate::infrastructure::cloud::credentials::sign_in_lock; use crate::infrastructure::remote::store::SettingsChange; -use crate::infrastructure::remote::wire::{AccessOutcome, AccessWants, ProtoRange, SessionMessage}; +use crate::infrastructure::remote::wire::{ + AccessOutcome, AccessWants, PROTO_MAX, ProtoRange, SessionMessage, +}; /// No per-peer limit: each test that needs one says so. fn unlimited() -> Timings { @@ -136,7 +138,7 @@ fn switches(daemon: &Daemon) -> (bool, bool, bool) { /// A relay that alters `presence` to claim version 1 for both changes /// nothing: the `hello`s decide, and access requests go through. #[tokio::test] -async fn presence_claiming_version_1_does_not_downgrade_two_version_2_peers() { +async fn presence_claiming_version_1_does_not_downgrade_two_current_peers() { let cloud = FakeCloud::start().await; cloud.claim_proto(1, 1); let (a, b) = asker_and_target(&cloud, fast()).await; @@ -144,10 +146,10 @@ async fn presence_claiming_version_1_does_not_downgrade_two_version_2_peers() { assert_eq!(presence, ProtoRange { min: 1, max: 1 }); a.link.open("mB", true).await.unwrap(); - assert_eq!(proto(&a, "mB"), Some(2)); + assert_eq!(proto(&a, "mB"), Some(PROTO_MAX)); let listed = a.link.machines(false).await.unwrap(); let listed = listed.iter().find(|machine| machine.id == "mB").unwrap(); - assert_eq!(listed.proto, Some(2)); + assert_eq!(listed.proto, Some(PROTO_MAX)); let mut events = app(&b); let _asking = ask(&a, AccessWants::Control).await; @@ -216,7 +218,11 @@ async fn a_protocol_2_message_in_a_version_1_session_is_an_unknown_type() { async fn hello_ranges_that_do_not_overlap_end_the_session() { let cloud = FakeCloud::start().await; let (a, b) = asker_and_target(&cloud, fast()).await; - b.link.speak(ProtoRange { min: 3, max: 3 }); + let later = PROTO_MAX + 1; + b.link.speak(ProtoRange { + min: later, + max: later, + }); let failure = a.link.open("mB", true).await.unwrap_err(); assert_eq!(failure.code, "unsupported", "{failure:?}"); diff --git a/src/daemon/remote/tests/cli.rs b/src/daemon/remote/tests/cli.rs index 803b034b..3b070edd 100644 --- a/src/daemon/remote/tests/cli.rs +++ b/src/daemon/remote/tests/cli.rs @@ -28,7 +28,7 @@ use crate::daemon::router::RuntimeState; use crate::infrastructure::inventory::LocalInventory; use crate::infrastructure::mgmt_client::MgmtSocketClient; use crate::infrastructure::remote::store::SettingsChange; -use crate::infrastructure::remote::wire::AppPresence; +use crate::infrastructure::remote::wire::{AppPresence, PROTO_MAX, PROTO_PAIR_SAVED}; use crate::infrastructure::runs::output::{ EndReason, RunEnd, StreamWriter, create_run_dir, publish_end, }; @@ -184,6 +184,12 @@ async fn the_cli_reads_and_controls_another_machine_through_the_daemon() { writer.append(b"one\ntwo\nthree\n").unwrap(); b.source.set_run(RUN, Ok(run_dir.clone())); let (socket, _shutdown, _dir) = socket(&a).await; + // A and B agree on the latest protocol, 3 (`pair.saved`) or later, in + // the session every command below goes through. + let agreed = |daemon: &Daemon| daemon.link.shared.view().protos.get("mB").copied(); + a.link.open("mB", true).await.unwrap(); + assert_eq!(agreed(&a), Some(PROTO_MAX)); + const { assert!(PROTO_MAX >= PROTO_PAIR_SAVED) }; // `--machine` names B by its name in any case, and A itself locally. let resolving = socket.clone(); @@ -280,6 +286,7 @@ async fn the_cli_reads_and_controls_another_machine_through_the_daemon() { "Stopping 'web' on teo-mini…\n'web' stopped on teo-mini.\n" ); assert_eq!(b.source.host().state().stops.len(), 1); + assert_eq!(agreed(&a), Some(PROTO_MAX)); // With controls off on B, nothing is sent and the refusal says why. controls(&b, false).await; diff --git a/src/daemon/remote/tests/convergence.rs b/src/daemon/remote/tests/convergence.rs index 3674c175..b95d3392 100644 --- a/src/daemon/remote/tests/convergence.rs +++ b/src/daemon/remote/tests/convergence.rs @@ -195,7 +195,7 @@ impl Drop for Sandbox { } /// `localify` as `cargo test` builds it, next to this test binary's folder. -fn localify_binary() -> PathBuf { +pub(super) fn localify_binary() -> PathBuf { let binary = std::env::current_exe() .ok() .and_then(|test| Some(test.parent()?.parent()?.join("localify"))) diff --git a/src/daemon/remote/tests/ssh_pairing.rs b/src/daemon/remote/tests/ssh_pairing.rs new file mode 100644 index 00000000..d364ca61 --- /dev/null +++ b/src/daemon/remote/tests/ssh_pairing.rs @@ -0,0 +1,737 @@ +//! Pairing over SSH (`docs/remote-machines.md`, "Pairing over SSH"; ADR +//! 0035): the one-shot acceptor in the daemon, the `--for-ssh` helper on +//! its line protocol, and the whole pairing driven from A. The SSH hop is +//! replaced by a direct pipe to the helper: the `localify` binary run here, +//! against B's management socket, in a temporary home. + +use std::io::{BufRead, BufReader, PipeWriter, Write}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::mpsc as sync_mpsc; +use std::time::Duration; + +use serde_json::Value; +use tokio::sync::mpsc; + +use super::convergence::localify_binary; +use super::viewing::serve_management; +use super::{Daemon, FakeCloud, cut_after_bs_confirm, daemon, next_pair_event, two, wait_until}; +use crate::cli::pair_ssh::{self, HelperArgs, Peer, Report, Target}; +use crate::daemon::remote::PairEvent; +use crate::infrastructure::mgmt_client::MgmtSocketClient; +use crate::infrastructure::remote::pairing::{Outcome, PinState}; +use crate::infrastructure::remote::ssh_pair::{self, ControlLine, HelperLine, ProtocolError}; + +fn account(daemon: &Daemon) -> String { + daemon.link.status().account.expect("connected") +} + +/// The helper run in a thread on OS pipes: what A would write to its stdin, +/// and the lines of its stdout. +struct Helper { + stdin: Option, + lines: sync_mpsc::Receiver, + done: std::thread::JoinHandle>, +} + +impl Helper { + fn start(socket: &Path, from: &str, account: &str) -> Self { + let (stdin_reader, stdin) = std::io::pipe().unwrap(); + let (out_reader, mut out) = std::io::pipe().unwrap(); + let client = MgmtSocketClient::new(socket); + let args = HelperArgs { + from: from.into(), + account: account.into(), + }; + let done = std::thread::spawn(move || { + pair_ssh::run_helper(&client, &args, stdin_reader, &mut out) + }); + let (tx, lines) = sync_mpsc::channel(); + std::thread::spawn(move || { + for line in BufReader::new(out_reader).lines() { + let Ok(line) = line else { return }; + if tx.send(line).is_err() { + return; + } + } + }); + Self { + stdin: Some(stdin), + lines, + done, + } + } + + /// The next stdout line, without blocking the daemons' runtime. + async fn next(&self) -> Value { + for _ in 0..300 { + if let Ok(line) = self.lines.try_recv() { + assert_eq!( + serde_json::from_str::(&line).unwrap()["v"], + 1, + "{line}" + ); + return serde_json::from_str(&line).unwrap(); + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + panic!("the helper wrote no line"); + } + + fn write(&mut self, line: &str) { + let stdin = self.stdin.as_mut().unwrap(); + stdin.write_all(line.as_bytes()).unwrap(); + stdin.write_all(b"\n").unwrap(); + } + + async fn exit_code(self) -> anyhow::Result { + drop(self.stdin); + tokio::task::spawn_blocking(move || self.done.join().unwrap()) + .await + .unwrap() + } +} + +/// The first line A wrote to B's stdin. +fn first_line(stdin: std::io::PipeReader) -> Result { + let mut line = String::new(); + BufReader::new(stdin).read_line(&mut line).unwrap(); + ssh_pair::parse_control_line(line.trim_end().as_bytes()) +} + +async fn code_of(events: &mut mpsc::Receiver) -> String { + let event = next_pair_event(events).await; + let PairEvent::Code { code, .. } = event else { + panic!("no code: {event:?}"); + }; + code +} + +// --- The acceptor -------------------------------------------------------------- + +#[tokio::test] +async fn an_acceptor_is_consumed_only_by_its_machine_and_only_once() { + let cloud = FakeCloud::start().await; + let (a, b) = two(&cloud).await; + let c = daemon(&cloud, "mC", "desk").await; + wait_until("B and C see each other", || b.sees("mC") && c.sees("mB")).await; + let (ready, mut accepted) = b.link.accept("mA", &account(&b)).await.unwrap(); + assert_eq!( + (ready.machine_id.as_str(), ready.account.as_str()), + ("mB", "u1") + ); + assert!(!ready.attempt.is_empty()); + + // Another machine's request cannot consume it: B is busy with it. + let mut from_c = c.link.pair("mB").await.unwrap(); + let event = next_pair_event(&mut from_c).await; + assert!( + matches!(&event, PairEvent::Cancelled { reason, .. } if reason == "busy"), + "{event:?}" + ); + + let mut from_a = a.link.pair("mB").await.unwrap(); + let PairEvent::Code { + pairing_id: id_a, + code: code_a, + .. + } = next_pair_event(&mut from_a).await + else { + panic!("no code on A"); + }; + let PairEvent::Code { + pairing_id: id_b, + code: code_b, + .. + } = next_pair_event(&mut accepted).await + else { + panic!("no code on B"); + }; + assert_eq!(code_a, code_b); + a.link.answer(&id_a, true).await.unwrap(); + b.link.answer(&id_b, true).await.unwrap(); + assert!(matches!( + next_pair_event(&mut from_a).await, + PairEvent::Paired { .. } + )); + assert!(matches!( + next_pair_event(&mut accepted).await, + PairEvent::Paired { .. } + )); + assert!(a.pinned("mB") && b.pinned("mA")); + + // Consumed: with nobody else to confirm on B, the next one is declined. + let mut again = a.link.pair("mB").await.unwrap(); + let event = next_pair_event(&mut again).await; + assert!( + matches!(&event, PairEvent::Cancelled { reason, .. } if reason == "nobody_to_confirm"), + "{event:?}" + ); +} + +#[tokio::test] +async fn an_acceptor_takes_one_pairing_at_a_time_and_counts_when_registered() { + let cloud = FakeCloud::start().await; + let (a, b) = two(&cloud).await; + let held = b.link.accept("mA", &account(&b)).await.unwrap(); + let busy = b.link.accept("mA", &account(&b)).await.unwrap_err(); + assert!(busy.to_string().contains("Another pairing"), "{busy}"); + drop(held); + // Four more, each given up at once: five in the hour. + for _ in 0..4 { + drop(b.link.accept("mA", &account(&b)).await.unwrap()); + } + let full = b.link.accept("mA", &account(&b)).await.unwrap_err(); + assert!(full.to_string().contains("5 pairing attempts"), "{full}"); + // The count is the target's, whoever asks. + let _subscription = b.link.subscribe(false); + let mut events = a.link.pair("mB").await.unwrap(); + let event = next_pair_event(&mut events).await; + assert!( + matches!(&event, PairEvent::Cancelled { reason, .. } if reason == "busy"), + "{event:?}" + ); +} + +#[tokio::test] +async fn an_acceptor_refuses_another_account_and_its_own_machine() { + let cloud = FakeCloud::start().await; + let (_a, b) = two(&cloud).await; + let error = b.link.accept("mA", "someone-else").await.unwrap_err(); + assert!( + error.to_string().contains("another Localify Cloud account"), + "{error}" + ); + assert!(b.link.accept("mB", &account(&b)).await.is_err()); + // Neither counted: five still fit. + for _ in 0..5 { + drop(b.link.accept("mA", &account(&b)).await.unwrap()); + } +} + +#[tokio::test] +async fn an_acceptors_two_minutes_start_when_it_is_registered() { + let cloud = FakeCloud::start().await; + let (a, b) = two(&cloud).await; + let (_, mut accepted) = b.link.accept("mA", &account(&b)).await.unwrap(); + // The test timings give a pairing 2.5 s. + let event = next_pair_event(&mut accepted).await; + assert!( + matches!(&event, PairEvent::Cancelled { reason, .. } if reason == "timeout"), + "{event:?}" + ); + let mut events = a.link.pair("mB").await.unwrap(); + let event = next_pair_event(&mut events).await; + assert!( + matches!(&event, PairEvent::Cancelled { reason, .. } if reason == "nobody_to_confirm"), + "{event:?}" + ); +} + +// --- The helper ---------------------------------------------------------------- + +#[test] +fn the_helper_refuses_a_terminal_on_either_side() { + assert!(pair_ssh::refuse_terminal(true, false).is_err()); + assert!(pair_ssh::refuse_terminal(false, true).is_err()); + assert!(pair_ssh::refuse_terminal(true, true).is_err()); + assert!(pair_ssh::refuse_terminal(false, false).is_ok()); +} + +#[tokio::test] +async fn the_helper_refuses_another_account_or_machine_and_writes_nothing() { + let cloud = FakeCloud::start().await; + let (_a, b) = two(&cloud).await; + let on_b = serve_management(&b).await; + for (from, asked) in [("mA", "someone-else".to_string()), ("mB", account(&b))] { + let mut helper = Helper::start(&on_b, from, &asked); + let lines = std::mem::replace(&mut helper.lines, sync_mpsc::channel().1); + let result = helper.exit_code().await; + assert!(result.is_err(), "{from} {asked}: {result:?}"); + // Its stdout closed with nothing on it. + assert!( + lines.recv_timeout(Duration::from_secs(2)).is_err(), + "{from} {asked}" + ); + } +} + +#[tokio::test] +async fn the_helper_confirms_only_on_its_exact_code() { + let cloud = FakeCloud::start().await; + let (a, b) = two(&cloud).await; + let on_b = serve_management(&b).await; + let mut helper = Helper::start(&on_b, "mA", &account(&b)); + let ready = helper.next().await; + assert_eq!(ready["event"], "ready"); + assert_eq!(ready["machineId"], "mB"); + let attempt = ready["attempt"].clone(); + + let mut events = a.link.pair("mB").await.unwrap(); + let code = code_of(&mut events).await; + let shown = helper.next().await; + assert_eq!(shown["event"], "code"); + assert_eq!(shown["attempt"], attempt); + assert_eq!(shown["code"], code.as_str()); + + // The same digits without their space are not the code. + helper.write(&format!( + r#"{{"v": 1, "confirm": "{}"}}"#, + code.replace(' ', "") + )); + let result = helper.next().await; + assert_eq!(result["event"], "result"); + assert_eq!(result["attempt"], attempt); + assert_eq!(result["outcome"], "cancelled"); + assert_eq!( + (result["local"].as_str(), result["peer"].as_str()), + (Some("not_pinned"), Some("not_pinned")) + ); + assert_eq!(helper.exit_code().await.unwrap(), 2); + assert!(matches!( + next_pair_event(&mut events).await, + PairEvent::Cancelled { .. } + )); + assert!(!a.pinned("mB") && !b.pinned("mA")); +} + +/// A management socket that takes connections and never answers. +fn silent_socket(dir: &Path) -> PathBuf { + let path = dir.join("silent.sock"); + let listener = std::os::unix::net::UnixListener::bind(&path).unwrap(); + std::thread::spawn(move || { + let mut held = Vec::new(); + for stream in listener.incoming() { + let Ok(stream) = stream else { return }; + held.push(stream); + } + }); + path +} + +#[test] +fn the_helper_never_waits_forever_for_its_daemon_and_writes_nothing() { + let dir = tempfile::tempdir().unwrap(); + let client = MgmtSocketClient::new(&silent_socket(dir.path())); + let args = HelperArgs { + from: "mA".into(), + account: "u1".into(), + }; + // The daemon never answers: the wait bounds it. + let (input, _open) = std::io::pipe().unwrap(); + let mut out = Vec::new(); + let started = std::time::Instant::now(); + let wait = Duration::from_millis(300); + let error = pair_ssh::run_helper_within(&client, &args, input, &mut out, wait).unwrap_err(); + assert!(error.to_string().contains("did not answer"), "{error}"); + assert!(out.is_empty()); + assert!(started.elapsed() < Duration::from_secs(5)); + + // A gives up and closes stdin while it waits: it stops at once. + let (input, closed) = std::io::pipe().unwrap(); + drop(closed); + let started = std::time::Instant::now(); + let wait = Duration::from_secs(60); + let error = pair_ssh::run_helper_within(&client, &args, input, &mut out, wait).unwrap_err(); + assert!(error.to_string().contains("gave up"), "{error}"); + assert!(out.is_empty()); + assert!(started.elapsed() < Duration::from_secs(5)); +} + +#[tokio::test] +async fn a_closed_stdin_cancels_the_helper() { + let cloud = FakeCloud::start().await; + let (a, b) = two(&cloud).await; + let on_b = serve_management(&b).await; + + // Before any code: `ready`, then `result`. + let mut helper = Helper::start(&on_b, "mA", &account(&b)); + assert_eq!(helper.next().await["event"], "ready"); + helper.stdin = None; + let result = helper.next().await; + assert_eq!( + (result["event"].as_str(), result["outcome"].as_str()), + (Some("result"), Some("cancelled")) + ); + assert_eq!(helper.exit_code().await.unwrap(), 2); + + // After the code, before a confirm. + let mut helper = Helper::start(&on_b, "mA", &account(&b)); + assert_eq!(helper.next().await["event"], "ready"); + let mut events = a.link.pair("mB").await.unwrap(); + code_of(&mut events).await; + assert_eq!(helper.next().await["event"], "code"); + helper.stdin = None; + let result = helper.next().await; + assert_eq!(result["outcome"], "cancelled"); + assert_eq!(helper.exit_code().await.unwrap(), 2); + assert!(matches!( + next_pair_event(&mut events).await, + PairEvent::Cancelled { .. } + )); + assert!(!a.pinned("mB") && !b.pinned("mA")); +} + +// --- End to end ---------------------------------------------------------------- + +/// A config that points the `localify` binary at B's management socket, +/// in a temporary home. +fn helper_config(home: &Path, socket: &Path) -> PathBuf { + let config = home.join("config.toml"); + let root = home.display(); + std::fs::write( + &config, + format!( + "[paths]\ndata_dir = \"{root}/data\"\npid_file = \"{root}/localify.pid\"\nlog_file = \"{root}/localify.log\"\ncerts_dir = \"{root}/data/certs\"\nsocket_path = \"{}\"\n", + socket.display() + ), + ) + .unwrap(); + config +} + +/// The command `ssh` would run on B, run here instead. +fn helper_command(home: &Path, socket: &Path, account: &str) -> Command { + helper_command_from(home, socket, "mA", account) +} + +fn helper_command_from(home: &Path, socket: &Path, from: &str, account: &str) -> Command { + let mut command = Command::new(localify_binary()); + command + .arg("--config") + .arg(helper_config(home, socket)) + .args([ + "machines", + "pair", + "--accept", + "--for-ssh", + "--from", + from, + "--account", + account, + ]) + .current_dir(home) + .env_clear() + .env("HOME", home) + .env("XDG_STATE_HOME", home.join("state")) + .env("PATH", "/usr/bin:/bin"); + command +} + +/// Runs `localify machines pair mB --over-ssh` on A's daemon, against the +/// helper on `peer`. +async fn pair_over_pipes(a: &Daemon, on_a: &Path, peer: Peer) -> Report { + let target = Target { + machine_id: "mB".into(), + name: "teo-mini".into(), + own_id: "mA".into(), + account: account(a), + }; + drive_from(on_a, target, peer).await +} + +async fn drive_from(on: &Path, target: Target, peer: Peer) -> Report { + let client = MgmtSocketClient::new(on); + tokio::task::spawn_blocking(move || { + pair_ssh::drive(&client, &target, peer, std::time::Instant::now()) + }) + .await + .unwrap() +} + +#[tokio::test] +async fn pairing_over_ssh_pins_both_sides_when_the_codes_match() { + let cloud = FakeCloud::start().await; + let (a, b) = two(&cloud).await; + let (on_a, on_b) = (serve_management(&a).await, serve_management(&b).await); + let home = tempfile::tempdir().unwrap(); + let peer = Peer::spawn(helper_command(home.path(), &on_b, &account(&b)), "teo-mini").unwrap(); + let report = pair_over_pipes(&a, &on_a, peer).await; + assert_eq!(report.outcome, Outcome::Paired, "{report:?}"); + assert_eq!( + (report.local, report.peer), + (PinState::Pinned, PinState::Pinned) + ); + assert_eq!(report.exit_code(), 0); + assert!(a.pinned("mB") && b.pinned("mA")); +} + +#[tokio::test] +async fn either_machine_can_initiate_a_pairing_over_ssh() { + let cloud = FakeCloud::start().await; + let (a, b) = two(&cloud).await; + let (on_a, on_b) = (serve_management(&a).await, serve_management(&b).await); + let home = tempfile::tempdir().unwrap(); + // B runs `localify machines pair laptop --over-ssh`; A accepts. + let command = helper_command_from(home.path(), &on_a, "mB", &account(&a)); + let peer = Peer::spawn(command, "laptop").unwrap(); + let target = Target { + machine_id: "mA".into(), + name: "laptop".into(), + own_id: "mB".into(), + account: account(&b), + }; + let report = drive_from(&on_b, target, peer).await; + assert_eq!(report.outcome, Outcome::Paired, "{report:?}"); + assert!(a.pinned("mB") && b.pinned("mA")); +} + +#[tokio::test] +async fn pairing_over_ssh_pins_nothing_when_the_codes_differ() { + let cloud = FakeCloud::start().await; + let (a, b) = two(&cloud).await; + let (on_a, on_b) = (serve_management(&a).await, serve_management(&b).await); + let home = tempfile::tempdir().unwrap(); + // Something between the machines shows A another code than B's. + let mut child = helper_command(home.path(), &on_b, &account(&b)) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let (stdin, stdout, stderr) = ( + child.stdin.take().unwrap(), + child.stdout.take().unwrap(), + child.stderr.take().unwrap(), + ); + let (altered, mut into_altered) = std::io::pipe().unwrap(); + std::thread::spawn(move || { + for line in BufReader::new(stdout).lines() { + let Ok(line) = line else { return }; + let mut value: Value = serde_json::from_str(&line).unwrap(); + if value["event"] == "code" { + let other = if value["code"] == "000 000" { + "000 001" + } else { + "000 000" + }; + value["code"] = other.into(); + } + if writeln!(into_altered, "{value}").is_err() { + return; + } + } + }); + let peer = Peer::from_pipes(stdin, altered, stderr, "teo-mini"); + let report = pair_over_pipes(&a, &on_a, peer).await; + assert_eq!(report.outcome, Outcome::Cancelled, "{report:?}"); + assert!(report.detail.contains("codes differ"), "{}", report.detail); + assert_eq!(report.exit_code(), 2); + let status = tokio::task::spawn_blocking(move || child.wait().unwrap()) + .await + .unwrap(); + assert_eq!(status.code(), Some(2)); + tokio::time::sleep(Duration::from_millis(300)).await; + assert!(!a.pinned("mB") && !b.pinned("mA")); +} + +#[tokio::test] +async fn pairing_over_ssh_cut_after_the_first_confirm_is_partial_then_completes() { + let cloud = FakeCloud::start().await; + let (a, b) = two(&cloud).await; + let (on_a, on_b) = (serve_management(&a).await, serve_management(&b).await); + let home = tempfile::tempdir().unwrap(); + cut_after_bs_confirm(&cloud); + let peer = Peer::spawn(helper_command(home.path(), &on_b, &account(&b)), "teo-mini").unwrap(); + let report = pair_over_pipes(&a, &on_a, peer).await; + // B saved, as its own result says; A never heard B's confirm. + assert_eq!(report.outcome, Outcome::Partial, "{report:?}"); + assert_eq!( + (report.local, report.peer), + (PinState::NotPinned, PinState::Pinned) + ); + assert_eq!(report.exit_code(), 4); + assert!(!a.pinned("mB") && b.pinned("mA")); + + // Pairing the same machines again completes it. + cloud.set_hook(None); + let peer = Peer::spawn(helper_command(home.path(), &on_b, &account(&b)), "teo-mini").unwrap(); + let report = pair_over_pipes(&a, &on_a, peer).await; + assert_eq!(report.outcome, Outcome::Paired, "{report:?}"); + assert!(a.pinned("mB") && b.pinned("mA")); +} + +#[tokio::test] +async fn a_ready_for_another_machine_or_account_pins_nothing() { + for (machine, account) in [("mX", "u1"), ("mB", "u2")] { + let (stdin, stdin_writer) = std::io::pipe().unwrap(); + let (stdout, mut stdout_writer) = std::io::pipe().unwrap(); + let (stderr, _stderr_writer) = std::io::pipe().unwrap(); + writeln!( + stdout_writer, + r#"{{"v": 1, "event": "ready", "machineId": "{machine}", "account": "{account}", "attempt": "at1"}}"# + ) + .unwrap(); + let peer = Peer::from_pipes(stdin_writer, stdout, stderr, "teo-mini"); + let target = Target { + machine_id: "mB".into(), + name: "teo-mini".into(), + own_id: "mA".into(), + account: "u1".into(), + }; + // This machine's daemon is never asked. + let client = MgmtSocketClient::new(Path::new("/nonexistent/localify.sock")); + let report = pair_ssh::drive(&client, &target, peer, std::time::Instant::now()); + assert_eq!(report.outcome, Outcome::Cancelled, "{report:?}"); + assert_eq!(report.exit_code(), 2); + // B was told to cancel. + assert_eq!(first_line(stdin), Ok(ControlLine::Cancel)); + } +} + +#[tokio::test] +async fn after_a_broken_line_nothing_from_b_is_trusted() { + let cloud = FakeCloud::start().await; + let (a, b) = two(&cloud).await; + let on_a = serve_management(&a).await; + // B's daemon holds the acceptor; its lines are written here. + let (ready, mut accepted) = b.link.accept("mA", &account(&b)).await.unwrap(); + let (stdin, stdin_writer) = std::io::pipe().unwrap(); + let (stdout, mut lines) = std::io::pipe().unwrap(); + let (stderr, _stderr_writer) = std::io::pipe().unwrap(); + let attempt = ready.attempt.clone(); + let ready = HelperLine::Ready { + machine_id: ready.machine_id, + account: ready.account, + attempt: attempt.clone(), + }; + lines.write_all(ready.to_line().as_bytes()).unwrap(); + let peer = Peer::from_pipes(stdin_writer, stdout, stderr, "teo-mini"); + let target = Target { + machine_id: "mB".into(), + name: "teo-mini".into(), + own_id: "mA".into(), + account: account(&a), + }; + let driving = tokio::spawn(async move { drive_from(&on_a, target, peer).await }); + + let code = code_of(&mut accepted).await; + let line = HelperLine::Code { + attempt: attempt.clone(), + code: code.clone(), + }; + lines.write_all(line.to_line().as_bytes()).unwrap(); + // The codes match: A confirms its side and B's. + let confirm = tokio::task::spawn_blocking(move || first_line(stdin)) + .await + .unwrap(); + assert_eq!(confirm, Ok(ControlLine::Confirm(code))); + + // Then B's stdout breaks the protocol, and claims success after that, + // while A's daemon still waits for B's. + let result = HelperLine::Result { + attempt, + outcome: Outcome::Paired, + local: PinState::Pinned, + peer: PinState::Pinned, + detail: String::new(), + }; + lines.write_all(b"not json\n").unwrap(); + lines.write_all(result.to_line().as_bytes()).unwrap(); + drop(lines); + + // B's daemon never answers: its 2 minutes (2.5 s here) decide. + let report = driving.await.unwrap(); + assert_eq!(report.outcome, Outcome::Partial, "{report:?}"); + assert_eq!( + (report.local, report.peer), + (PinState::NotPinned, PinState::Unknown) + ); + assert_eq!(report.exit_code(), 4); + assert!(report.detail.contains("cannot take"), "{}", report.detail); + assert!(!a.pinned("mB") && !b.pinned("mA")); +} + +#[tokio::test] +async fn a_line_after_b_s_result_undoes_that_result() { + let cloud = FakeCloud::start().await; + let (a, b) = two(&cloud).await; + let on_a = serve_management(&a).await; + let (ready, mut accepted) = b.link.accept("mA", &account(&b)).await.unwrap(); + let (stdin, stdin_writer) = std::io::pipe().unwrap(); + let (stdout, mut lines) = std::io::pipe().unwrap(); + let (stderr, _stderr_writer) = std::io::pipe().unwrap(); + let attempt = ready.attempt.clone(); + let ready = HelperLine::Ready { + machine_id: ready.machine_id, + account: ready.account, + attempt: attempt.clone(), + }; + lines.write_all(ready.to_line().as_bytes()).unwrap(); + let peer = Peer::from_pipes(stdin_writer, stdout, stderr, "teo-mini"); + let target = Target { + machine_id: "mB".into(), + name: "teo-mini".into(), + own_id: "mA".into(), + account: account(&a), + }; + let driving = tokio::spawn(async move { drive_from(&on_a, target, peer).await }); + + let PairEvent::Code { + pairing_id: id_b, + code, + .. + } = next_pair_event(&mut accepted).await + else { + panic!("no code on B"); + }; + let line = HelperLine::Code { + attempt: attempt.clone(), + code: code.clone(), + }; + lines.write_all(line.to_line().as_bytes()).unwrap(); + let confirm = tokio::task::spawn_blocking(move || first_line(stdin)) + .await + .unwrap(); + assert_eq!(confirm, Ok(ControlLine::Confirm(code))); + // B's daemon confirms too, so A's side finishes before B's `result`. + b.link.answer(&id_b, true).await.unwrap(); + wait_until("A pinned B", || a.pinned("mB")).await; + + // B claims success, then breaks the protocol before its stdout closes. + let result = HelperLine::Result { + attempt, + outcome: Outcome::Paired, + local: PinState::Pinned, + peer: PinState::Pinned, + detail: String::new(), + }; + lines.write_all(result.to_line().as_bytes()).unwrap(); + lines.write_all(b"not json\n").unwrap(); + drop(lines); + + let report = driving.await.unwrap(); + assert_ne!(report.outcome, Outcome::Paired, "{report:?}"); + assert_ne!(report.exit_code(), 0); + assert!(report.detail.contains("cannot take"), "{}", report.detail); +} + +#[tokio::test] +async fn a_malformed_or_foreign_line_from_b_ends_the_attempt() { + let cloud = FakeCloud::start().await; + let (a, b) = two(&cloud).await; + let on_a = serve_management(&a).await; + let _ = b; + for bad in [ + r#"{"v": 1, "event": "code", "attempt": "other", "code": "123 456"}"#, + r#"{"v": 2, "event": "code", "attempt": "at1", "code": "123 456"}"#, + "not json", + ] { + let (stdin, stdin_writer) = std::io::pipe().unwrap(); + let (stdout, mut stdout_writer) = std::io::pipe().unwrap(); + let (stderr, _stderr_writer) = std::io::pipe().unwrap(); + writeln!( + stdout_writer, + r#"{{"v": 1, "event": "ready", "machineId": "mB", "account": "u1", "attempt": "at1"}}"# + ) + .unwrap(); + writeln!(stdout_writer, "{bad}").unwrap(); + drop(stdout_writer); + let peer = Peer::from_pipes(stdin_writer, stdout, stderr, "teo-mini"); + let report = pair_over_pipes(&a, &on_a, peer).await; + assert_eq!(report.outcome, Outcome::Cancelled, "{bad}: {report:?}"); + assert_eq!(first_line(stdin), Ok(ControlLine::Cancel), "{bad}"); + } + tokio::time::sleep(Duration::from_millis(300)).await; + assert!(!a.pinned("mB")); +} diff --git a/src/infrastructure/file_security/mod.rs b/src/infrastructure/file_security/mod.rs index 7269dc15..5a99e210 100644 --- a/src/infrastructure/file_security/mod.rs +++ b/src/infrastructure/file_security/mod.rs @@ -46,7 +46,9 @@ pub fn write_private_file(path: &Path, contents: &[u8]) -> std::io::Result<()> { .open(path)?; // The mode above only applies to a new file. file.set_permissions(std::fs::Permissions::from_mode(0o600))?; - file.write_all(contents) + file.write_all(contents)?; + // On disk before any rename makes it the file others read. + file.sync_all() } /// Fallback for unsupported platforms — always returns an error. diff --git a/src/infrastructure/remote/mod.rs b/src/infrastructure/remote/mod.rs index 3a9d87d1..5e5163ec 100644 --- a/src/infrastructure/remote/mod.rs +++ b/src/infrastructure/remote/mod.rs @@ -2,12 +2,14 @@ //! (`docs/remote-machines.md`, "Trust" and "Wire protocol"): the files under //! `/remote/`, the Noise handshake and transport, the pairing //! commitment and code, and the JSON frames on the relay and inside -//! sessions; and on a target, the control executor and its request entries. +//! sessions; pairing over SSH's line protocol and `ssh` command; and on a +//! target, the control executor and its request entries. //! The relay link itself runs in the daemon. pub mod control; pub mod noise; pub mod pairing; pub mod requests; +pub mod ssh_pair; pub mod store; pub mod wire; diff --git a/src/infrastructure/remote/pairing.rs b/src/infrastructure/remote/pairing.rs index 3ca4b598..62832e1f 100644 --- a/src/infrastructure/remote/pairing.rs +++ b/src/infrastructure/remote/pairing.rs @@ -112,10 +112,7 @@ enum State { nonce: Nonce, }, /// Both: the code is shown, waiting for both answers. - Confirming { - mine: Option, - theirs: Option, - }, + Confirming, Finished, } @@ -125,6 +122,11 @@ pub struct Pairing { side: Side, h: [u8; HASH_LEN], state: State, + /// This side's answer, once its person gave it. Kept after the end, so + /// a cut session can still tell what may have been written. + mine: Option, + /// The peer's `pair.confirm`, once it arrived. + theirs: Option, } impl Pairing { @@ -134,6 +136,8 @@ impl Pairing { side: Side::Initiator, h, state: State::AwaitCommit, + mine: None, + theirs: None, } } @@ -146,6 +150,8 @@ impl Pairing { side: Side::Responder, h, state: State::Committed { nonce }, + mine: None, + theirs: None, }; Ok((pairing, SessionMessage::PairCommit { c: encode(&c) })) } @@ -154,9 +160,26 @@ impl Pairing { self.state == State::Finished } + /// This side's answer: `Some(true)` once it sent `pair.confirm` with + /// `accept: true`. Until then the peer cannot have written a pin. + pub fn mine(&self) -> Option { + self.mine + } + + /// The peer's `pair.confirm`, once it arrived. + pub fn theirs(&self) -> Option { + self.theirs + } + /// Takes the peer's next pairing message. pub fn receive(&mut self, message: &SessionMessage) -> Result, PairingError> { let state = std::mem::replace(&mut self.state, State::Finished); + if let (State::Confirming, None, SessionMessage::PairConfirm { accept }) = + (&state, self.theirs, message) + { + self.theirs = Some(*accept); + return Ok(self.settle(Vec::new())); + } let (state, steps) = self.next(state, message)?; self.state = state; Ok(steps) @@ -185,7 +208,7 @@ impl Pairing { let shown = format_code(code(&self.h, &theirs, &nonce)); let reveal = SessionMessage::PairReveal { n: encode(&nonce) }; Ok(( - confirming(), + State::Confirming, vec![Step::Send(reveal), Step::ShowCode(shown)], )) } @@ -205,47 +228,69 @@ impl Pairing { return Err(PairingError::NonceReuse); } let shown = format_code(code(&self.h, &nonce, &theirs)); - Ok((confirming(), vec![Step::ShowCode(shown)])) + Ok((State::Confirming, vec![Step::ShowCode(shown)])) } - ( - _, - State::Confirming { mine, theirs: None }, - SessionMessage::PairConfirm { accept }, - ) => Ok(settle(mine, Some(*accept), vec![])), (_, _, message) => Err(PairingError::OutOfOrder(name(message))), } } /// The person's answer, once the code is shown. pub fn answer(&mut self, accept: bool) -> Result, PairingError> { - let State::Confirming { mine: None, theirs } = self.state else { + if self.state != State::Confirming || self.mine.is_some() { return Err(PairingError::AlreadyAnswered); - }; - let send = vec![Step::Send(SessionMessage::PairConfirm { accept })]; - let (state, steps) = settle(Some(accept), theirs, send); - self.state = state; - Ok(steps) + } + self.mine = Some(accept); + Ok(self.settle(vec![Step::Send(SessionMessage::PairConfirm { accept })])) } -} -fn confirming() -> State { - State::Confirming { - mine: None, - theirs: None, + /// Ends the pairing once either answer is no, or both are yes. + fn settle(&mut self, mut steps: Vec) -> Vec { + match (self.mine, self.theirs) { + (Some(false), _) | (_, Some(false)) => { + steps.push(Step::Cancelled); + self.state = State::Finished; + } + (Some(true), Some(true)) => { + steps.push(Step::Paired); + self.state = State::Finished; + } + _ => self.state = State::Confirming, + } + steps } } -fn settle(mine: Option, theirs: Option, mut steps: Vec) -> (State, Vec) { - match (mine, theirs) { - (Some(false), _) | (_, Some(false)) => { - steps.push(Step::Cancelled); - (State::Finished, steps) - } - (Some(true), Some(true)) => { - steps.push(Step::Paired); - (State::Finished, steps) +/// What one side of a pairing holds: its own state as it verified it on +/// disk, or the peer's as this side learned it (`docs/remote-machines.md`, +/// "Partial results"). +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PinState { + Pinned, + NotPinned, + Unknown, +} + +/// How a pairing ended, from both sides' states. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Outcome { + /// Both sides are known to hold the other's pin. + Paired, + /// Nothing was written on either side. + Cancelled, + /// Anything else: one side may hold a pin the other lacks. Pairing + /// again with the same machines completes it. + Partial, +} + +impl Outcome { + pub fn of(local: PinState, peer: PinState) -> Self { + match (local, peer) { + (PinState::Pinned, PinState::Pinned) => Self::Paired, + (PinState::NotPinned, PinState::NotPinned) => Self::Cancelled, + _ => Self::Partial, } - _ => (State::Confirming { mine, theirs }, steps), } } @@ -459,6 +504,44 @@ mod tests { assert!(matches <= 1, "{matches} of 200 attempts matched"); } + #[test] + fn each_side_keeps_both_answers_after_the_end() { + let (mut a, mut b, _, _) = to_codes([12; 32], [12; 32]); + assert_eq!((a.mine(), a.theirs()), (None, None)); + a.answer(true).unwrap(); + b.receive(&confirm(true)).unwrap(); + b.answer(true).unwrap(); + a.receive(&confirm(true)).unwrap(); + assert!(a.is_finished() && b.is_finished()); + assert_eq!((a.mine(), a.theirs()), (Some(true), Some(true))); + assert_eq!((b.mine(), b.theirs()), (Some(true), Some(true))); + + let (mut a, _, _, _) = to_codes([13; 32], [13; 32]); + a.answer(true).unwrap(); + a.receive(&confirm(false)).unwrap(); + assert_eq!((a.mine(), a.theirs()), (Some(true), Some(false))); + } + + #[test] + fn the_outcome_is_paired_only_when_both_are_known_pinned() { + use PinState::{NotPinned, Pinned, Unknown}; + assert_eq!(Outcome::of(Pinned, Pinned), Outcome::Paired); + assert_eq!(Outcome::of(NotPinned, NotPinned), Outcome::Cancelled); + for (local, peer) in [ + (Pinned, Unknown), + (Pinned, NotPinned), + (NotPinned, Pinned), + (NotPinned, Unknown), + (Unknown, Unknown), + ] { + assert_eq!( + Outcome::of(local, peer), + Outcome::Partial, + "{local:?} {peer:?}" + ); + } + } + #[test] fn codes_are_six_digits_in_two_groups() { assert_eq!(format_code(482_913), "482 913"); diff --git a/src/infrastructure/remote/ssh_pair.rs b/src/infrastructure/remote/ssh_pair.rs new file mode 100644 index 00000000..32a6c6e7 --- /dev/null +++ b/src/infrastructure/remote/ssh_pair.rs @@ -0,0 +1,707 @@ +//! Pairing over SSH (`docs/remote-machines.md`, "Pairing over SSH"; ADR +//! 0035): the JSON lines between `localify machines pair --over-ssh` on the +//! initiator and `localify machines pair --accept --for-ssh` on the machine +//! it pairs with, and the `ssh` command line the initiator runs. +//! +//! The helper's stdout carries only these lines, each under 4 KiB with +//! `"v": 1`; its stderr is diagnostics, never parsed. The initiator writes +//! `confirm` or `cancel` to its stdin. + +use std::io::{self, BufRead, Read}; + +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +use super::pairing::{Outcome, PinState}; + +/// The protocol version both lines carry. +pub const VERSION: u64 = 1; +/// A line, its newline included, is at most this long. +pub const MAX_LINE: usize = 4096; + +/// What the helper's stdout says, in this order: `ready`, then `code` +/// unless the attempt ended first, then `result`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde( + tag = "event", + rename_all = "snake_case", + rename_all_fields = "camelCase" +)] +pub enum HelperLine { + /// The helper's daemon holds a one-shot acceptor for this account and + /// this initiating machine. + Ready { + machine_id: String, + account: String, + attempt: String, + }, + Code { + attempt: String, + code: String, + }, + Result { + attempt: String, + outcome: Outcome, + local: PinState, + peer: PinState, + detail: String, + }, +} + +/// What the initiator writes to the helper's stdin. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ControlLine { + /// Confirm, only if this is the helper's own code. + Confirm(String), + Cancel, +} + +/// Why a line ends the attempt. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum ProtocolError { + #[error("a line is longer than 4 KiB")] + TooLong, + #[error("a line is not one this protocol knows: {0}")] + Malformed(String), + #[error("a line says version {0}, and only version 1 is known")] + Version(String), + #[error("the {0} line came out of order or twice")] + OutOfOrder(&'static str), + #[error("a line names another attempt")] + Foreign, +} + +impl HelperLine { + /// The line to write, newline included. + pub fn to_line(&self) -> String { + let mut value = serde_json::to_value(self).unwrap_or(Value::Null); + if let Value::Object(fields) = &mut value { + fields.insert("v".into(), VERSION.into()); + } + format!("{value}\n") + } + + fn name(&self) -> &'static str { + match self { + Self::Ready { .. } => "ready", + Self::Code { .. } => "code", + Self::Result { .. } => "result", + } + } + + /// Bounds on what a line may carry, beyond its shape. + fn check(&self) -> Result<(), ProtocolError> { + let malformed = |what: &str| Err(ProtocolError::Malformed(what.to_string())); + match self { + Self::Ready { + machine_id, + account, + attempt, + } => { + if !is_id(machine_id) || !is_id(account) || !is_id(attempt) { + return malformed("ready carries an empty or invalid id"); + } + } + Self::Code { attempt, code } => { + if !is_id(attempt) || !is_code(code) { + return malformed("code is not six digits in two groups"); + } + } + Self::Result { attempt, .. } => { + if !is_id(attempt) { + return malformed("result carries an invalid attempt"); + } + } + } + Ok(()) + } +} + +impl ControlLine { + /// The line to write, newline included. + pub fn to_line(&self) -> String { + let value = match self { + Self::Confirm(code) => serde_json::json!({ "v": VERSION, "confirm": code }), + Self::Cancel => serde_json::json!({ "v": VERSION, "cancel": true }), + }; + format!("{value}\n") + } +} + +/// An id as the contract's machine ids, user ids and attempts are: short, +/// printable, no spaces. +fn is_id(text: &str) -> bool { + !text.is_empty() + && text.len() <= 128 + && text + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | ':' | '@')) +} + +/// `482 913`. +fn is_code(text: &str) -> bool { + let bytes = text.as_bytes(); + bytes.len() == 7 + && bytes[3] == b' ' + && bytes[..3].iter().chain(&bytes[4..]).all(u8::is_ascii_digit) +} + +/// The object of a line, once its version is checked. +fn versioned(line: &[u8]) -> Result, ProtocolError> { + if line.len() > MAX_LINE { + return Err(ProtocolError::TooLong); + } + let value: Value = serde_json::from_slice(line) + .map_err(|error| ProtocolError::Malformed(error.to_string()))?; + let Value::Object(mut fields) = value else { + return Err(ProtocolError::Malformed("not a JSON object".into())); + }; + match fields.remove("v") { + Some(Value::Number(v)) if v.as_u64() == Some(VERSION) => Ok(fields), + Some(other) => Err(ProtocolError::Version(other.to_string())), + None => Err(ProtocolError::Version("nothing".into())), + } +} + +/// One line of the helper's stdout, on its own. +pub fn parse_helper_line(line: &[u8]) -> Result { + let fields = versioned(line)?; + let parsed: HelperLine = serde_json::from_value(Value::Object(fields)) + .map_err(|error| ProtocolError::Malformed(error.to_string()))?; + parsed.check()?; + Ok(parsed) +} + +/// One line of the helper's stdin: exactly `confirm` with a code, or +/// `cancel: true`, and nothing else. +pub fn parse_control_line(line: &[u8]) -> Result { + let fields = versioned(line)?; + let mut keys: Vec<&str> = fields.keys().map(String::as_str).collect(); + keys.sort_unstable(); + match (keys.as_slice(), fields.get("confirm"), fields.get("cancel")) { + (["confirm"], Some(Value::String(code)), _) => Ok(ControlLine::Confirm(code.clone())), + (["cancel"], _, Some(Value::Bool(true))) => Ok(ControlLine::Cancel), + _ => Err(ProtocolError::Malformed( + "expected exactly confirm with a code, or cancel: true".into(), + )), + } +} + +/// The helper's lines as the initiator takes them: in order, each once, +/// all of one attempt. +#[derive(Debug, Default)] +pub struct HelperLines { + attempt: Option, + code: bool, + result: bool, +} + +impl HelperLines { + /// Takes the next line, or says why it ends the attempt. + pub fn take(&mut self, line: &[u8]) -> Result { + let parsed = parse_helper_line(line)?; + let in_order = match &parsed { + HelperLine::Ready { .. } => self.attempt.is_none(), + HelperLine::Code { .. } => self.attempt.is_some() && !self.code && !self.result, + HelperLine::Result { .. } => self.attempt.is_some() && !self.result, + }; + if !in_order { + return Err(ProtocolError::OutOfOrder(parsed.name())); + } + match &parsed { + HelperLine::Ready { attempt, .. } => self.attempt = Some(attempt.clone()), + HelperLine::Code { attempt, .. } | HelperLine::Result { attempt, .. } => { + if self.attempt.as_ref() != Some(attempt) { + return Err(ProtocolError::Foreign); + } + } + } + self.code |= matches!(parsed, HelperLine::Code { .. }); + self.result |= matches!(parsed, HelperLine::Result { .. }); + Ok(parsed) + } +} + +/// Reads one line of at most [`MAX_LINE`] bytes, without its newline. +/// `None` at the end of the stream; a longer line is +/// [`ProtocolError::TooLong`], and what follows it is not read. +pub fn read_line(reader: &mut impl BufRead) -> io::Result, ProtocolError>>> { + let mut line = Vec::new(); + let read = reader + .by_ref() + .take(MAX_LINE as u64) + .read_until(b'\n', &mut line)?; + if read == 0 { + return Ok(None); + } + if line.last() == Some(&b'\n') { + line.pop(); + } else if read == MAX_LINE { + return Ok(Some(Err(ProtocolError::TooLong))); + } + Ok(Some(Ok(line))) +} + +/// Why an argument of the `ssh` command is refused. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum ArgumentError { + #[error("The SSH destination must be one host or user@host that does not start with '-'.")] + Destination, + #[error("--remote-localify must be one absolute path, without a newline or a NUL.")] + RemoteLocalify, + #[error("A machine id or account id holds a newline or a NUL.")] + Unquotable, + #[error( + "Pairing over SSH needs OpenSSH 8.7 or newer on this machine, for its StdinNull and ForkAfterAuthentication options. `ssh -V` says: {0}" + )] + OldSsh(String), +} + +/// The oldest OpenSSH that has every option of [`SSH_OPTIONS`]. +const MIN_OPENSSH: (u32, u32) = (8, 7); + +/// Checks `ssh -V`'s output before `ssh` runs with options it may not +/// know. Another ssh, or a version that does not read as `OpenSSH_X.Y`, +/// fails closed. +pub fn require_openssh(version_output: &str) -> Result<(), ArgumentError> { + match openssh_version(version_output) { + Some(version) if version >= MIN_OPENSSH => Ok(()), + _ => { + let said = version_output.lines().next().unwrap_or_default().trim(); + let said = if said.is_empty() { "nothing" } else { said }; + Err(ArgumentError::OldSsh(said.to_string())) + } + } +} + +/// `(8, 7)` from `OpenSSH_8.7p1, LibreSSL 3.3.6`. +fn openssh_version(output: &str) -> Option<(u32, u32)> { + let version = output + .split_whitespace() + .find_map(|word| word.strip_prefix("OpenSSH_"))?; + let (major, rest) = version.split_once('.')?; + let minor: String = rest.chars().take_while(char::is_ascii_digit).collect(); + Some((major.parse().ok()?, minor.parse().ok()?)) +} + +/// The options the contract fixes: no shell, no prompt, a host key that +/// must already be trusted, stdin kept open, nothing forwarded, no shared +/// connection, 15 s to connect. +pub const SSH_OPTIONS: [&str; 22] = [ + "-T", + "-o", + "BatchMode=yes", + "-o", + "StrictHostKeyChecking=yes", + "-o", + "StdinNull=no", + "-o", + "ForkAfterAuthentication=no", + "-o", + "ForwardAgent=no", + "-o", + "ForwardX11=no", + "-o", + "ClearAllForwardings=yes", + "-o", + "ControlMaster=no", + "-o", + "ControlPath=none", + "-o", + "ConnectTimeout=15", + "--", +]; + +/// `ssh`'s arguments, run without a local shell: the fixed options, the +/// destination as one operand, and the remote command as one string. +pub fn ssh_args(destination: &str, remote_command: &str) -> Result, ArgumentError> { + let refused = destination.is_empty() + || destination.starts_with('-') + || destination + .chars() + .any(|c| c.is_control() || c.is_whitespace()); + if refused { + return Err(ArgumentError::Destination); + } + let mut args: Vec = SSH_OPTIONS + .iter() + .map(|option| option.to_string()) + .collect(); + args.push(destination.to_string()); + args.push(remote_command.to_string()); + Ok(args) +} + +/// The command the remote shell runs: the executable and fixed +/// arguments, each quoted for a POSIX shell. +pub fn remote_command( + executable: &str, + from: &str, + account: &str, +) -> Result { + let words = [ + executable, + "machines", + "pair", + "--accept", + "--for-ssh", + "--from", + from, + "--account", + account, + ]; + if words.iter().any(|word| word.contains(['\n', '\0'])) { + return Err(ArgumentError::Unquotable); + } + Ok(words.map(shell_quote).join(" ")) +} + +/// Checks `--remote-localify`: one absolute path. +pub fn remote_executable(path: &str) -> Result<&str, ArgumentError> { + if !path.starts_with('/') || path.contains(['\n', '\0']) { + return Err(ArgumentError::RemoteLocalify); + } + Ok(path) +} + +/// Single quotes, with each quote inside closed, escaped and reopened. +fn shell_quote(word: &str) -> String { + format!("'{}'", word.replace('\'', r"'\''")) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ready() -> String { + HelperLine::Ready { + machine_id: "mB".into(), + account: "u1".into(), + attempt: "at1".into(), + } + .to_line() + } + + fn code(attempt: &str) -> String { + HelperLine::Code { + attempt: attempt.into(), + code: "482 913".into(), + } + .to_line() + } + + fn result(attempt: &str) -> String { + HelperLine::Result { + attempt: attempt.into(), + outcome: Outcome::Paired, + local: PinState::Pinned, + peer: PinState::Pinned, + detail: String::new(), + } + .to_line() + } + + fn take(lines: &mut HelperLines, line: &str) -> Result { + lines.take(line.trim_end().as_bytes()) + } + + #[test] + fn lines_round_trip_with_their_version() { + let line = ready(); + assert!(line.ends_with('\n')); + let value: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(value["v"], 1); + assert_eq!(value["event"], "ready"); + assert_eq!(value["machineId"], "mB"); + let mut lines = HelperLines::default(); + assert!(matches!( + take(&mut lines, &line), + Ok(HelperLine::Ready { .. }) + )); + assert!(matches!( + take(&mut lines, &code("at1")), + Ok(HelperLine::Code { .. }) + )); + let Ok(HelperLine::Result { outcome, local, .. }) = take(&mut lines, &result("at1")) else { + panic!("no result"); + }; + assert_eq!((outcome, local), (Outcome::Paired, PinState::Pinned)); + } + + #[test] + fn a_cancel_before_any_code_is_ready_then_result() { + let mut lines = HelperLines::default(); + take(&mut lines, &ready()).unwrap(); + take(&mut lines, &result("at1")).unwrap(); + } + + #[test] + fn malformed_lines_end_the_attempt() { + for line in [ + "not json", + "[1, 2]", + r#"{"v": 1}"#, + r#"{"v": 1, "event": "hello"}"#, + r#"{"v": 1, "event": "ready", "machineId": "mB"}"#, + r#"{"v": 1, "event": "ready", "machineId": "", "account": "u1", "attempt": "a"}"#, + r#"{"v": 1, "event": "ready", "machineId": "m B", "account": "u1", "attempt": "a"}"#, + r#"{"v": 1, "event": "code", "attempt": "a", "code": "482913"}"#, + r#"{"v": 1, "event": "code", "attempt": "a", "code": "48a 913"}"#, + r#"{"v": 1, "event": "result", "attempt": "a", "outcome": "won", "local": "pinned", "peer": "pinned", "detail": ""}"#, + ] { + assert!( + matches!( + parse_helper_line(line.as_bytes()), + Err(ProtocolError::Malformed(_)) + ), + "{line}" + ); + } + } + + #[test] + fn a_version_other_than_1_is_refused() { + for line in [ + r#"{"event": "ready", "machineId": "mB", "account": "u1", "attempt": "a"}"#, + r#"{"v": 2, "event": "ready", "machineId": "mB", "account": "u1", "attempt": "a"}"#, + r#"{"v": "1", "event": "ready", "machineId": "mB", "account": "u1", "attempt": "a"}"#, + r#"{"v": 1.5, "cancel": true}"#, + ] { + assert!( + matches!( + parse_helper_line(line.as_bytes()), + Err(ProtocolError::Version(_)) + ), + "{line}" + ); + } + assert!(matches!( + parse_control_line(br#"{"v": 2, "cancel": true}"#), + Err(ProtocolError::Version(_)) + )); + } + + #[test] + fn duplicate_or_out_of_order_lines_end_the_attempt() { + let mut lines = HelperLines::default(); + assert_eq!( + take(&mut lines, &code("at1")), + Err(ProtocolError::OutOfOrder("code")) + ); + let mut lines = HelperLines::default(); + assert_eq!( + take(&mut lines, &result("at1")), + Err(ProtocolError::OutOfOrder("result")) + ); + let mut lines = HelperLines::default(); + take(&mut lines, &ready()).unwrap(); + assert_eq!( + take(&mut lines, &ready()), + Err(ProtocolError::OutOfOrder("ready")) + ); + take(&mut lines, &code("at1")).unwrap(); + assert_eq!( + take(&mut lines, &code("at1")), + Err(ProtocolError::OutOfOrder("code")) + ); + take(&mut lines, &result("at1")).unwrap(); + assert_eq!( + take(&mut lines, &result("at1")), + Err(ProtocolError::OutOfOrder("result")) + ); + // A code after the result. + let mut lines = HelperLines::default(); + take(&mut lines, &ready()).unwrap(); + take(&mut lines, &result("at1")).unwrap(); + assert_eq!( + take(&mut lines, &code("at1")), + Err(ProtocolError::OutOfOrder("code")) + ); + } + + #[test] + fn a_line_of_another_attempt_is_foreign() { + let mut lines = HelperLines::default(); + take(&mut lines, &ready()).unwrap(); + assert_eq!(take(&mut lines, &code("at2")), Err(ProtocolError::Foreign)); + let mut lines = HelperLines::default(); + take(&mut lines, &ready()).unwrap(); + assert_eq!( + take(&mut lines, &result("other")), + Err(ProtocolError::Foreign) + ); + } + + #[test] + fn lines_are_capped_at_4_kib() { + let long = format!( + r#"{{"v": 1, "event": "result", "attempt": "a", "outcome": "cancelled", "local": "not_pinned", "peer": "not_pinned", "detail": "{}"}}"#, + "x".repeat(MAX_LINE) + ); + assert_eq!( + parse_helper_line(long.as_bytes()), + Err(ProtocolError::TooLong) + ); + + let stream = format!("{}\n{}", "y".repeat(MAX_LINE + 10), ready()); + let mut reader = io::Cursor::new(stream.into_bytes()); + assert_eq!( + read_line(&mut reader).unwrap(), + Some(Err(ProtocolError::TooLong)) + ); + + let fits = format!("{}\nrest", "z".repeat(MAX_LINE - 1)); + let mut reader = io::Cursor::new(fits.into_bytes()); + let Some(Ok(line)) = read_line(&mut reader).unwrap() else { + panic!("a line of 4095 bytes and its newline fits"); + }; + assert_eq!(line.len(), MAX_LINE - 1); + assert_eq!(read_line(&mut reader).unwrap(), Some(Ok(b"rest".to_vec()))); + assert_eq!(read_line(&mut reader).unwrap(), None); + } + + #[test] + fn control_lines_are_exactly_confirm_or_cancel() { + assert_eq!( + parse_control_line( + ControlLine::Confirm("482 913".into()) + .to_line() + .trim_end() + .as_bytes() + ), + Ok(ControlLine::Confirm("482 913".into())) + ); + assert_eq!( + parse_control_line(ControlLine::Cancel.to_line().trim_end().as_bytes()), + Ok(ControlLine::Cancel) + ); + for line in [ + r#"{"v": 1}"#, + r#"{"v": 1, "cancel": false}"#, + r#"{"v": 1, "confirm": 482913}"#, + r#"{"v": 1, "confirm": "482 913", "cancel": true}"#, + r#"{"v": 1, "confirm": "482 913", "also": 1}"#, + "yes", + ] { + assert!( + matches!( + parse_control_line(line.as_bytes()), + Err(ProtocolError::Malformed(_)) + ), + "{line}" + ); + } + } + + #[test] + fn ssh_runs_with_exactly_the_contracts_options() { + let args = ssh_args("teo@mini.local", "'localify' 'machines'").unwrap(); + assert_eq!( + args.join(" "), + "-T -o BatchMode=yes -o StrictHostKeyChecking=yes -o StdinNull=no \ + -o ForkAfterAuthentication=no -o ForwardAgent=no -o ForwardX11=no \ + -o ClearAllForwardings=yes -o ControlMaster=no -o ControlPath=none \ + -o ConnectTimeout=15 -- teo@mini.local 'localify' 'machines'" + ); + // The destination and the command are one operand each. + assert_eq!(args[args.len() - 2], "teo@mini.local"); + assert_eq!(args[args.len() - 1], "'localify' 'machines'"); + } + + #[test] + fn a_destination_that_could_be_an_option_is_refused() { + for destination in [ + "", + "-oProxyCommand=touch /tmp/x", + "-p", + "host name", + "host\nname", + "host\0", + ] { + assert_eq!( + ssh_args(destination, "x"), + Err(ArgumentError::Destination), + "{destination:?}" + ); + } + assert!(ssh_args("mini", "x").is_ok()); + assert!(ssh_args("teo@[fe80::1%en0]", "x").is_ok()); + } + + #[test] + fn the_remote_command_quotes_every_word() { + assert_eq!( + remote_command("localify", "mA", "u1").unwrap(), + "'localify' 'machines' 'pair' '--accept' '--for-ssh' '--from' 'mA' '--account' 'u1'" + ); + let command = remote_command("/Users/t o/it's $HOME/`x`/localify", "mA", "u1").unwrap(); + assert!( + command.starts_with(r"'/Users/t o/it'\''s $HOME/`x`/localify' "), + "{command}" + ); + // What a POSIX shell makes of it. + let output = std::process::Command::new("sh") + .args(["-c", &format!("printf '%s\\n' {command}")]) + .output() + .unwrap(); + let words: Vec<&str> = std::str::from_utf8(&output.stdout) + .unwrap() + .lines() + .collect(); + assert_eq!(words[0], "/Users/t o/it's $HOME/`x`/localify"); + assert_eq!(words.len(), 9); + assert_eq!(&words[5..], ["--from", "mA", "--account", "u1"]); + } + + #[test] + fn a_remote_path_must_be_one_absolute_path() { + assert_eq!( + remote_executable("/opt/localify/bin/localify"), + Ok("/opt/localify/bin/localify") + ); + for path in ["localify", "~/bin/localify", "/bin/x\nrm", "/bin/x\0", ""] { + assert_eq!( + remote_executable(path), + Err(ArgumentError::RemoteLocalify), + "{path:?}" + ); + } + assert_eq!( + remote_command("/bin/localify", "m\nA", "u1"), + Err(ArgumentError::Unquotable) + ); + assert_eq!( + remote_command("/bin/localify", "mA", "u\u{0}1"), + Err(ArgumentError::Unquotable) + ); + } + + #[test] + fn only_openssh_8_7_or_newer_runs() { + for ok in [ + "OpenSSH_8.7p1, OpenSSL 3.0.2 15 Mar 2022", + "OpenSSH_8.9p1 Ubuntu-3ubuntu0.10, OpenSSL 3.0.2", + "OpenSSH_9.0", + "OpenSSH_10.3p1, LibreSSL 3.3.6", + ] { + assert_eq!(require_openssh(ok), Ok(()), "{ok}"); + } + for old in [ + "OpenSSH_8.6p1, OpenSSL 1.1.1k", + "OpenSSH_7.4p1, OpenSSL 1.0.2k-fips", + "OpenSSH_for_Windows_8.1p1, LibreSSL 3.0.2", + "Sun_SSH_1.1", + "OpenSSH_", + "", + ] { + let error = require_openssh(old).unwrap_err(); + assert!(error.to_string().contains("OpenSSH 8.7 or newer"), "{old}"); + } + let error = require_openssh("OpenSSH_8.6p1, OpenSSL 1.1.1k\n").unwrap_err(); + assert!( + error + .to_string() + .ends_with("says: OpenSSH_8.6p1, OpenSSL 1.1.1k") + ); + } +} diff --git a/src/infrastructure/remote/store.rs b/src/infrastructure/remote/store.rs index 71214df0..49914bd1 100644 --- a/src/infrastructure/remote/store.rs +++ b/src/infrastructure/remote/store.rs @@ -497,6 +497,13 @@ impl RemoteStore { .and_then(|()| { fs::rename(&temporary, &path) .with_context(|| format!("Could not write {}", path.display())) + }) + // The rename itself is durable only once the folder is synced: a + // pin `pair.saved` reported must survive a crash. + .and_then(|()| { + fs::File::open(&self.dir) + .and_then(|dir| dir.sync_all()) + .with_context(|| format!("Could not sync {}", self.dir.display())) }); if written.is_err() { let _ = fs::remove_file(&temporary); diff --git a/src/infrastructure/remote/wire.rs b/src/infrastructure/remote/wire.rs index baebbd5b..b904fc4d 100644 --- a/src/infrastructure/remote/wire.rs +++ b/src/infrastructure/remote/wire.rs @@ -8,9 +8,11 @@ use serde::{Deserialize, Serialize}; /// and `X-Localify-Proto` (`docs/remote-machines.md`, "Versioning"). The /// prologue's label does not follow them. pub const PROTO_MIN: u32 = 1; -pub const PROTO_MAX: u32 = 2; +pub const PROTO_MAX: u32 = 3; /// The version that adds access requests. pub const PROTO_ACCESS: u32 = 2; +/// The version that adds `pair.saved`. +pub const PROTO_PAIR_SAVED: u32 = 3; /// A relay frame, as text, never exceeds this. pub const MAX_FRAME_BYTES: usize = 64 * 1024; /// A session message, before encryption, never exceeds this. @@ -423,7 +425,8 @@ pub struct ControlResult { } /// The session messages this build handles. The access messages and -/// `expect.legacyId` belong to protocol 2 ([`SessionMessage::proto`]). +/// `expect.legacyId` belong to protocol 2, `pair.saved` to protocol 3 +/// ([`SessionMessage::proto`]). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "t", rename_all_fields = "camelCase")] pub enum SessionMessage { @@ -519,6 +522,9 @@ pub enum SessionMessage { PairReveal { n: String }, #[serde(rename = "pair.confirm")] PairConfirm { accept: bool }, + /// Protocol 3: this side durably wrote its pin. + #[serde(rename = "pair.saved")] + PairSaved, #[serde(rename = "pair.declined")] PairDeclined { reason: DeclineReason, @@ -576,6 +582,7 @@ impl SessionMessage { Self::AccessRequest { .. } | Self::AccessCancel { .. } | Self::AccessResult { .. } => { PROTO_ACCESS } + Self::PairSaved => PROTO_PAIR_SAVED, _ => 1, } } @@ -723,7 +730,8 @@ mod tests { let ours = ProtoRange::OURS; assert!(ours.overlaps(&ProtoRange { min: 1, max: 3 })); assert!(ours.overlaps(&ProtoRange { min: 2, max: 3 })); - assert!(!ours.overlaps(&ProtoRange { min: 3, max: 4 })); + assert!(ours.overlaps(&ProtoRange { min: 3, max: 4 })); + assert!(!ours.overlaps(&ProtoRange { min: 4, max: 5 })); } #[test] @@ -731,8 +739,17 @@ mod tests { let ours = ProtoRange::OURS; assert_eq!(ours.agreed(&ProtoRange { min: 1, max: 2 }), Some(2)); assert_eq!(ours.agreed(&ProtoRange { min: 1, max: 1 }), Some(1)); - assert_eq!(ours.agreed(&ProtoRange { min: 1, max: 9 }), Some(2)); - assert_eq!(ours.agreed(&ProtoRange { min: 3, max: 9 }), None); + assert_eq!(ours.agreed(&ProtoRange { min: 1, max: 9 }), Some(3)); + assert_eq!(ours.agreed(&ProtoRange { min: 4, max: 9 }), None); + } + + #[test] + fn pair_saved_uses_the_contract_name_and_takes_version_3() { + let saved = serde_json::to_value(SessionMessage::PairSaved).unwrap(); + assert_eq!(saved, json!({"t": "pair.saved"})); + let parsed: SessionMessage = serde_json::from_value(saved).unwrap(); + assert_eq!(parsed, SessionMessage::PairSaved); + assert_eq!(parsed.proto(), 3); } #[test] diff --git a/src/main.rs b/src/main.rs index 5ad14040..fd53ab6a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -525,7 +525,7 @@ enum UpdateCommands { #[derive(Subcommand)] enum MachinesCommands { - /// Pair with another machine: both show a code, and a person confirms it on each + /// Pair with another machine: both show a code, and a person confirms it on each, or --over-ssh compares them itself Pair { /// The machine's name or id #[arg(required_unless_present = "accept")] @@ -534,6 +534,26 @@ enum MachinesCommands { /// Wait on this machine for another one's pairing request #[arg(long, conflicts_with = "machine")] accept: bool, + + /// Pair with no person at either screen: start the accepting side on the machine through `ssh `, whose host key must already be trusted, and compare both codes here. Exits 0 paired, 2 nothing saved, 4 partial + #[arg(long = "over-ssh", value_name = "DESTINATION", requires = "machine")] + over_ssh: Option, + + /// With --over-ssh: the absolute path of localify on the other machine, when ssh's non-interactive shell does not find it + #[arg(long = "remote-localify", value_name = "PATH", requires = "over_ssh")] + remote_localify: Option, + + /// The accepting side --over-ssh starts: JSON lines on stdin and stdout, never a terminal + #[arg(long = "for-ssh", requires_all = ["accept", "from", "account"], hide = true)] + for_ssh: bool, + + /// With --for-ssh: the only machine id whose request this acceptor takes + #[arg(long, requires = "for_ssh", hide = true)] + from: Option, + + /// With --for-ssh: the account this machine must be signed in to + #[arg(long, requires = "for_ssh", hide = true)] + account: Option, }, /// Forget a paired machine here, and on it when a session is open @@ -1744,10 +1764,31 @@ fn main() -> Result<()> { }, Commands::Machines { json, command } => match command { None => cli::machines::list(json, &ctx), - Some(MachinesCommands::Pair { accept: true, .. }) => cli::machines::accept(&ctx), - Some(MachinesCommands::Pair { machine, .. }) => { - cli::machines::pair(machine.as_deref().unwrap_or_default(), &ctx) + Some(MachinesCommands::Pair { + for_ssh: true, + from: Some(from), + account: Some(account), + .. + }) => exit_with(cli::machines::accept_for_ssh(&from, &account, &ctx)?), + Some(MachinesCommands::Pair { accept: true, .. }) => { + exit_with(cli::machines::accept(&ctx)?) } + Some(MachinesCommands::Pair { + machine, + over_ssh: Some(destination), + remote_localify, + .. + }) => exit_with(cli::machines::pair_over_ssh( + machine.as_deref().unwrap_or_default(), + &destination, + remote_localify.as_deref(), + json, + &ctx, + )), + Some(MachinesCommands::Pair { machine, .. }) => exit_with(cli::machines::pair( + machine.as_deref().unwrap_or_default(), + &ctx, + )?), Some(MachinesCommands::Unpair { machine }) => { cli::machines::unpair(&machine, json, &ctx) }