diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index c7043843..0d0eb3f1 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -816,6 +816,8 @@ or removing a command fails until the table changes in the same commit. | `remote.hostInfo` | Return cached handshake capabilities of one connection | | `remote.workspaceTrust` | Read remote workspace trust decisions and one open workspace's trust | | `remote.editWorkspaceTrust` | Record or remove one remote workspace trust decision | +| `remote.connections` | Read the SSH connections the user saved | +| `remote.editConnections` | Save, remove or record a folder on one saved SSH connection | | `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 | @@ -5661,10 +5663,28 @@ place. `remote.probe` checks a saved SSH connection before a remote workspace is opened. The request is `{ connection: { host, port?, user?, authentication?, -identityFile?, connectTimeoutSeconds?, keepAliveSeconds? } }`; unknown fields, -including any password, are rejected. `authentication` is `auto` (default), -`agent`, `privateKey` (requires `identityFile`), or `password`. `host` is a -name, address, or SSH configuration alias without a user. +identityFile?, proxyJump?, connectTimeoutSeconds?, keepAliveSeconds? } }`; +unknown fields, including any password, are rejected. `authentication` is +`auto` (default), `agent`, `privateKey` (requires `identityFile`), or +`password`. `host` is a name, address, or SSH configuration alias without a +user. Text fields are trimmed and empty optional fields dropped first; +`identityFile` is dropped unless `authentication` is `privateKey`. Then: + +| Field | Accepted | +| --- | --- | +| `host` | 1 to 1024 bytes of ASCII letters, digits and `._-:%`, not starting with `-` | +| `port` | 1 to 65535; absent keeps the SSH configuration's port | +| `user` | at most 1024 bytes of ASCII letters, digits and `._-`, starting with a letter, digit or `_` | +| `identityFile` | at most 1024 bytes, no control characters; quoted for OpenSSH when it has spaces | +| `proxyJump` | `none`, or comma-separated `[user@]host[:port]`; absent keeps the SSH configuration's jump hosts | +| `connectTimeoutSeconds` | 1 to 600; absent is 15 | +| `keepAliveSeconds` | 1 to 3600; absent keeps the transport's default | + +A refused connection is `invalid_request` whose `details` is the JSON +`{ field, reason }`, where `reason` is `required`, `invalid` or `tooLong`. +Every field becomes an allowlisted SSH option; options that run a local +command, such as `ProxyCommand`, are only read from the user's own SSH +configuration. Core runs the system `ssh` with the probe of [`remote-workspace-protocol-v1`](remote-workspace-protocol-v1.md)'s bootstrap @@ -5689,7 +5709,7 @@ The result is `{ status, host, diagnostics }`: `host` is `{ system, machine, homeDirectory, serverTarget }` from `uname -s`, `uname -m` and `$HOME`; `serverTarget` is the server's Rust target or `null`. `diagnostics` is the redacted end of OpenSSH's standard error (at most -4 KiB). A malformed connection is `invalid_request`, a missing `ssh` is +4 KiB). A malformed connection is `invalid_request` as above, a missing `ssh` is `runtime_missing`, and cancellation or the five-minute bound are `cancelled` and `timed_out`. @@ -5698,6 +5718,48 @@ and `timed_out`. `diskTotalBytes` and `diskAvailableBytes` (the file system holding `$HOME`), and `uptimeSeconds`. +#### Saved connections + +The connection window lists the SSH connections the user saved. Native +clients keep them in one machine-local document, read it, and publish the +`document` an edit returns atomically, as for the trust decisions; Core +validates the document and applies every edit. + +`remote.connections` accepts `{ document: string|null }` and returns +`{ connections, storage: { relativePath: "remote/connections.json", +maximumBytes: 262144 } }`. `connections` is the list in the user's order; +each entry is `{ id, name, connection, recentFolders? }`, where `connection` +is the object `remote.probe` takes and `recentFolders` holds at most 10 +normalized absolute host paths, most recent first. + +`remote.editConnections` accepts `{ document }` with exactly one of: + +- `save: { id?, name, connection }` normalizes and checks the connection, + then adds an entry with a new id or replaces the entry `id` in place. + `name` is trimmed, 1 to 128 characters without control characters, and + unique among the entries regardless of case. Replacing an entry with + another `host`, `port`, `user` or `proxyJump` clears its recent folders, + which belong to the target and not to the name. +- `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. + +The result is `{ changed, document: string|null, connections, id? }`; `id` +names the entry a save wrote. 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. + +Bounds: 256 KiB per document and 128 entries. A document that cannot be +decoded, has duplicate keys, unknown fields, another version, a malformed +entry, or an id or name used twice is `parse_failed`; a malformed request or a +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). + +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. + #### Remote connections that stay open `remote.connect` takes `{ connection, servers: [{ target, path }], diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 6fedbf7a..9fd7b232 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -1009,6 +1009,11 @@ pub enum RemoteCommand { /// Records or removes one remote workspace trust decision /// (`remote.editWorkspaceTrust`). EditWorkspaceTrust, + /// Reads the SSH connections the user saved (`remote.connections`). + Connections, + /// Saves, removes or records a folder on one saved SSH connection + /// (`remote.editConnections`). + EditConnections, } #[derive(Debug, Clone)] @@ -1573,6 +1578,8 @@ impl CoreCommand { "remote.hostInfo" => Some(Self::Remote(RemoteCommand::HostInfo)), "remote.workspaceTrust" => Some(Self::Remote(RemoteCommand::WorkspaceTrust)), "remote.editWorkspaceTrust" => Some(Self::Remote(RemoteCommand::EditWorkspaceTrust)), + "remote.connections" => Some(Self::Remote(RemoteCommand::Connections)), + "remote.editConnections" => Some(Self::Remote(RemoteCommand::EditConnections)), "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 ae14e0c1..9e7d2a79 100644 --- a/rust/crates/core/src/runtime/dispatcher/remote.rs +++ b/rust/crates/core/src/runtime/dispatcher/remote.rs @@ -166,6 +166,36 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option, payload: Valu Err(error) => CoreResponse::failure(id, error), } } + RemoteCommand::Connections => { + match serde_json::from_value(payload) + .map_err(|error| { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid remote connections request", + ) + .with_details(error.to_string()) + }) + .and_then(lithe_workspace::connections::list) + { + Ok(value) => CoreResponse::success(id, value), + Err(error) => CoreResponse::failure(id, error), + } + } + RemoteCommand::EditConnections => { + match serde_json::from_value(payload) + .map_err(|error| { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid remote connections request", + ) + .with_details(error.to_string()) + }) + .and_then(lithe_workspace::connections::edit) + { + Ok(value) => CoreResponse::success(id, value), + Err(error) => CoreResponse::failure(id, error), + } + } RemoteCommand::Disconnect => { match serde_json::from_value::(payload) { Ok(request) => CoreResponse::success( diff --git a/rust/crates/remote/src/client/connections.rs b/rust/crates/remote/src/client/connections.rs new file mode 100644 index 00000000..0b17aec7 --- /dev/null +++ b/rust/crates/remote/src/client/connections.rs @@ -0,0 +1,555 @@ +//! Saved remote connections (design §3.1, S08 to S10, S12 and S15). +//! +//! The connection window lists the SSH connections the user saved, and every +//! request that reaches a host takes the [`SshConnection`] of one of them. This +//! module owns both: which fields a connection has, how they become an +//! [`SshHop`], and the machine-local document that keeps the list. +//! +//! - A connection carries only what selects the target and the +//! authentication. Passwords, passphrases and one-time codes never appear in +//! it (S12); a private key is a path OpenSSH reads, never its contents (S15). +//! - Every field becomes an allowlisted SSH option (S08). Options that run a +//! local command, such as `ProxyCommand`, stay in the user's own +//! `~/.ssh/config`. +//! - The document lives at [`STORAGE_PATH`] below the platform's +//! user-preference directory, never on a host or in a workspace. This module +//! validates and edits it; the platform adapter reads it and publishes edits +//! atomically. +//! +//! 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. + +use crate::client::transport::{is_jumps, is_ssh_user, Hop, SshHop, TransportChain}; +use crate::client::trust::host_path; +use serde::{Deserialize, Serialize}; +use std::fmt; + +/// Document location below the platform's user-preference directory. +pub const STORAGE_PATH: &str = "remote/connections.json"; + +/// Largest accepted document, in bytes. +pub const MAX_BYTES: usize = 256 * 1024; + +/// Seconds OpenSSH waits for the TCP connection when the connection sets none. +pub const DEFAULT_CONNECT_TIMEOUT_SECONDS: u32 = 15; + +/// Saved connections. +const MAX_CONNECTIONS: usize = 128; + +/// Longest connection name, in characters. +const MAX_NAME_CHARS: usize = 128; + +/// Longest host, user, private key path or jump host list, in bytes. +const MAX_FIELD_BYTES: usize = 1024; + +/// Longest connection id, in bytes. +const MAX_ID_BYTES: usize = 64; + +/// Ids drawn for a new entry before giving up. A random 128-bit id never +/// needs a second draw; the bound only stops a broken generator. +const ID_ATTEMPTS: usize = 16; + +/// Folders remembered per connection, most recent first. +const MAX_RECENT_FOLDERS: usize = 10; + +/// Longest connect timeout. OpenSSH accepts more, but a host that has not +/// answered in ten minutes is unreachable for a user waiting on a window. +const MAX_CONNECT_TIMEOUT_SECONDS: u32 = 600; + +/// Longest keep-alive interval. +const MAX_KEEP_ALIVE_SECONDS: u32 = 3600; + +/// 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)] +#[serde(rename_all = "camelCase")] +pub enum Authentication { + /// OpenSSH's own order: keys and agent first, then interactive methods. + #[default] + Auto, + /// Keys offered by the running SSH agent or the SSH configuration. + Agent, + /// Only the private key named by `identityFile`. + PrivateKey, + /// Password or keyboard-interactive prompts, without trying keys. + Password, +} + +impl Authentication { + fn is_auto(&self) -> bool { + *self == Self::Auto + } +} + +/// One SSH connection: the host, the account and how to authenticate. +/// Names stay in [`SavedConnection`]; secrets are never part of it. +#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] +#[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, + /// `None` keeps the port from the SSH configuration (22 by default). + #[serde(default, skip_serializing_if = "Option::is_none")] + port: Option, + /// `None` keeps the user from the SSH configuration. + #[serde(default, skip_serializing_if = "Option::is_none")] + user: Option, + #[serde(default, skip_serializing_if = "Authentication::is_auto")] + 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, + /// `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, + /// `None` uses [`DEFAULT_CONNECT_TIMEOUT_SECONDS`]. + #[serde(default, skip_serializing_if = "Option::is_none")] + connect_timeout_seconds: Option, + /// `None` keeps the transport's keep-alive default. + #[serde(default, skip_serializing_if = "Option::is_none")] + keep_alive_seconds: Option, +} + +/// Why a connection, a document or an edit was refused. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ConnectionError { + /// The offending field, for example `host`, `name` or `document`. + pub field: &'static str, + /// Why the field was refused. + pub reason: Reason, +} + +/// The kind of refusal, stable for clients to translate. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum Reason { + /// The field is empty but required. + Required, + /// The value has characters or a form the field does not accept, or is + /// out of range. + Invalid, + /// The value is longer than the field allows. + TooLong, + /// Another saved connection already uses the value. + Duplicate, + /// The list already holds as many entries as it may. + Full, + /// No saved connection has the id. + Unknown, +} + +impl ConnectionError { + fn at(field: &'static str, reason: Reason) -> Self { + Self { field, reason } + } +} + +impl fmt::Display for ConnectionError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + formatter, + "invalid remote connection at {} ({:?})", + self.field, self.reason + ) + } +} + +impl std::error::Error for ConnectionError {} + +impl SshConnection { + /// The connection as it is saved and used: text fields trimmed, empty + /// optional fields removed, and the private key path dropped unless the + /// connection authenticates with it. + pub fn normalized(mut self) -> Self { + fn trimmed(value: Option) -> Option { + value + .map(|text| text.trim().to_owned()) + .filter(|text| !text.is_empty()) + } + self.host = self.host.trim().to_owned(); + self.user = trimmed(self.user); + self.identity_file = match self.authentication { + Authentication::PrivateKey => trimmed(self.identity_file), + _ => None, + }; + self.proxy_jump = trimmed(self.proxy_jump); + self + } + + /// Checks every field of a normalized connection. + pub fn check(&self) -> Result<(), ConnectionError> { + use Reason::*; + let host = &self.host; + if host.is_empty() { + return Err(ConnectionError::at("host", Required)); + } + if host.len() > MAX_FIELD_BYTES { + return Err(ConnectionError::at("host", TooLong)); + } + // Host names, addresses (IPv6 with an optional zone) and SSH aliases. + // No `@`, since the user has its own field, no `/`, so an `ssh://` + // URI cannot smuggle in a user or port, and no leading `-`, which ssh + // would read as an option. + if host.starts_with('-') + || !host + .chars() + .all(|character| character.is_ascii_alphanumeric() || "._-:%".contains(character)) + { + return Err(ConnectionError::at("host", Invalid)); + } + if self.port == Some(0) { + return Err(ConnectionError::at("port", Invalid)); + } + if let Some(user) = &self.user { + if user.len() > MAX_FIELD_BYTES { + return Err(ConnectionError::at("user", TooLong)); + } + if !is_ssh_user(user) { + return Err(ConnectionError::at("user", Invalid)); + } + } + match (&self.authentication, &self.identity_file) { + (Authentication::PrivateKey, None) => { + return Err(ConnectionError::at("identityFile", Required)) + } + (Authentication::PrivateKey, Some(path)) => { + if path.len() > MAX_FIELD_BYTES { + return Err(ConnectionError::at("identityFile", TooLong)); + } + if path.trim() != path || path.chars().any(char::is_control) { + return Err(ConnectionError::at("identityFile", Invalid)); + } + } + (_, Some(_)) => return Err(ConnectionError::at("identityFile", Invalid)), + (_, None) => {} + } + if let Some(jumps) = &self.proxy_jump { + if jumps.len() > MAX_FIELD_BYTES { + return Err(ConnectionError::at("proxyJump", TooLong)); + } + if !is_jumps(jumps) { + return Err(ConnectionError::at("proxyJump", Invalid)); + } + } + if self + .connect_timeout_seconds + .is_some_and(|seconds| !(1..=MAX_CONNECT_TIMEOUT_SECONDS).contains(&seconds)) + { + return Err(ConnectionError::at("connectTimeoutSeconds", Invalid)); + } + if self + .keep_alive_seconds + .is_some_and(|seconds| !(1..=MAX_KEEP_ALIVE_SECONDS).contains(&seconds)) + { + return Err(ConnectionError::at("keepAliveSeconds", Invalid)); + } + Ok(()) + } + + /// The SSH hop of a normalized connection, refused before any process + /// starts when a field is malformed. + pub fn hop(&self) -> Result { + self.check()?; + let destination = match &self.user { + Some(user) => format!("{user}@{}", self.host), + None => self.host.clone(), + }; + let mut hop = SshHop::new(destination); + hop.port = self.port; + let mut option = |key: &str, value: String| hop.options.push((key.into(), value)); + option( + "ConnectTimeout", + self.connect_timeout_seconds + .unwrap_or(DEFAULT_CONNECT_TIMEOUT_SECONDS) + .to_string(), + ); + // OpenSSH keeps the first value, so the connection's interval comes + // before the transport's default. + if let Some(seconds) = self.keep_alive_seconds { + option("ServerAliveInterval", seconds.to_string()); + } + // Prompts must reach AskPass even when the user's configuration sets + // BatchMode for scripts. + option("BatchMode", "no".into()); + if let Some(jumps) = &self.proxy_jump { + option("ProxyJump", jumps.clone()); + } + match self.authentication { + Authentication::Auto => {} + Authentication::Agent => option("PreferredAuthentications", "publickey".into()), + Authentication::PrivateKey => { + let Some(identity) = self.identity_file.as_deref() else { + return Err(ConnectionError::at("identityFile", Reason::Required)); + }; + // ssh splits an option value on whitespace, so a path such as + // "~/My Keys/id_rsa" must be quoted (ssh_config quoting rules). + let identity = if identity + .chars() + .any(|c| c.is_whitespace() || c == '"' || c == '\\') + { + format!( + "\"{}\"", + identity.replace('\\', "\\\\").replace('"', "\\\"") + ) + } else { + identity.to_owned() + }; + option("IdentityFile", identity); + // Without this, keys from the agent are tried first and can + // use up the server's attempt limit before the chosen key. + option("IdentitiesOnly", "yes".into()); + option("PreferredAuthentications", "publickey".into()); + } + Authentication::Password => { + option( + "PreferredAuthentications", + "keyboard-interactive,password".into(), + ); + option("PubkeyAuthentication", "no".into()); + } + } + // The transport applies its own allowlist when it builds a command; + // the fields above must never produce a hop it refuses. + TransportChain::new(vec![Hop::Ssh(hop.clone())]) + .command(&["true".to_owned()]) + .map_err(|_| ConnectionError::at("host", Reason::Invalid))?; + Ok(hop) + } + + /// Whether `other` reaches another host or account: remembered folders + /// belong to the target, not to the name. + fn same_target(&self, other: &Self) -> bool { + self.host == other.host + && self.port == other.port + && self.user == other.user + && self.proxy_jump == other.proxy_jump + } +} + +/// One saved connection. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SavedConnection { + /// Stable id Core chose when the connection was first saved. + id: String, + /// Name the user gave, unique among the saved connections. + name: String, + connection: SshConnection, + /// Host folders opened over this connection, most recent first. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + recent_folders: Vec, +} + +impl SavedConnection { + fn check(&self) -> Result<(), ConnectionError> { + check_id(&self.id)?; + check_name(&self.name)?; + self.connection.check()?; + if self.recent_folders.len() > MAX_RECENT_FOLDERS { + return Err(ConnectionError::at("recentFolders", Reason::Full)); + } + for (index, folder) in self.recent_folders.iter().enumerate() { + if host_path(folder).is_none() { + return Err(ConnectionError::at("recentFolders", Reason::Invalid)); + } + if self.recent_folders[..index].contains(folder) { + return Err(ConnectionError::at("recentFolders", Reason::Duplicate)); + } + } + Ok(()) + } +} + +/// The validated document: saved connections in the user's order. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Connections { + version: u32, + #[serde(default)] + connections: Vec, +} + +impl Default for Connections { + fn default() -> Self { + Self { + version: 1, + connections: Vec::new(), + } + } +} + +impl Connections { + /// Reads `document`, or the empty document when there is none yet. + /// + /// Refuses documents over [`MAX_BYTES`], malformed JSON, duplicate keys, + /// unknown fields, other versions, more than 128 connections, malformed + /// entries, and ids or names used twice. + pub fn parse(document: Option<&str>) -> Result { + let Some(text) = document else { + return Ok(Self::default()); + }; + if text.len() > MAX_BYTES { + return Err(ConnectionError::at("document", Reason::TooLong)); + } + let connections: Self = serde_json::from_str(text) + .map_err(|_| ConnectionError::at("document", Reason::Invalid))?; + if connections.version != 1 { + return Err(ConnectionError::at("version", Reason::Invalid)); + } + if connections.connections.len() > MAX_CONNECTIONS { + return Err(ConnectionError::at("connections", Reason::Full)); + } + for (index, entry) in connections.connections.iter().enumerate() { + entry.check()?; + let earlier = &connections.connections[..index]; + if earlier.iter().any(|other| other.id == entry.id) { + return Err(ConnectionError::at("id", Reason::Duplicate)); + } + if earlier + .iter() + .any(|other| same_name(&other.name, &entry.name)) + { + return Err(ConnectionError::at("name", Reason::Duplicate)); + } + } + Ok(connections) + } + + /// The document text to publish, refused when it would exceed + /// [`MAX_BYTES`]. + pub fn text(&self) -> Result { + let mut text = serde_json::to_string_pretty(self) + .map_err(|_| ConnectionError::at("document", Reason::Invalid))?; + text.push('\n'); + if text.len() > MAX_BYTES { + return Err(ConnectionError::at("document", Reason::TooLong)); + } + Ok(text) + } + + /// Saved connections in the user's order. + pub fn entries(&self) -> &[SavedConnection] { + &self.connections + } + + /// The saved connection with `id`. + fn get(&self, id: &str) -> Option<&SavedConnection> { + self.connections.iter().find(|entry| entry.id == id) + } + + /// Saves `connection` under `name`, replacing the entry `id` or, without + /// one, appending a new entry with an id from `new_id`. Returns the id. + /// + /// Renaming keeps the remembered folders; pointing the entry at another + /// host, port, user or jump host forgets them. `new_id` is called until + /// it returns an unused valid id, at most 16 times. + pub fn save( + &mut self, + id: Option<&str>, + name: &str, + connection: SshConnection, + mut new_id: impl FnMut() -> String, + ) -> Result { + let name = name.trim(); + check_name(name)?; + let connection = connection.normalized(); + connection.check()?; + if self + .connections + .iter() + .any(|other| Some(other.id.as_str()) != id && same_name(&other.name, name)) + { + return Err(ConnectionError::at("name", Reason::Duplicate)); + } + match id { + Some(id) => { + let entry = self + .connections + .iter_mut() + .find(|entry| entry.id == id) + .ok_or(ConnectionError::at("id", Reason::Unknown))?; + if !entry.connection.same_target(&connection) { + entry.recent_folders.clear(); + } + entry.name = name.to_owned(); + entry.connection = connection; + Ok(entry.id.clone()) + } + None => { + if self.connections.len() >= MAX_CONNECTIONS { + return Err(ConnectionError::at("connections", Reason::Full)); + } + let id = (0..ID_ATTEMPTS) + .map(|_| new_id()) + .find(|candidate| check_id(candidate).is_ok() && self.get(candidate).is_none()) + .ok_or(ConnectionError::at("id", Reason::Invalid))?; + self.connections.push(SavedConnection { + id: id.clone(), + name: name.to_owned(), + connection, + recent_folders: Vec::new(), + }); + Ok(id) + } + } + } + + /// Removes the entry `id`; an absent id changes nothing. + pub fn remove(&mut self, id: &str) { + self.connections.retain(|entry| entry.id != id); + } + + /// Puts the host folder `path` first among the entry's recent folders, + /// keeping at most ten. + pub fn remember_folder(&mut self, id: &str, path: &str) -> Result<(), ConnectionError> { + let path = host_path(path).ok_or(ConnectionError::at("path", Reason::Invalid))?; + let entry = self + .connections + .iter_mut() + .find(|entry| entry.id == id) + .ok_or(ConnectionError::at("id", Reason::Unknown))?; + entry.recent_folders.retain(|folder| folder != path); + entry.recent_folders.insert(0, path.to_owned()); + entry.recent_folders.truncate(MAX_RECENT_FOLDERS); + Ok(()) + } +} + +/// Letters, digits and `-`, at most 64 bytes. +fn check_id(id: &str) -> Result<(), ConnectionError> { + let valid = !id.is_empty() + && id.len() <= MAX_ID_BYTES + && id + .chars() + .all(|character| character.is_ascii_alphanumeric() || character == '-'); + if valid { + Ok(()) + } else { + Err(ConnectionError::at("id", Reason::Invalid)) + } +} + +/// A trimmed name of at most 128 characters without control characters. +fn check_name(name: &str) -> Result<(), ConnectionError> { + if name.is_empty() { + return Err(ConnectionError::at("name", Reason::Required)); + } + if name.chars().count() > MAX_NAME_CHARS { + return Err(ConnectionError::at("name", Reason::TooLong)); + } + if name.trim() != name || name.chars().any(char::is_control) { + return Err(ConnectionError::at("name", Reason::Invalid)); + } + Ok(()) +} + +/// Names that differ only in letter case would look the same in a title. +fn same_name(left: &str, right: &str) -> bool { + left.to_lowercase() == right.to_lowercase() +} + +#[cfg(test)] +mod tests; diff --git a/rust/crates/remote/src/client/connections/tests.rs b/rust/crates/remote/src/client/connections/tests.rs new file mode 100644 index 00000000..ee84314c --- /dev/null +++ b/rust/crates/remote/src/client/connections/tests.rs @@ -0,0 +1,561 @@ +use super::*; +use crate::client::bootstrap::probe_command; +use serde_json::json; + +fn connection(value: serde_json::Value) -> SshConnection { + serde_json::from_value::(value) + .expect("valid connection") + .normalized() +} + +/// The local command line the connection produces for the probe. +fn command_line(value: serde_json::Value) -> Vec { + let hop = connection(value).hop().expect("valid hop"); + TransportChain::new(vec![Hop::Ssh(hop)]) + .command(&probe_command()) + .unwrap() +} + +fn option_value(command: &[String], key: &str) -> Option { + command + .windows(2) + .filter(|pair| pair[0] == "-o") + .find_map(|pair| pair[1].strip_prefix(&format!("{key}=")).map(str::to_owned)) +} + +fn refusal(value: serde_json::Value) -> ConnectionError { + connection(value.clone()) + .hop() + .expect_err(&format!("{value} was accepted")) +} + +/// Ids handed out in order, as Core's random generator would. +fn ids() -> impl FnMut() -> String { + let mut next = 0; + move || { + next += 1; + format!("id-{next}") + } +} + +/// Saves a connection to `host`, with an id derived from the host. +fn saved(connections: &mut Connections, name: &str, host: &str) -> String { + connections + .save(None, name, connection(json!({ "host": host })), || { + format!("id-{host}") + }) + .expect("saved") +} + +#[test] +fn private_key_connections_offer_only_the_chosen_key() { + let command = command_line(json!({ + "host": "devbox.example", + "port": 2222, + "user": "dev", + "authentication": "privateKey", + "identityFile": "~/.ssh/id_ed25519", + "connectTimeoutSeconds": 20, + "keepAliveSeconds": 30, + })); + assert!(command.windows(2).any(|pair| pair == ["-p", "2222"])); + assert_eq!(&command[command.len() - 2], "dev@devbox.example"); + assert_eq!( + option_value(&command, "IdentityFile").as_deref(), + Some("~/.ssh/id_ed25519") + ); + assert_eq!( + option_value(&command, "IdentitiesOnly").as_deref(), + Some("yes") + ); + assert_eq!( + option_value(&command, "PreferredAuthentications").as_deref(), + Some("publickey") + ); + assert_eq!( + option_value(&command, "ConnectTimeout").as_deref(), + Some("20") + ); + // OpenSSH keeps the first value, so the connection's interval must come + // before the transport's default. + assert_eq!( + option_value(&command, "ServerAliveInterval").as_deref(), + Some("30") + ); + assert_eq!(option_value(&command, "BatchMode").as_deref(), Some("no")); +} + +#[test] +fn other_authentication_methods_select_matching_ssh_options() { + let password = command_line(json!({ "host": "h", "authentication": "password" })); + assert_eq!( + option_value(&password, "PreferredAuthentications").as_deref(), + Some("keyboard-interactive,password") + ); + assert_eq!( + option_value(&password, "PubkeyAuthentication").as_deref(), + Some("no") + ); + + let agent = command_line(json!({ "host": "h", "authentication": "agent" })); + assert_eq!( + option_value(&agent, "PreferredAuthentications").as_deref(), + Some("publickey") + ); + assert_eq!(option_value(&agent, "IdentityFile"), None); + + // Automatic leaves the order to OpenSSH and the user's configuration, + // and an alias without a user, port or jump host stays untouched. + let automatic = command_line(json!({ "host": "devbox" })); + assert_eq!(option_value(&automatic, "PreferredAuthentications"), None); + assert_eq!(option_value(&automatic, "ProxyJump"), None); + assert_eq!(&automatic[automatic.len() - 2], "devbox"); + assert!(!automatic.iter().any(|argument| argument == "-p")); + assert_eq!( + option_value(&automatic, "ConnectTimeout").as_deref(), + Some(DEFAULT_CONNECT_TIMEOUT_SECONDS.to_string().as_str()) + ); +} + +#[test] +fn jump_hosts_and_quoted_key_paths_reach_ssh() { + let command = command_line(json!({ + "host": "fe80::1%en0", + "authentication": "privateKey", + "identityFile": "~/My Keys/id_rsa", + "proxyJump": "ops@bastion.example.com:2200,jump2", + })); + assert_eq!( + option_value(&command, "ProxyJump").as_deref(), + Some("ops@bastion.example.com:2200,jump2") + ); + assert_eq!( + option_value(&command, "IdentityFile").as_deref(), + Some("\"~/My Keys/id_rsa\"") + ); + assert_eq!(&command[command.len() - 2], "fe80::1%en0"); + + let direct = command_line(json!({ "host": "box", "proxyJump": "none" })); + assert_eq!(option_value(&direct, "ProxyJump").as_deref(), Some("none")); +} + +#[test] +fn normalizing_trims_fields_and_keeps_a_key_only_for_key_authentication() { + let trimmed = connection(json!({ + "host": " box ", + "user": " ", + "identityFile": "~/.ssh/id_ed25519", + "proxyJump": "", + })); + assert_eq!(trimmed, connection(json!({ "host": "box" }))); + let key = connection(json!({ + "host": "box", + "authentication": "privateKey", + "identityFile": " ~/.ssh/id_ed25519 ", + })); + assert_eq!(key.identity_file.as_deref(), Some("~/.ssh/id_ed25519")); + // Defaults are left out, so the document only shows what the user set. + assert_eq!( + serde_json::to_value(&trimmed).unwrap(), + json!({ "host": "box" }) + ); +} + +#[test] +fn malformed_connections_name_the_field_before_ssh_starts() { + use Reason::*; + for (value, field, reason) in [ + (json!({ "host": "" }), "host", Required), + (json!({ "host": "dev@box" }), "host", Invalid), + (json!({ "host": "-oProxyCommand=x" }), "host", Invalid), + (json!({ "host": "ssh://box" }), "host", Invalid), + (json!({ "host": "box name" }), "host", Invalid), + (json!({ "host": "a".repeat(1025) }), "host", TooLong), + (json!({ "host": "box", "port": 0 }), "port", Invalid), + ( + json!({ "host": "box", "user": "-oProxyCommand=x" }), + "user", + Invalid, + ), + (json!({ "host": "box", "user": "a b" }), "user", Invalid), + (json!({ "host": "box", "user": "a:b" }), "user", Invalid), + ( + json!({ "host": "box", "authentication": "privateKey" }), + "identityFile", + Required, + ), + ( + json!({ "host": "box", "authentication": "privateKey", "identityFile": "key\nProxyCommand x" }), + "identityFile", + Invalid, + ), + ( + json!({ "host": "box", "proxyJump": "-oProxyCommand=x" }), + "proxyJump", + Invalid, + ), + ( + json!({ "host": "box", "proxyJump": "bastion," }), + "proxyJump", + Invalid, + ), + ( + json!({ "host": "box", "proxyJump": "ssh://bastion" }), + "proxyJump", + Invalid, + ), + ( + json!({ "host": "box", "connectTimeoutSeconds": 0 }), + "connectTimeoutSeconds", + Invalid, + ), + ( + json!({ "host": "box", "connectTimeoutSeconds": 601 }), + "connectTimeoutSeconds", + Invalid, + ), + ( + json!({ "host": "box", "keepAliveSeconds": 0 }), + "keepAliveSeconds", + Invalid, + ), + ( + json!({ "host": "box", "keepAliveSeconds": 3601 }), + "keepAliveSeconds", + Invalid, + ), + ] { + assert_eq!( + refusal(value.clone()), + ConnectionError { field, reason }, + "{value}" + ); + } + // Secrets and local commands have no field to arrive in. + for value in [ + json!({ "host": "h", "password": "x" }), + json!({ "host": "h", "proxyCommand": "nc %h %p" }), + ] { + assert!(serde_json::from_value::(value).is_err()); + } +} + +#[test] +fn saved_connections_round_trip_through_the_document() { + let mut connections = Connections::parse(None).unwrap(); + assert!(connections.entries().is_empty()); + let id = connections + .save( + None, + " Build box ", + connection(json!({ "host": "build.example", "user": "ci", "port": 2222 })), + ids(), + ) + .unwrap(); + connections.remember_folder(&id, "/srv/app").unwrap(); + let text = connections.text().unwrap(); + assert!(text.ends_with('\n')); + let read = Connections::parse(Some(&text)).unwrap(); + assert_eq!(read, connections); + let entry = read.get(&id).unwrap(); + assert_eq!(entry.name, "Build box"); + assert_eq!(entry.connection.host, "build.example"); + assert_eq!( + serde_json::from_str::(&text).unwrap(), + json!({ + "version": 1, + "connections": [{ + "id": id, + "name": "Build box", + "connection": { "host": "build.example", "port": 2222, "user": "ci" }, + "recentFolders": ["/srv/app"], + }], + }) + ); +} + +#[test] +fn saving_refuses_names_that_only_differ_in_case_and_unknown_ids() { + let mut connections = Connections::default(); + let first = saved(&mut connections, "Devbox", "devbox"); + assert_eq!( + connections.save( + None, + "devbox", + connection(json!({ "host": "other" })), + ids() + ), + Err(ConnectionError::at("name", Reason::Duplicate)) + ); + // An entry keeps its own name when the user edits it. + assert_eq!( + connections.save( + Some(&first), + "DEVBOX", + connection(json!({ "host": "devbox" })), + ids() + ), + Ok(first.clone()) + ); + assert_eq!( + connections.save( + Some("missing"), + "Other", + connection(json!({ "host": "h" })), + ids() + ), + Err(ConnectionError::at("id", Reason::Unknown)) + ); + for (name, reason) in [ + ("", Reason::Required), + (" ", Reason::Required), + ("tab\there", Reason::Invalid), + ] { + assert_eq!( + connections.save(None, name, connection(json!({ "host": "h" })), ids()), + Err(ConnectionError::at("name", reason)), + "{name:?}" + ); + } + let long = "名".repeat(129); + assert_eq!( + connections.save(None, &long, connection(json!({ "host": "h" })), ids()), + Err(ConnectionError::at("name", Reason::TooLong)) + ); + assert_eq!(connections.entries().len(), 1); +} + +#[test] +fn recent_folders_follow_the_target_not_the_name() { + let mut connections = Connections::default(); + let id = saved(&mut connections, "Devbox", "devbox"); + for index in 0..12 { + connections + .remember_folder(&id, &format!("/srv/{index}")) + .unwrap(); + } + connections.remember_folder(&id, "/srv/5").unwrap(); + let folders = &connections.get(&id).unwrap().recent_folders; + assert_eq!(folders.len(), 10); + assert_eq!(folders[0], "/srv/5"); + assert_eq!(folders[1], "/srv/11"); + assert_eq!( + folders.iter().filter(|folder| *folder == "/srv/5").count(), + 1 + ); + for path in ["srv", "/srv/../etc", "/srv/", ""] { + assert_eq!( + connections.remember_folder(&id, path), + Err(ConnectionError::at("path", Reason::Invalid)), + "{path:?}" + ); + } + assert_eq!( + connections.remember_folder("missing", "/srv"), + Err(ConnectionError::at("id", Reason::Unknown)) + ); + + // Renaming or changing how to authenticate keeps the folders. + connections + .save( + Some(&id), + "Renamed", + connection( + json!({ "host": "devbox", "authentication": "agent", "keepAliveSeconds": 30 }), + ), + ids(), + ) + .unwrap(); + assert_eq!(connections.get(&id).unwrap().recent_folders.len(), 10); + // Another host, port, user or jump host forgets them. + for target in [ + json!({ "host": "other" }), + json!({ "host": "other", "port": 2222 }), + json!({ "host": "other", "port": 2222, "user": "dev" }), + json!({ "host": "other", "port": 2222, "user": "dev", "proxyJump": "bastion" }), + ] { + connections.remember_folder(&id, "/srv").unwrap(); + connections + .save(Some(&id), "Renamed", connection(target.clone()), ids()) + .unwrap(); + assert!( + connections.get(&id).unwrap().recent_folders.is_empty(), + "{target}" + ); + } +} + +#[test] +fn removing_keeps_the_order_and_ignores_absent_ids() { + let mut connections = Connections::default(); + let first = saved(&mut connections, "One", "one"); + let mut second_ids = || "second".to_owned(); + connections + .save( + None, + "Two", + connection(json!({ "host": "two" })), + &mut second_ids, + ) + .unwrap(); + let mut third_ids = || "third".to_owned(); + connections + .save( + None, + "Three", + connection(json!({ "host": "three" })), + &mut third_ids, + ) + .unwrap(); + connections.remove("second"); + let before = connections.clone(); + connections.remove("missing"); + assert_eq!(connections, before); + let names: Vec<_> = connections + .entries() + .iter() + .map(|entry| entry.name.as_str()) + .collect(); + assert_eq!(names, ["One", "Three"]); + assert_eq!(connections.entries()[0].id, first); +} + +#[test] +fn new_ids_are_drawn_until_one_is_valid_and_unused() { + let mut connections = Connections::default(); + let mut first = || "taken".to_owned(); + connections + .save( + None, + "One", + connection(json!({ "host": "one" })), + &mut first, + ) + .unwrap(); + let mut candidates = ["taken", "bad id", "", "fresh"] + .into_iter() + .map(str::to_owned); + let id = connections + .save(None, "Two", connection(json!({ "host": "two" })), || { + candidates.next().unwrap() + }) + .unwrap(); + assert_eq!(id, "fresh"); +} + +#[test] +fn the_list_holds_at_most_128_connections() { + let mut connections = Connections::default(); + for index in 0..128 { + saved( + &mut connections, + &format!("Host {index}"), + &format!("h{index}"), + ); + } + assert_eq!( + connections.save(None, "One more", connection(json!({ "host": "h" })), ids()), + Err(ConnectionError::at("connections", Reason::Full)) + ); + // Editing an entry still works when the list is full. + let id = connections.entries()[0].id.to_owned(); + assert!(connections + .save( + Some(&id), + "Host 0", + connection(json!({ "host": "h0", "port": 22 })), + ids() + ) + .is_ok()); + assert!(Connections::parse(Some(&connections.text().unwrap())).is_ok()); +} + +#[test] +fn stored_documents_are_checked_like_edits() { + let entry = + |id: &str, name: &str| json!({ "id": id, "name": name, "connection": { "host": "h" } }); + let document = |connections: serde_json::Value| { + json!({ "version": 1, "connections": connections }).to_string() + }; + for (text, field, reason) in [ + ("{".to_owned(), "document", Reason::Invalid), + ("[]".to_owned(), "document", Reason::Invalid), + ( + r#"{"version":1,"version":1,"connections":[]}"#.to_owned(), + "document", + Reason::Invalid, + ), + ( + json!({ "version": 1, "connections": [], "extra": true }).to_string(), + "document", + Reason::Invalid, + ), + ( + json!({ "version": 2 }).to_string(), + "version", + Reason::Invalid, + ), + ( + document(json!([entry("a", "One"), entry("a", "Two")])), + "id", + Reason::Duplicate, + ), + ( + document(json!([entry("a", "One"), entry("b", "ONE")])), + "name", + Reason::Duplicate, + ), + ( + document(json!([entry("a b", "One")])), + "id", + Reason::Invalid, + ), + ( + document(json!([entry("a", " One")])), + "name", + Reason::Invalid, + ), + ( + document( + json!([{ "id": "a", "name": "One", "connection": { "host": "h", "port": 0 } }]), + ), + "port", + Reason::Invalid, + ), + ( + document( + json!([{ "id": "a", "name": "One", "connection": { "host": "h" }, "recentFolders": ["relative"] }]), + ), + "recentFolders", + Reason::Invalid, + ), + ( + document( + json!([{ "id": "a", "name": "One", "connection": { "host": "h" }, "recentFolders": ["/a", "/a"] }]), + ), + "recentFolders", + Reason::Duplicate, + ), + ( + document( + json!([{ "id": "a", "name": "One", "connection": { "host": "h", "password": "x" } }]), + ), + "document", + Reason::Invalid, + ), + ( + document(json!((0..129) + .map(|index| entry(&format!("i{index}"), &format!("n{index}"))) + .collect::>())), + "connections", + Reason::Full, + ), + (" ".repeat(MAX_BYTES + 1), "document", Reason::TooLong), + ] { + assert_eq!( + Connections::parse(Some(&text)), + Err(ConnectionError { field, reason }), + "{text:.80}" + ); + } +} diff --git a/rust/crates/remote/src/client/mod.rs b/rust/crates/remote/src/client/mod.rs index 7418923e..2e55993d 100644 --- a/rust/crates/remote/src/client/mod.rs +++ b/rust/crates/remote/src/client/mod.rs @@ -1,5 +1,7 @@ //! Client side of Lithe remote workspaces. //! +//! - [`connections`] keeps the SSH connections the user saved and turns each +//! into an SSH hop with allowlisted options only. //! - [`transport`] turns a chain of hops (SSH, container exec) into the local //! command line that runs a program at the end of the chain. //! - [`bootstrap`] probes the platform at the end of the chain and describes @@ -26,6 +28,7 @@ pub mod bootstrap; #[cfg(all(test, unix))] mod command; pub mod connection_log; +pub mod connections; pub mod forward; pub mod launch; pub mod session; diff --git a/rust/crates/remote/src/client/transport.rs b/rust/crates/remote/src/client/transport.rs index 0e79c5c8..fd14bcba 100644 --- a/rust/crates/remote/src/client/transport.rs +++ b/rust/crates/remote/src/client/transport.rs @@ -402,7 +402,7 @@ fn allowed_option(key: &str, value: &str) -> Result<&'static str, TransportError OptionSyntax::Methods => value .split(',') .all(|method| AUTHENTICATION_METHODS.contains(&method)), - OptionSyntax::Jumps => value == "none" || value.split(',').all(is_jump_host), + OptionSyntax::Jumps => is_jumps(value), }; if !well_formed { return Err(TransportError::InvalidHop { @@ -422,13 +422,18 @@ fn is_port(value: &str) -> bool { } /// A login name that ssh cannot read as an option or a host separator. -fn is_ssh_user(user: &str) -> bool { +pub(crate) fn is_ssh_user(user: &str) -> bool { let mut characters = user.chars(); matches!(characters.next(), Some(first) if first.is_ascii_alphanumeric() || first == '_') && characters .all(|character| character.is_ascii_alphanumeric() || "._-".contains(character)) } +/// A `ProxyJump` value: `none`, or comma-separated jump hosts. +pub(crate) fn is_jumps(value: &str) -> bool { + value == "none" || value.split(',').all(is_jump_host) +} + /// `[user@]host[:port]`, where `host` is a host name, an SSH alias or a /// bracketed IPv6 address. fn is_jump_host(jump: &str) -> bool { diff --git a/rust/crates/workspace/src/connections.rs b/rust/crates/workspace/src/connections.rs new file mode 100644 index 00000000..47e75d16 --- /dev/null +++ b/rust/crates/workspace/src/connections.rs @@ -0,0 +1,145 @@ +//! `remote.connections` and `remote.editConnections`: 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 +//! entry, picks ids and applies one edit at a time; it never stores a secret. +//! The rules are in `lithe_remote::client::connections`. + +use crate::sessions::nonce; +use lithe_protocol::{CoreError, ErrorCode}; +use lithe_remote::client::connections::{ + self, ConnectionError, Connections, Reason, SshConnection, +}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +/// `remote.connections`: the saved connections. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ListRequest { + /// Current document text; `null` when the source does not exist. + document: Option, +} + +/// `remote.editConnections`: exactly one of `save`, `remove` and +/// `rememberFolder`. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct EditRequest { + /// Current document text; `null` when the source does not exist. + document: Option, + #[serde(default)] + save: Option, + #[serde(default)] + remove: Option, + #[serde(default)] + remember_folder: Option, +} + +/// Adds a connection, or replaces the entry `id`. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SaveRequest { + #[serde(default)] + id: Option, + name: String, + connection: SshConnection, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct IdRequest { + id: String, +} + +/// A host folder opened over the entry `id`. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct FolderRequest { + id: String, + path: String, +} + +/// Where the native client keeps the document. +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct Storage { + relative_path: &'static str, + maximum_bytes: usize, +} + +const STORAGE: Storage = Storage { + relative_path: connections::STORAGE_PATH, + maximum_bytes: connections::MAX_BYTES, +}; + +/// Reads the document. +pub fn list(request: ListRequest) -> Result { + let connections = parse(request.document.as_deref())?; + Ok(json!({ "connections": connections.entries(), "storage": STORAGE })) +} + +/// 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. +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) => { + id = Some( + after + .save(save.id.as_deref(), &save.name, save.connection, nonce) + .map_err(invalid_request)?, + ); + } + (None, Some(remove), None) => after.remove(&remove.id), + (None, None, Some(folder)) => after + .remember_folder(&folder.id, &folder.path) + .map_err(invalid_request)?, + _ => { + return Err(invalid_request(ConnectionError { + field: "operation", + reason: Reason::Invalid, + })) + } + } + let changed = after != before; + let document = if changed { + Some(after.text().map_err(invalid_request)?) + } else { + None + }; + let mut result = json!({ + "changed": changed, + "document": document, + "connections": after.entries(), + }); + if let Some(id) = id { + result["id"] = json!(id); + } + Ok(result) +} + +/// 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 { + Connections::parse(document).map_err(|error| { + CoreError::new( + ErrorCode::ParseFailed, + "Invalid remote connections document", + ) + .with_details(json!(error).to_string()) + }) +} + +/// A refused connection or edit, with the field and the reason as details. +pub(crate) fn invalid_request(error: ConnectionError) -> CoreError { + CoreError::new(ErrorCode::InvalidRequest, "Invalid remote connection") + .with_details(json!(error).to_string()) +} + +#[cfg(test)] +mod tests; diff --git a/rust/crates/workspace/src/connections/tests.rs b/rust/crates/workspace/src/connections/tests.rs new file mode 100644 index 00000000..37dee133 --- /dev/null +++ b/rust/crates/workspace/src/connections/tests.rs @@ -0,0 +1,110 @@ +use super::*; + +fn list_request(value: Value) -> ListRequest { + serde_json::from_value(value).expect("valid list request") +} + +fn edit_request(value: Value) -> EditRequest { + serde_json::from_value(value).expect("valid edit request") +} + +fn details(error: &CoreError) -> Value { + serde_json::from_str(error.details.as_deref().expect("details")).expect("JSON details") +} + +#[test] +fn a_missing_document_lists_nothing_and_says_where_to_keep_one() { + let result = list(list_request(json!({ "document": null }))).unwrap(); + assert_eq!(result["connections"], json!([])); + assert_eq!( + result["storage"], + json!({ "relativePath": "remote/connections.json", "maximumBytes": 262144 }) + ); +} + +#[test] +fn saving_returns_the_document_to_write_and_the_new_id() { + let result = edit(edit_request(json!({ + "document": null, + "save": { "name": "Build box", "connection": { "host": "build.example", "user": "dev" } }, + }))) + .unwrap(); + assert_eq!(result["changed"], json!(true)); + let id = result["id"].as_str().expect("id"); + assert_eq!(id.len(), 32); + assert!(id.bytes().all(|byte| byte.is_ascii_hexdigit())); + assert_eq!(result["connections"][0]["id"], json!(id)); + + let document = result["document"].as_str().expect("document"); + let listed = list(list_request(json!({ "document": document }))).unwrap(); + assert_eq!(listed["connections"], result["connections"]); +} + +#[test] +fn an_edit_that_changes_nothing_returns_no_document() { + let result = edit(edit_request(json!({ + "document": null, + "remove": { "id": "absent" }, + }))) + .unwrap(); + assert_eq!(result["changed"], json!(false)); + assert_eq!(result["document"], Value::Null); + assert!(result.get("id").is_none()); +} + +#[test] +fn each_edit_carries_exactly_one_operation() { + for request in [ + json!({ "document": null }), + json!({ + "document": null, + "remove": { "id": "a" }, + "rememberFolder": { "id": "a", "path": "/srv" }, + }), + ] { + let error = edit(edit_request(request)).expect_err("refused"); + assert!(matches!(error.code, ErrorCode::InvalidRequest)); + assert_eq!( + details(&error), + json!({ "field": "operation", "reason": "invalid" }) + ); + } +} + +#[test] +fn a_damaged_source_is_a_parse_failure_and_a_bad_edit_is_a_bad_request() { + let error = list(list_request( + json!({ "document": "{\"version\":2,\"connections\":[]}" }), + )) + .expect_err("unknown version"); + assert!(matches!(error.code, ErrorCode::ParseFailed)); + assert_eq!( + details(&error), + json!({ "field": "version", "reason": "invalid" }) + ); + + let error = edit(edit_request(json!({ + "document": null, + "save": { "name": "Box", "connection": { "host": "dev@box" } }, + }))) + .expect_err("host with a user"); + assert!(matches!(error.code, ErrorCode::InvalidRequest)); + assert_eq!( + details(&error), + json!({ "field": "host", "reason": "invalid" }) + ); +} + +#[test] +fn requests_cannot_carry_a_secret_or_an_unknown_field() { + for request in [ + json!({ "document": null, "save": { "name": "Box", "connection": { "host": "box", "password": "x" } } }), + json!({ "document": null, "save": { "name": "Box", "password": "x", "connection": { "host": "box" } } }), + json!({ "document": null, "extra": true }), + ] { + assert!( + serde_json::from_value::(request.clone()).is_err(), + "{request} was accepted" + ); + } +} diff --git a/rust/crates/workspace/src/lib.rs b/rust/crates/workspace/src/lib.rs index e257aead..fa2eace4 100644 --- a/rust/crates/workspace/src/lib.rs +++ b/rust/crates/workspace/src/lib.rs @@ -7,14 +7,16 @@ //! [`remote_path`] / [`local_path`] translate schema-owned paths between the //! two namespaces. Without a host every call is the local filesystem. //! -//! The session side owns the long-lived connections: [`probe`] checks that a -//! saved SSH connection reaches a usable host, [`sessions`] opens and keeps the +//! 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), [`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); this crate only supplies the IO boundary. +pub mod connections; pub mod fs; pub mod host; pub mod probe; diff --git a/rust/crates/workspace/src/probe.rs b/rust/crates/workspace/src/probe.rs index 78e56019..04d09b11 100644 --- a/rust/crates/workspace/src/probe.rs +++ b/rust/crates/workspace/src/probe.rs @@ -11,15 +11,13 @@ use lithe_protocol::{CoreError, ErrorCode}; use lithe_remote::client::bootstrap::{parse_probe, probe_command}; +use lithe_remote::client::connections::SshConnection; use lithe_remote::client::{Hop, SshHop, TransportChain}; use lithe_request_context::events as execution_events; use serde::{Deserialize, Serialize}; use std::process::{Command, ExitStatus}; use std::time::{Duration, Instant}; -/// Seconds OpenSSH waits for the TCP connection when the profile sets none. -const DEFAULT_CONNECT_TIMEOUT_SECONDS: u32 = 15; - /// Upper bound for one probe, including the time the user needs to answer /// prompts. Each prompt is additionally bounded by the AskPass session. const PROBE_DEADLINE: Duration = Duration::from_secs(5 * 60); @@ -27,48 +25,6 @@ const PROBE_DEADLINE: Duration = Duration::from_secs(5 * 60); /// Bytes of OpenSSH's standard error kept as diagnostics. const DIAGNOSTICS_LIMIT: usize = 4 * 1024; -/// 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)] -#[serde(rename_all = "camelCase")] -pub enum Authentication { - /// OpenSSH's own order: keys and agent first, then interactive methods. - #[default] - Auto, - /// Keys offered by the running SSH agent or the SSH configuration. - Agent, - /// Only the private key named by `identityFile`. - PrivateKey, - /// Password or keyboard-interactive prompts, without trying keys. - Password, -} - -/// One saved SSH connection. Only facts that change the target or the -/// authentication are sent; names and colors stay in the host. -#[derive(Clone, Debug, Deserialize)] -#[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, - /// `None` keeps the port from the SSH configuration (22 by default). - #[serde(default)] - port: Option, - /// `None` keeps the user from the SSH configuration. - #[serde(default)] - user: Option, - #[serde(default)] - authentication: Authentication, - /// Private key path; required for [`Authentication::PrivateKey`]. OpenSSH - /// expands a leading `~` itself. - #[serde(default)] - identity_file: Option, - #[serde(default)] - connect_timeout_seconds: Option, - /// `None` keeps the transport's keep-alive default. - #[serde(default)] - keep_alive_seconds: Option, -} - /// `remote.probe`: the saved connection to check. #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -226,83 +182,14 @@ pub fn respond(request_id: &str, answer: Option) -> bool { lithe_git_host::authentication::respond(request_id, answer) } +/// 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 { - let invalid = |reason: &str| CoreError::new(ErrorCode::InvalidRequest, reason.to_string()); - let host = connection.host.trim(); - if host.is_empty() || host.contains('@') { - return Err(invalid("Enter a host name or address without a user")); - } - let destination = match connection.user.as_deref().map(str::trim) { - Some(user) if !user.is_empty() => { - if user.starts_with('-') - || user - .chars() - .any(|character| matches!(character, '@' | ':') || character.is_whitespace()) - { - return Err(invalid("The user name contains characters SSH cannot use")); - } - format!("{user}@{host}") - } - _ => host.to_string(), - }; - let mut hop = SshHop::new(destination); - hop.port = connection.port.filter(|port| *port != 0); - let mut option = |key: &str, value: String| hop.options.push((key.into(), value)); - option( - "ConnectTimeout", - connection - .connect_timeout_seconds - .filter(|seconds| *seconds > 0) - .unwrap_or(DEFAULT_CONNECT_TIMEOUT_SECONDS) - .to_string(), - ); - if let Some(seconds) = connection.keep_alive_seconds { - option("ServerAliveInterval", seconds.to_string()); - } - // Prompts must reach AskPass even when the user's configuration sets - // BatchMode for scripts. - option("BatchMode", "no".into()); - match connection.authentication { - Authentication::Auto => {} - Authentication::Agent => option("PreferredAuthentications", "publickey".into()), - Authentication::PrivateKey => { - let identity = connection - .identity_file - .as_deref() - .map(str::trim) - .filter(|path| !path.is_empty()) - .ok_or_else(|| invalid("Choose a private key file"))?; - if identity.chars().any(char::is_control) { - return Err(invalid("The private key path is invalid")); - } - // ssh splits an option value on whitespace, so a path such as - // "~/My Keys/id_rsa" must be quoted (ssh_config quoting rules). - let identity = if identity - .chars() - .any(|c| c.is_whitespace() || c == '"' || c == '\\') - { - format!( - "\"{}\"", - identity.replace('\\', "\\\\").replace('"', "\\\"") - ) - } else { - identity.to_string() - }; - option("IdentityFile", identity); - // Without this, keys from the agent are tried first and can use - // up the server's attempt limit before the chosen key is offered. - option("IdentitiesOnly", "yes".into()); - option("PreferredAuthentications", "publickey".into()); - } - Authentication::Password => { - option( - "PreferredAuthentications", - "keyboard-interactive,password".into(), - ); - option("PubkeyAuthentication", "no".into()); - } - } - Ok(hop) + connection + .clone() + .normalized() + .hop() + .map_err(crate::connections::invalid_request) } /// Interprets the finished probe. OpenSSH reports connection failures only diff --git a/rust/crates/workspace/src/probe/tests.rs b/rust/crates/workspace/src/probe/tests.rs index 1e2b920e..1402284c 100644 --- a/rust/crates/workspace/src/probe/tests.rs +++ b/rust/crates/workspace/src/probe/tests.rs @@ -9,118 +9,17 @@ use std::sync::atomic::{AtomicU64, Ordering}; #[cfg(unix)] use std::sync::OnceLock; -fn connection(value: serde_json::Value) -> SshConnection { - serde_json::from_value(value).expect("valid connection") -} - -/// The local command line the connection produces for the probe. -fn command_line(value: serde_json::Value) -> Vec { - let hop = ssh_hop(&connection(value)).expect("valid hop"); - TransportChain::new(vec![Hop::Ssh(hop)]) - .command(&probe_command()) - .unwrap() -} - -fn option_value(command: &[String], key: &str) -> Option { - command - .windows(2) - .filter(|pair| pair[0] == "-o") - .find_map(|pair| pair[1].strip_prefix(&format!("{key}=")).map(str::to_owned)) -} - +// The connection rules live in `lithe_remote::client::connections`; the +// probe only reports a refusal as a bad request that names the field. #[test] -fn private_key_connections_offer_only_the_chosen_key() { - let command = command_line(json!({ - "host": "devbox.example", - "port": 2222, - "user": "dev", - "authentication": "privateKey", - "identityFile": "~/.ssh/id_ed25519", - "connectTimeoutSeconds": 20, - "keepAliveSeconds": 30, - })); - assert!(command.windows(2).any(|pair| pair == ["-p", "2222"])); - assert_eq!(&command[command.len() - 2], "dev@devbox.example"); - assert_eq!( - option_value(&command, "IdentityFile").as_deref(), - Some("~/.ssh/id_ed25519") - ); - assert_eq!( - option_value(&command, "IdentitiesOnly").as_deref(), - Some("yes") - ); - assert_eq!( - option_value(&command, "PreferredAuthentications").as_deref(), - Some("publickey") - ); - assert_eq!( - option_value(&command, "ConnectTimeout").as_deref(), - Some("20") - ); - // OpenSSH keeps the first value, so the profile's interval must come - // before the transport's default. - assert_eq!( - option_value(&command, "ServerAliveInterval").as_deref(), - Some("30") - ); - assert_eq!(option_value(&command, "BatchMode").as_deref(), Some("no")); -} - -#[test] -fn other_authentication_methods_select_matching_ssh_options() { - let password = command_line(json!({ "host": "h", "authentication": "password" })); - assert_eq!( - option_value(&password, "PreferredAuthentications").as_deref(), - Some("keyboard-interactive,password") - ); - assert_eq!( - option_value(&password, "PubkeyAuthentication").as_deref(), - Some("no") - ); - - let agent = command_line(json!({ "host": "h", "authentication": "agent" })); - assert_eq!( - option_value(&agent, "PreferredAuthentications").as_deref(), - Some("publickey") - ); - assert_eq!(option_value(&agent, "IdentityFile"), None); - - // Automatic leaves the order to OpenSSH and the user's configuration, - // and an alias without a user or port stays untouched. - let automatic = command_line(json!({ "host": "devbox" })); - assert_eq!(option_value(&automatic, "PreferredAuthentications"), None); - assert_eq!(&automatic[automatic.len() - 2], "devbox"); - assert!(!automatic.iter().any(|argument| argument == "-p")); - assert_eq!( - option_value(&automatic, "ConnectTimeout").as_deref(), - Some(DEFAULT_CONNECT_TIMEOUT_SECONDS.to_string().as_str()) - ); -} - -#[test] -fn malformed_connections_are_rejected_before_ssh_starts() { - for value in [ - json!({ "host": "" }), - json!({ "host": "dev@box" }), - json!({ "host": "-oProxyCommand=touch x" }), - json!({ "host": "box", "user": "-oProxyCommand=x" }), - json!({ "host": "box", "user": "a b" }), - json!({ "host": "box", "authentication": "privateKey" }), - ] { - let hop = ssh_hop(&connection(value.clone())); - let command = hop.and_then(|hop| { - TransportChain::new(vec![Hop::Ssh(hop)]) - .command(&probe_command()) - .map_err(|error| CoreError::new(ErrorCode::InvalidRequest, error.to_string())) - }); - assert!( - matches!(command, Err(ref error) if matches!(error.code, ErrorCode::InvalidRequest)), - "{value} was accepted" - ); - } - assert!( - serde_json::from_value::(json!({ "host": "h", "password": "x" })).is_err() - ); +fn malformed_connections_name_the_field_in_the_error() { + let connection: SshConnection = + serde_json::from_value(json!({ "host": "dev@box" })).expect("decodes"); + let error = ssh_hop(&connection).expect_err("host with a user is refused"); + assert!(matches!(error.code, ErrorCode::InvalidRequest)); + let details: serde_json::Value = + serde_json::from_str(error.details.as_deref().expect("details")).unwrap(); + assert_eq!(details, json!({ "field": "host", "reason": "invalid" })); } #[test] @@ -403,22 +302,6 @@ fn closing_all_connections_with_none_open_succeeds() { assert_eq!(sessions::close_registry(&connections), 0); } -// ssh splits an option value on whitespace, so a key path with spaces must -// reach it quoted. -#[cfg(unix)] -#[test] -fn private_key_paths_with_spaces_are_quoted() { - let command = command_line(json!({ - "host": "devbox.example", - "authentication": "privateKey", - "identityFile": "/Users/me/My Keys/id_rsa", - })); - assert_eq!( - option_value(&command, "IdentityFile").as_deref(), - Some("\"/Users/me/My Keys/id_rsa\"") - ); -} - /// A scratch directory no other fixture shares, even across processes. #[cfg(unix)] fn temporary_root(label: &str) -> PathBuf { diff --git a/rust/crates/workspace/src/sessions.rs b/rust/crates/workspace/src/sessions.rs index 20338cf1..6f3e4514 100644 --- a/rust/crates/workspace/src/sessions.rs +++ b/rust/crates/workspace/src/sessions.rs @@ -7,9 +7,10 @@ //! it by id. OpenSSH runs in its own process tree, which closing a connection //! ends. -use crate::probe::{classify, diagnostics, ssh_hop, ProbeStatus, ProbedHost, SshConnection}; +use crate::probe::{classify, diagnostics, 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::session::{ClientError, ConnectOptions}; use lithe_remote::client::trust::Target;