diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index ec26804b..94064712 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -828,6 +828,8 @@ or removing a command fails until the table changes in the same commit. | `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 | | `remote.listWslDistributions` | List the WSL distributions installed on this Windows machine | +| `remote.preferences` | Read the remote workspace settings and what each automatic value resolves to | +| `remote.editPreferences` | Set the SSH program or the reconnect limit, or make one automatic again | | `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 | @@ -5698,6 +5700,12 @@ 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. +`remote.probe`, `remote.connect`, `remote.effectiveSettings` and +`remote.sshConfigHosts` also take an optional `preferences`: the text of the +remote preferences document (see "Remote workspace preferences"), `null` or +absent when it does not exist. Its SSH program is the OpenSSH client they +start; a damaged document is `parse_failed` before anything starts. + Core runs the system `ssh` with the probe of [`remote-workspace-protocol-v1`](remote-workspace-protocol-v1.md)'s bootstrap and relays every OpenSSH question through the same AskPass transport as Git. @@ -5917,6 +5925,62 @@ its redacted message for display; it is never logged. Cancellation and the bound are `cancelled` and `timed_out`. Nothing is saved: the window lists the distributions each time it opens. +#### Remote workspace preferences + +The settings page "Tools › Remote Workspace" edits two values that apply to +every connection. Native clients keep them in one machine-local document, +read it, and publish the `document` an edit returns atomically, as for the +saved connections; Core validates the document, applies every edit and +tells what each automatic value resolves to. + +`remote.preferences` accepts `{ document: string|null, homeDirectory? }` +and returns `{ preferences, ssh, reconnect, storage, sshConfig? }`: + +- `preferences` is `{ sshProgram, reconnectLimitSeconds }`, the stored + values; `null` is automatic. +- `ssh` is `{ source, path, status }`, the OpenSSH client every connection + starts. `source` is `setting` for a stored program and `automatic` + otherwise, which is the first executable `ssh` (`ssh.exe` on Windows) in an + absolute directory of Core's `PATH`. `path` is that program, or `null` when + automatic finds none; then the system looks `ssh` up when it starts. + `status` is `found`, `missing` or `notExecutable`; a stored program that + disappeared is reported, not refused, so the page can show it. +- `reconnect` is `{ source, limitSeconds, delaysMilliseconds }`: how long a + workspace whose connection dropped keeps reconnecting (automatic: 60 + seconds) and the pauses before each attempt. Pauses start at one second, + double up to 30 seconds and add up to the limit; the last one is shortened + to fit. A limit of 0 never reconnects, so the list is empty. Clients wait + these pauses and decide nothing else about the schedule. +- `storage` is `{ relativePath: "remote/preferences.json", maximumBytes: + 16384 }`. +- `sshConfig` is `{ path, exists }` for `.ssh/config` below `homeDirectory`, + returned only with one, for the page to show and open. A relative home is + `invalid_request` with `{ field: "homeDirectory", reason: "relative" }`. + +`remote.editPreferences` accepts `{ document }` with exactly one of: + +- `sshProgram: { path: string|null }` stores the trimmed absolute path of an + existing executable file, or makes the program automatic with `null`. +- `reconnectLimit: { seconds: number|null }` stores 0 to 3600 seconds, or + makes the limit automatic with `null`. + +The result is `{ changed, document: string|null }`; an unchanged edit +returns a `null` document and must not create a source. Neither or both +fields is `invalid_request` with `{ field: "operation", reason: "invalid" +}`; a refused value is `invalid_request` with `{ field, reason }`, where +`field` is `sshProgram` or `reconnectLimitSeconds` and `reason` is +`invalid` (empty, surrounding spaces or control characters), `tooLong` +(over 4096 bytes), `relative`, `missing`, `notExecutable` or `outOfRange`. + +A document of more than 16 KiB, that cannot be decoded, has unknown fields +or another version than 1, or holds a value an edit would refuse other than +a missing or not executable program is `parse_failed` with the same +`details`. The document omits automatic values. + +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, sha256 }], diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index a2a2142c..0efcefa5 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -1040,6 +1040,11 @@ pub enum RemoteCommand { /// Lists the WSL distributions installed on this Windows machine /// (`remote.listWslDistributions`). ListWslDistributions, + /// Reads the remote workspace preferences and what each automatic value + /// resolves to (`remote.preferences`). + Preferences, + /// Changes one remote workspace preference (`remote.editPreferences`). + EditPreferences, } #[derive(Debug, Clone)] @@ -1620,6 +1625,8 @@ impl CoreCommand { "remote.listWslDistributions" => { Some(Self::Remote(RemoteCommand::ListWslDistributions)) } + "remote.preferences" => Some(Self::Remote(RemoteCommand::Preferences)), + "remote.editPreferences" => Some(Self::Remote(RemoteCommand::EditPreferences)), "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 e333cc21..1cc905f9 100644 --- a/rust/crates/core/src/runtime/dispatcher/remote.rs +++ b/rust/crates/core/src/runtime/dispatcher/remote.rs @@ -269,6 +269,18 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option, payload: Valu "Invalid Motty hosts request", lithe_workspace::motty::hosts, ), + RemoteCommand::Preferences => answer( + id, + payload, + "Invalid remote preferences request", + lithe_workspace::preferences::read, + ), + RemoteCommand::EditPreferences => answer( + id, + payload, + "Invalid remote preferences request", + lithe_workspace::preferences::edit, + ), RemoteCommand::Disconnect => { match serde_json::from_value::(payload) { Ok(request) => CoreResponse::success( diff --git a/rust/crates/core/src/tests/remote_sessions.rs b/rust/crates/core/src/tests/remote_sessions.rs index 89fa9313..c79efe69 100644 --- a/rust/crates/core/src/tests/remote_sessions.rs +++ b/rust/crates/core/src/tests/remote_sessions.rs @@ -1325,7 +1325,36 @@ fn connection_window_helpers_answer_through_the_dispatcher() { let details: Value = serde_json::from_str(both["error"]["details"].as_str().unwrap()).unwrap(); assert_eq!(details, json!({"field": "wsl", "reason": "invalid"})); + // The settings page reads automatic values and stores an edit; a damaged + // document stops the SSH commands before OpenSSH starts. + let preferences = call("remote.preferences", json!({"document": null})); + assert_eq!( + preferences["data"]["reconnect"]["delaysMilliseconds"], + json!([1000, 2000, 4000, 8000, 16000, 29000]), + "{preferences}" + ); + let edited = call( + "remote.editPreferences", + json!({"document": null, "reconnectLimit": {"seconds": 3}}), + ); + assert_eq!(edited["data"]["changed"], true, "{edited}"); + let stored = call( + "remote.preferences", + json!({"document": edited["data"]["document"]}), + ); + assert_eq!( + stored["data"]["reconnect"], + json!({"source": "setting", "limitSeconds": 3, "delaysMilliseconds": [1000, 2000]}), + "{stored}" + ); + let damaged = call( + "remote.effectiveSettings", + json!({"connection": {"host": "devbox"}, "preferences": "{\"version\":9}"}), + ); + assert_eq!(damaged["error"]["code"], "parse_failed", "{damaged}"); + for (command, payload) in [ + ("remote.editPreferences", json!({"document": null})), ( "remote.connect", json!({"wsl": {"distribution": "Ubuntu", "program": "C:\\x.exe"}, diff --git a/rust/crates/remote/src/client/mod.rs b/rust/crates/remote/src/client/mod.rs index 5358afbb..e2a5157a 100644 --- a/rust/crates/remote/src/client/mod.rs +++ b/rust/crates/remote/src/client/mod.rs @@ -29,6 +29,8 @@ //! 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. +//! - [`preferences`] keeps the settings page's machine-local values: the +//! OpenSSH client to start and how long a lost session is reconnected. //! //! The transport layer deliberately knows nothing about files or processes. //! Supporting a new kind of remote means adding a hop, not new capabilities. @@ -47,6 +49,7 @@ pub mod forward_set; pub mod launch; #[cfg(feature = "motty")] pub mod motty; +pub mod preferences; pub mod prompt; pub mod session; pub mod ssh_config; diff --git a/rust/crates/remote/src/client/preferences.rs b/rust/crates/remote/src/client/preferences.rs new file mode 100644 index 00000000..e8540268 --- /dev/null +++ b/rust/crates/remote/src/client/preferences.rs @@ -0,0 +1,371 @@ +//! Remote workspace preferences: the page "Tools › Remote Workspace" of the +//! settings window (design §10, D6). +//! +//! The document holds only the values the user changed; every missing value +//! is automatic, and [`Preferences::ssh`] and [`Preferences::reconnect`] say +//! what automatic resolves to, so the page shows the value that takes effect. +//! +//! - `sshProgram` replaces the `ssh` found on `PATH` for every OpenSSH +//! process Core starts: probes, connections and `ssh -G`. It must be an +//! absolute path; an edit also requires an executable file there. Core +//! never stores a value that starts something other than an executable the +//! user chose. +//! - `reconnectLimitSeconds` bounds how long a client keeps reconnecting a +//! lost session automatically. [`reconnect_delays`] turns it into the +//! pauses between attempts, so every client waits the same way. +//! - The document lives at [`STORAGE_PATH`] below the platform's +//! user-preference directory, never on a host or in a workspace. It holds +//! no secret. 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 it +//! in the user's language next to the row it concerns. + +use serde::{Deserialize, Serialize}; +use std::ffi::OsStr; +use std::fmt; +use std::path::{Path, PathBuf}; + +/// Document location below the platform's user-preference directory. +pub const STORAGE_PATH: &str = "remote/preferences.json"; + +/// Largest accepted document, in bytes. +pub const MAX_BYTES: usize = 16 * 1024; + +/// Longest accepted SSH program path, in bytes. +pub const MAX_PROGRAM_BYTES: usize = 4096; + +/// Reconnect limit when the document sets none. +pub const DEFAULT_RECONNECT_LIMIT_SECONDS: u32 = 60; + +/// Largest reconnect limit; 0 turns automatic reconnection off. +pub const MAX_RECONNECT_LIMIT_SECONDS: u32 = 60 * 60; + +/// Pause after the first failed attempt; each later pause doubles. +const FIRST_PAUSE_MILLISECONDS: u64 = 1_000; + +/// Longest pause between two attempts. +const MAX_PAUSE_MILLISECONDS: u64 = 30_000; + +/// Program name OpenSSH installs on `PATH`. +const SSH_NAME: &str = "ssh"; + +/// Why a document or an edit was refused. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PreferenceError { + /// `document`, `version`, `sshProgram` or `reconnectLimitSeconds`. + pub field: &'static str, + /// Why the field was refused. + pub reason: PreferenceReason, +} + +/// The kind of refusal, stable for clients to translate. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum PreferenceReason { + /// The value has characters or a form the field does not accept. + Invalid, + /// The value is longer than the field allows. + TooLong, + /// The path is not absolute. + Relative, + /// Nothing exists at the path. + Missing, + /// The path names a directory or a file that cannot be run. + NotExecutable, + /// The number is outside the field's range. + OutOfRange, +} + +impl PreferenceError { + fn at(field: &'static str, reason: PreferenceReason) -> Self { + Self { field, reason } + } +} + +impl fmt::Display for PreferenceError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + formatter, + "invalid remote preference at {} ({:?})", + self.field, self.reason + ) + } +} + +impl std::error::Error for PreferenceError {} + +/// The validated document. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Preferences { + version: u32, + /// Absolute path of the OpenSSH client; `None` uses `ssh` on `PATH`. + #[serde(default, skip_serializing_if = "Option::is_none")] + ssh_program: Option, + /// `None` uses [`DEFAULT_RECONNECT_LIMIT_SECONDS`]. + #[serde(default, skip_serializing_if = "Option::is_none")] + reconnect_limit_seconds: Option, +} + +impl Default for Preferences { + fn default() -> Self { + Self { + version: 1, + ssh_program: None, + reconnect_limit_seconds: None, + } + } +} + +/// Whether a value is the user's or the automatic one. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum Source { + /// Nothing is set; Lithe picks the value. + Automatic, + /// The document sets the value. + Setting, +} + +/// What is at the SSH program path when the page reads it. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum ProgramStatus { + /// An executable file. + Found, + /// Nothing; for the automatic value, no `ssh` on `PATH`. + Missing, + /// A directory or a file that cannot be run. + NotExecutable, +} + +/// The OpenSSH client Core starts. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SshProgram { + pub source: Source, + /// The setting, or the first `ssh` on `PATH`; `None` when automatic + /// finds none. + pub path: Option, + pub status: ProgramStatus, +} + +impl SshProgram { + /// The program to start: the path, or `ssh` for the system to look up + /// when automatic finds none, so the start fails as it always did. + pub fn command(&self) -> &str { + self.path.as_deref().unwrap_or(SSH_NAME) + } +} + +/// How long a lost session is reconnected automatically. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Reconnect { + pub source: Source, + /// The limit that takes effect; 0 turns automatic reconnection off. + pub limit_seconds: u32, + /// The pause before each attempt, in order; empty when the limit is 0. + pub delays_milliseconds: Vec, +} + +impl Preferences { + /// Reads `document`, or the empty document when there is none yet. + /// + /// Refuses documents over [`MAX_BYTES`], malformed JSON, unknown fields, + /// other versions, relative or overlong SSH program paths and reconnect + /// limits over [`MAX_RECONNECT_LIMIT_SECONDS`]. Whether the program + /// still exists is reported by [`Self::ssh`], not refused, so a removed + /// client does not hide the page that changes it. + pub fn parse(document: Option<&str>) -> Result { + let Some(text) = document else { + return Ok(Self::default()); + }; + if text.len() > MAX_BYTES { + return Err(PreferenceError::at("document", PreferenceReason::TooLong)); + } + let preferences: Self = serde_json::from_str(text) + .map_err(|_| PreferenceError::at("document", PreferenceReason::Invalid))?; + if preferences.version != 1 { + return Err(PreferenceError::at("version", PreferenceReason::Invalid)); + } + if let Some(program) = &preferences.ssh_program { + check_program_form(program)?; + } + if let Some(limit) = preferences.reconnect_limit_seconds { + check_limit(limit)?; + } + Ok(preferences) + } + + /// The document text to publish. + pub fn text(&self) -> Result { + let mut text = serde_json::to_string_pretty(self) + .map_err(|_| PreferenceError::at("document", PreferenceReason::Invalid))?; + text.push('\n'); + if text.len() > MAX_BYTES { + return Err(PreferenceError::at("document", PreferenceReason::TooLong)); + } + Ok(text) + } + + /// The stored SSH program, `None` when automatic. + pub fn ssh_program(&self) -> Option<&str> { + self.ssh_program.as_deref() + } + + /// The stored reconnect limit, `None` when automatic. + pub fn reconnect_limit_seconds(&self) -> Option { + self.reconnect_limit_seconds + } + + /// Sets the SSH program, or makes it automatic with `None`. The path is + /// trimmed and must name an executable file now. + pub fn set_ssh_program(&mut self, path: Option<&str>) -> Result<(), PreferenceError> { + let Some(path) = path.map(str::trim) else { + self.ssh_program = None; + return Ok(()); + }; + check_program_form(path)?; + match program_status(Path::new(path)) { + ProgramStatus::Found => {} + ProgramStatus::Missing => { + return Err(PreferenceError::at("sshProgram", PreferenceReason::Missing)) + } + ProgramStatus::NotExecutable => { + return Err(PreferenceError::at( + "sshProgram", + PreferenceReason::NotExecutable, + )) + } + } + self.ssh_program = Some(path.to_owned()); + Ok(()) + } + + /// Sets the reconnect limit, or makes it automatic with `None`. + pub fn set_reconnect_limit(&mut self, seconds: Option) -> Result<(), PreferenceError> { + if let Some(seconds) = seconds { + check_limit(seconds)?; + } + self.reconnect_limit_seconds = seconds; + Ok(()) + } + + /// The OpenSSH client that takes effect, looking `ssh` up in `path` + /// (the value of `PATH`) when automatic. + pub fn ssh(&self, path: Option<&OsStr>) -> SshProgram { + match &self.ssh_program { + Some(program) => SshProgram { + source: Source::Setting, + path: Some(program.clone()), + status: program_status(Path::new(program)), + }, + None => { + let found = path.and_then(|path| find_on_path(SSH_NAME, path)); + SshProgram { + source: Source::Automatic, + status: if found.is_some() { + ProgramStatus::Found + } else { + ProgramStatus::Missing + }, + path: found.map(|found| found.to_string_lossy().into_owned()), + } + } + } + } + + /// The reconnect limit that takes effect and its pauses. + pub fn reconnect(&self) -> Reconnect { + let limit_seconds = self + .reconnect_limit_seconds + .unwrap_or(DEFAULT_RECONNECT_LIMIT_SECONDS); + Reconnect { + source: match self.reconnect_limit_seconds { + Some(_) => Source::Setting, + None => Source::Automatic, + }, + limit_seconds, + delays_milliseconds: reconnect_delays(limit_seconds), + } + } +} + +/// The pauses before each reconnect attempt within `limit_seconds`: 1 s, +/// doubling up to 30 s, the last one shortened so they add up to the limit. +/// The default limit gives 1, 2, 4, 8, 16 and 29 seconds. +pub fn reconnect_delays(limit_seconds: u32) -> Vec { + let mut remaining = u64::from(limit_seconds) * 1_000; + let mut pause = FIRST_PAUSE_MILLISECONDS; + let mut delays = Vec::new(); + while remaining > 0 { + let next = pause.min(remaining); + delays.push(next); + remaining -= next; + pause = (pause * 2).min(MAX_PAUSE_MILLISECONDS); + } + delays +} + +fn check_program_form(path: &str) -> Result<(), PreferenceError> { + let refused = |reason| Err(PreferenceError::at("sshProgram", reason)); + if path.len() > MAX_PROGRAM_BYTES { + return refused(PreferenceReason::TooLong); + } + if path.is_empty() || path.trim() != path || path.chars().any(char::is_control) { + return refused(PreferenceReason::Invalid); + } + if !Path::new(path).is_absolute() { + return refused(PreferenceReason::Relative); + } + Ok(()) +} + +fn check_limit(seconds: u32) -> Result<(), PreferenceError> { + if seconds > MAX_RECONNECT_LIMIT_SECONDS { + return Err(PreferenceError::at( + "reconnectLimitSeconds", + PreferenceReason::OutOfRange, + )); + } + Ok(()) +} + +fn program_status(path: &Path) -> ProgramStatus { + match path.metadata() { + Err(_) => ProgramStatus::Missing, + Ok(metadata) if is_executable(&metadata) => ProgramStatus::Found, + Ok(_) => ProgramStatus::NotExecutable, + } +} + +/// The first executable `name` in the directories of `path`, as the system +/// would start it. +fn find_on_path(name: &str, path: &OsStr) -> Option { + let file = format!("{name}{}", std::env::consts::EXE_SUFFIX); + std::env::split_paths(path) + .filter(|directory| directory.is_absolute()) + .map(|directory| directory.join(&file)) + .find(|candidate| { + candidate + .metadata() + .is_ok_and(|metadata| is_executable(&metadata)) + }) +} + +#[cfg(unix)] +fn is_executable(metadata: &std::fs::Metadata) -> bool { + use std::os::unix::fs::PermissionsExt; + metadata.is_file() && metadata.permissions().mode() & 0o111 != 0 +} + +#[cfg(not(unix))] +fn is_executable(metadata: &std::fs::Metadata) -> bool { + metadata.is_file() +} + +#[cfg(test)] +mod tests; diff --git a/rust/crates/remote/src/client/preferences/tests.rs b/rust/crates/remote/src/client/preferences/tests.rs new file mode 100644 index 00000000..6b0eec40 --- /dev/null +++ b/rust/crates/remote/src/client/preferences/tests.rs @@ -0,0 +1,194 @@ +use super::*; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// A scratch directory, removed when dropped. +struct Scratch(PathBuf); + +impl Scratch { + fn new(label: &str) -> Self { + static SEQUENCE: AtomicU64 = AtomicU64::new(0); + let path = std::env::temp_dir().join(format!( + "lithe-remote-preferences-{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) + } + + /// Creates `name` in the directory, executable when `executable`. + fn file(&self, name: &str, executable: bool) -> PathBuf { + let path = self.0.join(name); + std::fs::write(&path, b"#!/bin/sh\n").unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = if executable { 0o755 } else { 0o644 }; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap(); + } + #[cfg(not(unix))] + let _ = executable; + path + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn ssh_file_name() -> String { + format!("ssh{}", std::env::consts::EXE_SUFFIX) +} + +fn refusal(document: &str) -> PreferenceError { + Preferences::parse(Some(document)).expect_err("the document was accepted") +} + +#[test] +fn a_missing_document_is_every_value_automatic() { + let preferences = Preferences::parse(None).unwrap(); + assert_eq!(preferences, Preferences::default()); + assert_eq!(preferences.ssh_program(), None); + let reconnect = preferences.reconnect(); + assert_eq!(reconnect.source, Source::Automatic); + assert_eq!(reconnect.limit_seconds, DEFAULT_RECONNECT_LIMIT_SECONDS); + assert_eq!( + reconnect.delays_milliseconds, + vec![1_000, 2_000, 4_000, 8_000, 16_000, 29_000] + ); + assert_eq!(preferences.text().unwrap(), "{\n \"version\": 1\n}\n"); +} + +#[test] +fn the_document_refuses_other_versions_unknown_fields_and_bad_values() { + let at = |field, reason| PreferenceError { field, reason }; + assert_eq!( + refusal("{\"version\":2}"), + at("version", PreferenceReason::Invalid) + ); + assert_eq!( + refusal("{\"version\":1,\"sshPath\":\"/usr/bin/ssh\"}"), + at("document", PreferenceReason::Invalid) + ); + assert_eq!( + refusal("{\"version\":1,\"sshProgram\":\"bin/ssh\"}"), + at("sshProgram", PreferenceReason::Relative) + ); + assert_eq!( + refusal("{\"version\":1,\"sshProgram\":\"\"}"), + at("sshProgram", PreferenceReason::Invalid) + ); + assert_eq!( + refusal("{\"version\":1,\"reconnectLimitSeconds\":3601}"), + at("reconnectLimitSeconds", PreferenceReason::OutOfRange) + ); + let long = format!("{{\"version\":1,\"sshProgram\":\"/{}\"}}", "a".repeat(5000)); + assert_eq!(refusal(&long), at("sshProgram", PreferenceReason::TooLong)); + let huge = format!("{{\"version\":1,\"x\":\"{}\"}}", "a".repeat(MAX_BYTES)); + assert_eq!(refusal(&huge), at("document", PreferenceReason::TooLong)); +} + +#[test] +fn a_stored_program_that_disappeared_is_reported_not_refused() { + let scratch = Scratch::new("gone"); + let path = scratch.0.join(ssh_file_name()); + let document = serde_json::json!({ "version": 1, "sshProgram": path }).to_string(); + let preferences = Preferences::parse(Some(&document)).unwrap(); + let ssh = preferences.ssh(None); + assert_eq!(ssh.source, Source::Setting); + assert_eq!(ssh.status, ProgramStatus::Missing); + assert_eq!(ssh.command(), path.to_string_lossy()); +} + +#[test] +fn automatic_finds_the_first_executable_ssh_on_path() { + let first = Scratch::new("first"); + let second = Scratch::new("second"); + let found = second.file(&ssh_file_name(), true); + #[cfg(unix)] + first.file(&ssh_file_name(), false); + let path = std::env::join_paths([PathBuf::from("relative"), first.0.clone(), second.0.clone()]) + .unwrap(); + let ssh = Preferences::default().ssh(Some(&path)); + assert_eq!(ssh.source, Source::Automatic); + assert_eq!(ssh.status, ProgramStatus::Found); + assert_eq!(ssh.path.as_deref(), Some(found.to_string_lossy().as_ref())); + + let empty = Scratch::new("empty"); + let none = Preferences::default().ssh(Some(empty.0.as_os_str())); + assert_eq!(none.status, ProgramStatus::Missing); + assert_eq!(none.path, None); + assert_eq!(none.command(), "ssh"); +} + +#[test] +fn an_edit_requires_an_executable_file_and_round_trips() { + let scratch = Scratch::new("edit"); + let program = scratch.file(&ssh_file_name(), true); + let mut preferences = Preferences::default(); + let refused = |result: Result<(), PreferenceError>| result.unwrap_err().reason; + + assert_eq!( + refused(preferences.set_ssh_program(Some("ssh"))), + PreferenceReason::Relative + ); + let missing = scratch.0.join("nothing"); + assert_eq!( + refused(preferences.set_ssh_program(Some(&missing.to_string_lossy()))), + PreferenceReason::Missing + ); + assert_eq!( + refused(preferences.set_ssh_program(Some(&scratch.0.to_string_lossy()))), + PreferenceReason::NotExecutable + ); + #[cfg(unix)] + { + let plain = scratch.file("plain", false); + assert_eq!( + refused(preferences.set_ssh_program(Some(&plain.to_string_lossy()))), + PreferenceReason::NotExecutable + ); + } + assert_eq!(preferences, Preferences::default()); + + let padded = format!(" {} ", program.to_string_lossy()); + preferences.set_ssh_program(Some(&padded)).unwrap(); + preferences.set_reconnect_limit(Some(0)).unwrap(); + assert_eq!( + refused(preferences.set_reconnect_limit(Some(MAX_RECONNECT_LIMIT_SECONDS + 1))), + PreferenceReason::OutOfRange + ); + let text = preferences.text().unwrap(); + let read = Preferences::parse(Some(&text)).unwrap(); + assert_eq!(read, preferences); + assert_eq!(read.ssh_program(), Some(program.to_string_lossy().as_ref())); + let ssh = read.ssh(None); + assert_eq!( + (ssh.source, ssh.status), + (Source::Setting, ProgramStatus::Found) + ); + let reconnect = read.reconnect(); + assert_eq!( + (reconnect.source, reconnect.limit_seconds), + (Source::Setting, 0) + ); + assert!(reconnect.delays_milliseconds.is_empty()); + + preferences.set_ssh_program(None).unwrap(); + preferences.set_reconnect_limit(None).unwrap(); + assert_eq!(preferences, Preferences::default()); +} + +#[test] +fn reconnect_pauses_double_up_to_thirty_seconds_and_add_up_to_the_limit() { + assert_eq!(reconnect_delays(1), vec![1_000]); + assert_eq!(reconnect_delays(2), vec![1_000, 1_000]); + let hour = reconnect_delays(MAX_RECONNECT_LIMIT_SECONDS); + assert_eq!(hour.iter().sum::(), 3_600_000); + assert_eq!(&hour[..6], &[1_000, 2_000, 4_000, 8_000, 16_000, 30_000]); + assert!(hour.iter().all(|pause| *pause <= 30_000)); + assert_eq!(hour.len(), 124); +} diff --git a/rust/crates/workspace/src/lib.rs b/rust/crates/workspace/src/lib.rs index 77d36b48..30ad89c9 100644 --- a/rust/crates/workspace/src/lib.rs +++ b/rust/crates/workspace/src/lib.rs @@ -16,8 +16,9 @@ //! connections (over OpenSSH or `wsl.exe`), [`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. +//! a verified file to the host, [`trust`] keys remote workspace trust by +//! what the connection resolves, and [`preferences`] keeps the settings +//! page's values, including the SSH program every OpenSSH start uses. //! Domain semantics stay in their engines (Git, build, language servers); //! this crate only supplies the IO boundary. @@ -26,6 +27,7 @@ pub mod forwards; pub mod fs; pub mod host; pub mod motty; +pub mod preferences; pub mod probe; mod scope; pub mod sessions; diff --git a/rust/crates/workspace/src/preferences.rs b/rust/crates/workspace/src/preferences.rs new file mode 100644 index 00000000..601483f3 --- /dev/null +++ b/rust/crates/workspace/src/preferences.rs @@ -0,0 +1,163 @@ +//! `remote.preferences` and `remote.editPreferences`: the values of the +//! settings page "Tools › Remote Workspace" (design §10, D6), and the SSH +//! program every OpenSSH process Core starts uses. +//! +//! The document is machine-local and read and published by the native client +//! like the saved connections; Core validates it, applies one edit at a time +//! and tells what every automatic value resolves to. The rules are in +//! `lithe_remote::client::preferences`. + +use lithe_protocol::{CoreError, ErrorCode}; +use lithe_remote::client::preferences::{self, PreferenceError, Preferences}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::path::PathBuf; + +/// `remote.preferences`: the current document and, for the SSH +/// configuration row, the user's home directory. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ReadRequest { + /// Current document text; `null` when the source does not exist. + document: Option, + /// Absolute home directory; `sshConfig` is returned only with it. + #[serde(default)] + home_directory: Option, +} + +/// `remote.editPreferences`: exactly one of `sshProgram` and +/// `reconnectLimit`. +#[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)] + ssh_program: Option, + #[serde(default)] + reconnect_limit: Option, +} + +/// The SSH program to use; `path: null` makes it automatic. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ProgramEdit { + path: Option, +} + +/// The reconnect limit; `seconds: null` makes it automatic. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct LimitEdit { + seconds: Option, +} + +/// 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: preferences::STORAGE_PATH, + maximum_bytes: preferences::MAX_BYTES, +}; + +/// The stored values, what each one resolves to, and where the document +/// and the user's SSH configuration are. +pub fn read(request: ReadRequest) -> Result { + let preferences = parse(request.document.as_deref())?; + let ssh = preferences.ssh(std::env::var_os("PATH").as_deref()); + let mut result = json!({ + "preferences": { + "sshProgram": preferences.ssh_program(), + "reconnectLimitSeconds": preferences.reconnect_limit_seconds(), + }, + "ssh": ssh, + "reconnect": preferences.reconnect(), + "storage": STORAGE, + }); + if let Some(home) = request.home_directory { + let home = PathBuf::from(home); + if !home.is_absolute() { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "The home directory must be an absolute path", + ) + .with_details(json!({ "field": "homeDirectory", "reason": "relative" }).to_string())); + } + let path = home.join(".ssh").join("config"); + result["sshConfig"] = json!({ + "path": path.to_string_lossy(), + "exists": path.is_file(), + }); + } + Ok(result) +} + +/// Applies one edit. An edit that changes nothing returns a `null` document, +/// so the native client creates no source. +pub fn edit(request: EditRequest) -> Result { + let before = parse(request.document.as_deref())?; + let mut after = before.clone(); + match (request.ssh_program, request.reconnect_limit) { + (Some(program), None) => after + .set_ssh_program(program.path.as_deref()) + .map_err(invalid_request)?, + (None, Some(limit)) => after + .set_reconnect_limit(limit.seconds) + .map_err(invalid_request)?, + _ => { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Invalid remote preferences edit", + ) + .with_details(json!({ "field": "operation", "reason": "invalid" }).to_string())) + } + } + let changed = after != before; + let document = if changed { + Some(after.text().map_err(invalid_request)?) + } else { + None + }; + Ok(json!({ "changed": changed, "document": document })) +} + +/// The OpenSSH client to start under the preferences in `document`: the +/// setting, else the first `ssh` on `PATH`, else `ssh` for the system to +/// look up. `stand_in`, which tests set, replaces all of them. +pub(crate) fn ssh_program( + stand_in: Option<&str>, + document: Option<&str>, +) -> Result { + if let Some(program) = stand_in { + return Ok(program.to_owned()); + } + let preferences = parse(document)?; + let ssh = preferences.ssh(std::env::var_os("PATH").as_deref()); + Ok(ssh.command().to_owned()) +} + +/// 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 { + Preferences::parse(document).map_err(|error| { + CoreError::new( + ErrorCode::ParseFailed, + "Invalid remote preferences document", + ) + .with_details(json!(error).to_string()) + }) +} + +/// A refused edit, with the field and the reason as details. +fn invalid_request(error: PreferenceError) -> CoreError { + CoreError::new(ErrorCode::InvalidRequest, "Invalid remote preference") + .with_details(json!(error).to_string()) +} + +#[cfg(test)] +mod tests; diff --git a/rust/crates/workspace/src/preferences/tests.rs b/rust/crates/workspace/src/preferences/tests.rs new file mode 100644 index 00000000..068c56fe --- /dev/null +++ b/rust/crates/workspace/src/preferences/tests.rs @@ -0,0 +1,136 @@ +use super::*; + +fn request(value: Value) -> T { + serde_json::from_value(value).expect("the request decodes") +} + +fn details(error: &CoreError) -> Value { + serde_json::from_str(error.details.as_deref().expect("details")).expect("JSON details") +} + +#[test] +fn reading_no_document_reports_automatic_values_and_the_storage() { + let home = std::env::temp_dir(); + let result = read(request(json!({ + "document": null, + "homeDirectory": home.to_string_lossy(), + }))) + .unwrap(); + assert_eq!( + result["preferences"], + json!({ "sshProgram": null, "reconnectLimitSeconds": null }) + ); + assert_eq!(result["ssh"]["source"], "automatic"); + assert_eq!(result["reconnect"]["source"], "automatic"); + assert_eq!(result["reconnect"]["limitSeconds"], 60); + assert_eq!( + result["storage"], + json!({ "relativePath": "remote/preferences.json", "maximumBytes": 16384 }) + ); + let config = home.join(".ssh").join("config"); + assert_eq!( + result["sshConfig"]["path"], + config.to_string_lossy().as_ref() + ); + assert_eq!(result["sshConfig"]["exists"], config.is_file()); + + let without_home = read(request(json!({ "document": null }))).unwrap(); + assert!(without_home.get("sshConfig").is_none()); + let relative = read(request( + json!({ "document": null, "homeDirectory": "home" }), + )); + assert!(matches!( + relative.unwrap_err().code, + ErrorCode::InvalidRequest + )); +} + +#[test] +fn a_damaged_document_is_a_parse_failure_with_the_field() { + for document in ["not json", "{\"version\":1,\"sshProgram\":\"ssh\"}"] { + let error = read(request(json!({ "document": document }))).unwrap_err(); + assert!(matches!(error.code, ErrorCode::ParseFailed)); + assert!(details(&error)["field"].is_string()); + let error = ssh_program(None, Some(document)).unwrap_err(); + assert!(matches!(error.code, ErrorCode::ParseFailed)); + } +} + +#[test] +fn an_edit_changes_one_value_and_publishes_the_document() { + let limit = edit(request(json!({ + "document": null, + "reconnectLimit": { "seconds": 120 }, + }))) + .unwrap(); + assert_eq!(limit["changed"], true); + let document = limit["document"].as_str().unwrap().to_owned(); + let state = read(request(json!({ "document": document }))).unwrap(); + assert_eq!(state["preferences"]["reconnectLimitSeconds"], 120); + assert_eq!(state["reconnect"]["source"], "setting"); + + let same = edit(request(json!({ + "document": document, + "reconnectLimit": { "seconds": 120 }, + }))) + .unwrap(); + assert_eq!(same, json!({ "changed": false, "document": null })); + + let automatic = edit(request(json!({ + "document": document, + "reconnectLimit": { "seconds": null }, + }))) + .unwrap(); + assert_eq!(automatic["document"], "{\n \"version\": 1\n}\n"); +} + +#[test] +fn an_edit_names_exactly_one_value_and_refuses_bad_programs_by_field() { + for both_or_neither in [ + json!({ "document": null }), + json!({ + "document": null, + "sshProgram": { "path": null }, + "reconnectLimit": { "seconds": null }, + }), + ] { + let error = edit(request(both_or_neither)).unwrap_err(); + assert!(matches!(error.code, ErrorCode::InvalidRequest)); + assert_eq!(details(&error)["field"], "operation"); + } + let missing = std::env::temp_dir().join("lithe-remote-preferences-no-such-ssh"); + let error = edit(request(json!({ + "document": null, + "sshProgram": { "path": missing.to_string_lossy() }, + }))) + .unwrap_err(); + assert!(matches!(error.code, ErrorCode::InvalidRequest)); + assert_eq!( + details(&error), + json!({ "field": "sshProgram", "reason": "missing" }) + ); + let error = edit(request(json!({ + "document": null, + "reconnectLimit": { "seconds": 3601 }, + }))) + .unwrap_err(); + assert_eq!( + details(&error), + json!({ "field": "reconnectLimitSeconds", "reason": "outOfRange" }) + ); +} + +#[test] +fn the_setting_is_the_program_every_ssh_start_uses() { + let directory = std::env::temp_dir(); + let program = directory.join("lithe-remote-preferences-chosen-ssh"); + let document = json!({ "version": 1, "sshProgram": program }).to_string(); + assert_eq!( + ssh_program(None, Some(&document)).unwrap(), + program.to_string_lossy() + ); + assert_eq!( + ssh_program(Some("/stand-in/ssh"), Some("not json")).unwrap(), + "/stand-in/ssh" + ); +} diff --git a/rust/crates/workspace/src/probe.rs b/rust/crates/workspace/src/probe.rs index 8b85d26a..d66d8bda 100644 --- a/rust/crates/workspace/src/probe.rs +++ b/rust/crates/workspace/src/probe.rs @@ -31,6 +31,10 @@ const DIAGNOSTICS_LIMIT: usize = 4 * 1024; #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ProbeRequest { connection: SshConnection, + /// Remote preferences document, whose SSH program starts OpenSSH; + /// `null` or absent is every value automatic. + #[serde(default)] + preferences: Option, } /// Stable outcome of a probe. Failures to connect are results, not Core @@ -83,12 +87,11 @@ pub fn probe(request: ProbeRequest) -> Result { probe_with(request, None) } -/// `ssh_program` replaces the `ssh` found on `PATH`; tests use a stand-in. +/// `ssh_program` replaces the preferences' SSH program; tests use a +/// stand-in. fn probe_with(request: ProbeRequest, ssh_program: Option<&str>) -> Result { let mut hop = ssh_hop(&request.connection)?; - if let Some(program) = ssh_program { - hop.program = program.into(); - } + hop.program = crate::preferences::ssh_program(ssh_program, request.preferences.as_deref())?; let chain = TransportChain::new(vec![Hop::Ssh(hop)]); let argv = chain.command(&probe_command()).map_err(|error| { CoreError::new(ErrorCode::InvalidRequest, "Invalid SSH connection") diff --git a/rust/crates/workspace/src/sessions.rs b/rust/crates/workspace/src/sessions.rs index e3febe8b..a2f4a3f6 100644 --- a/rust/crates/workspace/src/sessions.rs +++ b/rust/crates/workspace/src/sessions.rs @@ -78,6 +78,10 @@ pub struct ConnectRequest { /// A WSL distribution on this machine, reached through `wsl.exe`. #[serde(default)] wsl: Option, + /// Remote preferences document, whose SSH program starts OpenSSH; + /// `null` or absent is every value automatic. Unused for `wsl`. + #[serde(default)] + preferences: Option, servers: Vec, server_version: String, /// Install root on the remote; `None` is `$HOME/.lithe-server`. @@ -346,16 +350,15 @@ impl Client { } /// The hop that starts the chain, with `program` in place of the system -/// client when set. Exactly one of `connection` and `wsl` must be set. +/// client when set; OpenSSH is otherwise the preferences' SSH program. +/// Exactly one of `connection` and `wsl` must be set. fn first_hop(request: &ConnectRequest, program: Option<&str>) -> Result { let refused = |field, reason| crate::connections::invalid_request(ConnectionError { field, reason }); match (&request.connection, &request.wsl) { (Some(connection), None) => { let mut hop = ssh_hop(connection)?; - if let Some(program) = program { - hop.program = program.into(); - } + hop.program = crate::preferences::ssh_program(program, request.preferences.as_deref())?; Ok(Hop::Ssh(hop)) } (None, Some(distribution)) => { diff --git a/rust/crates/workspace/src/ssh_configuration.rs b/rust/crates/workspace/src/ssh_configuration.rs index d3731306..8f1a7446 100644 --- a/rust/crates/workspace/src/ssh_configuration.rs +++ b/rust/crates/workspace/src/ssh_configuration.rs @@ -32,6 +32,10 @@ const IMPORT_DEADLINE: Duration = Duration::from_secs(30); #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct EffectiveRequest { connection: SshConnection, + /// Remote preferences document, whose SSH program runs `ssh -G`; + /// `null` or absent is every value automatic. + #[serde(default)] + preferences: Option, } /// `remote.sshConfigHosts`: where the configuration is, and the saved @@ -43,6 +47,10 @@ pub struct HostsRequest { home_directory: String, /// Current connections document; `null` when the source does not exist. document: Option, + /// Remote preferences document, whose SSH program runs `ssh -G`; + /// `null` or absent is every value automatic. + #[serde(default)] + preferences: Option, } /// The values the connection uses and where each comes from. @@ -50,13 +58,15 @@ pub fn effective_settings(request: EffectiveRequest) -> Result effective_with(request, None) } -/// `ssh_program` replaces the `ssh` found on `PATH`; tests use a stand-in. +/// `ssh_program` replaces the preferences' SSH program; tests use a +/// stand-in. fn effective_with( request: EffectiveRequest, ssh_program: Option<&str>, ) -> Result { + let program = crate::preferences::ssh_program(ssh_program, request.preferences.as_deref())?; let connection = request.connection.normalized(); - let hop = with_program(ssh_hop(&connection)?, ssh_program); + let hop = with_program(ssh_hop(&connection)?, &program); let deadline = Instant::now() + COMMAND_DEADLINE; let configured = print_configuration(&hop, true, deadline)?; let baseline = print_configuration(&hop, false, deadline)?; @@ -87,6 +97,7 @@ fn hosts_with(request: HostsRequest, ssh_program: Option<&str>) -> Result) -> Result( }) } -fn with_program(mut hop: SshHop, ssh_program: Option<&str>) -> SshHop { - if let Some(program) = ssh_program { - hop.program = program.into(); - } +fn with_program(mut hop: SshHop, program: &str) -> SshHop { + hop.program = program.into(); hop } diff --git a/rust/crates/workspace/src/ssh_configuration/tests.rs b/rust/crates/workspace/src/ssh_configuration/tests.rs index 2129cbd7..f1931f04 100644 --- a/rust/crates/workspace/src/ssh_configuration/tests.rs +++ b/rust/crates/workspace/src/ssh_configuration/tests.rs @@ -201,6 +201,7 @@ fn configuration_hosts_are_listed_with_what_they_resolve_to() { let request = HostsRequest { home_directory: home.path().display().to_string(), document: Some(document), + preferences: None, }; let result = hosts_with(request, Some(&ssh)).unwrap(); @@ -254,6 +255,7 @@ fn a_home_without_configuration_lists_nothing() { let request = HostsRequest { home_directory: home.path().display().to_string(), document: None, + preferences: None, }; let result = hosts_with(request, Some("ssh-is-never-run")).unwrap(); @@ -269,6 +271,7 @@ fn a_relative_home_is_refused() { let request = HostsRequest { home_directory: "home".into(), document: None, + preferences: None, }; let error = ssh_config_hosts(request).unwrap_err();