From 2304b579ac53c17d7516b1462e28d318c105d5f5 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 21 Nov 2026 15:49:39 +0800 Subject: [PATCH] =?UTF-8?q?feat(remote):=20=E8=BF=9E=E6=8E=A5=E7=AA=97?= =?UTF-8?q?=E5=8F=A3=E7=9A=84=E5=9C=B0=E5=9D=80=E8=A7=A3=E6=9E=90=E3=80=81?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E3=80=81=E5=AF=BC=E5=85=A5=E3=80=81ssh=20-G?= =?UTF-8?q?=20=E7=94=9F=E6=95=88=E5=80=BC=E5=92=8C=E8=BF=9E=E6=8E=A5?= =?UTF-8?q?=E9=98=B6=E6=AE=B5=EF=BC=88#2231=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - remote.parseAddress:把快速连接输入的 [ssh://][user@]host[:port](IPv6 写成 [地址])拆成表单字段,按 remote.probe 的规则检查,出错时指出 host/user/port 哪一项。 - remote.connections 新增可选 query:名称、分组和 [user@]host[:port] 都包含每个词(不分大小写)的条目才留在 sections 里。 - remote.editConnections 新增 import(批量添加,重名自动加 " (2)" 后缀,fills 只给缺颜色/分组的已有条目补上)和 markConnected(记录 lastConnectedAt,换目标时与最近文件夹一起清除)。 - remote.effectiveSettings:用 ssh -G 分别带和不带配置文件(-F none)各跑一次,给出主机名、端口、用户、密钥、跳板、连接超时、保活间隔的实际值和来源(connection/sshConfig/default)。 - remote.sshConfigHosts:读取 ~/.ssh/config 及其 Include(只读家目录内,最多 64 个文件、每个 1 MiB、16 层),列出每个 Host 名(最多 256 个),给出状态(importable/exists/pattern/invalid/unreadable)、解析结果和被谁当作跳板。 - remote.mottyHosts:只读打开 Motty 的 config.db(格式 28),不打开 vault;逐项列出每个主机会导入哪些设置、哪些不导入及原因;数据库不存在或格式不支持时作为结果返回。 - remote.connect 新增 remoteStage 事件(authenticated/platformChecked/uploading/installed);认证询问新增 kind(hostKey/password/passphrase/code/other),主机密钥询问带 keyType 和 fingerprint。 - ssh -G 使用与 remote.probe 相同的受限环境、允许列表选项和 10 秒上限(导入整体 30 秒),可取消,诊断输出已脱敏。 - lithe-remote 新增 motty 特性(rusqlite bundled),只有桌面端 Core 打开,宿主服务端不带 SQLite。 - 更新契约 rust-core-api.md 和测试。 --- rust/Cargo.lock | 82 ++- rust/contracts/rust-core-api.md | 141 +++- rust/crates/core/src/protocol/command.rs | 19 +- .../core/src/runtime/dispatcher/remote.rs | 43 ++ rust/crates/core/src/tests/remote_sessions.rs | 46 ++ rust/crates/remote/Cargo.toml | 7 +- rust/crates/remote/src/client/connections.rs | 376 +++++++++- .../remote/src/client/connections/tests.rs | 277 ++++++++ rust/crates/remote/src/client/launch.rs | 62 +- rust/crates/remote/src/client/mod.rs | 10 + rust/crates/remote/src/client/motty.rs | 657 ++++++++++++++++++ rust/crates/remote/src/client/motty/tests.rs | 384 ++++++++++ rust/crates/remote/src/client/prompt.rs | 161 +++++ rust/crates/remote/src/client/ssh_config.rs | 454 ++++++++++++ .../remote/src/client/ssh_config/tests.rs | 314 +++++++++ rust/crates/remote/src/client/transport.rs | 88 ++- rust/crates/remote/tests/connection_log.rs | 1 + rust/crates/remote/tests/server.rs | 49 +- rust/crates/workspace/Cargo.toml | 2 +- rust/crates/workspace/src/connections.rs | 139 +++- .../crates/workspace/src/connections/tests.rs | 106 +++ rust/crates/workspace/src/lib.rs | 13 +- rust/crates/workspace/src/motty.rs | 87 +++ rust/crates/workspace/src/probe.rs | 40 +- rust/crates/workspace/src/probe/tests.rs | 51 ++ rust/crates/workspace/src/sessions.rs | 76 +- .../crates/workspace/src/ssh_configuration.rs | 282 ++++++++ .../workspace/src/ssh_configuration/tests.rs | 288 ++++++++ 28 files changed, 4149 insertions(+), 106 deletions(-) create mode 100644 rust/crates/remote/src/client/motty.rs create mode 100644 rust/crates/remote/src/client/motty/tests.rs create mode 100644 rust/crates/remote/src/client/prompt.rs create mode 100644 rust/crates/remote/src/client/ssh_config.rs create mode 100644 rust/crates/remote/src/client/ssh_config/tests.rs create mode 100644 rust/crates/workspace/src/motty.rs create mode 100644 rust/crates/workspace/src/ssh_configuration.rs create mode 100644 rust/crates/workspace/src/ssh_configuration/tests.rs diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 447dcd7c..3e143337 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -8,6 +8,18 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + [[package]] name = "aho-corasick" version = "1.1.5" @@ -383,6 +395,18 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + [[package]] name = "fastrand" version = "2.5.0" @@ -563,12 +587,30 @@ dependencies = [ "regex-syntax", ] +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + [[package]] name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +[[package]] +name = "hashlink" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" +dependencies = [ + "hashbrown 0.14.5", +] + [[package]] name = "html5ever" version = "0.39.0" @@ -818,7 +860,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" dependencies = [ "equivalent", - "hashbrown", + "hashbrown 0.17.1", "serde", "serde_core", ] @@ -858,6 +900,17 @@ version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +[[package]] +name = "libsqlite3-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + [[package]] name = "litemap" version = "0.8.2" @@ -1473,6 +1526,7 @@ dependencies = [ "libc", "lithe-diagnostics", "lithe-platform", + "rusqlite", "serde", "serde_json", "sha2", @@ -1761,6 +1815,12 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + [[package]] name = "potential_utf" version = "0.1.5" @@ -1959,6 +2019,20 @@ dependencies = [ "uuid", ] +[[package]] +name = "rusqlite" +version = "0.32.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", +] + [[package]] name = "rustc-hash" version = "2.1.3" @@ -2570,6 +2644,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version_check" version = "0.9.5" diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 40a46a0e..d0d6a076 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -820,7 +820,11 @@ or removing a command fails until the table changes in the same commit. | `remote.stopForward` | Stop one port forward and close its local port | | `remote.forwards` | List the running port forwards of one connection | | `remote.connections` | Read the SSH connections the user saved | -| `remote.editConnections` | Save, remove or record a folder on one saved SSH connection | +| `remote.editConnections` | Save, remove or import saved SSH connections, or record a folder or a connection time | +| `remote.parseAddress` | Split a quick-connect address into connection fields | +| `remote.effectiveSettings` | Tell what OpenSSH makes of a connection and where each value comes from | +| `remote.sshConfigHosts` | List the Host aliases of the user's SSH configuration for an import | +| `remote.mottyHosts` | List the SSH hosts saved in Motty for an import | | `git.historyRewritePreview` | Review undo, message edit, squash, or drop with complete messages, eligibility, and an immutable checkout expectation | | `git.remotes` | Return configured fetch remote names and URLs | | `git.tags` | Return tag names, tag object IDs, target IDs, dates, and annotations | @@ -1322,7 +1326,8 @@ Each event has `operationId` and `type`: | `output` | `invocationId`, `stream` (`stdout`/`stderr`), `text`, `progress`, `truncated`, optional `progressDetails` (`stage`, nullable `percent`, `completed`, `total`) | | `finished` | `invocationId`, nullable `exitCode`, monotonic `durationMilliseconds`, nullable `error`, `expectedExit` | | `requestFinished` | nullable `error`, including failures before a child started; `unconfirmedInvocations`, the started records without `finished`; `failureRecord`, true when `error` is set, is not a cancellation, and no record of the request failed or is unconfirmed, so the host shows the error as its own record | -| `authentication` | `requestId`, `prompt`, `secret`, `attempt`, optional `retry`, `workingDirectory` | +| `authentication` | `requestId`, `prompt`, `secret`, `attempt`, optional `retry`, `workingDirectory`; for `remote.*`, `kind` and optional `keyType` and `fingerprint` (see Remote connections) | +| `remoteStage` | `stage` of a `remote.connect` (see Remote connections that stay open) | | `remoteResult` | `remote`, `succeeded`, nullable structured `error`, updated/deleted reference lists and counts, `referencesTruncated`, `referencesAvailable` | `invocationId` is scoped to the request. `workingDirectory` is a native @@ -5698,6 +5703,16 @@ once with `remote.authRespond` (`{ requestId, answer: string | null }`, returning `{ accepted }`, with the bounds of `git.authRespond`). Null cancels the prompt. Core never stores or emits an answer. +Each question also carries `kind`, what the answer is, so the window can +show a fitting form: `hostKey` (an unknown host key to accept with `yes` or +decline with `no`), `password`, `passphrase` (of a private key), `code` (a +one-time or verification code) or `other`. A `hostKey` question adds +`keyType` (such as `ED25519`) and `fingerprint` (such as `SHA256:…`) when +OpenSSH's text names them, each at most 128 characters. OpenSSH hands +questions to AskPass only as text, so the kinds follow its English wording; +a question in any other wording is `other` and the window shows its +`prompt`. + The result is `{ status, host, diagnostics }`: | `status` | Meaning | @@ -5746,6 +5761,17 @@ named with the first entry's spelling. An empty list has no sections; a list without groups has the single `null` section. Clients render the sections as given and do not regroup or reorder the entries. +An entry also carries `lastConnectedAt`, seconds since the Unix epoch of the +last session opened over it, once one has. Replacing the entry's target +clears it with the recent folders. + +`remote.connections` also takes an optional `query` of at most 256 +characters. With one, `sections` keeps only the entries whose name, group +and `[user@]host[:port]` contain every whitespace-separated word of it, +regardless of case, and drops the sections left empty; `connections` stays +the whole list. A longer query is `invalid_request` with `{ field: "query", +reason: "tooLong" }`. + `remote.editConnections` accepts `{ document }` with exactly one of: - `save: { id?, name, connection, color?, group? }` normalizes and checks @@ -5762,9 +5788,18 @@ given and do not regroup or reorder the entries. - `remove: { id }` removes the entry; an absent id changes nothing. - `rememberFolder: { id, path }` moves `path` to the front of the entry's recent folders and keeps 10. +- `markConnected: { id }` records the current time as the entry's + `lastConnectedAt`; an unknown id is refused with `reason: "unknown"`. +- `import: { entries: [{ name, connection, color?, group? }], fills: [{ id, + color?, group? }] }` adds every entry in order, each checked as for a save. + A name already taken, regardless of case, gets the first free ` (2)` to + ` (256)` suffix, so an import never replaces an entry. A fill gives the + saved entry `id` a color or a group only where it has none. The first + refusal leaves the list as it was. The result is `{ changed, document: string|null, connections, sections, -id? }`; `id` names the entry a save wrote. An unchanged edit returns a `null` +id?, ids? }`; `id` names the entry a save wrote and `ids` the entries an +import added, in order. An unchanged edit returns a `null` document and must not create a source. Requests never carry a secret: a password field is an unknown field and is rejected. @@ -5775,14 +5810,96 @@ refused edit is `invalid_request`. Both carry `details` as the JSON `{ field, reason }`, where `reason` is `required`, `invalid`, `tooLong`, `duplicate`, `full` (128 entries) or `unknown` (no entry has the id). -The document stays at version 1 and omits `color` and `group` when they are -unset. A build from before these fields refuses a document that sets one as -having an unknown field. +The document stays at version 1 and omits `color`, `group` and +`lastConnectedAt` when they are unset. A build from before these fields +refuses a document that sets one as having an unknown field. Native clients keep the document below their platform user-preference directory, never on a host, in a workspace or in an installed package. This user-settings resource does not affect code signatures or update deltas. +#### Connection window helpers + +`remote.parseAddress` takes `{ text }`, a quick-connect address +`[ssh://][user@]host[:port]` where an IPv6 host is written `[address]`, and +returns `{ host, user?, port? }` for the form. The fields are checked as for +`remote.probe`; a refused address is `invalid_request` with `{ field, +reason }`, where `field` is `host`, `user` or `port`. Nothing is resolved or +contacted. + +`remote.effectiveSettings` takes `{ connection }`, as for `remote.probe`, +and returns what OpenSSH would use for it, without connecting: +`{ hostName, port, user, identityFiles, proxyJump, connectTimeoutSeconds, +keepAliveSeconds }`, each `{ value, source }`. `source` is `connection` when +the saved connection sets the value, `sshConfig` when the user's or the +system's SSH configuration does, and `default` otherwise. `identityFiles` is +a list of paths as written in the configuration, empty for password +authentication; `proxyJump` is `null` for a direct connection. Core runs +`ssh -G` for the connection twice, with and without the configuration +files (`-F none`), and compares the two. Both runs use the connection's +allowlisted options, the restricted environment of `remote.probe` and a +10 second bound, because `Match exec` lines still run commands. A missing +`ssh` is `runtime_missing`, a client that fails is `process_failed` with its +redacted standard error in `details`, the bound is `timed_out`, and output +without one of the values is `parse_failed`. + +`remote.sshConfigHosts` takes `{ homeDirectory, document }`: the user's +absolute home directory and the current connections document. Core reads +`.ssh/config` below it and the files it includes, in the order OpenSSH +reads them, up to 64 files of at most 1 MiB, 16 levels deep, and never a +file outside the home directory. The result is `{ files, hosts, truncated }`: +`files` are the paths read, and `hosts` lists each `Host` name once, +regardless of case, up to 256 (`truncated` is `true` when more were left +out). Each host is `{ alias, status, resolved?, existingId?, existingName?, +usedAsJumpBy }`: + +| `status` | Meaning | +| --- | --- | +| `importable` | `ssh -G` read it; `resolved` is `{ hostName, user, port, proxyJump? }` | +| `exists` | As `importable`, and the saved entry `existingId` (`existingName`) already reaches the alias or the same host, port and user | +| `pattern` | The name has wildcards or a negation and names no single host | +| `invalid` | Lithe refuses the name as a host | +| `unreadable` | `ssh -G` failed or timed out for it | + +`usedAsJumpBy` names the aliases whose `ProxyJump` goes through the host. +Each alias runs `ssh -G` as for `remote.effectiveSettings`, within 30 +seconds for the whole list. A missing `ssh` or a cancellation ends the +request as `runtime_missing` or `cancelled`; a relative home directory is +`invalid_request`, and a damaged document `parse_failed`. A home without +`.ssh/config` lists nothing. The host imports a selection with +`remote.editConnections`' `import`. + +`remote.mottyHosts` takes `{ configDirectory, document }`: the platform's +absolute user configuration directory (`~/Library/Application Support`, +`%APPDATA%` or `~/.config`) and the current connections document. Core opens +`motty/config.db` below it read only, waiting at most 500 ms while Motty +writes, and never opens Motty's vault, so no password or key is read. The +result names the `database` path and is either `{ database, unavailable }`, +where `unavailable` is `missing`, `unreadable`, `tooLarge` (over 64 MiB or +4096 records) or `unsupportedFormat` (a layout other than `28`), or +`{ database, format, groups, candidates }`. `groups` are Motty's groups with +at least one host, in Motty's order. Each candidate, in Motty's order, is +`{ key, name, address, system?, color?, group?, status, existingId?, +connection?, fields }`: + +- `key` is Motty's id of the host and `name` its label, the name an import + saves it under; `address` is `[user@]host[:port]` and `system` Motty's + operating system tag. `color` is the nearest connection color. +- `status` is `importable` (every setting is imported), `partial` (the + connection is imported without some settings), `exists` (the saved entry + `existingId` probably reaches the same host) or `unsupported` (not an SSH + host, or Lithe refuses its address). `connection` is what the import saves + and is absent for `unsupported`. +- `fields` lists every setting of the host as `{ motty, value, lithe?, + skip? }`: `lithe` names the connection field it becomes, or `skip` says why + it is not imported: `secret` (stored in Motty's vault), `noSetting`, + `protocol` (not SSH), `command` (a jump route that runs a command), + `kerberos` (left to the SSH configuration), `extraKey` (only the first key + file is imported) or `invalid`. + +A relative directory is `invalid_request` and a damaged document +`parse_failed`. Nothing is written to Motty's files. + #### Remote connections that stay open `remote.connect` takes `{ connection, servers: [{ target, path, sha256 }], @@ -5797,7 +5914,17 @@ installed server only when its own `sha256sum` or `shasum` computes that SHA-256; otherwise it receives the build through the same stream, checks it the same way (a host with neither tool checks the size and `--identity`, and never reuses that upload), and starts it, so the user authenticates once. -Prompts are relayed as for `remote.probe`. The result is `{ status, session, +Prompts are relayed as for `remote.probe`. + +While it connects, Core emits `remoteStage` events on the request's event +channel, so the window can show the steps: `{ stage: "authenticated" }` once +the host's shell prints its first line, `{ stage: "platformChecked" }` once +the shell reported its platform, `{ stage: "uploading", sentBytes, +totalBytes }` when a build starts to be sent and after each part of at most 256 KiB, +and `{ stage: "installed", uploaded }` once the server is in place, where +`uploaded` tells whether a build was sent now. Stages only move forward; a +failed attempt stops after the last stage reached, so a host without a +matching build stops after `platformChecked`. The result is `{ status, session, host, diagnostics }`; `session` is `{ id, uploaded, hostName, userName, homeDirectory }` and is set only for `connected`. A host without a matching build is `unsupportedPlatform` and nothing is uploaded. diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index fbea4a51..1790ecf1 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -1018,9 +1018,20 @@ pub enum RemoteCommand { Forwards, /// Reads the SSH connections the user saved (`remote.connections`). Connections, - /// Saves, removes or records a folder on one saved SSH connection - /// (`remote.editConnections`). + /// Saves, removes, imports or records a folder or a connection time on + /// the saved SSH connections (`remote.editConnections`). EditConnections, + /// Splits a quick-connect `[user@]host[:port]` into connection fields + /// (`remote.parseAddress`). + ParseAddress, + /// Tells what OpenSSH makes of a connection and where each value comes + /// from (`remote.effectiveSettings`). + EffectiveSettings, + /// Lists the `Host` aliases of the user's SSH configuration for an + /// import (`remote.sshConfigHosts`). + SshConfigHosts, + /// Lists the SSH hosts saved in Motty for an import (`remote.mottyHosts`). + MottyHosts, } #[derive(Debug, Clone)] @@ -1590,6 +1601,10 @@ impl CoreCommand { "remote.forwards" => Some(Self::Remote(RemoteCommand::Forwards)), "remote.connections" => Some(Self::Remote(RemoteCommand::Connections)), "remote.editConnections" => Some(Self::Remote(RemoteCommand::EditConnections)), + "remote.parseAddress" => Some(Self::Remote(RemoteCommand::ParseAddress)), + "remote.effectiveSettings" => Some(Self::Remote(RemoteCommand::EffectiveSettings)), + "remote.sshConfigHosts" => Some(Self::Remote(RemoteCommand::SshConfigHosts)), + "remote.mottyHosts" => Some(Self::Remote(RemoteCommand::MottyHosts)), "git.historyRewritePreview" => Some(Self::Git(GitCommand::HistoryRewritePreview)), "git.remotes" => Some(Self::Git(GitCommand::Remotes)), "git.tags" => Some(Self::Git(GitCommand::Tags)), diff --git a/rust/crates/core/src/runtime/dispatcher/remote.rs b/rust/crates/core/src/runtime/dispatcher/remote.rs index ba8a7e8d..9a5ffb42 100644 --- a/rust/crates/core/src/runtime/dispatcher/remote.rs +++ b/rust/crates/core/src/runtime/dispatcher/remote.rs @@ -233,6 +233,30 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option, payload: Valu Err(error) => CoreResponse::failure(id, error), } } + RemoteCommand::ParseAddress => answer( + id, + payload, + "Invalid remote address request", + lithe_workspace::connections::parse_address, + ), + RemoteCommand::EffectiveSettings => answer( + id, + payload, + "Invalid effective SSH settings request", + lithe_workspace::ssh_configuration::effective_settings, + ), + RemoteCommand::SshConfigHosts => answer( + id, + payload, + "Invalid SSH configuration hosts request", + lithe_workspace::ssh_configuration::ssh_config_hosts, + ), + RemoteCommand::MottyHosts => answer( + id, + payload, + "Invalid Motty hosts request", + lithe_workspace::motty::hosts, + ), RemoteCommand::Disconnect => { match serde_json::from_value::(payload) { Ok(request) => CoreResponse::success( @@ -277,6 +301,25 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option, payload: Valu } } +/// Decodes `payload` as `run`'s request and answers with its result; a +/// payload that does not decode is refused with `message`. +fn answer( + id: Option, + payload: Value, + message: &'static str, + run: impl FnOnce(R) -> Result, +) -> CoreResponse { + match serde_json::from_value(payload) + .map_err(|error| { + CoreError::new(ErrorCode::InvalidRequest, message).with_details(error.to_string()) + }) + .and_then(run) + { + Ok(value) => CoreResponse::success(id, value), + Err(error) => CoreResponse::failure(id, error), + } +} + /// A `remote.*Forward` payload that does not decode. fn invalid_forward_request(error: &serde_json::Error) -> CoreError { CoreError::new(ErrorCode::InvalidRequest, "Invalid port forward request") diff --git a/rust/crates/core/src/tests/remote_sessions.rs b/rust/crates/core/src/tests/remote_sessions.rs index 91cb756b..bab92c04 100644 --- a/rust/crates/core/src/tests/remote_sessions.rs +++ b/rust/crates/core/src/tests/remote_sessions.rs @@ -1249,6 +1249,52 @@ fn remote_workspace_trust_keys_the_host_real_path_on_the_connected_target() { ); } +// The connections window's helpers answer through the dispatcher: a quick +// address splits into fields, a missing Motty database is a result, and a +// malformed connection names its field before any `ssh -G` runs. +#[test] +fn connection_window_helpers_answer_through_the_dispatcher() { + let call = |command: &str, payload: Value| -> Value { + serde_json::from_str(&crate::execute_json( + &json!({"id": test_support::unique_id(), "command": command, + "timeoutMilliseconds": 30_000, "payload": payload}) + .to_string(), + )) + .unwrap() + }; + + let address = call("remote.parseAddress", json!({"text": "dev@build-box:2222"})); + assert_eq!( + address["data"], + json!({"host": "build-box", "user": "dev", "port": 2222}), + "{address}" + ); + + let directory = + std::env::temp_dir().join(format!("lithe-core-motty-absent-{}", std::process::id())); + let motty = call( + "remote.mottyHosts", + json!({"configDirectory": directory, "document": null}), + ); + assert_eq!(motty["data"]["unavailable"], "missing", "{motty}"); + + for (command, payload) in [ + ( + "remote.effectiveSettings", + json!({"connection": {"host": "dev@box"}}), + ), + ( + "remote.sshConfigHosts", + json!({"homeDirectory": "relative"}), + ), + ("remote.parseAddress", json!({"text": "box", "extra": 1})), + ] { + let response = call(command, payload); + assert_eq!(response["ok"], false, "{response}"); + assert_eq!(response["error"]["code"], "invalid_request", "{response}"); + } +} + // The ports page: a forward reaches a program listening on the host's // wildcard address, a second click returns the same forward, a target on // another machine waits for the user's confirmation, and every failure keeps diff --git a/rust/crates/remote/Cargo.toml b/rust/crates/remote/Cargo.toml index 543768eb..70ef9557 100644 --- a/rust/crates/remote/Cargo.toml +++ b/rust/crates/remote/Cargo.toml @@ -10,6 +10,10 @@ autotests = false [features] default = ["client"] client = ["dep:sha2"] +# Reads Motty's SQLite configuration database for an import. SQLite is +# bundled because Windows has no system library; only the desktop Core turns +# it on, never the host server. +motty = ["client", "dep:rusqlite"] # Host adapters must not become desktop client dependencies. Linux releases # target musl so the same static executable works in minimal containers. server = ["dep:libc", "dep:lithe-platform", "dep:sha2", "dep:trash"] @@ -20,13 +24,14 @@ server = ["dep:libc", "dep:lithe-platform", "dep:sha2", "dep:trash"] # macOS (scripts/rust-core/affected-crates.mjs). [package.metadata.lithe-ci] hosts = ["macos"] -test-features = ["server"] +test-features = ["server", "motty"] [dependencies] base64 = "0.22" serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = { version = "0.10", optional = true } +rusqlite = { version = "0.32", features = ["bundled"], optional = true } libc = { version = "0.2", optional = true } trash = { version = "5.2.6", default-features = false, features = ["chrono"], optional = true } # The server checks socket peers with the same code as the AskPass channel. diff --git a/rust/crates/remote/src/client/connections.rs b/rust/crates/remote/src/client/connections.rs index 3800dcad..84de0175 100644 --- a/rust/crates/remote/src/client/connections.rs +++ b/rust/crates/remote/src/client/connections.rs @@ -18,7 +18,13 @@ //! //! - An entry may carry a [`Label`]: an accent color and a group. Neither //! reaches SSH; [`Connections::sections`] turns the groups into the -//! headings the window lists the entries under. +//! headings the window lists the entries under, and +//! [`Connections::sections_matching`] keeps only the entries a search +//! finds. +//! - [`parse_address`] splits what the user typed in the quick-connect box, +//! such as `dev@build.example:2222`, into the form's fields. +//! - [`Connections::import`] adds the entries an import chose in one edit, +//! and [`Connections::existing`] tells which candidates are already saved. //! //! Every refusal names the field and the reason, so a client can explain each //! one in the user's language next to the field it concerns. @@ -66,6 +72,15 @@ const MAX_CONNECT_TIMEOUT_SECONDS: u32 = 600; /// Longest keep-alive interval. const MAX_KEEP_ALIVE_SECONDS: u32 = 3600; +/// Latest accepted connection time: the last second of the year 9999. +const MAX_TIMESTAMP_SECONDS: u64 = 253_402_300_799; + +/// Suffix numbers tried when an imported name is taken, `Name (2)` onwards. +const MAX_NAME_SUFFIX: usize = 256; + +/// Longest search query, in characters. +const MAX_QUERY_CHARS: usize = 256; + /// How the connection proves the user's identity. Every method still lets /// OpenSSH ask follow-up questions, such as a one-time code. #[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] @@ -134,29 +149,29 @@ pub struct Section<'a> { #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct SshConnection { /// Host name, address, or a `Host` alias from the user's SSH configuration. - host: String, + pub(crate) host: String, /// `None` keeps the port from the SSH configuration (22 by default). #[serde(default, skip_serializing_if = "Option::is_none")] - port: Option, + pub(crate) port: Option, /// `None` keeps the user from the SSH configuration. #[serde(default, skip_serializing_if = "Option::is_none")] - user: Option, + pub(crate) user: Option, #[serde(default, skip_serializing_if = "Authentication::is_auto")] - authentication: Authentication, + pub(crate) authentication: Authentication, /// Private key path; required for, and only kept with, /// [`Authentication::PrivateKey`]. OpenSSH expands a leading `~` itself. #[serde(default, skip_serializing_if = "Option::is_none")] - identity_file: Option, + pub(crate) identity_file: Option, /// `ProxyJump`: `none`, or comma-separated `[user@]host[:port]` jump /// hosts. `None` keeps the jump hosts of the SSH configuration. #[serde(default, skip_serializing_if = "Option::is_none")] - proxy_jump: Option, + pub(crate) proxy_jump: Option, /// `None` uses [`DEFAULT_CONNECT_TIMEOUT_SECONDS`]. #[serde(default, skip_serializing_if = "Option::is_none")] - connect_timeout_seconds: Option, + pub(crate) connect_timeout_seconds: Option, /// `None` keeps the transport's keep-alive default. #[serde(default, skip_serializing_if = "Option::is_none")] - keep_alive_seconds: Option, + pub(crate) keep_alive_seconds: Option, } /// Why a connection, a document or an edit was refused. @@ -374,6 +389,156 @@ impl SshConnection { && self.user == other.user && self.proxy_jump == other.proxy_jump } + + /// A connection to `host` with every other field left to the SSH + /// configuration. + pub fn to_host(host: impl Into) -> Self { + Self { + host: host.into(), + ..Self::default() + } + } + + /// Host name, address or SSH alias. + pub fn host(&self) -> &str { + &self.host + } + + /// Port the connection sets, if any. + pub fn port(&self) -> Option { + self.port + } + + /// User the connection sets, if any. + pub fn user(&self) -> Option<&str> { + self.user.as_deref() + } + + /// How the connection authenticates. + pub fn authentication(&self) -> Authentication { + self.authentication + } + + /// Private key path for [`Authentication::PrivateKey`]. + pub fn identity_file(&self) -> Option<&str> { + self.identity_file.as_deref() + } + + /// `ProxyJump` the connection sets, if any. + pub fn proxy_jump(&self) -> Option<&str> { + self.proxy_jump.as_deref() + } + + /// Connect timeout the connection sets, if any. + pub fn connect_timeout_seconds(&self) -> Option { + self.connect_timeout_seconds + } + + /// Keep-alive interval the connection sets, if any. + pub fn keep_alive_seconds(&self) -> Option { + self.keep_alive_seconds + } + + /// Whether `other` probably reaches the same account on the same host: + /// the hosts match regardless of case, and the port and the user match + /// where both connections set them. Imports use it to mark candidates + /// that are already saved; it is a hint for the user, not an identity. + fn probably_same(&self, other: &Self) -> bool { + self.host.eq_ignore_ascii_case(&other.host) + && (self.port.is_none() || other.port.is_none() || self.port == other.port) + && (self.user.is_none() || other.user.is_none() || self.user == other.user) + } + + /// Words a search compares the query with: the host, the user and the + /// `user@host:port` spelling. + fn search_text(&self) -> String { + let mut text = self.host.clone(); + if let Some(user) = &self.user { + text = format!("{user}@{text}"); + } + if let Some(port) = self.port { + text = format!("{text}:{port}"); + } + format!("{text} {}", self.host) + } +} + +/// Fields read from a quick-connect address. +#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Address { + /// Host name, address or SSH alias. + pub host: String, + /// User before the `@`, if any. + #[serde(skip_serializing_if = "Option::is_none")] + pub user: Option, + /// Port after the host, if any. + #[serde(skip_serializing_if = "Option::is_none")] + pub port: Option, +} + +/// Splits `[ssh://][user@]host[:port]` into the fields of a connection. +/// +/// IPv6 addresses take a port only in brackets (`[fe80::1]:2222`); an +/// address with several colons and no brackets is all host. The result +/// passes the same checks as a saved connection, and a refusal names the +/// field the user has to correct. +pub fn parse_address(text: &str) -> Result { + let mut rest = text.trim(); + if let Some(stripped) = rest.strip_prefix("ssh://") { + rest = stripped.strip_suffix('/').unwrap_or(stripped); + } + if rest.is_empty() { + return Err(ConnectionError::at("host", Reason::Required)); + } + let (user, rest) = match rest.rsplit_once('@') { + Some((user, host)) => (Some(user), host), + None => (None, rest), + }; + let (host, port) = if let Some(bracketed) = rest.strip_prefix('[') { + let (host, after) = bracketed + .split_once(']') + .ok_or(ConnectionError::at("host", Reason::Invalid))?; + match after { + "" => (host, None), + _ => match after.strip_prefix(':') { + Some(port) => (host, Some(port)), + None => return Err(ConnectionError::at("host", Reason::Invalid)), + }, + } + } else { + match rest.split_once(':') { + Some((host, port)) if !port.contains(':') => (host, Some(port)), + _ => (rest, None), + } + }; + let port = match port { + None => None, + // `u16::from_str` would also take a leading `+`. + Some(port) => Some( + Some(port) + .filter(|port| !port.is_empty() && port.bytes().all(|byte| byte.is_ascii_digit())) + .and_then(|port| port.parse::().ok()) + .filter(|port| *port != 0) + .ok_or(ConnectionError::at("port", Reason::Invalid))?, + ), + }; + if user == Some("") { + return Err(ConnectionError::at("user", Reason::Required)); + } + let address = Address { + host: host.to_owned(), + user: user.map(str::to_owned), + port, + }; + SshConnection { + host: address.host.clone(), + user: address.user.clone(), + port, + ..SshConnection::default() + } + .check()?; + Ok(address) } /// One saved connection. @@ -394,15 +559,94 @@ pub struct SavedConnection { /// Host folders opened over this connection, most recent first. #[serde(default, skip_serializing_if = "Vec::is_empty")] recent_folders: Vec, + /// Seconds since the Unix epoch when a session last opened over this + /// connection. Like the folders, it belongs to the target. + #[serde(default, skip_serializing_if = "Option::is_none")] + last_connected_at: Option, +} + +/// One entry an import adds. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ImportEntry { + /// Name to save the entry under; a taken name gets a ` (2)` style suffix. + pub name: String, + /// The connection, checked as for a save. + pub connection: SshConnection, + /// Accent color, if the import keeps one. + #[serde(default)] + pub color: Option, + /// Group, if the import keeps one. + #[serde(default)] + pub group: Option, +} + +/// Color and group an import gives an entry that is already saved, where +/// the entry has none. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct LabelFill { + /// The saved entry. + pub id: String, + /// Color to set when the entry has none. + #[serde(default)] + pub color: Option, + /// Group to set when the entry has none. + #[serde(default)] + pub group: Option, } impl SavedConnection { + /// Stable id of the entry. + pub fn id(&self) -> &str { + &self.id + } + + /// Name the user gave the entry. + pub fn name(&self) -> &str { + &self.name + } + + /// The SSH connection of the entry. + pub fn connection(&self) -> &SshConnection { + &self.connection + } + + /// Accent color of the entry. + pub fn color(&self) -> Option { + self.color + } + + /// Group of the entry. + pub fn group(&self) -> Option<&str> { + self.group.as_deref() + } + + /// Whether every word of `terms` (lowercase) appears in the entry's name, + /// group or address. + fn matches(&self, terms: &[String]) -> bool { + let text = format!( + "{} {} {}", + self.name, + self.group.as_deref().unwrap_or(""), + self.connection.search_text() + ) + .to_lowercase(); + terms.iter().all(|term| text.contains(term.as_str())) + } + fn check(&self) -> Result<(), ConnectionError> { check_id(&self.id)?; check_name(&self.name)?; if let Some(group) = &self.group { check_group(group)?; } + if self + .last_connected_at + .is_some_and(|at| at == 0 || at > MAX_TIMESTAMP_SECONDS) + { + return Err(ConnectionError::at("lastConnectedAt", Reason::Invalid)); + } self.connection.check()?; if self.recent_folders.len() > MAX_RECENT_FOLDERS { return Err(ConnectionError::at("recentFolders", Reason::Full)); @@ -501,9 +745,42 @@ impl Connections { /// sections. Groups that differ only in case share the section, which /// shows the first entry's spelling. pub fn sections(&self) -> Vec> { + self.sections_where(|_| true) + } + + /// The [`Self::sections`] of the entries a search for `query` finds. + /// + /// The query is split at whitespace; an entry matches when every word + /// appears, regardless of case, in its name, its group, its host, its + /// user or its `user@host:port` spelling. A blank query keeps every + /// entry, and sections without a match are left out. Queries longer than + /// 256 characters are refused. + pub fn sections_matching(&self, query: &str) -> Result>, ConnectionError> { + if query.chars().count() > MAX_QUERY_CHARS { + return Err(ConnectionError::at("query", Reason::TooLong)); + } + let terms: Vec = query.split_whitespace().map(str::to_lowercase).collect(); + Ok(self.sections_where(|entry| entry.matches(&terms))) + } + + /// The saved entry that probably reaches the same account on the same + /// host as `connection`: same host regardless of case, and the same + /// port and user where both set them. + pub fn existing(&self, connection: &SshConnection) -> Option<&SavedConnection> { + self.connections + .iter() + .find(|entry| entry.connection.probably_same(connection)) + } + + /// The entry `id`, if it exists. + pub fn entry(&self, id: &str) -> Option<&SavedConnection> { + self.get(id) + } + + fn sections_where(&self, keep: impl Fn(&SavedConnection) -> bool) -> Vec> { let mut sections: Vec> = Vec::new(); let mut ungrouped = Vec::new(); - for entry in &self.connections { + for entry in self.connections.iter().filter(|entry| keep(entry)) { let Some(group) = entry.group.as_deref() else { ungrouped.push(entry.id.as_str()); continue; @@ -579,6 +856,7 @@ impl Connections { .ok_or(ConnectionError::at("id", Reason::Unknown))?; if !entry.connection.same_target(&connection) { entry.recent_folders.clear(); + entry.last_connected_at = None; } entry.name = name.to_owned(); entry.connection = connection; @@ -601,12 +879,90 @@ impl Connections { color: label.color, group, recent_folders: Vec::new(), + last_connected_at: None, }); Ok(id) } } } + /// Adds every entry of `entries`, in order, and gives the saved entries + /// of `fills` the color and group they lack. Returns the new ids. + /// + /// Each entry is checked as for [`Self::save`]. A name that is already + /// taken, regardless of case, gets the first free ` (2)` to ` (256)` + /// suffix, so importing never replaces an entry. A fill only sets a + /// color or a group where the entry has none. The first refusal leaves + /// the list as it was. + pub fn import( + &mut self, + entries: Vec, + fills: Vec, + mut new_id: impl FnMut() -> String, + ) -> Result, ConnectionError> { + let mut after = self.clone(); + for fill in fills { + let entry = after + .get(&fill.id) + .ok_or(ConnectionError::at("id", Reason::Unknown))? + .clone(); + let label = Label { + color: entry.color.or(fill.color), + group: entry.group.clone().or(fill.group), + }; + after.save( + Some(&fill.id), + &entry.name, + entry.connection.clone(), + label, + &mut new_id, + )?; + } + let mut ids = Vec::with_capacity(entries.len()); + for entry in entries { + let name = after.free_name(entry.name.trim())?; + let label = Label { + color: entry.color, + group: entry.group, + }; + ids.push(after.save(None, &name, entry.connection, label, &mut new_id)?); + } + *self = after; + Ok(ids) + } + + /// `name`, or `name (2)` and so on when an entry already uses it. + fn free_name(&self, name: &str) -> Result { + check_name(name)?; + let taken = |candidate: &str| { + self.connections + .iter() + .any(|entry| same_name(&entry.name, candidate)) + }; + if !taken(name) { + return Ok(name.to_owned()); + } + (2..=MAX_NAME_SUFFIX) + .map(|number| format!("{name} ({number})")) + .find(|candidate| check_name(candidate).is_ok() && !taken(candidate)) + .ok_or(ConnectionError::at("name", Reason::Duplicate)) + } + + /// Records that a session opened over the entry `id` at `at`, in seconds + /// since the Unix epoch. + pub fn mark_connected(&mut self, id: &str, at: u64) -> Result<(), ConnectionError> { + if at == 0 || at > MAX_TIMESTAMP_SECONDS { + return Err(ConnectionError::at("at", Reason::Invalid)); + } + let entry = self + .connections + .iter_mut() + .find(|entry| entry.id == id) + .ok_or(ConnectionError::at("id", Reason::Unknown))?; + entry.last_connected_at = Some(at); + Ok(()) + } + /// Removes the entry `id`; an absent id changes nothing. pub fn remove(&mut self, id: &str) { self.connections.retain(|entry| entry.id != id); diff --git a/rust/crates/remote/src/client/connections/tests.rs b/rust/crates/remote/src/client/connections/tests.rs index 2476f8f3..20f82624 100644 --- a/rust/crates/remote/src/client/connections/tests.rs +++ b/rust/crates/remote/src/client/connections/tests.rs @@ -726,3 +726,280 @@ fn stored_documents_are_checked_like_edits() { ); } } + +#[test] +fn quick_connect_addresses_split_into_user_host_and_port() { + let parsed = |text: &str| parse_address(text).expect(text); + assert_eq!( + parsed("dev@build.example:2222"), + Address { + host: "build.example".into(), + user: Some("dev".into()), + port: Some(2222), + } + ); + assert_eq!(parsed(" build-box ").host, "build-box"); + assert_eq!(parsed("build-box").user, None); + assert_eq!(parsed("ssh://ops@10.0.0.8:22/").port, Some(22)); + assert_eq!(parsed("ssh://ops@10.0.0.8").host, "10.0.0.8"); + // IPv6 takes a port only in brackets. + assert_eq!(parsed("[fe80::1]:2200").host, "fe80::1"); + assert_eq!(parsed("[fe80::1]:2200").port, Some(2200)); + assert_eq!(parsed("ci@[fe80::1]").port, None); + assert_eq!(parsed("fe80::1").host, "fe80::1"); + assert_eq!(parsed("fe80::1").port, None); +} + +#[test] +fn quick_connect_addresses_name_the_field_to_correct() { + let refused = |text: &str| parse_address(text).expect_err(text); + assert_eq!(refused(""), ConnectionError::at("host", Reason::Required)); + assert_eq!( + refused("ssh://"), + ConnectionError::at("host", Reason::Required) + ); + assert_eq!( + refused("@build.example"), + ConnectionError::at("user", Reason::Required) + ); + for port in [ + "build.example:", + "build.example:0", + "build.example:65536", + "build.example:+22", + "build.example:2x", + ] { + assert_eq!( + refused(port), + ConnectionError::at("port", Reason::Invalid), + "{port}" + ); + } + assert_eq!( + refused("[fe80::1"), + ConnectionError::at("host", Reason::Invalid) + ); + assert_eq!( + refused("[fe80::1]2200"), + ConnectionError::at("host", Reason::Invalid) + ); + assert_eq!(refused("build example").field, "host"); + assert_eq!(refused("-oProxyCommand=x").field, "host"); +} + +#[test] +fn searches_match_every_word_in_name_group_or_address() { + let mut connections = Connections::parse(None).unwrap(); + let staging = connections + .save( + None, + "Staging API", + connection(json!({ "host": "api.staging.example", "user": "deploy", "port": 2222 })), + Label { + color: None, + group: Some("Servers".into()), + }, + ids(), + ) + .unwrap(); + let build = saved(&mut connections, "Build box", "build-box"); + let ids_of = |sections: Vec>| -> Vec { + sections + .into_iter() + .flat_map(|section| section.ids.into_iter().map(str::to_owned)) + .collect() + }; + let found = |query: &str| ids_of(connections.sections_matching(query).unwrap()); + assert_eq!(found(""), vec![staging.clone(), build.clone()]); + assert_eq!(found(" BUILD "), vec![build.clone()]); + assert_eq!(found("servers api"), vec![staging.clone()]); + assert_eq!(found("deploy@api"), vec![staging.clone()]); + assert_eq!(found(":2222"), vec![staging.clone()]); + assert!(found("servers build").is_empty()); + let sections = connections.sections_matching("build").unwrap(); + assert_eq!(sections.len(), 1); + assert_eq!(sections[0].group, None); + assert_eq!( + connections.sections_matching(&"x".repeat(257)).unwrap_err(), + ConnectionError::at("query", Reason::TooLong) + ); +} + +#[test] +fn imports_add_entries_with_free_names_and_fill_missing_labels() { + let mut connections = Connections::parse(None).unwrap(); + let build = saved(&mut connections, "Build box", "build-box"); + let entry = |name: &str, host: &str| ImportEntry { + name: name.into(), + connection: connection(json!({ "host": host })), + color: Some(Color::Green), + group: Some("lab".into()), + }; + let fill = LabelFill { + id: build.clone(), + color: Some(Color::Red), + group: Some("Lab".into()), + }; + let added = connections + .import( + vec![ + entry("build box", "other.example"), + entry("Gpu", "gpu.example"), + entry("Gpu", "gpu2.example"), + ], + vec![fill], + ids(), + ) + .unwrap(); + assert_eq!(added.len(), 3); + let names: Vec<&str> = connections + .entries() + .iter() + .map(SavedConnection::name) + .collect(); + assert_eq!(names, ["Build box", "build box (2)", "Gpu", "Gpu (2)"]); + let existing = connections.entry(&build).unwrap(); + assert_eq!(existing.color(), Some(Color::Red)); + assert_eq!(existing.group(), Some("Lab")); + // Imported groups take the spelling already in use. + assert!(connections + .entries() + .iter() + .all(|entry| entry.group() == Some("Lab"))); + + // A fill never replaces a label the entry has. + connections + .import( + Vec::new(), + vec![LabelFill { + id: build.clone(), + color: Some(Color::Blue), + group: Some("Other".into()), + }], + ids(), + ) + .unwrap(); + assert_eq!(connections.entry(&build).unwrap().color(), Some(Color::Red)); + assert_eq!(connections.entry(&build).unwrap().group(), Some("Lab")); +} + +#[test] +fn a_refused_import_leaves_the_list_as_it_was() { + let mut connections = Connections::parse(None).unwrap(); + saved(&mut connections, "Build box", "build-box"); + let before = connections.clone(); + let import = |name: &str, host: &str| ImportEntry { + name: name.into(), + connection: connection(json!({ "host": host })), + color: None, + group: None, + }; + let error = connections + .import( + vec![import("Fine", "fine.example"), import("Broken", "bad host")], + Vec::new(), + ids(), + ) + .unwrap_err(); + assert_eq!(error.field, "host"); + assert_eq!(connections, before); + let unknown = connections + .import( + Vec::new(), + vec![LabelFill { + id: "missing".into(), + color: None, + group: None, + }], + ids(), + ) + .unwrap_err(); + assert_eq!(unknown, ConnectionError::at("id", Reason::Unknown)); + assert_eq!(connections, before); +} + +#[test] +fn existing_entries_are_found_by_host_and_the_fields_both_set() { + let mut connections = Connections::parse(None).unwrap(); + let id = connections + .save( + None, + "Build", + connection(json!({ "host": "Build.Example", "user": "ci", "port": 2222 })), + Label::default(), + ids(), + ) + .unwrap(); + let found = |value: serde_json::Value| { + connections + .existing(&connection(value)) + .map(|entry| entry.id().to_owned()) + }; + assert_eq!(found(json!({ "host": "build.example" })), Some(id.clone())); + assert_eq!( + found(json!({ "host": "build.example", "user": "ci", "port": 2222 })), + Some(id.clone()) + ); + assert_eq!( + found(json!({ "host": "build.example", "user": "root" })), + None + ); + assert_eq!(found(json!({ "host": "build.example", "port": 22 })), None); + assert_eq!(found(json!({ "host": "other.example" })), None); + assert_eq!( + connections + .existing(&SshConnection::to_host("BUILD.example")) + .map(SavedConnection::id), + Some(id.as_str()) + ); +} + +#[test] +fn the_last_connection_time_belongs_to_the_target() { + let mut connections = Connections::parse(None).unwrap(); + let id = saved(&mut connections, "Build", "build-box"); + connections.mark_connected(&id, 1_790_000_000).unwrap(); + let text = connections.text().unwrap(); + assert!(text.contains("\"lastConnectedAt\": 1790000000"), "{text}"); + assert_eq!(Connections::parse(Some(&text)).unwrap(), connections); + + // Renaming keeps it, another host forgets it. + connections + .save( + Some(&id), + "Renamed", + connection(json!({ "host": "build-box" })), + Label::default(), + ids(), + ) + .unwrap(); + assert!(connections.text().unwrap().contains("lastConnectedAt")); + connections + .save( + Some(&id), + "Renamed", + connection(json!({ "host": "other.example" })), + Label::default(), + ids(), + ) + .unwrap(); + assert!(!connections.text().unwrap().contains("lastConnectedAt")); + + for at in [0, 253_402_300_800] { + assert_eq!( + connections.mark_connected(&id, at).unwrap_err(), + ConnectionError::at("at", Reason::Invalid) + ); + } + assert_eq!( + connections + .mark_connected("missing", 1_790_000_000) + .unwrap_err(), + ConnectionError::at("id", Reason::Unknown) + ); + let stored = text.replace("1790000000", "0"); + assert_eq!( + Connections::parse(Some(&stored)).unwrap_err(), + ConnectionError::at("lastConnectedAt", Reason::Invalid) + ); +} diff --git a/rust/crates/remote/src/client/launch.rs b/rust/crates/remote/src/client/launch.rs index 93e9d80f..05041a87 100644 --- a/rust/crates/remote/src/client/launch.rs +++ b/rust/crates/remote/src/client/launch.rs @@ -116,6 +116,32 @@ pub struct Launched { pub uploaded: bool, } +/// How far a launch got, for the connection window's steps. Reported in +/// this order; `Uploading` repeats while the binary is sent and is skipped +/// when the host keeps an installed server. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Stage { + /// The remote shell printed its first line, so OpenSSH authenticated. + Authenticated, + /// The shell reported its platform. + PlatformChecked, + /// Part of the server binary reached the stream. + Uploading { + /// Bytes written so far. + sent: usize, + /// Size of the binary. + total: usize, + }, + /// The server is in place. + Installed { + /// Whether the binary was sent now rather than kept from before. + uploaded: bool, + }, +} + +/// Bytes written between two `Uploading` reports. +const UPLOAD_CHUNK: usize = 256 * 1024; + /// Why an install directory cannot hold the server safely. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum UnsafeReason { @@ -304,20 +330,28 @@ impl LaunchError { /// stage. Two failures are left to the caller, which knows more: a shell that /// never answered the probe, whose cause the SSH process tells, and /// [`LaunchError::NoArtifact`], which the caller's `artifact_for` decided. +/// +/// `stage` is told each [`Stage`] as it is reached. pub fn launch( output: &mut impl Read, input: &mut impl Write, artifact_for: impl FnOnce(&ProbeReport) -> Option, log: &ConnectionLog, + mut stage: impl FnMut(Stage), ) -> Result { - let report = probe(output).inspect_err(|error| log.launch_failed("probe", error))?; + let report = + probe(output, &mut stage).inspect_err(|error| log.launch_failed("probe", error))?; log.shell_started(report.target()); + stage(Stage::PlatformChecked); let artifact = artifact_for(&report).ok_or_else(|| LaunchError::NoArtifact(Box::new(report.clone())))?; let name = install_name(&artifact).inspect_err(|error| log.launch_failed("artifact", error))?; let started = Instant::now(); - let deployment = deploy(output, input, &artifact, &name) + let deployment = deploy(output, input, &artifact, &name, &mut stage) .inspect_err(|error| log.launch_failed("deploy", error))?; + stage(Stage::Installed { + uploaded: deployment.uploaded, + }); log.deployed( &artifact, &deployment, @@ -331,11 +365,19 @@ pub fn launch( } /// Reads the probe block, skipping output before it such as a login banner. -fn probe(output: &mut impl Read) -> Result { +/// OpenSSH prints its banner on standard error, so the first line here +/// comes from the authenticated shell. +fn probe( + output: &mut impl Read, + stage: &mut impl FnMut(Stage), +) -> Result { let mut probe_output = Vec::new(); loop { let line = read_line(output, NOISE_LIMIT.saturating_sub(probe_output.len()))? .ok_or(LaunchError::NoShell)?; + if probe_output.is_empty() { + stage(Stage::Authenticated); + } probe_output.extend_from_slice(&line); probe_output.push(b'\n'); if String::from_utf8_lossy(&line).trim_end() == PROBE_END { @@ -372,6 +414,7 @@ fn deploy( input: &mut impl Write, artifact: &ServerArtifact, name: &str, + stage: &mut impl FnMut(Stage), ) -> Result { let binary = artifact.binary(); writeln!( @@ -389,10 +432,15 @@ fn deploy( verification: Verification::Sha256, }), INSTALL_NEEDED => { - input - .write_all(binary) - .and_then(|()| input.flush()) - .map_err(LaunchError::Io)?; + let total = binary.len(); + stage(Stage::Uploading { sent: 0, total }); + let mut sent = 0; + for chunk in binary.chunks(UPLOAD_CHUNK) { + input.write_all(chunk).map_err(LaunchError::Io)?; + sent += chunk.len(); + stage(Stage::Uploading { sent, total }); + } + input.flush().map_err(LaunchError::Io)?; let verification = installed(&answer(output)?)?; Ok(Deployment { uploaded: true, diff --git a/rust/crates/remote/src/client/mod.rs b/rust/crates/remote/src/client/mod.rs index a03c4ddd..c2466767 100644 --- a/rust/crates/remote/src/client/mod.rs +++ b/rust/crates/remote/src/client/mod.rs @@ -19,6 +19,12 @@ //! identified by a random id instead of the host or user name. //! - [`trust`] keeps the machine-local trust decisions on remote workspaces, //! keyed by the target and the host's real path. +//! - [`ssh_config`] reads what OpenSSH makes of a connection (`ssh -G`) and +//! the `Host` aliases of the user's SSH configuration. +//! - `motty` (feature `motty`) reads the SSH hosts of a Motty configuration +//! database, read only, for an import. +//! - [`prompt`] tells what an OpenSSH question asks for, so the window can +//! show a host key, password, passphrase or code form. //! //! The transport layer deliberately knows nothing about files or processes. //! Supporting a new kind of remote means adding a hop, not new capabilities. @@ -34,7 +40,11 @@ pub mod connections; pub mod forward; pub mod forward_set; pub mod launch; +#[cfg(feature = "motty")] +pub mod motty; +pub mod prompt; pub mod session; +pub mod ssh_config; pub mod transport; pub mod trust; diff --git a/rust/crates/remote/src/client/motty.rs b/rust/crates/remote/src/client/motty.rs new file mode 100644 index 00000000..8daaefda --- /dev/null +++ b/rust/crates/remote/src/client/motty.rs @@ -0,0 +1,657 @@ +//! SSH hosts of a Motty configuration database, for an import (#2231). +//! +//! Motty keeps its hosts, groups and jump routes in a SQLite database +//! (`config.db`): table `records(kind, id, stamp, deleted, payload)` with a +//! JSON payload `{"o": order, "d": data}` per record, and `meta.format` +//! naming the layout. Passwords and keys live in a separate vault, which +//! this module never opens. +//! +//! [`read`] opens the database read only and refuses layouts other than +//! [`SUPPORTED_FORMAT`]. [`candidates`] turns each host into a connection +//! the import can save and lists, field by field, what is imported and why +//! the rest is not, so the window shows the user exactly what changes. +//! Nothing is written to Motty's files. + +use crate::client::connections::{Authentication, Color, Connections, SshConnection}; +use serde::Serialize; +use serde_json::{Map, Value}; +use std::path::Path; +use std::time::Duration; + +/// The only database layout read. +pub const SUPPORTED_FORMAT: &str = "28"; + +/// Largest database read, in bytes. +const MAX_DATABASE_BYTES: u64 = 64 * 1024 * 1024; + +/// Records read in total. +const MAX_RECORDS: usize = 4096; + +/// Largest record payload read, in bytes. +const MAX_PAYLOAD_BYTES: usize = 256 * 1024; + +/// Jump hosts followed for one host. +const MAX_JUMPS: usize = 8; + +/// How long a read waits while Motty writes the database. +const BUSY_TIMEOUT: Duration = Duration::from_millis(500); + +/// Why the database could not be read. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum ReadError { + /// There is no database at the path. + Missing, + /// The database could not be opened or queried. + Unreadable, + /// The database is larger than 64 MiB or holds more than 4096 records. + TooLarge, + /// The layout is not [`SUPPORTED_FORMAT`]. + UnsupportedFormat, +} + +/// One record that is not deleted. +#[derive(Clone, Debug, PartialEq)] +pub struct Record { + /// `host`, `group` or `proxy`. + pub kind: String, + /// Motty's id of the record. + pub id: String, + /// Motty's order of the record among its kind. + pub order: i64, + /// The record's `d` object. + pub data: Map, +} + +/// The records of a database. +#[derive(Clone, Debug, PartialEq)] +pub struct Catalog { + /// `meta.format` of the database. + pub format: String, + /// Hosts, groups and jump routes, in Motty's order. + pub records: Vec, +} + +/// Reads the hosts, groups and jump routes of the database at `path`. +pub fn read(path: &Path) -> Result { + let metadata = std::fs::metadata(path).map_err(|_| ReadError::Missing)?; + if !metadata.is_file() { + return Err(ReadError::Missing); + } + if metadata.len() > MAX_DATABASE_BYTES { + return Err(ReadError::TooLarge); + } + let database = rusqlite::Connection::open_with_flags( + path, + rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX, + ) + .map_err(|_| ReadError::Unreadable)?; + database + .busy_timeout(BUSY_TIMEOUT) + .map_err(|_| ReadError::Unreadable)?; + let format: String = database + .query_row("SELECT value FROM meta WHERE key = 'format'", [], |row| { + row.get(0) + }) + .map_err(|_| ReadError::Unreadable)?; + if format != SUPPORTED_FORMAT { + return Err(ReadError::UnsupportedFormat); + } + let mut statement = database + .prepare( + "SELECT kind, id, payload FROM records \ + WHERE deleted = 0 AND kind IN ('host', 'group', 'proxy') \ + ORDER BY kind, id LIMIT ?1", + ) + .map_err(|_| ReadError::Unreadable)?; + let mut rows = statement + .query([MAX_RECORDS as i64 + 1]) + .map_err(|_| ReadError::Unreadable)?; + let mut records = Vec::new(); + while let Some(row) = rows.next().map_err(|_| ReadError::Unreadable)? { + if records.len() == MAX_RECORDS { + return Err(ReadError::TooLarge); + } + let kind: String = row.get(0).map_err(|_| ReadError::Unreadable)?; + let id: String = row.get(1).map_err(|_| ReadError::Unreadable)?; + let payload = match row.get_ref(2).map_err(|_| ReadError::Unreadable)? { + rusqlite::types::ValueRef::Blob(bytes) | rusqlite::types::ValueRef::Text(bytes) => { + bytes + } + _ => continue, + }; + if payload.len() > MAX_PAYLOAD_BYTES { + continue; + } + // A record Lithe cannot read is left out, as if Motty had none. + let Ok(Value::Object(mut payload)) = serde_json::from_slice::(payload) else { + continue; + }; + let Some(Value::Object(data)) = payload.remove("d") else { + continue; + }; + let order = payload.get("o").and_then(Value::as_i64).unwrap_or(i64::MAX); + records.push(Record { + kind, + id, + order, + data, + }); + } + records.sort_by(|left, right| { + (left.kind.as_str(), left.order, left.id.as_str()).cmp(&( + right.kind.as_str(), + right.order, + right.id.as_str(), + )) + }); + Ok(Catalog { format, records }) +} + +/// What an import does with a host. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum Status { + /// Every setting is imported. + Importable, + /// The connection is imported without some settings. + Partial, + /// A saved connection probably reaches the same host already. + Exists, + /// The host is not an SSH host, or Lithe refuses its address. + Unsupported, +} + +/// Why a Motty setting is not imported. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum Skip { + /// A password or key stored in Motty's vault, which Lithe never reads. + Secret, + /// Lithe has no such setting. + NoSetting, + /// The host uses another protocol than SSH. + Protocol, + /// The jump route runs a command, which connections may not. + Command, + /// Kerberos is left to the SSH configuration. + Kerberos, + /// Only the first key file is imported. + ExtraKey, + /// Lithe refuses the value. + Invalid, +} + +/// How one Motty setting maps to the connection. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Field { + /// Motty's name of the setting. + pub motty: String, + /// The value as the window shows it. + pub value: String, + /// The connection field it becomes; `None` when it is not imported. + #[serde(skip_serializing_if = "Option::is_none")] + pub lithe: Option<&'static str>, + /// Why it is not imported. + #[serde(skip_serializing_if = "Option::is_none")] + pub skip: Option, +} + +/// One Motty host and what an import makes of it. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Candidate { + /// Motty's id of the host, for choosing hosts. + pub key: String, + /// The host's label, the name the import saves it under. + pub name: String, + /// `[user@]host[:port]`, as the window shows it. + pub address: String, + /// Motty's operating system tag, for the icon. + #[serde(skip_serializing_if = "Option::is_none")] + pub system: Option, + /// Color, mapped to the nearest of Lithe's colors. + #[serde(skip_serializing_if = "Option::is_none")] + pub color: Option, + /// Group name. + #[serde(skip_serializing_if = "Option::is_none")] + pub group: Option, + /// What the import does with it. + pub status: Status, + /// The saved connection that probably reaches the same host. + #[serde(skip_serializing_if = "Option::is_none")] + pub existing_id: Option, + /// The connection the import saves; `None` when it is unsupported. + #[serde(skip_serializing_if = "Option::is_none")] + pub connection: Option, + /// Every setting the host has, imported or not. + pub fields: Vec, +} + +/// The hosts of a database and what an import makes of them. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Report { + /// `meta.format` of the database. + pub format: String, + /// Groups that have at least one host, in Motty's order. + pub groups: Vec, + /// Hosts in Motty's order. + pub candidates: Vec, +} + +/// What an import makes of every host of `catalog`, compared with the +/// saved `connections`. +pub fn candidates(catalog: &Catalog, connections: &Connections) -> Report { + let of_kind = |kind: &'static str| { + catalog + .records + .iter() + .filter(move |record| record.kind == kind) + }; + let hosts: Vec<&Record> = of_kind("host").collect(); + let group_records: Vec<&Record> = of_kind("group").collect(); + let proxies: Vec<&Record> = of_kind("proxy") + .filter(|proxy| !boolean(&proxy.data, "stopped")) + .collect(); + let group_name = |value: &str| -> Option { + let value = value.trim(); + if value.is_empty() { + return None; + } + let named = group_records + .iter() + .find(|group| group.id == value) + .and_then(|group| text(&group.data, "name")); + Some(named.unwrap_or(value).trim().to_owned()).filter(|name| !name.is_empty()) + }; + let mut groups: Vec = Vec::new(); + let candidates = hosts + .iter() + .map(|host| { + let candidate = candidate(host, &hosts, &proxies, &group_name, connections); + if let Some(group) = &candidate.group { + if !groups.iter().any(|known| known.eq_ignore_ascii_case(group)) { + groups.push(group.clone()); + } + } + candidate + }) + .collect(); + Report { + format: catalog.format.clone(), + groups, + candidates, + } +} + +fn candidate( + host: &Record, + hosts: &[&Record], + proxies: &[&Record], + group_name: &dyn Fn(&str) -> Option, + connections: &Connections, +) -> Candidate { + let data = &host.data; + let mut fields = Vec::new(); + let address = text(data, "address").unwrap_or("").trim().to_owned(); + let user = text(data, "user") + .map(str::trim) + .filter(|user| !user.is_empty()); + let port = data + .get("port") + .and_then(Value::as_u64) + .and_then(|port| u16::try_from(port).ok()) + .filter(|port| *port != 0); + let label = text(data, "label") + .map(str::trim) + .filter(|label| !label.is_empty()) + .unwrap_or(&address) + .to_owned(); + fields.push(imported("label", label.clone(), "name")); + fields.push(imported("address", address.clone(), "host")); + if let Some(user) = user { + fields.push(imported("user", user.to_owned(), "user")); + } + if let Some(port) = port { + fields.push(imported("port", port.to_string(), "port")); + } + let color = text(data, "color").and_then(nearest_color); + if let Some(hex) = text(data, "color").filter(|_| color.is_some()) { + fields.push(imported("color", hex.trim().to_owned(), "color")); + } + let group = text(data, "group").and_then(group_name); + if let Some(group) = &group { + fields.push(imported("group", group.clone(), "group")); + } + + let mut connection = SshConnection::to_host(address.clone()); + connection.user = user.map(str::to_owned); + connection.port = port; + + let protocol = text(data, "protocol") + .unwrap_or("") + .trim() + .to_ascii_lowercase(); + let ssh = protocol.is_empty() || protocol == "ssh"; + if !ssh { + fields.push(skipped("protocol", protocol.clone(), Skip::Protocol)); + } + + let options = data.get("ssh_options").and_then(Value::as_object); + let key_files: Vec = options + .and_then(|options| options.get("identity_files")) + .and_then(Value::as_array) + .map(|files| { + files + .iter() + .filter_map(Value::as_str) + .map(str::trim) + .filter(|file| !file.is_empty()) + .map(str::to_owned) + .collect() + }) + .unwrap_or_default(); + let method = text(data, "authentication") + .unwrap_or("") + .trim() + .to_ascii_lowercase(); + match method.as_str() { + "password" => connection.authentication = Authentication::Password, + "agent" => connection.authentication = Authentication::Agent, + // Keys, or Motty's automatic choice: the first key file decides. + "" | "key" | "publickey" => { + if let Some(first) = key_files.first() { + connection.authentication = Authentication::PrivateKey; + connection.identity_file = Some(first.clone()); + } + } + _ => {} + } + match method.as_str() { + "" => {} + "password" | "agent" | "key" | "publickey" => { + fields.push(imported("authentication", method.clone(), "authentication")); + } + "kerberos" => fields.push(skipped("authentication", method.clone(), Skip::Kerberos)), + _ => fields.push(skipped("authentication", method.clone(), Skip::NoSetting)), + } + let mut keys = key_files.iter(); + if let Some(chosen) = &connection.identity_file { + keys.next(); + fields.push(imported( + "ssh_options.identity_files", + chosen.clone(), + "identityFile", + )); + } + for extra in keys { + fields.push(skipped( + "ssh_options.identity_files", + extra.clone(), + Skip::ExtraKey, + )); + } + for secret in ["identity", "credential"] { + if data.get(secret).is_some_and(present) { + fields.push(skipped(secret, String::new(), Skip::Secret)); + } + } + if let Some(interval) = options + .and_then(|options| options.get("server_alive_interval")) + .and_then(Value::as_u64) + .and_then(|seconds| u32::try_from(seconds).ok()) + .filter(|seconds| *seconds != 0) + { + connection.keep_alive_seconds = Some(interval); + fields.push(imported( + "ssh_options.server_alive_interval", + interval.to_string(), + "keepAliveSeconds", + )); + } + for (key, value) in options.into_iter().flatten() { + let handled = matches!(key.as_str(), "identity_files" | "server_alive_interval") + // Lithe offers only the chosen key, with `IdentitiesOnly`. + || (key == "identities_only" && connection.identity_file.is_some()); + if !handled && present(value) { + fields.push(skipped( + &format!("ssh_options.{key}"), + display(value), + Skip::NoSetting, + )); + } + } + match jump_route(host, hosts, proxies) { + Jump::None => {} + Jump::Route(route) => { + connection.proxy_jump = Some(route.clone()); + fields.push(imported("proxy", route, "proxyJump")); + } + Jump::Command => fields.push(skipped("proxy", String::new(), Skip::Command)), + } + for (key, value) in data { + if !HANDLED.contains(&key.as_str()) && present(value) { + fields.push(skipped(key, display(value), Skip::NoSetting)); + } + } + + let connection = connection.normalized(); + let valid = ssh && connection.check().is_ok(); + if ssh && !valid { + if let Some(field) = fields.iter_mut().find(|field| field.motty == "address") { + field.lithe = None; + field.skip = Some(Skip::Invalid); + } + } + let existing_id = valid + .then(|| connections.existing(&connection)) + .flatten() + .map(|entry| entry.id().to_owned()); + let status = if !valid { + Status::Unsupported + } else if existing_id.is_some() { + Status::Exists + } else if fields.iter().any(|field| field.skip.is_some()) { + Status::Partial + } else { + Status::Importable + }; + Candidate { + key: host.id.clone(), + name: label, + address: display_address(&address, user, port), + system: text(data, "system") + .map(str::trim) + .filter(|system| !system.is_empty()) + .map(str::to_owned), + color, + group, + status, + existing_id, + connection: valid.then_some(connection), + fields, + } +} + +/// Host settings [`candidate`] maps itself, and those that only change how +/// Motty shows a host. +const HANDLED: &[&str] = &[ + "label", + "address", + "user", + "port", + "color", + "group", + "protocol", + "authentication", + "ssh_options", + "identity", + "credential", + "proxy", + "id", + "icon", + "system", + "order", + "pinned", +]; + +fn imported(motty: &str, value: String, lithe: &'static str) -> Field { + Field { + motty: motty.to_owned(), + value, + lithe: Some(lithe), + skip: None, + } +} + +fn skipped(motty: &str, value: String, skip: Skip) -> Field { + Field { + motty: motty.to_owned(), + value, + lithe: None, + skip: Some(skip), + } +} + +enum Jump { + None, + Route(String), + Command, +} + +/// The jump route of `host`: the jump host of its proxy record, after the +/// jump host's own route, as OpenSSH's comma-separated `ProxyJump`. +fn jump_route(host: &Record, hosts: &[&Record], proxies: &[&Record]) -> Jump { + let mut route: Vec = Vec::new(); + let mut target = host.id.clone(); + for _ in 0..MAX_JUMPS { + let Some(proxy) = proxies + .iter() + .find(|proxy| text(&proxy.data, "target_id") == Some(target.as_str())) + else { + break; + }; + if boolean(&proxy.data, "via_shell") + || text(&proxy.data, "relay_command").is_some_and(|command| !command.trim().is_empty()) + { + return Jump::Command; + } + let jump_host = + text(&proxy.data, "jump_id").and_then(|id| hosts.iter().find(|host| host.id == id)); + let (address, user, port) = match jump_host { + Some(jump) => ( + text(&jump.data, "address").unwrap_or("").trim().to_owned(), + text(&jump.data, "user").map(str::to_owned), + jump.data.get("port").and_then(Value::as_u64), + ), + None => ( + text(&proxy.data, "jump_address") + .unwrap_or("") + .trim() + .to_owned(), + text(&proxy.data, "jump_user").map(str::to_owned), + proxy.data.get("jump_port").and_then(Value::as_u64), + ), + }; + if address.is_empty() { + break; + } + let port = port + .and_then(|port| u16::try_from(port).ok()) + .filter(|port| *port != 0); + let user = user + .as_deref() + .map(str::trim) + .filter(|user| !user.is_empty()); + route.insert(0, display_address(&address, user, port)); + match jump_host { + Some(jump) if jump.id != target => target = jump.id.clone(), + _ => break, + } + } + if route.is_empty() { + Jump::None + } else { + Jump::Route(route.join(",")) + } +} + +/// `[user@]host[:port]`, with an IPv6 host in brackets when a port follows. +fn display_address(host: &str, user: Option<&str>, port: Option) -> String { + let mut text = String::new(); + if let Some(user) = user { + text.push_str(user); + text.push('@'); + } + match port { + Some(port) if host.contains(':') => text.push_str(&format!("[{host}]:{port}")), + Some(port) => text.push_str(&format!("{host}:{port}")), + None => text.push_str(host), + } + text +} + +/// The Lithe color closest to Motty's `#rrggbb` color. +fn nearest_color(hex: &str) -> Option { + let hex = hex.trim().strip_prefix('#')?; + if hex.len() != 6 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return None; + } + let channel = + |index: usize| i32::from(u8::from_str_radix(&hex[index..index + 2], 16).unwrap_or(0)); + let (red, green, blue) = (channel(0), channel(2), channel(4)); + // Motty's palette (Tailwind 500 shades), which maps exactly. + [ + (Color::Red, 0xef, 0x44, 0x44), + (Color::Orange, 0xf9, 0x73, 0x16), + (Color::Yellow, 0xea, 0xb3, 0x08), + (Color::Green, 0x22, 0xc5, 0x5e), + (Color::Blue, 0x3b, 0x82, 0xf6), + (Color::Purple, 0xa8, 0x55, 0xf7), + ] + .into_iter() + .min_by_key(|(_, r, g, b)| (red - r).pow(2) + (green - g).pow(2) + (blue - b).pow(2)) + .map(|(color, ..)| color) +} + +fn text<'a>(data: &'a Map, key: &str) -> Option<&'a str> { + data.get(key).and_then(Value::as_str) +} + +fn boolean(data: &Map, key: &str) -> bool { + data.get(key).and_then(Value::as_bool).unwrap_or(false) +} + +/// Whether a setting has a value: not null, `false`, `0`, empty text, an +/// empty list or an object of such values. +fn present(value: &Value) -> bool { + match value { + Value::Null => false, + Value::Bool(set) => *set, + Value::Number(number) => number.as_f64() != Some(0.0), + Value::String(text) => !text.trim().is_empty(), + Value::Array(items) => items.iter().any(present), + Value::Object(fields) => fields.values().any(present), + } +} + +/// A short form of a setting's value for the window. +fn display(value: &Value) -> String { + match value { + Value::String(text) => text.trim().to_owned(), + Value::Bool(_) => String::new(), + Value::Array(items) => items + .iter() + .filter(|item| present(item)) + .map(display) + .collect::>() + .join(", "), + Value::Object(_) => String::new(), + other => other.to_string(), + } +} + +#[cfg(test)] +mod tests; diff --git a/rust/crates/remote/src/client/motty/tests.rs b/rust/crates/remote/src/client/motty/tests.rs new file mode 100644 index 00000000..343c08b2 --- /dev/null +++ b/rust/crates/remote/src/client/motty/tests.rs @@ -0,0 +1,384 @@ +use super::*; +use crate::client::connections::Label; +use serde_json::json; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// A Motty database in a scratch directory, removed when dropped. +struct Database { + directory: PathBuf, + path: PathBuf, +} + +impl Database { + fn new(format: &str) -> Self { + static SEQUENCE: AtomicU64 = AtomicU64::new(0); + let directory = std::env::temp_dir().join(format!( + "lithe-remote-motty-{}-{}", + std::process::id(), + SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + let _ = std::fs::remove_dir_all(&directory); + std::fs::create_dir_all(&directory).unwrap(); + let path = directory.join("config.db"); + let database = rusqlite::Connection::open(&path).unwrap(); + database + .execute_batch( + "CREATE TABLE records (kind TEXT NOT NULL, id TEXT NOT NULL, stamp TEXT NOT NULL, \ + deleted INTEGER NOT NULL DEFAULT 0, payload BLOB, PRIMARY KEY (kind, id)) WITHOUT ROWID;\ + CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID;", + ) + .unwrap(); + database + .execute( + "INSERT INTO meta (key, value) VALUES ('format', ?1)", + [format], + ) + .unwrap(); + Self { directory, path } + } + + fn insert(&self, kind: &str, id: &str, deleted: bool, payload: serde_json::Value) { + rusqlite::Connection::open(&self.path) + .unwrap() + .execute( + "INSERT INTO records (kind, id, stamp, deleted, payload) VALUES (?1, ?2, '1', ?3, ?4)", + rusqlite::params![kind, id, deleted, payload.to_string().into_bytes()], + ) + .unwrap(); + } + + fn host(&self, id: &str, order: i64, data: serde_json::Value) { + let mut data = data; + data["id"] = json!(id); + self.insert("host", id, false, json!({ "o": order, "d": data })); + } + + fn report(&self, connections: &Connections) -> Report { + candidates(&read(&self.path).expect("readable"), connections) + } +} + +impl Drop for Database { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.directory); + } +} + +fn find<'a>(report: &'a Report, key: &str) -> &'a Candidate { + report + .candidates + .iter() + .find(|candidate| candidate.key == key) + .unwrap_or_else(|| panic!("no candidate {key}")) +} + +fn field<'a>(candidate: &'a Candidate, motty: &str) -> &'a Field { + candidate + .fields + .iter() + .find(|field| field.motty == motty) + .unwrap_or_else(|| panic!("no field {motty}")) +} + +#[test] +fn ssh_hosts_become_connections_in_mottys_order() { + let database = Database::new(SUPPORTED_FORMAT); + database.insert( + "group", + "g1", + false, + json!({ "o": 0, "d": { "name": "Build machines" } }), + ); + database.host( + "b", + 2, + json!({ + "label": "GPU box", + "address": "gpu.example", + "user": "ml", + "port": 2222, + "color": "#22c55e", + "group": "g1", + "system": "ubuntu", + "ssh_options": { "server_alive_interval": 30, "identities_only": true, "identity_files": ["~/.ssh/gpu"] }, + }), + ); + database.host( + "a", + 1, + json!({ "label": "", "address": "build.example", "port": 0, "group": "Build Machines", "color": "" }), + ); + database.host( + "gone", + 0, + json!({ "label": "Old", "address": "old.example" }), + ); + database.insert( + "host", + "deleted", + true, + json!({ "o": 0, "d": { "address": "deleted.example" } }), + ); + + let report = database.report(&Connections::default()); + assert_eq!(report.format, "28"); + let keys: Vec<&str> = report + .candidates + .iter() + .map(|candidate| candidate.key.as_str()) + .collect(); + assert_eq!(keys, ["gone", "a", "b"]); + assert_eq!(report.groups, ["Build Machines"]); + + let gpu = find(&report, "b"); + assert_eq!(gpu.status, Status::Importable); + assert_eq!(gpu.name, "GPU box"); + assert_eq!(gpu.address, "ml@gpu.example:2222"); + assert_eq!(gpu.system.as_deref(), Some("ubuntu")); + assert_eq!(gpu.color, Some(Color::Green)); + assert_eq!(gpu.group.as_deref(), Some("Build machines")); + assert_eq!( + serde_json::to_value(gpu.connection.as_ref().unwrap()).unwrap(), + json!({ + "host": "gpu.example", + "port": 2222, + "user": "ml", + "authentication": "privateKey", + "identityFile": "~/.ssh/gpu", + "keepAliveSeconds": 30, + }) + ); + assert_eq!( + field(gpu, "ssh_options.identity_files").lithe, + Some("identityFile") + ); + + // A blank label takes the address, and port 0 is no port. + let build = find(&report, "a"); + assert_eq!(build.name, "build.example"); + assert_eq!(build.address, "build.example"); + assert_eq!(build.color, None); + assert_eq!(build.status, Status::Importable); +} + +#[test] +fn settings_lithe_has_no_place_for_are_listed_with_the_reason() { + let database = Database::new(SUPPORTED_FORMAT); + database.host( + "h", + 0, + json!({ + "label": "Partly", + "address": "partly.example", + "authentication": "kerberos", + "identity": "motty-key-1", + "credential": "stored", + "forward_x11": true, + "agent_forward": false, + "encoding": "gbk", + "terminal": "", + "ssh_options": { "server_alive_count_max": 5, "identity_files": [] }, + }), + ); + database.host( + "k", + 1, + json!({ + "address": "keys.example", + "authentication": "key", + "ssh_options": { "identity_files": ["~/.ssh/one", "~/.ssh/two"] }, + }), + ); + let report = database.report(&Connections::default()); + let partly = find(&report, "h"); + assert_eq!(partly.status, Status::Partial); + assert_eq!(field(partly, "authentication").skip, Some(Skip::Kerberos)); + assert_eq!(field(partly, "identity").skip, Some(Skip::Secret)); + assert_eq!( + field(partly, "identity").value, + "", + "the key reference is not shown" + ); + assert_eq!(field(partly, "credential").skip, Some(Skip::Secret)); + assert_eq!(field(partly, "forward_x11").skip, Some(Skip::NoSetting)); + assert_eq!(field(partly, "encoding").value, "gbk"); + assert_eq!( + field(partly, "ssh_options.server_alive_count_max").skip, + Some(Skip::NoSetting) + ); + for unset in ["agent_forward", "terminal"] { + assert!( + partly.fields.iter().all(|field| field.motty != unset), + "{unset}" + ); + } + assert_eq!( + serde_json::to_value(partly.connection.as_ref().unwrap()).unwrap(), + json!({ "host": "partly.example" }) + ); + + let keys = find(&report, "k"); + assert_eq!(keys.status, Status::Partial); + let files: Vec<(&str, Option)> = keys + .fields + .iter() + .filter(|field| field.motty == "ssh_options.identity_files") + .map(|field| (field.value.as_str(), field.skip)) + .collect(); + assert_eq!( + files, + [("~/.ssh/one", None), ("~/.ssh/two", Some(Skip::ExtraKey))] + ); +} + +#[test] +fn other_protocols_and_refused_addresses_are_not_imported() { + let database = Database::new(SUPPORTED_FORMAT); + database.host( + "t", + 0, + json!({ "label": "Router", "address": "router.example", "protocol": "telnet" }), + ); + database.host( + "bad", + 1, + json!({ "label": "Bad", "address": "-oProxyCommand=x" }), + ); + let report = database.report(&Connections::default()); + let telnet = find(&report, "t"); + assert_eq!(telnet.status, Status::Unsupported); + assert_eq!(telnet.connection, None); + assert_eq!(field(telnet, "protocol").skip, Some(Skip::Protocol)); + let bad = find(&report, "bad"); + assert_eq!(bad.status, Status::Unsupported); + assert_eq!(field(bad, "address").skip, Some(Skip::Invalid)); +} + +#[test] +fn jump_routes_follow_proxy_records_and_refuse_commands() { + let database = Database::new(SUPPORTED_FORMAT); + database.host( + "edge", + 0, + json!({ "address": "edge.example", "user": "ops", "port": 2200 }), + ); + database.host("inner", 1, json!({ "address": "inner.example" })); + database.host("target", 2, json!({ "address": "target.example" })); + database.host("relayed", 3, json!({ "address": "relayed.example" })); + database.host("paused", 4, json!({ "address": "paused.example" })); + database.insert( + "proxy", + "p1", + false, + json!({ "o": 0, "d": { "target_id": "target", "jump_id": "inner" } }), + ); + database.insert( + "proxy", + "p2", + false, + json!({ "o": 1, "d": { "target_id": "inner", "jump_id": "edge" } }), + ); + database.insert( + "proxy", + "p3", + false, + json!({ "o": 2, "d": { "target_id": "relayed", "jump_address": "x.example", "relay_command": "nc %h %p" } }), + ); + database.insert( + "proxy", + "p4", + false, + json!({ "o": 3, "d": { "target_id": "paused", "jump_address": "x.example", "stopped": true } }), + ); + let report = database.report(&Connections::default()); + let target = find(&report, "target"); + assert_eq!( + target.connection.as_ref().unwrap().proxy_jump(), + Some("ops@edge.example:2200,inner.example") + ); + assert_eq!(field(target, "proxy").lithe, Some("proxyJump")); + let relayed = find(&report, "relayed"); + assert_eq!(relayed.status, Status::Partial); + assert_eq!(field(relayed, "proxy").skip, Some(Skip::Command)); + assert_eq!(relayed.connection.as_ref().unwrap().proxy_jump(), None); + assert!(find(&report, "paused") + .fields + .iter() + .all(|field| field.motty != "proxy")); +} + +#[test] +fn hosts_already_saved_are_marked_with_the_entry() { + let database = Database::new(SUPPORTED_FORMAT); + database.host( + "h", + 0, + json!({ "label": "Build", "address": "Build.Example", "user": "ci" }), + ); + let mut connections = Connections::default(); + let id = connections + .save( + None, + "Mine", + SshConnection::to_host("build.example"), + Label::default(), + || "saved-1".to_owned(), + ) + .unwrap(); + let report = database.report(&connections); + let build = find(&report, "h"); + assert_eq!(build.status, Status::Exists); + assert_eq!(build.existing_id.as_deref(), Some(id.as_str())); +} + +#[test] +fn colors_map_to_the_nearest_lithe_color() { + assert_eq!(nearest_color("#ef4444"), Some(Color::Red)); + assert_eq!(nearest_color("#F97316"), Some(Color::Orange)); + assert_eq!(nearest_color("#eab308"), Some(Color::Yellow)); + assert_eq!(nearest_color("#3b82f6"), Some(Color::Blue)); + assert_eq!(nearest_color("#a855f7"), Some(Color::Purple)); + assert_eq!(nearest_color("#10b981"), Some(Color::Green)); + assert_eq!(nearest_color(""), None); + assert_eq!(nearest_color("red"), None); + assert_eq!(nearest_color("#12345"), None); +} + +#[test] +fn unreadable_databases_say_why() { + let database = Database::new("27"); + assert_eq!(read(&database.path), Err(ReadError::UnsupportedFormat)); + assert_eq!( + read(&database.directory.join("absent.db")), + Err(ReadError::Missing) + ); + assert_eq!(read(&database.directory), Err(ReadError::Missing)); + let garbage = database.directory.join("garbage.db"); + std::fs::write(&garbage, b"not a database").unwrap(); + assert_eq!(read(&garbage), Err(ReadError::Unreadable)); +} + +#[test] +fn records_lithe_cannot_read_are_left_out() { + let database = Database::new(SUPPORTED_FORMAT); + database.insert("host", "text", false, json!("not an object")); + database.insert("host", "nodata", false, json!({ "o": 0 })); + database.host("ok", 0, json!({ "address": "ok.example" })); + let report = database.report(&Connections::default()); + let keys: Vec<&str> = report + .candidates + .iter() + .map(|candidate| candidate.key.as_str()) + .collect(); + assert_eq!(keys, ["ok"]); +} + +#[test] +fn reading_never_changes_the_database() { + let database = Database::new(SUPPORTED_FORMAT); + database.host("h", 0, json!({ "address": "h.example" })); + let before = std::fs::read(&database.path).unwrap(); + read(&database.path).unwrap(); + assert_eq!(std::fs::read(&database.path).unwrap(), before); +} diff --git a/rust/crates/remote/src/client/prompt.rs b/rust/crates/remote/src/client/prompt.rs new file mode 100644 index 00000000..a59294ed --- /dev/null +++ b/rust/crates/remote/src/client/prompt.rs @@ -0,0 +1,161 @@ +//! What an OpenSSH question asks for, so the connection window can show a +//! fitting form: a host key to confirm, a password, a key passphrase or a +//! one-time code. +//! +//! OpenSSH hands its questions to AskPass only as text. The categories match +//! its stable English wording; anything else stays `other`, and the window +//! then shows the question as asked. + +use serde::Serialize; + +/// The kind of answer a question expects. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum PromptKind { + /// An unknown host key to accept (`yes`) or decline (`no`). + HostKey, + /// The account's password. + Password, + /// The passphrase of a private key. + Passphrase, + /// A one-time or verification code. + Code, + /// Any other question. + Other, +} + +/// A classified question. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Prompt { + /// What the answer is. + pub kind: PromptKind, + /// The host key's algorithm as OpenSSH names it, such as `ED25519`. + /// Only set for [`PromptKind::HostKey`]. + #[serde(skip_serializing_if = "Option::is_none")] + pub key_type: Option, + /// The host key's fingerprint, such as `SHA256:…`. Only set for + /// [`PromptKind::HostKey`]. + #[serde(skip_serializing_if = "Option::is_none")] + pub fingerprint: Option, +} + +/// Longest algorithm and fingerprint kept; OpenSSH's are far shorter. +const MAX_KEY_TEXT: usize = 128; + +/// Classifies one question as OpenSSH asked it. +pub fn classify(prompt: &str) -> Prompt { + let lower = prompt.to_ascii_lowercase(); + let has = |needles: &[&str]| needles.iter().any(|needle| lower.contains(needle)); + let kind = if has(&[ + "authenticity of host", + "continue connecting", + "key fingerprint is", + ]) { + PromptKind::HostKey + } else if has(&["passphrase"]) { + PromptKind::Passphrase + } else if has(&["password"]) && !has(&["one-time", "one time"]) { + PromptKind::Password + } else if has(&[ + "verification code", + "one-time", + "one time", + "otp", + "token", + "authenticator", + "two-factor", + "passcode", + ]) { + PromptKind::Code + } else { + PromptKind::Other + }; + let (key_type, fingerprint) = if kind == PromptKind::HostKey { + host_key(prompt) + } else { + (None, None) + }; + Prompt { + kind, + key_type, + fingerprint, + } +} + +/// Reads `ED25519 key fingerprint is SHA256:….` from a host key question. +fn host_key(prompt: &str) -> (Option, Option) { + const MARKER: &str = " key fingerprint is "; + for line in prompt.lines() { + let Some(at) = line.find(MARKER) else { + continue; + }; + let key_type = line[..at].split_whitespace().last().map(str::to_owned); + let fingerprint = line[at + MARKER.len()..] + .split_whitespace() + .next() + .map(|word| word.trim_end_matches('.').to_owned()); + let bounded = |text: Option| { + text.filter(|text| { + !text.is_empty() + && text.len() <= MAX_KEY_TEXT + && text.chars().all(|c| c.is_ascii_graphic()) + }) + }; + return (bounded(key_type), bounded(fingerprint)); + } + (None, None) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn unknown_host_keys_carry_the_algorithm_and_fingerprint() { + let prompt = classify( + "The authenticity of host 'build-box (192.0.2.10)' can't be established.\n\ + ED25519 key fingerprint is SHA256:Q2xhdWRlRXhhbXBsZUZpbmdlcnByaW50.\n\ + This key is not known by any other names.\n\ + Are you sure you want to continue connecting (yes/no/[fingerprint])? ", + ); + assert_eq!(prompt.kind, PromptKind::HostKey); + assert_eq!(prompt.key_type.as_deref(), Some("ED25519")); + assert_eq!( + prompt.fingerprint.as_deref(), + Some("SHA256:Q2xhdWRlRXhhbXBsZUZpbmdlcnByaW50") + ); + } + + #[test] + fn a_host_key_question_without_a_fingerprint_line_has_none() { + let prompt = classify("Are you sure you want to continue connecting (yes/no)? "); + assert_eq!(prompt.kind, PromptKind::HostKey); + assert_eq!(prompt.key_type, None); + assert_eq!(prompt.fingerprint, None); + } + + #[test] + fn secrets_are_told_apart_by_their_wording() { + let cases = [ + ("dev@build-box's password: ", PromptKind::Password), + ("(dev@build-box) Password: ", PromptKind::Password), + ( + "Enter passphrase for key '/home/dev/.ssh/id_ed25519': ", + PromptKind::Passphrase, + ), + ( + "Enter passphrase for /home/dev/.ssh/id_ed25519: ", + PromptKind::Passphrase, + ), + ("Verification code: ", PromptKind::Code), + ("One-time password (OATH) for `dev': ", PromptKind::Code), + ("Enter PIN for ED25519-SK key: ", PromptKind::Other), + ]; + for (text, kind) in cases { + let prompt = classify(text); + assert_eq!(prompt.kind, kind, "{text}"); + assert_eq!(prompt.fingerprint, None, "{text}"); + } + } +} diff --git a/rust/crates/remote/src/client/ssh_config.rs b/rust/crates/remote/src/client/ssh_config.rs new file mode 100644 index 00000000..80e8a4a6 --- /dev/null +++ b/rust/crates/remote/src/client/ssh_config.rs @@ -0,0 +1,454 @@ +//! What OpenSSH makes of a saved connection, and the hosts the user's SSH +//! configuration names (design §3.1). +//! +//! - [`effective_settings`] reads two `ssh -G` outputs of the same hop, one +//! with and one without the configuration files (see +//! [`crate::client::SshHop::configuration_command`]), and tells for every +//! value the window shows whether the connection, the SSH configuration or +//! a default set it. +//! - [`configuration_files`] and [`host_aliases`] find the `Host` aliases of +//! `~/.ssh/config` and the files it includes, without running anything; +//! [`configured_host`] reads one alias's `ssh -G` output for the import +//! list. +//! +//! Nothing here starts a process: the caller runs `ssh -G` with the +//! restricted environment of the transport and passes the output in. Only +//! files below the user's home directory are read, at most 64 files of +//! 1 MiB each, 16 `Include` levels deep, as OpenSSH bounds its own reading. + +use crate::client::connections::{Authentication, SshConnection, DEFAULT_CONNECT_TIMEOUT_SECONDS}; +use crate::client::transport::SSH_KEEPALIVE_SECONDS; +use serde::Serialize; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +/// `Include` levels followed, as OpenSSH's own `READCONF_MAX_DEPTH`. +const MAX_INCLUDE_DEPTH: usize = 16; + +/// Configuration files read in total. +const MAX_FILES: usize = 64; + +/// Largest configuration file read, in bytes. +const MAX_FILE_BYTES: u64 = 1024 * 1024; + +/// Aliases listed for an import. +pub const MAX_ALIASES: usize = 256; + +/// Directory entries a wildcard `Include` examines per directory. +const MAX_DIRECTORY_ENTRIES: usize = 1024; + +/// Where an effective value comes from. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum Source { + /// The saved connection sets it. + Connection, + /// The user's or the system's SSH configuration sets it. + SshConfig, + /// Neither does: it is OpenSSH's or Lithe's default. + Default, +} + +/// One value and where it comes from. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Effective { + /// The value OpenSSH uses. + pub value: T, + /// Where it comes from. + pub source: Source, +} + +/// The values a connection uses, as `ssh -G` prints them. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct EffectiveSettings { + /// Name or address OpenSSH connects to after applying `HostName`. + pub host_name: Effective, + /// TCP port. + pub port: Effective, + /// Login name; the local user name by default. + pub user: Effective, + /// Private key paths OpenSSH offers, as written in the configuration. + /// Empty for password authentication. + pub identity_files: Effective>, + /// Jump hosts, or `None` for a direct connection. + pub proxy_jump: Effective>, + /// Seconds to wait for the TCP connection. + pub connect_timeout_seconds: Effective, + /// Seconds between keep-alive probes. + pub keep_alive_seconds: Effective, +} + +/// Why `ssh -G` output could not be read. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct OutputError { + /// The key that is missing or malformed. + pub key: &'static str, +} + +/// `ssh -G` output: lowercase keys and their values in order. Keys such as +/// `identityfile` repeat. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct Output { + values: BTreeMap>, +} + +impl Output { + /// Reads `ssh -G` output, one `key value` pair per line. + pub fn parse(text: &str) -> Self { + let mut values: BTreeMap> = BTreeMap::new(); + for line in text.lines() { + let Some((key, value)) = line.trim().split_once(' ') else { + continue; + }; + values + .entry(key.to_ascii_lowercase()) + .or_default() + .push(value.trim().to_owned()); + } + Self { values } + } + + fn first(&self, key: &str) -> Option<&str> { + self.values + .get(key) + .and_then(|values| values.first()) + .map(String::as_str) + } + + fn all(&self, key: &str) -> Vec { + self.values.get(key).cloned().unwrap_or_default() + } + + fn required(&self, key: &'static str) -> Result<&str, OutputError> { + self.first(key).ok_or(OutputError { key }) + } + + fn number(&self, key: &'static str) -> Result { + self.required(key)?.parse().map_err(|_| OutputError { key }) + } + + /// `proxyjump`, absent when unset or `none`. + fn jumps(&self) -> Option { + self.first("proxyjump") + .filter(|jumps| !jumps.eq_ignore_ascii_case("none")) + .map(str::to_owned) + } +} + +/// The settings `connection` uses: `configured` is the `ssh -G` output of +/// its hop, `baseline` the same command with `-F none`. +/// +/// A field the connection sets comes from the connection. Otherwise a value +/// that differs from the baseline comes from the SSH configuration, and an +/// equal one is a default. The connect timeout and the keep-alive interval +/// are always passed on the command line, which wins over the configuration +/// files, so they come from the connection or are Lithe's defaults. +pub fn effective_settings( + connection: &SshConnection, + configured: &Output, + baseline: &Output, +) -> Result { + let source = |set: bool, key: &str| { + if set { + Source::Connection + } else if configured.values.get(key) != baseline.values.get(key) { + Source::SshConfig + } else { + Source::Default + } + }; + let host_name = configured.required("hostname")?.to_owned(); + let host_source = match source(false, "hostname") { + // Without a `HostName`, OpenSSH connects to the host the connection + // names. + Source::Default => Source::Connection, + other => other, + }; + let identity_files = match connection.authentication() { + Authentication::Password => Effective { + value: Vec::new(), + source: Source::Connection, + }, + Authentication::PrivateKey => Effective { + value: configured.all("identityfile"), + source: Source::Connection, + }, + Authentication::Auto | Authentication::Agent => Effective { + value: configured.all("identityfile"), + source: source(false, "identityfile"), + }, + }; + let lithe_default = |set: bool| { + if set { + Source::Connection + } else { + Source::Default + } + }; + Ok(EffectiveSettings { + host_name: Effective { + value: host_name, + source: host_source, + }, + port: Effective { + value: configured.number("port")?, + source: source(connection.port().is_some(), "port"), + }, + user: Effective { + value: configured.required("user")?.to_owned(), + source: source(connection.user().is_some(), "user"), + }, + identity_files, + proxy_jump: Effective { + value: configured.jumps(), + source: source(connection.proxy_jump().is_some(), "proxyjump"), + }, + connect_timeout_seconds: Effective { + value: configured + .number("connecttimeout") + .unwrap_or(DEFAULT_CONNECT_TIMEOUT_SECONDS), + source: lithe_default(connection.connect_timeout_seconds().is_some()), + }, + keep_alive_seconds: Effective { + value: configured + .number("serveraliveinterval") + .unwrap_or(SSH_KEEPALIVE_SECONDS), + source: lithe_default(connection.keep_alive_seconds().is_some()), + }, + }) +} + +/// A `Host` line's names, as the import lists them. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum HostName { + /// A name a connection can use as its host. + Alias(String), + /// A pattern with `*`, `?` or `!`, which names no single host. + Pattern(String), +} + +/// What one alias resolves to, read from its `ssh -G` output. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ConfiguredHost { + /// Name or address after `HostName`. + pub host_name: String, + /// Login name. + pub user: String, + /// TCP port. + pub port: u16, + /// Jump hosts, if any. + #[serde(skip_serializing_if = "Option::is_none")] + pub proxy_jump: Option, +} + +/// Reads one alias's `ssh -G` output. +pub fn configured_host(output: &Output) -> Result { + Ok(ConfiguredHost { + host_name: output.required("hostname")?.to_owned(), + user: output.required("user")?.to_owned(), + port: output.number("port")?, + proxy_jump: output.jumps(), + }) +} + +/// The hosts named by `jumps` (`[user@]host[:port]`, comma separated), for +/// telling which aliases other hosts jump through. +pub fn jump_hosts(jumps: &str) -> Vec { + jumps + .split(',') + .map(|jump| { + let host = jump.rsplit_once('@').map_or(jump, |(_, host)| host); + let host = match host.strip_prefix('[') { + Some(bracketed) => bracketed.split(']').next().unwrap_or(bracketed), + None => host.split(':').next().unwrap_or(host), + }; + host.trim().to_owned() + }) + .filter(|host| !host.is_empty()) + .collect() +} + +/// The names on the `Host` lines of `text`, in order, and the arguments of +/// its `Include` lines. `Match` blocks name no host and are skipped. +pub fn host_aliases(text: &str) -> (Vec, Vec) { + let mut names = Vec::new(); + let mut includes = Vec::new(); + for line in text.lines() { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + let (keyword, arguments) = split_keyword(line); + if keyword.eq_ignore_ascii_case("host") { + for word in words(arguments) { + if word.contains(['*', '?', '!']) { + names.push(HostName::Pattern(word)); + } else { + names.push(HostName::Alias(word)); + } + } + } else if keyword.eq_ignore_ascii_case("include") { + includes.extend(words(arguments)); + } + } + (names, includes) +} + +/// The user's configuration file and every file it includes, in the order +/// OpenSSH reads them, with their text. `home` is the user's home +/// directory. A missing `~/.ssh/config` gives no files. +pub fn configuration_files(home: &Path) -> Vec<(PathBuf, String)> { + let ssh_directory = home.join(".ssh"); + let mut files = Vec::new(); + read_configuration( + &ssh_directory.join("config"), + home, + &ssh_directory, + 0, + &mut files, + ); + files +} + +fn read_configuration( + path: &Path, + home: &Path, + ssh_directory: &Path, + depth: usize, + files: &mut Vec<(PathBuf, String)>, +) { + if depth > MAX_INCLUDE_DEPTH + || files.len() >= MAX_FILES + || files.iter().any(|(read, _)| read == path) + { + return; + } + let Ok(metadata) = std::fs::metadata(path) else { + return; + }; + if !metadata.is_file() || metadata.len() > MAX_FILE_BYTES { + return; + } + let Ok(text) = std::fs::read_to_string(path) else { + return; + }; + let (_, includes) = host_aliases(&text); + files.push((path.to_owned(), text)); + for include in includes { + for included in expand_include(&include, home, ssh_directory) { + read_configuration(&included, home, ssh_directory, depth + 1, files); + } + } +} + +/// The files an `Include` argument names: `~` is the home directory, a +/// relative path is below `~/.ssh`, and `*` and `?` match within one path +/// component, in sorted order as OpenSSH's `glob` returns them. Paths +/// outside the home directory are left out. +fn expand_include(argument: &str, home: &Path, ssh_directory: &Path) -> Vec { + let path = if let Some(rest) = argument.strip_prefix("~/") { + home.join(rest) + } else if Path::new(argument).is_absolute() { + PathBuf::from(argument) + } else { + ssh_directory.join(argument) + }; + if path + .components() + .any(|component| matches!(component, std::path::Component::ParentDir)) + || !path.starts_with(home) + { + return Vec::new(); + } + let mut matches = vec![PathBuf::new()]; + for component in path.components() { + let part = component.as_os_str().to_string_lossy(); + if !part.contains(['*', '?']) { + for candidate in &mut matches { + candidate.push(component.as_os_str()); + } + continue; + } + let mut next = Vec::new(); + for directory in &matches { + let Ok(entries) = std::fs::read_dir(directory) else { + continue; + }; + let mut names: Vec = entries + .take(MAX_DIRECTORY_ENTRIES) + .filter_map(Result::ok) + .map(|entry| entry.file_name().to_string_lossy().into_owned()) + .filter(|name| !name.starts_with('.') && wildcard_match(&part, name)) + .collect(); + names.sort(); + next.extend(names.into_iter().map(|name| directory.join(name))); + } + matches = next; + } + matches.truncate(MAX_FILES); + matches +} + +/// `*` matches any run of characters and `?` one character. +fn wildcard_match(pattern: &str, name: &str) -> bool { + let pattern: Vec = pattern.chars().collect(); + let name: Vec = name.chars().collect(); + let (mut p, mut n) = (0, 0); + let (mut star, mut resume) = (None, 0); + while n < name.len() { + if p < pattern.len() && (pattern[p] == '?' || pattern[p] == name[n]) { + p += 1; + n += 1; + } else if p < pattern.len() && pattern[p] == '*' { + star = Some(p); + resume = n; + p += 1; + } else if let Some(position) = star { + p = position + 1; + resume += 1; + n = resume; + } else { + return false; + } + } + pattern[p..].iter().all(|character| *character == '*') +} + +/// `Keyword arguments` or `Keyword=arguments`. +fn split_keyword(line: &str) -> (&str, &str) { + let end = line + .find(|character: char| character.is_whitespace() || character == '=') + .unwrap_or(line.len()); + let (keyword, rest) = line.split_at(end); + let rest = rest.trim_start(); + let rest = rest.strip_prefix('=').unwrap_or(rest); + (keyword, rest.trim()) +} + +/// Whitespace-separated words, where double quotes keep spaces in a word. +fn words(text: &str) -> Vec { + let mut words = Vec::new(); + let mut current = String::new(); + let mut quoted = false; + for character in text.chars() { + match character { + '"' => quoted = !quoted, + character if character.is_whitespace() && !quoted => { + if !current.is_empty() { + words.push(std::mem::take(&mut current)); + } + } + character => current.push(character), + } + } + if !current.is_empty() { + words.push(current); + } + words +} + +#[cfg(test)] +mod tests; diff --git a/rust/crates/remote/src/client/ssh_config/tests.rs b/rust/crates/remote/src/client/ssh_config/tests.rs new file mode 100644 index 00000000..c063a531 --- /dev/null +++ b/rust/crates/remote/src/client/ssh_config/tests.rs @@ -0,0 +1,314 @@ +use super::*; +use serde_json::json; +use std::sync::atomic::{AtomicU64, Ordering}; + +fn connection(value: serde_json::Value) -> SshConnection { + serde_json::from_value::(value) + .expect("valid connection") + .normalized() +} + +/// `ssh -G` output with the values the tests compare, as OpenSSH prints +/// them; `extra` lines replace or add keys. +fn output(extra: &[&str]) -> Output { + let mut lines = vec![ + "user dev", + "hostname build.example", + "port 22", + "connecttimeout 15", + "serveraliveinterval 15", + "identityfile ~/.ssh/id_rsa", + "identityfile ~/.ssh/id_ed25519", + "identitiesonly no", + ]; + for line in extra { + let key = line.split(' ').next().unwrap(); + if key != "identityfile" { + lines.retain(|existing| !existing.starts_with(&format!("{key} "))); + } + lines.push(line); + } + Output::parse(&lines.join("\n")) +} + +/// A scratch home directory, removed when dropped. +struct ScratchHome(PathBuf); + +impl ScratchHome { + fn new(label: &str) -> Self { + static SEQUENCE: AtomicU64 = AtomicU64::new(0); + let path = std::env::temp_dir().join(format!( + "lithe-remote-ssh-config-{label}-{}-{}", + std::process::id(), + SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(path.join(".ssh")).unwrap(); + Self(path) + } + + fn write(&self, relative: &str, text: &str) { + let path = self.0.join(relative); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + + fn file_names(&self) -> Vec { + configuration_files(&self.0) + .into_iter() + .map(|(path, _)| { + path.strip_prefix(&self.0) + .unwrap() + .to_string_lossy() + .replace('\\', "/") + }) + .collect() + } +} + +impl Drop for ScratchHome { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +#[test] +fn values_the_connection_sets_come_from_the_connection() { + let saved = connection(json!({ + "host": "build", + "port": 2222, + "user": "ci", + "proxyJump": "bastion.example", + "connectTimeoutSeconds": 30, + "keepAliveSeconds": 60, + })); + let configured = output(&[ + "hostname build.internal.example", + "port 2222", + "user ci", + "proxyjump bastion.example", + "connecttimeout 30", + "serveraliveinterval 60", + ]); + let baseline = output(&[ + "hostname build", + "port 2222", + "user ci", + "proxyjump bastion.example", + "connecttimeout 30", + "serveraliveinterval 60", + ]); + let settings = effective_settings(&saved, &configured, &baseline).unwrap(); + assert_eq!( + settings.host_name, + Effective { + value: "build.internal.example".into(), + source: Source::SshConfig, + } + ); + assert_eq!(settings.port.source, Source::Connection); + assert_eq!(settings.user.source, Source::Connection); + assert_eq!( + settings.proxy_jump, + Effective { + value: Some("bastion.example".into()), + source: Source::Connection, + } + ); + assert_eq!(settings.connect_timeout_seconds.value, 30); + assert_eq!(settings.connect_timeout_seconds.source, Source::Connection); + assert_eq!(settings.keep_alive_seconds.value, 60); + assert_eq!(settings.keep_alive_seconds.source, Source::Connection); +} + +#[test] +fn values_left_to_ssh_come_from_the_configuration_or_a_default() { + let saved = connection(json!({ "host": "build.example" })); + let configured = output(&[ + "user ops", + "port 2200", + "identityfile ~/.ssh/work_ed25519", + "proxyjump jump.example", + ]); + let settings = effective_settings(&saved, &configured, &output(&[])).unwrap(); + assert_eq!(settings.host_name.source, Source::Connection); + assert_eq!( + settings.user, + Effective { + value: "ops".into(), + source: Source::SshConfig, + } + ); + assert_eq!(settings.port.value, 2200); + assert_eq!(settings.port.source, Source::SshConfig); + assert_eq!(settings.identity_files.source, Source::SshConfig); + assert_eq!( + settings.identity_files.value.last().map(String::as_str), + Some("~/.ssh/work_ed25519") + ); + assert_eq!(settings.proxy_jump.value.as_deref(), Some("jump.example")); + assert_eq!(settings.proxy_jump.source, Source::SshConfig); + // Lithe passes both on the command line, so the files cannot set them. + assert_eq!(settings.connect_timeout_seconds.value, 15); + assert_eq!(settings.connect_timeout_seconds.source, Source::Default); + assert_eq!(settings.keep_alive_seconds.source, Source::Default); + + let plain = effective_settings(&saved, &output(&[]), &output(&[])).unwrap(); + assert_eq!(plain.user.source, Source::Default); + assert_eq!(plain.port.source, Source::Default); + assert_eq!(plain.identity_files.source, Source::Default); + assert_eq!( + plain.proxy_jump, + Effective { + value: None, + source: Source::Default, + } + ); +} + +#[test] +fn authentication_decides_the_key_files_shown() { + let configured = output(&["identityfile ~/.ssh/chosen"]); + let password = connection(json!({ "host": "h", "authentication": "password" })); + let settings = effective_settings(&password, &configured, &output(&[])).unwrap(); + assert!(settings.identity_files.value.is_empty()); + assert_eq!(settings.identity_files.source, Source::Connection); + + let key = connection(json!({ + "host": "h", + "authentication": "privateKey", + "identityFile": "~/.ssh/chosen", + })); + let settings = effective_settings(&key, &configured, &output(&[])).unwrap(); + assert_eq!(settings.identity_files.source, Source::Connection); + assert!(settings + .identity_files + .value + .contains(&"~/.ssh/chosen".to_owned())); +} + +#[test] +fn output_without_required_keys_is_refused() { + let saved = connection(json!({ "host": "h" })); + let missing = Output::parse("user dev\nport 22\n"); + assert_eq!( + effective_settings(&saved, &missing, &missing).unwrap_err(), + OutputError { key: "hostname" } + ); + let bad_port = output(&["port many"]); + assert_eq!( + effective_settings(&saved, &bad_port, &bad_port).unwrap_err(), + OutputError { key: "port" } + ); + assert_eq!( + configured_host(&output(&["proxyjump none"])).unwrap(), + ConfiguredHost { + host_name: "build.example".into(), + user: "dev".into(), + port: 22, + proxy_jump: None, + } + ); +} + +#[test] +fn settings_serialize_with_their_sources() { + let saved = connection(json!({ "host": "h", "port": 2222 })); + let settings = effective_settings(&saved, &output(&["port 2222"]), &output(&[])).unwrap(); + let value = serde_json::to_value(settings).unwrap(); + assert_eq!( + value["port"], + json!({ "value": 2222, "source": "connection" }) + ); + assert_eq!( + value["proxyJump"], + json!({ "value": null, "source": "default" }) + ); + assert_eq!(value["hostName"]["source"], "connection"); + assert_eq!(value["keepAliveSeconds"]["value"], 15); +} + +#[test] +fn host_lines_list_aliases_patterns_and_includes() { + let (names, includes) = host_aliases( + "# Build machines\n\ + Host build gpu-1 \"two words\"\n\ + \tHostName build.example\n\ + host=*.lab !secret dev?\n\ + Match host other exec \"true\"\n\ + \x20 Include config.d/* ~/extra\n\ + HOST staging\n", + ); + assert_eq!( + names, + vec![ + HostName::Alias("build".into()), + HostName::Alias("gpu-1".into()), + HostName::Alias("two words".into()), + HostName::Pattern("*.lab".into()), + HostName::Pattern("!secret".into()), + HostName::Pattern("dev?".into()), + HostName::Alias("staging".into()), + ] + ); + assert_eq!(includes, vec!["config.d/*", "~/extra"]); +} + +#[test] +fn jump_lists_name_their_hosts() { + assert_eq!( + jump_hosts("ops@bastion:2200,[fe80::1]:22, inner"), + vec!["bastion", "fe80::1", "inner"] + ); + assert!(jump_hosts("").is_empty()); +} + +#[test] +fn includes_are_read_in_order_below_the_home_directory() { + let home = ScratchHome::new("includes"); + home.write( + ".ssh/config", + "Include config.d/*.conf\nInclude ~/other/ssh\nInclude /etc/ssh/ssh_config\nInclude ../escape\nHost main\n", + ); + home.write(".ssh/config.d/b.conf", "Host b\n"); + home.write(".ssh/config.d/a.conf", "Host a\nInclude config\n"); + home.write(".ssh/config.d/.hidden.conf", "Host hidden\n"); + home.write(".ssh/config.d/c.txt", "Host c\n"); + home.write("other/ssh", "Host other\n"); + assert_eq!( + home.file_names(), + vec![ + ".ssh/config", + ".ssh/config.d/a.conf", + ".ssh/config.d/b.conf", + "other/ssh" + ] + ); +} + +#[test] +fn missing_large_and_deep_configurations_stop_reading() { + let home = ScratchHome::new("bounds"); + assert!(home.file_names().is_empty()); + + home.write(".ssh/config", "Include big\nInclude level1\n"); + home.write(".ssh/big", &"#".repeat(MAX_FILE_BYTES as usize + 1)); + for level in 1..=20 { + home.write( + &format!(".ssh/level{level}"), + &format!("Include level{}\n", level + 1), + ); + } + let names = home.file_names(); + assert!(!names.contains(&".ssh/big".to_owned())); + assert_eq!(names.len(), 1 + MAX_INCLUDE_DEPTH); +} + +#[test] +fn wildcards_match_within_one_name() { + assert!(wildcard_match("*.conf", "a.conf")); + assert!(wildcard_match("a?c", "abc")); + assert!(wildcard_match("*", "anything")); + assert!(!wildcard_match("*.conf", "a.conf.bak")); + assert!(!wildcard_match("a?c", "ac")); +} diff --git a/rust/crates/remote/src/client/transport.rs b/rust/crates/remote/src/client/transport.rs index 4d16dac7..f58f20f4 100644 --- a/rust/crates/remote/src/client/transport.rs +++ b/rust/crates/remote/src/client/transport.rs @@ -34,10 +34,10 @@ use std::ffi::OsString; use std::fmt; use std::process::Command; -/// Seconds between SSH keep-alive probes. Together with -/// [`SSH_KEEPALIVE_MISSES`] it bounds how long a dead network path stays +/// Seconds between SSH keep-alive probes. OpenSSH gives up after three +/// unanswered probes, which bounds how long a dead network path stays /// undetected. -const SSH_KEEPALIVE_SECONDS: u32 = 15; +pub const SSH_KEEPALIVE_SECONDS: u32 = 15; const SSH_KEEPALIVE_MISSES: u32 = 3; /// Options every SSH hop passes before the hop's own. ssh keeps the first @@ -382,6 +382,32 @@ fn kept_ssh_variables( .collect() } +impl SshHop { + /// Local command line that prints the configuration OpenSSH would use + /// for this hop (`ssh -G`) and exits without connecting. + /// + /// It passes exactly the options [`TransportChain::command`] passes, so + /// the printed values are the ones a connection uses. With + /// `user_configuration` false it adds `-F none`, which leaves out the + /// user's and the system's configuration files; comparing both outputs + /// tells which values those files set. OpenSSH still evaluates `Match + /// exec` lines of the user's configuration, as it does when connecting. + pub fn configuration_command( + &self, + user_configuration: bool, + ) -> Result, TransportError> { + validate_ssh_destination(&self.destination)?; + let mut command = vec![self.program.clone(), "-G".into()]; + if !user_configuration { + command.extend(["-F".into(), "none".into()]); + } + command.extend(ssh_options(self)?); + command.push("--".into()); + command.push(self.destination.clone()); + Ok(command) + } +} + fn ssh_command(hop: &SshHop, remote: &[Word]) -> Result, TransportError> { validate_ssh_destination(&hop.destination)?; let mut command: Vec = vec![ @@ -392,6 +418,18 @@ fn ssh_command(hop: &SshHop, remote: &[Word]) -> Result, TransportErro "-e".into(), "none".into(), ]; + command.extend(ssh_options(hop)?); + command.push("--".into()); + command.push(hop.destination.clone()); + let remote_command = shell_join(remote)?; + let mut words: Vec = command.into_iter().map(Word::Raw).collect(); + words.push(Word::Generated(remote_command)); + Ok(words) +} + +/// The port and `-o` options of `hop`, in the order ssh must see them. +fn ssh_options(hop: &SshHop) -> Result, TransportError> { + let mut command = Vec::new(); if let Some(port) = hop.port { command.push("-p".into()); command.push(port.to_string()); @@ -414,12 +452,7 @@ fn ssh_command(hop: &SshHop, remote: &[Word]) -> Result, TransportErro "-o".into(), format!("ServerAliveCountMax={SSH_KEEPALIVE_MISSES}"), ]); - command.push("--".into()); - command.push(hop.destination.clone()); - let remote_command = shell_join(remote)?; - let mut words: Vec = command.into_iter().map(Word::Raw).collect(); - words.push(Word::Generated(remote_command)); - Ok(words) + Ok(command) } fn container_command(hop: &ContainerHop, inner: Vec) -> Result, TransportError> { @@ -672,6 +705,43 @@ mod tests { assert_eq!(chain.identity(), "ssh:dev@box:2222"); } + // `ssh -G` must see the options the connection itself passes, so the + // effective values match what a connection really uses. + #[test] + fn configuration_commands_pass_the_same_options_as_the_connection() { + let mut hop = SshHop::new("dev@box"); + hop.port = Some(2222); + hop.options.push(("connecttimeout".into(), "10".into())); + let options = strings(&[ + "-p", + "2222", + "-o", + "ForwardAgent=no", + "-o", + "ForwardX11=no", + "-o", + "ClearAllForwardings=yes", + "-o", + "ConnectTimeout=10", + "-o", + "ServerAliveInterval=15", + "-o", + "ServerAliveCountMax=3", + "--", + "dev@box", + ]); + let mut configured = strings(&["ssh", "-G"]); + configured.extend(options.clone()); + assert_eq!(hop.configuration_command(true).unwrap(), configured); + let mut baseline = strings(&["ssh", "-G", "-F", "none"]); + baseline.extend(options); + assert_eq!(hop.configuration_command(false).unwrap(), baseline); + assert!(matches!( + SshHop::new("-oProxyCommand=x").configuration_command(true), + Err(TransportError::InvalidHop { .. }) + )); + } + // A destination such as `-oProxyCommand=...` would otherwise be parsed by // ssh as an option and run an arbitrary local command. #[test] diff --git a/rust/crates/remote/tests/connection_log.rs b/rust/crates/remote/tests/connection_log.rs index 2e643059..8962c699 100644 --- a/rust/crates/remote/tests/connection_log.rs +++ b/rust/crates/remote/tests/connection_log.rs @@ -203,6 +203,7 @@ fn run_launch( )) }, log, + |_| {}, ); (result, child, output, input.inner) } diff --git a/rust/crates/remote/tests/server.rs b/rust/crates/remote/tests/server.rs index eaa5a242..cb91f3ad 100644 --- a/rust/crates/remote/tests/server.rs +++ b/rust/crates/remote/tests/server.rs @@ -3,7 +3,9 @@ mod support; -use lithe_remote::client::launch::{launch, launch_command, LaunchError, Launched, UnsafeReason}; +use lithe_remote::client::launch::{ + launch, launch_command, LaunchError, Launched, Stage, UnsafeReason, +}; use lithe_remote::client::session::ClientError; use lithe_remote::client::{ ConnectionKind, ConnectionLog, RemoteSession, ServerArtifact, TransportChain, WriteOptions, @@ -818,6 +820,21 @@ fn run_launch( ChildStdout, ChildStdin, ) { + let (result, child, output, input, _) = run_launch_with_stages(root); + (result, child, output, input) +} + +/// [`run_launch`], also returning the stages the launch reported. +fn run_launch_with_stages( + root: &str, +) -> ( + Result, + Child, + ChildStdout, + ChildStdin, + Vec, +) { + let mut stages = Vec::new(); let mut child = Command::new("sh") .args(&launch_command(Some(root), &["--stdio"])[1..]) .stdin(Stdio::piped()) @@ -839,15 +856,39 @@ fn run_launch( )) }, &ConnectionLog::begin(ConnectionKind::Ssh), + |stage| stages.push(stage), ); - (result, child, output, input) + (result, child, output, input, stages) } /// Launches the server, checks that it serves a request and returns whether -/// this launch uploaded it. +/// this launch uploaded it. The stages must come in order, with the upload's +/// progress counting up to the binary's size only when it was sent. fn start_server(root: &str) -> bool { - let (launched, mut child, output, input) = run_launch(root); + let (launched, mut child, output, input, stages) = run_launch_with_stages(root); let launched = launched.unwrap(); + assert_eq!(&stages[..2], [Stage::Authenticated, Stage::PlatformChecked]); + assert_eq!( + stages.last(), + Some(&Stage::Installed { + uploaded: launched.uploaded + }) + ); + let progress: Vec<(usize, usize)> = stages[2..stages.len() - 1] + .iter() + .map(|stage| match stage { + Stage::Uploading { sent, total } => (*sent, *total), + other => panic!("unexpected stage {other:?}"), + }) + .collect(); + if launched.uploaded { + let total = std::fs::metadata(SERVER).unwrap().len() as usize; + assert_eq!(progress.first(), Some(&(0, total))); + assert_eq!(progress.last(), Some(&(total, total))); + assert!(progress.windows(2).all(|pair| pair[0].0 < pair[1].0)); + } else { + assert!(progress.is_empty(), "{progress:?}"); + } let (session, _events) = RemoteSession::from_streams(output, input, &options()).unwrap(); session.stat("/").unwrap(); session.shutdown(STEP_TIMEOUT); diff --git a/rust/crates/workspace/Cargo.toml b/rust/crates/workspace/Cargo.toml index d152c8ee..63f7c63e 100644 --- a/rust/crates/workspace/Cargo.toml +++ b/rust/crates/workspace/Cargo.toml @@ -14,7 +14,7 @@ lithe-diagnostics = { path = "../diagnostics" } lithe-git-host = { path = "../git-host" } lithe-platform = { path = "../platform" } lithe-protocol = { path = "../protocol" } -lithe-remote = { path = "../remote", default-features = false, features = ["client"] } +lithe-remote = { path = "../remote", default-features = false, features = ["client", "motty"] } lithe-request-context = { path = "../request-context" } rand = "0.8" serde = { version = "1.0", features = ["derive"] } diff --git a/rust/crates/workspace/src/connections.rs b/rust/crates/workspace/src/connections.rs index 01d85e82..cf1f6a77 100644 --- a/rust/crates/workspace/src/connections.rs +++ b/rust/crates/workspace/src/connections.rs @@ -1,5 +1,6 @@ -//! `remote.connections` and `remote.editConnections`: the SSH connections the -//! user saved for remote development (design §3.1, S08 to S10, S12, S15). +//! `remote.connections`, `remote.editConnections` and `remote.parseAddress`: +//! the SSH connections the user saved for remote development (design §3.1, +//! S08 to S10, S12, S15). //! //! The list lives in a machine-local document that the native client reads //! and publishes atomically, like the trust decisions. Core validates every @@ -9,7 +10,7 @@ use crate::sessions::nonce; use lithe_protocol::{CoreError, ErrorCode}; use lithe_remote::client::connections::{ - self, Color, ConnectionError, Connections, Label, Reason, SshConnection, + self, Color, ConnectionError, Connections, ImportEntry, Label, LabelFill, Reason, SshConnection, }; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; @@ -20,10 +21,14 @@ use serde_json::{json, Value}; pub struct ListRequest { /// Current document text; `null` when the source does not exist. document: Option, + /// Words every listed entry's name, address or group contains, + /// regardless of case. `connections` still holds every entry. + #[serde(default)] + query: Option, } -/// `remote.editConnections`: exactly one of `save`, `remove` and -/// `rememberFolder`. +/// `remote.editConnections`: exactly one of `save`, `remove`, +/// `rememberFolder`, `import` and `markConnected`. #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct EditRequest { @@ -35,6 +40,17 @@ pub struct EditRequest { remove: Option, #[serde(default)] remember_folder: Option, + #[serde(default)] + import: Option, + #[serde(default)] + mark_connected: Option, +} + +/// `remote.parseAddress`: a quick-connect address. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct AddressRequest { + text: String, } /// Adds a connection, or replaces the entry `id`. A missing `color` or @@ -58,6 +74,16 @@ struct IdRequest { id: String, } +/// Entries to add, and color and group for entries already saved. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ImportRequest { + #[serde(default)] + entries: Vec, + #[serde(default)] + fills: Vec, +} + /// A host folder opened over the entry `id`. #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -83,48 +109,80 @@ const STORAGE: Storage = Storage { /// order the window shows them. pub fn list(request: ListRequest) -> Result { let connections = parse(request.document.as_deref())?; + let sections = match request.query.as_deref() { + Some(query) => connections + .sections_matching(query) + .map_err(invalid_request)?, + None => connections.sections(), + }; Ok(json!({ "connections": connections.entries(), - "sections": connections.sections(), + "sections": sections, "storage": STORAGE, })) } +/// Splits `[user@]host[:port]` into connection fields, or names the field +/// to correct. +pub fn parse_address(request: AddressRequest) -> Result { + connections::parse_address(&request.text) + .map(|address| json!(address)) + .map_err(invalid_request) +} + /// Applies one edit. An edit that changes nothing returns a `null` /// document, so the native client creates no source; `id` names the entry a -/// save wrote. +/// save wrote, `ids` the entries an import added. pub fn edit(request: EditRequest) -> Result { let before = parse(request.document.as_deref())?; let mut after = before.clone(); let mut id = None; - match (request.save, request.remove, request.remember_folder) { - (Some(save), None, None) => { - let label = Label { - color: save.color, - group: save.group, - }; - id = Some( - after - .save( - save.id.as_deref(), - &save.name, - save.connection, - label, - nonce, - ) - .map_err(invalid_request)?, - ); - } - (None, Some(remove), None) => after.remove(&remove.id), - (None, None, Some(folder)) => after + let mut ids = None; + let operations = [ + request.save.is_some(), + request.remove.is_some(), + request.remember_folder.is_some(), + request.import.is_some(), + request.mark_connected.is_some(), + ]; + if operations.iter().filter(|operation| **operation).count() != 1 { + return Err(invalid_request(ConnectionError { + field: "operation", + reason: Reason::Invalid, + })); + } + if let Some(save) = request.save { + let label = Label { + color: save.color, + group: save.group, + }; + id = Some( + after + .save( + save.id.as_deref(), + &save.name, + save.connection, + label, + nonce, + ) + .map_err(invalid_request)?, + ); + } else if let Some(remove) = request.remove { + after.remove(&remove.id); + } else if let Some(folder) = request.remember_folder { + after .remember_folder(&folder.id, &folder.path) - .map_err(invalid_request)?, - _ => { - return Err(invalid_request(ConnectionError { - field: "operation", - reason: Reason::Invalid, - })) - } + .map_err(invalid_request)?; + } else if let Some(import) = request.import { + ids = Some( + after + .import(import.entries, import.fills, nonce) + .map_err(invalid_request)?, + ); + } else if let Some(entry) = request.mark_connected { + after + .mark_connected(&entry.id, now_seconds()) + .map_err(invalid_request)?; } let changed = after != before; let document = if changed { @@ -141,12 +199,23 @@ pub fn edit(request: EditRequest) -> Result { if let Some(id) = id { result["id"] = json!(id); } + if let Some(ids) = ids { + result["ids"] = json!(ids); + } Ok(result) } +/// Seconds since the Unix epoch; 0, which the edit refuses, when the clock +/// is before it. +fn now_seconds() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_secs()) +} + /// A stored document that cannot be decoded is a parse failure, not a bad /// request: the caller sent what the source holds. -fn parse(document: Option<&str>) -> Result { +pub(crate) fn parse(document: Option<&str>) -> Result { Connections::parse(document).map_err(|error| { CoreError::new( ErrorCode::ParseFailed, diff --git a/rust/crates/workspace/src/connections/tests.rs b/rust/crates/workspace/src/connections/tests.rs index 66a8432d..f2f3c670 100644 --- a/rust/crates/workspace/src/connections/tests.rs +++ b/rust/crates/workspace/src/connections/tests.rs @@ -119,6 +119,112 @@ fn each_edit_carries_exactly_one_operation() { } } +#[test] +fn a_query_lists_only_the_matching_sections() { + let first = edit(edit_request(json!({ + "document": null, + "save": { "name": "Web", "connection": { "host": "web.example" }, "group": "Production" }, + }))) + .unwrap(); + let second = edit(edit_request(json!({ + "document": first["document"], + "save": { "name": "Lab", "connection": { "host": "lab.example", "user": "dev" } }, + }))) + .unwrap(); + let lab = second["id"].clone(); + + let listed = list(list_request(json!({ + "document": second["document"], + "query": "DEV lab", + }))) + .unwrap(); + + assert_eq!(listed["sections"], json!([{ "group": null, "ids": [lab] }])); + assert_eq!(listed["connections"].as_array().unwrap().len(), 2); +} + +#[test] +fn an_address_is_split_into_fields_or_names_the_field_to_fix() { + let address = + parse_address(serde_json::from_value(json!({ "text": "dev@build-box:2222" })).unwrap()) + .unwrap(); + assert_eq!( + address, + json!({ "host": "build-box", "user": "dev", "port": 2222 }) + ); + + let error = parse_address(serde_json::from_value(json!({ "text": "box:99999" })).unwrap()) + .expect_err("port out of range"); + assert_eq!( + details(&error), + json!({ "field": "port", "reason": "invalid" }) + ); +} + +#[test] +fn an_import_adds_entries_under_free_names_and_fills_labels() { + let first = edit(edit_request(json!({ + "document": null, + "save": { "name": "Web", "connection": { "host": "web.example" } }, + }))) + .unwrap(); + let web = first["id"].as_str().unwrap().to_owned(); + + let imported = edit(edit_request(json!({ + "document": first["document"], + "import": { + "entries": [{ + "name": "web", + "connection": { "host": "web2.example" }, + "color": "blue", + "group": "Imported", + }], + "fills": [{ "id": web, "color": "green", "group": "Production" }], + }, + }))) + .unwrap(); + + assert_eq!(imported["changed"], json!(true)); + let ids = imported["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 1); + let connections = imported["connections"].as_array().unwrap(); + assert_eq!(connections[0]["color"], json!("green")); + assert_eq!(connections[0]["group"], json!("Production")); + assert_eq!(connections[1]["id"], ids[0]); + assert_eq!(connections[1]["name"], json!("web (2)")); + assert_eq!(connections[1]["group"], json!("Imported")); +} + +#[test] +fn marking_a_connection_records_when_it_was_last_connected() { + let first = edit(edit_request(json!({ + "document": null, + "save": { "name": "Web", "connection": { "host": "web.example" } }, + }))) + .unwrap(); + let web = first["id"].clone(); + + let marked = edit(edit_request(json!({ + "document": first["document"], + "markConnected": { "id": web }, + }))) + .unwrap(); + + let at = marked["connections"][0]["lastConnectedAt"] + .as_u64() + .expect("timestamp"); + assert!(at > 1_700_000_000, "{at}"); + let error = edit(edit_request(json!({ + "document": first["document"], + "markConnected": { "id": "absent" }, + }))) + .expect_err("unknown entry"); + assert_eq!( + details(&error), + json!({ "field": "id", "reason": "unknown" }) + ); +} + #[test] fn a_damaged_source_is_a_parse_failure_and_a_bad_edit_is_a_bad_request() { let error = list(list_request( diff --git a/rust/crates/workspace/src/lib.rs b/rust/crates/workspace/src/lib.rs index 3176d0f1..0e59d2fa 100644 --- a/rust/crates/workspace/src/lib.rs +++ b/rust/crates/workspace/src/lib.rs @@ -8,10 +8,13 @@ //! two namespaces. Without a host every call is the local filesystem. //! //! The session side owns the long-lived connections: [`connections`] keeps -//! the SSH connections the user saved, [`probe`] checks that a saved SSH -//! connection reaches a usable host, [`sessions`] opens and keeps the -//! connections, [`host`] forwards finite requests and owned streaming resources -//! (processes, terminals, watches), [`forwards`] keeps the port forwards of +//! the SSH connections the user saved, [`ssh_configuration`] tells what +//! OpenSSH makes of them and lists the hosts of the user's SSH configuration, +//! [`motty`] lists the hosts saved in Motty for an import, [`probe`] checks +//! that a saved SSH connection reaches a usable host, [`sessions`] opens and +//! keeps the connections, [`host`] forwards finite requests and owned +//! streaming resources (processes, terminals, watches), [`forwards`] keeps the +//! port forwards of //! the ports page, [`upload`] streams a verified file to the host, and //! [`trust`] keys remote workspace trust by what the connection resolves. //! Domain semantics stay in their engines (Git, build, language servers); @@ -21,9 +24,11 @@ pub mod connections; pub mod forwards; pub mod fs; pub mod host; +pub mod motty; pub mod probe; mod scope; pub mod sessions; +pub mod ssh_configuration; #[cfg(feature = "test-support")] pub mod test_support; pub mod trust; diff --git a/rust/crates/workspace/src/motty.rs b/rust/crates/workspace/src/motty.rs new file mode 100644 index 00000000..bcd770a7 --- /dev/null +++ b/rust/crates/workspace/src/motty.rs @@ -0,0 +1,87 @@ +//! `remote.mottyHosts`: the SSH hosts saved in Motty, and what an import +//! into the saved connections makes of each (design §3.1). +//! +//! Core opens Motty's configuration database read-only and never reads its +//! vault, so passwords and keys stay where they are. A database that is +//! missing or in another layout is a result, not an error, so the import +//! page can say why it has nothing to offer. The rules are in +//! `lithe_remote::client::motty`. + +use crate::connections::parse; +use lithe_protocol::{CoreError, ErrorCode}; +use lithe_remote::client::motty; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::path::PathBuf; + +/// The database, relative to the platform's user configuration directory. +const DATABASE: [&str; 2] = ["motty", "config.db"]; + +/// `remote.mottyHosts`: where Motty keeps its data, and the saved +/// connections to compare with. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct HostsRequest { + /// The platform's user configuration directory (`~/Library/Application + /// Support` on macOS, `%APPDATA%` on Windows, `~/.config` on Linux). + config_directory: String, + /// Current connections document; `null` when the source does not exist. + document: Option, +} + +/// The hosts of Motty's database, or `unavailable` with the reason. +pub fn hosts(request: HostsRequest) -> Result { + let directory = PathBuf::from(&request.config_directory); + if !directory.is_absolute() { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "The configuration directory must be an absolute path", + )); + } + let saved = parse(request.document.as_deref())?; + let database = DATABASE + .iter() + .fold(directory, |path, component| path.join(component)); + let path = database.display().to_string(); + Ok(match motty::read(&database) { + Ok(catalog) => { + let mut report = json!(motty::candidates(&catalog, &saved)); + report["database"] = json!(path); + report + } + Err(reason) => json!({ "database": path, "unavailable": reason }), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_missing_database_is_a_result_that_says_so() { + let directory = std::env::temp_dir().join(format!( + "lithe-workspace-motty-missing-{}", + std::process::id() + )); + let result = hosts(HostsRequest { + config_directory: directory.display().to_string(), + document: None, + }) + .unwrap(); + assert_eq!(result["unavailable"], "missing"); + assert!(result["database"] + .as_str() + .unwrap() + .ends_with(&format!("motty{}config.db", std::path::MAIN_SEPARATOR))); + } + + #[test] + fn a_relative_directory_is_refused() { + let error = hosts(HostsRequest { + config_directory: "motty".into(), + document: None, + }) + .unwrap_err(); + assert!(matches!(error.code, ErrorCode::InvalidRequest)); + } +} diff --git a/rust/crates/workspace/src/probe.rs b/rust/crates/workspace/src/probe.rs index 3dda703e..46385dcf 100644 --- a/rust/crates/workspace/src/probe.rs +++ b/rust/crates/workspace/src/probe.rs @@ -9,6 +9,7 @@ //! //! Note: .agents/notes/implemented/feature/2026-10-24-remote-ssh-connections.md +use lithe_git_host::authentication::Challenge; use lithe_protocol::{CoreError, ErrorCode}; use lithe_remote::client::bootstrap::{parse_probe, probe_command}; use lithe_remote::client::connections::SshConnection; @@ -131,17 +132,7 @@ fn probe_with(request: ProbeRequest, ssh_program: Option<&str>) -> Result { - for challenge in challenges { - execution_events::emit(serde_json::json!({ - "type": "authentication", - "requestId": challenge.request_id, - "prompt": execution_events::redact(&challenge.prompt), - "secret": challenge.secret, - "attempt": challenge.attempt, - })); - } - } + Ok(challenges) => challenges.into_iter().for_each(relay_challenge), Err(error) => { stop = Some( CoreError::new( @@ -184,6 +175,33 @@ pub fn respond(request_id: &str, answer: Option) -> bool { lithe_git_host::authentication::respond(request_id, answer) } +/// Relays one OpenSSH question as an `authentication` event. `kind` tells +/// the window which form to show; a host key question also carries the +/// key's algorithm and fingerprint, which are public. +pub(crate) fn relay_challenge(challenge: Challenge) { + execution_events::emit(challenge_event(&challenge)); +} + +/// The `authentication` event of `challenge`. +pub(crate) fn challenge_event(challenge: &Challenge) -> serde_json::Value { + let prompt = lithe_remote::client::prompt::classify(&challenge.prompt); + let mut event = serde_json::json!({ + "type": "authentication", + "requestId": challenge.request_id, + "prompt": execution_events::redact(&challenge.prompt), + "secret": challenge.secret, + "attempt": challenge.attempt, + "kind": prompt.kind, + }); + if let Some(key_type) = prompt.key_type { + event["keyType"] = key_type.into(); + } + if let Some(fingerprint) = prompt.fingerprint { + event["fingerprint"] = fingerprint.into(); + } + event +} + /// The SSH hop of `connection`, refused with the field and the reason when /// one is malformed. The rules are in `lithe_remote::client::connections`. pub(crate) fn ssh_hop(connection: &SshConnection) -> Result { diff --git a/rust/crates/workspace/src/probe/tests.rs b/rust/crates/workspace/src/probe/tests.rs index ad500d0c..518bd198 100644 --- a/rust/crates/workspace/src/probe/tests.rs +++ b/rust/crates/workspace/src/probe/tests.rs @@ -22,6 +22,57 @@ fn malformed_connections_name_the_field_in_the_error() { assert_eq!(details, json!({ "field": "host", "reason": "invalid" })); } +// The window picks the form from `kind`; a host key question carries the +// public fingerprint so the user can compare it before trusting the key. +#[test] +fn questions_are_relayed_with_their_kind_and_the_host_key() { + let host_key = challenge_event(&Challenge { + request_id: "request-1".into(), + prompt: "The authenticity of host 'build-box (10.0.0.5)' can't be established.\nED25519 key fingerprint is SHA256:fakeFingerprintForTests0123456789abcdefgh.\nAre you sure you want to continue connecting (yes/no/[fingerprint])? ".into(), + secret: false, + attempt: 1, + }); + assert_eq!(host_key["type"], "authentication"); + assert_eq!(host_key["kind"], "hostKey"); + assert_eq!(host_key["keyType"], "ED25519"); + assert_eq!( + host_key["fingerprint"], + "SHA256:fakeFingerprintForTests0123456789abcdefgh" + ); + assert_eq!(host_key["secret"], false); + + let password = challenge_event(&Challenge { + request_id: "request-2".into(), + prompt: "dev@build-box's password: ".into(), + secret: true, + attempt: 2, + }); + assert_eq!(password["kind"], "password"); + assert_eq!(password["attempt"], 2); + assert!(password.get("fingerprint").is_none()); +} + +#[test] +fn launch_stages_become_remote_stage_events() { + use crate::sessions::stage_event; + use lithe_remote::client::launch::Stage; + assert_eq!( + stage_event(Stage::Authenticated), + json!({ "type": "remoteStage", "stage": "authenticated" }) + ); + assert_eq!( + stage_event(Stage::Uploading { + sent: 1024, + total: 4096 + }), + json!({ "type": "remoteStage", "stage": "uploading", "sentBytes": 1024, "totalBytes": 4096 }) + ); + assert_eq!( + stage_event(Stage::Installed { uploaded: false }), + json!({ "type": "remoteStage", "stage": "installed", "uploaded": false }) + ); +} + #[test] fn ssh_failures_map_to_stable_statuses() { let cases: [(&str, ProbeStatus); 6] = [ diff --git a/rust/crates/workspace/src/sessions.rs b/rust/crates/workspace/src/sessions.rs index 0234bc18..52b2f81c 100644 --- a/rust/crates/workspace/src/sessions.rs +++ b/rust/crates/workspace/src/sessions.rs @@ -7,11 +7,11 @@ //! it by id. OpenSSH runs in its own process tree, which closing a connection //! ends, together with the connection's port forwards. -use crate::probe::{classify, diagnostics, ssh_hop, ProbeStatus, ProbedHost}; +use crate::probe::{classify, diagnostics, relay_challenge, ssh_hop, ProbeStatus, ProbedHost}; use lithe_git_host::ProcessTree; use lithe_protocol::{CoreError, ErrorCode}; use lithe_remote::client::connections::SshConnection; -use lithe_remote::client::launch::{launch, launch_command, LaunchError, Launched}; +use lithe_remote::client::launch::{launch, launch_command, LaunchError, Launched, Stage}; use lithe_remote::client::session::{ClientError, ConnectOptions}; use lithe_remote::client::trust::Target; use lithe_remote::client::{ @@ -406,6 +406,9 @@ fn connect_logged( // this thread keeps relaying prompts and observing cancellation. Killing // the tree ends the helper's reads. let (finished, launched) = mpsc::channel(); + // Events can only be sent from the request's thread, so the helper hands + // its stages over. + let (stage_sender, stages) = mpsc::channel(); let launch_log = log.clone(); std::thread::spawn(move || { let artifact_for = |report: &lithe_remote::client::bootstrap::ProbeReport| { @@ -426,7 +429,16 @@ fn connect_logged( } } }; - let result = launch(&mut output, &mut input, artifact_for, &launch_log); + let result = launch( + &mut output, + &mut input, + artifact_for, + &launch_log, + |stage| { + // log-exempt: User cancellation: abandon drops the stage receiver before killing the SSH tree. + let _ = stage_sender.send(stage); + }, + ); // log-exempt: User cancellation: abandon drops the launch receiver before killing the SSH tree. let _ = finished.send((result, output, input)); }); @@ -454,18 +466,9 @@ fn connect_logged( &mut child, ); } + relay_stages(&stages); match authentication.poll() { - Ok(challenges) => { - for challenge in challenges { - execution_events::emit(serde_json::json!({ - "type": "authentication", - "requestId": challenge.request_id, - "prompt": execution_events::redact(&challenge.prompt), - "secret": challenge.secret, - "attempt": challenge.attempt, - })); - } - } + Ok(challenges) => challenges.into_iter().for_each(relay_challenge), Err(error) => { return abandon( CoreError::new( @@ -491,6 +494,8 @@ fn connect_logged( } } }; + // The helper sent its last stages before the result. + relay_stages(&stages); // Only called once the OpenSSH tree has ended, so joining the reader // cannot block; it guarantees the last bytes OpenSSH printed (the reason @@ -887,6 +892,49 @@ fn wait_for_exit(child: &mut Child, grace: Duration) -> Option) { + let mut upload = None; + for stage in stages.try_iter() { + if matches!(stage, Stage::Uploading { .. }) { + upload = Some(stage); + continue; + } + if let Some(upload) = upload.take() { + execution_events::emit(stage_event(upload)); + } + execution_events::emit(stage_event(stage)); + } + if let Some(upload) = upload { + execution_events::emit(stage_event(upload)); + } +} + +/// The `remoteStage` event of `stage`. +pub(crate) fn stage_event(stage: Stage) -> serde_json::Value { + match stage { + Stage::Authenticated => { + serde_json::json!({ "type": "remoteStage", "stage": "authenticated" }) + } + Stage::PlatformChecked => { + serde_json::json!({ "type": "remoteStage", "stage": "platformChecked" }) + } + Stage::Uploading { sent, total } => serde_json::json!({ + "type": "remoteStage", + "stage": "uploading", + "sentBytes": sent, + "totalBytes": total, + }), + Stage::Installed { uploaded } => serde_json::json!({ + "type": "remoteStage", + "stage": "installed", + "uploaded": uploaded, + }), + } +} + fn join_diagnostics(summary: &str, stderr: &str) -> String { if stderr.is_empty() { summary.to_owned() diff --git a/rust/crates/workspace/src/ssh_configuration.rs b/rust/crates/workspace/src/ssh_configuration.rs new file mode 100644 index 00000000..d3731306 --- /dev/null +++ b/rust/crates/workspace/src/ssh_configuration.rs @@ -0,0 +1,282 @@ +//! `remote.effectiveSettings` and `remote.sshConfigHosts`: what OpenSSH +//! makes of a saved connection, and the hosts the user's SSH configuration +//! names, for the overview and the import page (design §3.1). +//! +//! Both run the local `ssh -G`, which prints the configuration a connection +//! would use and exits without connecting. It runs with the transport's +//! restricted environment and a deadline, because `Match exec` lines of the +//! user's configuration still run commands. Configuration files are only +//! read below the home directory the request names. The rules are in +//! `lithe_remote::client::ssh_config`. + +use crate::connections::parse; +use crate::probe::{diagnostics, ssh_hop}; +use lithe_protocol::{CoreError, ErrorCode}; +use lithe_remote::client::connections::{Connections, SshConnection}; +use lithe_remote::client::ssh_config::{self, HostName, Output, MAX_ALIASES}; +use lithe_remote::client::{Hop, SshHop, TransportChain}; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::path::PathBuf; +use std::process::Command; +use std::time::{Duration, Instant}; + +/// Upper bound for one `ssh -G`. +const COMMAND_DEADLINE: Duration = Duration::from_secs(10); + +/// Upper bound for reading every alias of an import. +const IMPORT_DEADLINE: Duration = Duration::from_secs(30); + +/// `remote.effectiveSettings`: the connection to explain. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct EffectiveRequest { + connection: SshConnection, +} + +/// `remote.sshConfigHosts`: where the configuration is, and the saved +/// connections to compare with. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct HostsRequest { + /// The user's home directory; `.ssh/config` below it is read. + home_directory: String, + /// Current connections document; `null` when the source does not exist. + document: Option, +} + +/// The values the connection uses and where each comes from. +pub fn effective_settings(request: EffectiveRequest) -> Result { + effective_with(request, None) +} + +/// `ssh_program` replaces the `ssh` found on `PATH`; tests use a stand-in. +fn effective_with( + request: EffectiveRequest, + ssh_program: Option<&str>, +) -> Result { + let connection = request.connection.normalized(); + let hop = with_program(ssh_hop(&connection)?, ssh_program); + let deadline = Instant::now() + COMMAND_DEADLINE; + let configured = print_configuration(&hop, true, deadline)?; + let baseline = print_configuration(&hop, false, deadline)?; + let settings = ssh_config::effective_settings(&connection, &configured, &baseline) + .map_err(|error| unreadable_output(error.key))?; + Ok(json!(settings)) +} + +/// The `Host` aliases of the user's configuration, in the order OpenSSH +/// reads them, with what each resolves to and whether a saved connection +/// already reaches it. +/// +/// Every alias is listed once, regardless of case, up to +/// [`MAX_ALIASES`]. `status` is `importable`, `exists` (with the saved +/// entry), `pattern` for names with wildcards, `invalid` for names Lithe +/// refuses as a host, or `unreadable` when `ssh -G` failed for it. +/// `usedAsJumpBy` names the aliases that jump through it. +pub fn ssh_config_hosts(request: HostsRequest) -> Result { + hosts_with(request, None) +} + +fn hosts_with(request: HostsRequest, ssh_program: Option<&str>) -> Result { + let home = PathBuf::from(&request.home_directory); + if !home.is_absolute() { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "The home directory must be an absolute path", + )); + } + let saved = parse(request.document.as_deref())?; + let files = ssh_config::configuration_files(&home); + let (names, truncated) = distinct_names(&files); + + let deadline = Instant::now() + IMPORT_DEADLINE; + let mut hosts: Vec = Vec::with_capacity(names.len()); + let mut jumps: Vec<(String, String)> = Vec::new(); + for name in names { + let alias = match name { + HostName::Pattern(pattern) => { + hosts.push(json!({ "alias": pattern, "status": "pattern" })); + continue; + } + HostName::Alias(alias) => alias, + }; + let connection = SshConnection::to_host(alias.clone()); + let Ok(hop) = ssh_hop(&connection) else { + hosts.push(json!({ "alias": alias, "status": "invalid" })); + continue; + }; + let hop = with_program(hop, ssh_program); + let resolved = + print_configuration(&hop, true, deadline.min(Instant::now() + COMMAND_DEADLINE)) + .and_then(|output| { + ssh_config::configured_host(&output) + .map_err(|error| unreadable_output(error.key)) + }); + let configured = match resolved { + Ok(configured) => configured, + // Without a client, or once the user cancelled, no alias can be read. + Err(error) + if matches!(error.code, ErrorCode::RuntimeMissing | ErrorCode::Cancelled) => + { + return Err(error) + } + Err(_) => { + hosts.push(json!({ "alias": alias, "status": "unreadable" })); + continue; + } + }; + if let Some(proxy_jump) = &configured.proxy_jump { + for jump in ssh_config::jump_hosts(proxy_jump) { + jumps.push((jump.to_lowercase(), alias.clone())); + } + } + let mut host = json!({ "alias": alias, "status": "importable" }); + if let Some(entry) = existing(&saved, &alias, &configured) { + host["status"] = json!("exists"); + host["existingId"] = json!(entry.id()); + host["existingName"] = json!(entry.name()); + } + host["resolved"] = json!(configured); + hosts.push(host); + } + for host in &mut hosts { + let alias = host["alias"].as_str().unwrap_or_default().to_lowercase(); + let users: Vec<&str> = jumps + .iter() + .filter(|(jump, _)| *jump == alias) + .map(|(_, user)| user.as_str()) + .collect(); + host["usedAsJumpBy"] = json!(users); + } + let files: Vec = files + .iter() + .map(|(path, _)| path.display().to_string()) + .collect(); + Ok(json!({ + "files": files, + "hosts": hosts, + "truncated": truncated, + })) +} + +/// Names of every file's `Host` lines, each once regardless of case, at most +/// [`MAX_ALIASES`]; `true` when some were left out. +fn distinct_names(files: &[(PathBuf, String)]) -> (Vec, bool) { + let mut seen: Vec = Vec::new(); + let mut names = Vec::new(); + for (_, text) in files { + for name in ssh_config::host_aliases(text).0 { + let word = match &name { + HostName::Alias(word) | HostName::Pattern(word) => word.to_lowercase(), + }; + if seen.contains(&word) { + continue; + } + if names.len() == MAX_ALIASES { + return (names, true); + } + seen.push(word); + names.push(name); + } + } + (names, false) +} + +/// The saved entry that reaches `alias`, either through the alias itself or +/// through the address it resolves to. +fn existing<'a>( + saved: &'a Connections, + alias: &str, + configured: &ssh_config::ConfiguredHost, +) -> Option<&'a lithe_remote::client::connections::SavedConnection> { + saved.existing(&SshConnection::to_host(alias)).or_else(|| { + let resolved: SshConnection = serde_json::from_value(json!({ + "host": configured.host_name, + "user": configured.user, + "port": configured.port, + })) + .ok()?; + saved.existing(&resolved) + }) +} + +fn with_program(mut hop: SshHop, ssh_program: Option<&str>) -> SshHop { + if let Some(program) = ssh_program { + hop.program = program.into(); + } + hop +} + +/// Runs `ssh -G` for `hop`, with or without the configuration files, and +/// reads its output. +fn print_configuration( + hop: &SshHop, + user_configuration: bool, + deadline: Instant, +) -> Result { + let argv = hop + .configuration_command(user_configuration) + .map_err(|error| { + CoreError::new(ErrorCode::InvalidRequest, "Invalid SSH connection") + .with_details(error.to_string()) + })?; + let (program, arguments) = argv + .split_first() + .expect("a configuration command always names the client"); + let mut process = Command::new(program); + process.args(arguments); + TransportChain::new(vec![Hop::Ssh(hop.clone())]).restrict_environment(&mut process); + let mut stop = None; + let outcome = lithe_git_host::run( + &mut process, + None, + || { + if let Err(error) = lithe_protocol::cancellation::check() { + stop = Some(error); + } else if Instant::now() >= deadline { + stop = Some(CoreError::new( + ErrorCode::TimedOut, + "OpenSSH did not print its configuration in time", + )); + } + stop.is_some() + }, + || {}, + |_, _| {}, + ); + if let Some(error) = stop { + return Err(error); + } + match outcome.failure { + None => {} + Some(lithe_git_host::Failure::Start(error)) => { + return Err( + CoreError::new(ErrorCode::RuntimeMissing, "Could not start the SSH client") + .with_details(error.to_string()), + ) + } + Some(failure) => { + return Err( + CoreError::new(ErrorCode::ProcessFailed, "The SSH client failed") + .with_details(format!("{failure:?}")), + ) + } + } + if !outcome.status.is_some_and(|status| status.success()) { + return Err(CoreError::new( + ErrorCode::ProcessFailed, + "OpenSSH could not read its configuration", + ) + .with_details(diagnostics(&String::from_utf8_lossy(&outcome.stderr)))); + } + Ok(Output::parse(&String::from_utf8_lossy(&outcome.stdout))) +} + +fn unreadable_output(key: &str) -> CoreError { + CoreError::new(ErrorCode::ParseFailed, "Unexpected ssh -G output") + .with_details(format!("missing or malformed `{key}`")) +} + +#[cfg(test)] +mod tests; diff --git a/rust/crates/workspace/src/ssh_configuration/tests.rs b/rust/crates/workspace/src/ssh_configuration/tests.rs new file mode 100644 index 00000000..2129cbd7 --- /dev/null +++ b/rust/crates/workspace/src/ssh_configuration/tests.rs @@ -0,0 +1,288 @@ +use super::*; +use std::path::Path; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// A directory removed when dropped. +struct Directory(PathBuf); + +impl Directory { + fn new(label: &str) -> Self { + static SEQUENCE: AtomicU64 = AtomicU64::new(0); + let path = std::env::temp_dir().join(format!( + "lithe-workspace-ssh-{label}-{}-{}", + std::process::id(), + SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).unwrap(); + Self(path) + } + + fn write(&self, relative: &str, text: &str) { + let path = self.0.join(relative); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + + fn path(&self) -> &Path { + &self.0 + } +} + +impl Drop for Directory { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// Stand-in for OpenSSH that prints `ssh -G` output: `configured` for the +/// destination with the configuration files, `baseline` with `-F none`. +/// Both are shell `case` arms keyed on the destination, the last argument. +#[cfg(unix)] +fn fake_ssh(directory: &Directory, configured: &str, baseline: &str) -> String { + use std::os::unix::fs::PermissionsExt; + let program = directory.path().join("ssh"); + std::fs::write( + &program, + format!( + "#!/bin/sh\nfor last; do :; done\ncase \" $* \" in\n*\" -F none \"*)\ncase \"$last\" in\n{baseline}\nesac;;\n*)\ncase \"$last\" in\n{configured}\nesac;;\nesac\n" + ), + ) + .unwrap(); + std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap(); + program.display().to_string() +} + +fn lines(values: &[&str]) -> String { + values.join("\n") +} + +const DEFAULTS: &[&str] = &[ + "user localdev", + "port 22", + "identityfile ~/.ssh/id_ed25519", + "connecttimeout 15", + "serveraliveinterval 15", + "proxyjump none", +]; + +#[cfg(unix)] +#[test] +fn effective_settings_tell_where_each_value_comes_from() { + let directory = Directory::new("effective"); + let configured = format!( + "*) echo '{}';;", + lines(&[ + "hostname 10.0.0.5", + "user dev", + "port 2222", + "identityfile ~/.ssh/build_key", + "connecttimeout 15", + "serveraliveinterval 15", + "proxyjump jump-box", + ]) + ); + let baseline = format!("*) echo 'hostname build-box\n{}';;", lines(DEFAULTS)); + let ssh = fake_ssh(&directory, &configured, &baseline); + let request: EffectiveRequest = serde_json::from_value(json!({ + "connection": { "host": "build-box", "user": "dev" } + })) + .unwrap(); + + let settings = effective_with(request, Some(&ssh)).unwrap(); + + assert_eq!( + settings["hostName"], + json!({ "value": "10.0.0.5", "source": "sshConfig" }) + ); + assert_eq!( + settings["user"], + json!({ "value": "dev", "source": "connection" }) + ); + assert_eq!( + settings["port"], + json!({ "value": 2222, "source": "sshConfig" }) + ); + assert_eq!( + settings["identityFiles"], + json!({ "value": ["~/.ssh/build_key"], "source": "sshConfig" }) + ); + assert_eq!( + settings["proxyJump"], + json!({ "value": "jump-box", "source": "sshConfig" }) + ); + assert_eq!( + settings["connectTimeoutSeconds"], + json!({ "value": 15, "source": "default" }) + ); + assert_eq!( + settings["keepAliveSeconds"], + json!({ "value": 15, "source": "default" }) + ); +} + +#[cfg(unix)] +#[test] +fn a_failing_client_reports_its_redacted_output() { + let directory = Directory::new("failing"); + let ssh = fake_ssh( + &directory, + "*) echo 'bad configuration in /Users/someone/.ssh/config' >&2; exit 255;;", + "*) exit 255;;", + ); + let request: EffectiveRequest = + serde_json::from_value(json!({ "connection": { "host": "build-box" } })).unwrap(); + + let error = effective_with(request, Some(&ssh)).unwrap_err(); + + assert!(matches!(error.code, ErrorCode::ProcessFailed)); + let details = error.details.unwrap(); + assert!(details.contains("/.ssh/config"), "{details}"); + assert!(!details.contains("someone"), "{details}"); +} + +#[test] +fn a_missing_client_is_a_missing_runtime() { + let directory = Directory::new("missing"); + let ssh = directory.path().join("no-ssh-here").display().to_string(); + let request: EffectiveRequest = + serde_json::from_value(json!({ "connection": { "host": "build-box" } })).unwrap(); + + let error = effective_with(request, Some(&ssh)).unwrap_err(); + + assert!(matches!(error.code, ErrorCode::RuntimeMissing)); +} + +#[test] +fn a_malformed_connection_names_the_field() { + let request: EffectiveRequest = serde_json::from_value(json!({ + "connection": { "host": "dev@build-box" } + })) + .unwrap(); + + let error = effective_settings(request).unwrap_err(); + + assert!(matches!(error.code, ErrorCode::InvalidRequest)); + assert!(error.details.unwrap().contains("\"host\"")); +} + +#[cfg(unix)] +#[test] +fn configuration_hosts_are_listed_with_what_they_resolve_to() { + let home = Directory::new("hosts"); + home.write( + ".ssh/config", + "Include conf.d/*\nHost build-box gpu\n HostName 10.0.0.5\nHost *.internal !bastion\n User ops\nHost jump-box\n HostName 203.0.113.7\n", + ); + home.write(".ssh/conf.d/lab", "Host lab Build-Box\n User lab\n"); + let ssh = fake_ssh( + &home, + &lines(&[ + "build-box) echo 'hostname 10.0.0.5\nuser dev\nport 22\nproxyjump jump-box';;", + "gpu) echo 'hostname 10.0.0.9\nuser dev\nport 2200\nproxyjump admin@jump-box:2222';;", + "jump-box) echo 'hostname 203.0.113.7\nuser dev\nport 22\nproxyjump none';;", + "lab) echo 'no configuration' >&2; exit 255;;", + ]), + "*) exit 1;;", + ); + let saved = crate::connections::edit( + serde_json::from_value(json!({ + "document": null, + "save": { + "name": "GPU", + "connection": { "host": "10.0.0.9", "user": "dev", "port": 2200 } + }, + })) + .unwrap(), + ) + .unwrap(); + let saved_id = saved["id"].as_str().unwrap().to_owned(); + let document = saved["document"].as_str().unwrap().to_owned(); + let request = HostsRequest { + home_directory: home.path().display().to_string(), + document: Some(document), + }; + + let result = hosts_with(request, Some(&ssh)).unwrap(); + + let files: Vec<&str> = result["files"] + .as_array() + .unwrap() + .iter() + .map(|file| file.as_str().unwrap()) + .collect(); + assert_eq!(files.len(), 2); + assert!(files[0].ends_with("config") && files[1].ends_with("lab")); + let hosts = result["hosts"].as_array().unwrap(); + let summary: Vec<(&str, &str)> = hosts + .iter() + .map(|host| { + ( + host["alias"].as_str().unwrap(), + host["status"].as_str().unwrap(), + ) + }) + .collect(); + // `Build-Box` in the included file repeats `build-box` regardless of + // case. + assert_eq!( + summary, + [ + ("build-box", "importable"), + ("gpu", "exists"), + ("*.internal", "pattern"), + ("!bastion", "pattern"), + ("jump-box", "importable"), + ("lab", "unreadable"), + ] + ); + let build = &hosts[0]; + assert_eq!( + build["resolved"], + json!({ "hostName": "10.0.0.5", "user": "dev", "port": 22, "proxyJump": "jump-box" }) + ); + assert_eq!(hosts[1]["existingId"], json!(saved_id)); + assert_eq!(hosts[1]["existingName"], "GPU"); + assert_eq!(hosts[4]["usedAsJumpBy"], json!(["build-box", "gpu"])); + assert_eq!(build["usedAsJumpBy"], json!([])); + assert_eq!(result["truncated"], false); +} + +#[test] +fn a_home_without_configuration_lists_nothing() { + let home = Directory::new("empty"); + let request = HostsRequest { + home_directory: home.path().display().to_string(), + document: None, + }; + + let result = hosts_with(request, Some("ssh-is-never-run")).unwrap(); + + assert_eq!( + result, + json!({ "files": [], "hosts": [], "truncated": false }) + ); +} + +#[test] +fn a_relative_home_is_refused() { + let request = HostsRequest { + home_directory: "home".into(), + document: None, + }; + + let error = ssh_config_hosts(request).unwrap_err(); + + assert!(matches!(error.code, ErrorCode::InvalidRequest)); +} + +#[test] +fn aliases_stop_at_the_limit() { + let text: String = (0..MAX_ALIASES + 3) + .map(|index| format!("Host host-{index}\n")) + .collect(); + let (names, truncated) = distinct_names(&[(PathBuf::from("config"), text)]); + + assert_eq!(names.len(), MAX_ALIASES); + assert!(truncated); +}