From 8ccf0276e30b21b581afbd56c8ca094c69b49f8a Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 22 Nov 2026 08:22:01 +0800 Subject: [PATCH] feat(remote): remember a remote workspace's ports and restore its forwards (Refs 1lck/Lithe-IDEA#2231) Add remote.portRecords, remote.editPortRecords and remote.restoreForwards. The ports page keeps added ports (a URL keeps its scheme and path, never its query or fragment), labels, chosen local ports, the local forwards left running with their S28 confirmation, and host/reverse rules, keyed like workspace trust by the connection target and the host real path. Rules never record allInterfaces and never start on their own. Trust and port records now share sessions::workspace_key. --- rust/contracts/rust-core-api.md | 88 ++- rust/crates/core/src/protocol/command.rs | 12 + .../core/src/runtime/dispatcher/remote.rs | 18 + rust/crates/core/src/runtime/request_trace.rs | 1 + rust/crates/core/src/tests/remote_sessions.rs | 204 +++++ rust/crates/remote/src/client/forward_set.rs | 9 + rust/crates/remote/src/client/mod.rs | 4 + rust/crates/remote/src/client/port_records.rs | 621 +++++++++++++++ .../remote/src/client/port_records/tests.rs | 705 ++++++++++++++++++ rust/crates/remote/src/client/trust.rs | 5 +- rust/crates/workspace/src/forwards.rs | 4 +- rust/crates/workspace/src/lib.rs | 7 +- rust/crates/workspace/src/port_records.rs | 222 ++++++ rust/crates/workspace/src/sessions.rs | 29 + rust/crates/workspace/src/trust.rs | 25 +- 15 files changed, 1925 insertions(+), 29 deletions(-) create mode 100644 rust/crates/remote/src/client/port_records.rs create mode 100644 rust/crates/remote/src/client/port_records/tests.rs create mode 100644 rust/crates/workspace/src/port_records.rs diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 2a5454bc..33cbb45d 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -823,6 +823,9 @@ or removing a command fails until the table changes in the same commit. | `remote.stopForward` | Stop one port forward and close the port it listens on | | `remote.forwards` | List the running port forwards of one connection | | `remote.parseForwardAddress` | Read a port, `host:port` or URL typed into the ports page into a forward target | +| `remote.portRecords` | Read what the ports page remembers of one open remote workspace | +| `remote.editPortRecords` | Record or forget one port row or forwarding rule of a remote workspace | +| `remote.restoreForwards` | Start again the local forwards a remote workspace left running | | `remote.connections` | Read the SSH connections the user saved | | `remote.editConnections` | Save, remove or import saved SSH connections, or record a folder or a connection time | | `remote.parseAddress` | Split a quick-connect address into connection fields | @@ -6219,7 +6222,8 @@ that could not reach their target (always 0 for a local forward). except a host forward's, which the host closes with its port. An unknown id returns `stopped: false`. `remote.disconnect`, `remote.closeAll` and a lost connection close every port the connection opened on either side, - and a reconnect reopens none of them. Requests on a + and a reconnect reopens none of them by itself: the native client calls + `remote.restoreForwards` (see "Remote port records"). Requests on a connection whose session ended are `connection_closed` and forget it, as for the other commands. @@ -6296,6 +6300,88 @@ as for `toolchains/global.json`. The file is separate from that document so hosts that predate remote trust still read theirs. This user-settings resource does not affect code signatures or update deltas. +#### Remote port records + +The ports page remembers what the user set by hand when a remote workspace +closes or its connection drops, so the next connection to the same workspace +shows it again. Records are keyed like workspace trust, by the connection's +target and the workspace's real path on the host, and never carry over to +another host, account, container or folder. + +| Command | Request | Result | +| --- | --- | --- | +| `remote.portRecords` | `{ document, sessionId, workspace }` | `{ records, workspace, storage: { relativePath: "remote/ports.json", maximumBytes: 262144 } }` | +| `remote.editPortRecords` | `{ document, sessionId, workspace }` and one of `port`, `removePort`, `rule`, `removeRule` | `{ changed, document: string\|null, records }` | +| `remote.restoreForwards` | `{ document, sessionId, workspace }` | `{ forwards }` | + +`document` is the current text of the source, `null` when there is none, and +`workspace` the absolute host path as opened; the result's `workspace` is its +real path. `records` is `{ ports, rules }` of that workspace: + +- A **row** is `{ host?, port, added?, label?, localPort?, forwardTarget?, + confirmedTarget? }`, one for each port on each address. `host` is absent + for the host's own loopback address, which `localhost`, `127.0.0.1`, `::1` + and the wildcard addresses all name; otherwise it is an IP address in + canonical form or a name in lower case. Rows are ordered by port, then by + host, the loopback row first. + - `added: { host, scheme?, path? }` is the address the user added the row + with, as `remote.parseForwardAddress` read it and for the same row. Its + path keeps no query and no fragment, which can carry an access token + such as Jupyter's `?token=`; the native client keeps the full address in + memory only. + - `label` is 1 to 64 characters without control characters; + `localPort` is the local port the user chose (absent uses `port`). + - `forwardTarget` is the target of the local forward the user started for + the row and has not stopped, as `remote.forwards` lists it; it must name + the row's address. `confirmedTarget: true` keeps the user's confirmation + of a target outside the host's loopback interface; it is dropped for a + loopback target and without `forwardTarget`, so stopping the forward + forgets it. +- A **rule** is a forward that listens on the host, `{ kind: "host", + listenPort?, targetHost, targetPort, label? }` or `{ kind: "reverse", + listenPort?, localPort, label? }`, in the order the user added them. + `listenPort` `0` is stored as absent. There is no `allInterfaces`: listening + on every host interface is asked at each start and never remembered. + +`remote.editPortRecords` applies one change: `port` replaces the row it names +and removes it when nothing is left to remember; `removePort: { host?, port }` +forgets a row, any spelling of its host accepted; `rule` adds a rule or +renames the same rule (rules that differ only in their labels are the same); +`removeRule` forgets the same rule whatever its label. Removing an absent row +or rule changes nothing. An unchanged edit returns a `null` document and must +not create a source. The workspace edited last comes first; a workspace with +nothing left is dropped. + +`remote.restoreForwards` starts again, in row order, the local forward of +every row with a `forwardTarget`, each as `remote.startForward` would with +the row's `localPort` (or `port`) and `allowNonLoopbackTarget` set to its +`confirmedTarget`. Each entry of `forwards` is `{ host?, port }` with either +`{ forward, created }` or `{ error }`, the error `remote.startForward` would +have returned, such as `forward_target_not_confirmed`; one failure does not +stop the others. A forward that already runs returns `created: false`. Rules +never start this way: host and reverse forwards ask the user at each start. + +Bounds: 256 KiB per document, 64 workspaces, 128 rows and 64 rules per +workspace. Unlike trust decisions the records are a convenience: past 64 +workspaces, or when the document would outgrow 256 KiB, the workspace edited +longest ago is dropped instead of refusing the edit. A full workspace refuses +a new row or rule. A document that cannot be decoded, has duplicate keys, +unknown fields (`allInterfaces` included), another version, more than 64 +workspaces, a workspace, row or rule listed twice, or a value an edit never +writes is `parse_failed` with `details.field`. A malformed request, none or +more than one change (`details.field` `change`), a refused row or rule, or a +full list is `invalid_request` with `details.field`. A missing workspace is +`workspace_not_found`, a closed session `connection_closed`, and a host real +path that is not normalized `parse_failed`. + +Native clients keep the document below their platform user-preference +directory, next to the remote preferences and the saved connections, never on +the host, in a workspace or in an installed package. They retain the exact +bytes, verify them before atomic publication and reread after Save, as for +`toolchains/remote-trust.json`. The document holds no secret; Core never logs +its addresses. This user-settings resource does not affect code signatures or +update deltas. + ### Git patch discovery and rebase amendment preconditions `git.patchExport` accepts optional `metadataOnly` (default false). In metadata diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 0b1a9b0d..a4f565c3 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -1027,6 +1027,15 @@ pub enum RemoteCommand { /// Reads a port, `host:port` or URL typed into the ports page /// (`remote.parseForwardAddress`). ParseForwardAddress, + /// Reads what the ports page remembers of one open remote workspace + /// (`remote.portRecords`). + PortRecords, + /// Records or forgets one port row or forwarding rule of an open remote + /// workspace (`remote.editPortRecords`). + EditPortRecords, + /// Starts again the local forwards the user left running in an open + /// remote workspace (`remote.restoreForwards`). + RestoreForwards, /// Reads the SSH connections the user saved (`remote.connections`). Connections, /// Saves, removes, imports or records a folder or a connection time on @@ -1624,6 +1633,9 @@ impl CoreCommand { "remote.stopForward" => Some(Self::Remote(RemoteCommand::StopForward)), "remote.forwards" => Some(Self::Remote(RemoteCommand::Forwards)), "remote.parseForwardAddress" => Some(Self::Remote(RemoteCommand::ParseForwardAddress)), + "remote.portRecords" => Some(Self::Remote(RemoteCommand::PortRecords)), + "remote.editPortRecords" => Some(Self::Remote(RemoteCommand::EditPortRecords)), + "remote.restoreForwards" => Some(Self::Remote(RemoteCommand::RestoreForwards)), "remote.connections" => Some(Self::Remote(RemoteCommand::Connections)), "remote.editConnections" => Some(Self::Remote(RemoteCommand::EditConnections)), "remote.parseAddress" => Some(Self::Remote(RemoteCommand::ParseAddress)), diff --git a/rust/crates/core/src/runtime/dispatcher/remote.rs b/rust/crates/core/src/runtime/dispatcher/remote.rs index 208afe01..ff65d32f 100644 --- a/rust/crates/core/src/runtime/dispatcher/remote.rs +++ b/rust/crates/core/src/runtime/dispatcher/remote.rs @@ -239,6 +239,24 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option, payload: Valu Err(error) => CoreResponse::failure(id, error), } } + RemoteCommand::PortRecords => answer( + id, + payload, + "Invalid remote port records request", + lithe_workspace::port_records::read, + ), + RemoteCommand::EditPortRecords => answer( + id, + payload, + "Invalid remote port records request", + lithe_workspace::port_records::edit, + ), + RemoteCommand::RestoreForwards => answer( + id, + payload, + "Invalid remote port records request", + lithe_workspace::port_records::restore, + ), RemoteCommand::Connections => { match serde_json::from_value(payload) .map_err(|error| { diff --git a/rust/crates/core/src/runtime/request_trace.rs b/rust/crates/core/src/runtime/request_trace.rs index d31e5c07..419644b6 100644 --- a/rust/crates/core/src/runtime/request_trace.rs +++ b/rust/crates/core/src/runtime/request_trace.rs @@ -294,6 +294,7 @@ mod tests { "remote.startForward", "remote.startHostForward", "remote.startReverseForward", + "remote.restoreForwards", "debug.launch", ] { assert!(!is_hot(method), "{method}"); diff --git a/rust/crates/core/src/tests/remote_sessions.rs b/rust/crates/core/src/tests/remote_sessions.rs index 8b2e82d6..11ddbb79 100644 --- a/rust/crates/core/src/tests/remote_sessions.rs +++ b/rust/crates/core/src/tests/remote_sessions.rs @@ -1249,6 +1249,210 @@ fn remote_workspace_trust_keys_the_host_real_path_on_the_connected_target() { ); } +// The ports page's records: keyed like trust by the real path on the +// connected target, an added URL never keeps its query, and a reconnect +// starts again only the local forwards the user left running, each with the +// confirmation it was given. +#[test] +fn remote_port_records_key_the_real_path_and_restore_running_forwards() { + let host = HostFixture::new(); + let project = host.root.join("host/projects/app"); + let sibling = host.root.join("host/projects/other"); + std::fs::create_dir_all(&project).unwrap(); + std::fs::create_dir_all(&sibling).unwrap(); + let link = host.root.join("host/link"); + std::os::unix::fs::symlink(&project, &link).unwrap(); + // Holds a port number on the host's loopback interface for the test. + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let call = |command: &str, payload: Value| -> Value { + serde_json::from_str(&crate::execute_json( + &json!({"id": test_support::unique_id(), "command": command, + "timeoutMilliseconds": 30_000, "payload": payload}) + .to_string(), + )) + .unwrap() + }; + let ok = |response: Value| -> Value { + assert_eq!(response["ok"], true, "{response}"); + response["data"].clone() + }; + let error = |response: Value| -> Value { + assert_eq!(response["ok"], false, "{response}"); + response["error"].clone() + }; + let field = |error: &Value| -> Value { + serde_json::from_str::(error["details"].as_str().unwrap()).unwrap()["field"].clone() + }; + let workspace = |command: &str, document: &Value, workspace: &std::path::Path| { + call( + command, + json!({"document": document, "sessionId": host.id, "workspace": workspace}), + ) + }; + let edit = |document: &Value, change: Value| { + let mut payload = change; + payload["document"] = document.clone(); + payload["sessionId"] = json!(host.id); + payload["workspace"] = json!(link); + call("remote.editPortRecords", payload) + }; + + let empty = ok(workspace("remote.portRecords", &Value::Null, &link)); + assert_eq!( + empty["storage"], + json!({"relativePath": "remote/ports.json", "maximumBytes": 262_144}) + ); + assert_eq!(empty["workspace"], json!(project), "{empty}"); + assert_eq!(empty["records"], json!({"ports": [], "rules": []})); + + // An added URL keeps its scheme and path; the token in its query stays + // in the page. + let notebook = json!({"port": {"port": port, "label": "Notebook", + "added": {"host": "localhost", "scheme": "http", "path": "/lab?token=secret"}, + "forwardTarget": "127.0.0.1"}}); + let added = ok(edit(&Value::Null, notebook.clone())); + assert_eq!(added["changed"], true, "{added}"); + assert_eq!( + added["records"]["ports"], + json!([{"port": port, "label": "Notebook", "forwardTarget": "127.0.0.1", + "added": {"host": "localhost", "scheme": "http", "path": "/lab"}}]) + ); + let document = added["document"].clone(); + assert!( + document + .as_str() + .is_some_and(|text| !text.contains("token")), + "{added}" + ); + let repeated = ok(edit(&document, notebook)); + assert_eq!(repeated["changed"], false, "{repeated}"); + assert!(repeated["document"].is_null(), "{repeated}"); + + // A database on the host's network, once without and once with the + // user's confirmation, and a rule that listens on the host. + let mut document = document; + for change in [ + json!({"port": {"host": "192.0.2.10", "port": 5432, "forwardTarget": "192.0.2.10"}}), + json!({"port": {"host": "192.0.2.11", "port": 5432, "forwardTarget": "192.0.2.11", + "confirmedTarget": true}}), + json!({"rule": {"kind": "host", "targetHost": "192.0.2.20", "targetPort": 80, + "label": "Web"}}), + ] { + let edited = ok(edit(&document, change)); + assert_eq!(edited["changed"], true, "{edited}"); + document = edited["document"].clone(); + } + let records = ok(workspace("remote.portRecords", &document, &project))["records"].clone(); + assert_eq!(records["ports"].as_array().unwrap().len(), 3, "{records}"); + assert_eq!(records["rules"].as_array().unwrap().len(), 1, "{records}"); + assert_eq!( + ok(workspace("remote.portRecords", &document, &sibling))["records"], + json!({"ports": [], "rules": []}) + ); + + // A reconnect starts the forwards again; the rule waits for the user. + let restore = || workspace("remote.restoreForwards", &document, &link); + let restored = ok(restore()); + let forwards = restored["forwards"].as_array().unwrap(); + assert_eq!(forwards.len(), 3, "{restored}"); + let row = |host: Option<&str>| { + forwards + .iter() + .find(|forward| forward.get("host").and_then(Value::as_str) == host) + .unwrap() + .clone() + }; + let loopback = row(None); + assert_eq!(loopback["port"], port, "{restored}"); + assert_eq!(loopback["created"], true, "{restored}"); + assert_eq!(loopback["forward"]["targetHost"], "127.0.0.1", "{restored}"); + assert_eq!( + row(Some("192.0.2.10"))["error"]["code"], + "forward_target_not_confirmed" + ); + assert_eq!( + row(Some("192.0.2.11"))["forward"]["loopbackTarget"], + false, + "{restored}" + ); + let running = ok(call("remote.forwards", json!({"sessionId": host.id}))); + assert_eq!( + running["forwards"].as_array().unwrap().len(), + 2, + "{running}" + ); + let again = ok(restore()); + for forward in again["forwards"].as_array().unwrap() { + assert_ne!(forward["created"], true, "{again}"); + } + + let removed = ok(edit(&document, json!({"removePort": {"port": port}}))); + assert_eq!(removed["changed"], true, "{removed}"); + assert_eq!( + removed["records"]["ports"].as_array().unwrap().len(), + 2, + "{removed}" + ); + let unruled = ok(edit( + &document, + json!({"removeRule": {"kind": "host", "targetHost": "192.0.2.20", "targetPort": 80}}), + )); + assert_eq!(unruled["records"]["rules"], json!([]), "{unruled}"); + + // Each failure keeps its own category. + assert_eq!( + error(workspace( + "remote.portRecords", + &json!("{\"version\":1,\"everything\":true}"), + &link + ))["code"], + "parse_failed" + ); + let unchanged = error(edit(&document, json!({}))); + assert_eq!(unchanged["code"], "invalid_request", "{unchanged}"); + assert_eq!(field(&unchanged), "change", "{unchanged}"); + assert_eq!( + field(&error(edit( + &document, + json!({"removePort": {"port": port}, "removeRule": {"kind": "reverse", "localPort": 1}}) + ))), + "change" + ); + assert_eq!( + error(edit( + &document, + json!({"rule": {"kind": "reverse", "localPort": 3000, "allInterfaces": true}}) + ))["code"], + "invalid_request" + ); + assert_eq!( + error(workspace( + "remote.portRecords", + &document, + std::path::Path::new("projects/app") + ))["code"], + "invalid_request" + ); + assert_eq!( + error(workspace( + "remote.restoreForwards", + &document, + &host.root.join("host/missing") + ))["code"], + "workspace_not_found" + ); + assert_eq!( + error(call( + "remote.portRecords", + json!({"document": document, "sessionId": test_support::unique_id(), + "workspace": project}) + ))["code"], + "connection_closed" + ); + drop(listener); +} + // The connections window's helpers answer through the dispatcher: a quick // address splits into fields, a missing Motty database is a result, and a // malformed connection names its field before any `ssh -G` runs. diff --git a/rust/crates/remote/src/client/forward_set.rs b/rust/crates/remote/src/client/forward_set.rs index 95197ea9..40c56d28 100644 --- a/rust/crates/remote/src/client/forward_set.rs +++ b/rust/crates/remote/src/client/forward_set.rs @@ -835,6 +835,15 @@ pub(crate) fn is_target_host(host: &str) -> bool { TargetHost::parse(host).is_ok() } +/// The host a forward to `host` reaches, as [`ForwardInfo`] lists it, and +/// whether it is on the host's loopback interface, so that a forward to it +/// starts without a confirmation; `None` for a host no forward can target. +pub(crate) fn canonical_target(host: &str) -> Option<(String, bool)> { + TargetHost::parse(host) + .ok() + .map(|target| (target.host, target.loopback)) +} + /// True for the host's loopback interface: `localhost` or a loopback address, /// IPv6 in brackets or not and IPv4-mapped included. Names are not resolved. pub(crate) fn is_loopback_host(host: &str) -> bool { diff --git a/rust/crates/remote/src/client/mod.rs b/rust/crates/remote/src/client/mod.rs index 3ddb5b03..5d0b8713 100644 --- a/rust/crates/remote/src/client/mod.rs +++ b/rust/crates/remote/src/client/mod.rs @@ -25,6 +25,9 @@ //! identified by a random id instead of the host or user name. //! - [`trust`] keeps the machine-local trust decisions on remote workspaces, //! keyed by the target and the host's real path. +//! - [`port_records`] keeps what the ports page remembers of each remote +//! workspace, keyed like trust: added ports, labels, the forwards to start +//! again and the rules that listen on the host. //! - [`ssh_config`] reads what OpenSSH makes of a connection (`ssh -G`) and //! the `Host` aliases of the user's SSH configuration. //! - `motty` (feature `motty`) reads the SSH hosts of a Motty configuration @@ -52,6 +55,7 @@ pub mod host_forward; pub mod launch; #[cfg(feature = "motty")] pub mod motty; +pub mod port_records; pub mod preferences; pub mod prompt; pub mod session; diff --git a/rust/crates/remote/src/client/port_records.rs b/rust/crates/remote/src/client/port_records.rs new file mode 100644 index 00000000..eac0162c --- /dev/null +++ b/rust/crates/remote/src/client/port_records.rs @@ -0,0 +1,621 @@ +//! Machine-local port records of remote workspaces (design §8, S27, S28). +//! +//! The ports page keeps what the user set by hand when the workspace closes +//! or the connection drops. For each connection and workspace it remembers: +//! +//! - the ports the user added, with the address typed. A URL keeps its scheme +//! and path, never its query or fragment, which can carry an access token; +//! - a label and the local port the user chose for a row; +//! - the local forwards the user started and did not stop. Only these start +//! again after a reconnect ([`WorkspaceRecords::restorable`]). One to a +//! machine other than the host keeps the confirmation the user gave for it +//! (S28), and stopping the forward forgets that confirmation; +//! - the forwarding rules that listen on the host, host and reverse forwards. +//! They never start on their own: each start asks again, and listening on +//! every host interface is never part of a rule (S27). +//! +//! Records are keyed like workspace trust, by the [`Target`] and the +//! workspace's real path as the host resolves it, so another host, account, +//! container or folder never sees them. They are stored only on the local +//! machine, in the document at [`STORAGE_PATH`] below the platform's +//! user-preference directory, and hold no secret. Unlike trust decisions they +//! are a convenience: beyond [`MAX_WORKSPACES`] workspaces, or once the +//! document would outgrow [`MAX_BYTES`], the workspace edited longest ago is +//! dropped instead of refusing the edit. +//! +//! This module validates and merges. The caller resolves the target and the +//! real path over an open session; the platform adapter reads the document +//! and publishes edits atomically. + +use crate::client::forward_address; +use crate::client::forward_set::{canonical_target, MAX_FORWARDS}; +use crate::client::trust::{host_path, Target}; +use serde::{Deserialize, Serialize}; +use std::fmt; + +/// Document location below the platform's user-preference directory, next to +/// the remote preferences and the saved connections. +pub const STORAGE_PATH: &str = "remote/ports.json"; + +/// Largest accepted document, in bytes. +pub const MAX_BYTES: usize = 256 * 1024; + +/// Workspaces with records; the one edited longest ago makes room. +pub const MAX_WORKSPACES: usize = 64; + +/// Port rows of one workspace. +pub const MAX_PORTS: usize = 128; + +/// Forwarding rules of one workspace: as many as one connection runs. +pub const MAX_RULES: usize = MAX_FORWARDS; + +/// Longest label, in characters. +const MAX_LABEL_CHARS: usize = 64; + +/// A port of the host that the ports page lists as one row, and what the +/// user set for it. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PortRecord { + /// The address the port is on, as the ports page keys its rows. Absent + /// for the host's own loopback address, which `localhost`, `127.0.0.1`, + /// `::1` and the every-interface addresses all name; otherwise an IP + /// address in canonical form or a name in lower case. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub host: Option, + /// TCP port, 1 to 65535. + pub port: u16, + /// The address the user added the row with; absent for a listening port + /// the user did not add. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub added: Option, + /// Name the user gave the row. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option, + /// Local port the user chose; absent forwards on the row's own number. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub local_port: Option, + /// Target host of the local forward the user started for the row and did + /// not stop, as `remote.startForward` lists it. It starts again after a + /// reconnect. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub forward_target: Option, + /// The user confirmed that forward although its target is outside the + /// host's loopback interface (S28). Kept only with `forward_target`, and + /// only for such a target. + #[serde(default, skip_serializing_if = "is_false")] + pub confirmed_target: bool, +} + +/// An address typed into the ports page, as `remote.parseForwardAddress` +/// read it. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct AddedAddress { + /// The host read: an IP address, an IPv6 one without brackets, or a name + /// in lower case; `localhost` for a port alone. + pub host: String, + /// URL scheme in lower case, when the address was a URL. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scheme: Option, + /// The URL's path without its query and fragment; absent when nothing + /// but `/` remains. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub path: Option, +} + +/// A forwarding rule that listens on the host. Two rules are the same rule +/// when they differ only in their labels. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde( + tag = "kind", + rename_all = "camelCase", + rename_all_fields = "camelCase", + deny_unknown_fields +)] +pub enum Rule { + /// A host port on the host's loopback interface that connects to another + /// server from the host. + Host { + /// Host port; absent lets the host choose one at each start. + #[serde(default, skip_serializing_if = "Option::is_none")] + listen_port: Option, + /// The server, as `remote.forwards` lists the target. + target_host: String, + /// Its TCP port. + target_port: u16, + /// Name the user gave the rule. + #[serde(default, skip_serializing_if = "Option::is_none")] + label: Option, + }, + /// A host loopback port that reaches a port on this machine's loopback + /// interface. + Reverse { + /// Host port; absent lets the host choose one at each start. + #[serde(default, skip_serializing_if = "Option::is_none")] + listen_port: Option, + /// The port on this machine's loopback interface. + local_port: u16, + /// Name the user gave the rule. + #[serde(default, skip_serializing_if = "Option::is_none")] + label: Option, + }, +} + +impl Rule { + /// Whether `other` is the same rule, whatever the labels. + fn same(&self, other: &Rule) -> bool { + self.unlabelled() == other.unlabelled() + } + + fn unlabelled(&self) -> Rule { + let mut rule = self.clone(); + match &mut rule { + Rule::Host { label, .. } | Rule::Reverse { label, .. } => *label = None, + } + rule + } +} + +/// What the ports page remembers of one workspace. +#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceRecords { + /// Rows by port, then by host, the loopback row first. + pub ports: Vec, + /// Rules in the order the user added them. + pub rules: Vec, +} + +impl WorkspaceRecords { + /// The local forwards to start again after a reconnect, with the target + /// host of each. + pub fn restorable(&self) -> impl Iterator { + self.ports.iter().filter_map(|record| { + record + .forward_target + .as_deref() + .map(|target| (record, target)) + }) + } +} + +/// Why a document, a target, a path or a record was refused. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct PortRecordError { + /// The offending field, for example `document`, `host` or `added`. + pub field: &'static str, +} + +fn at(field: &'static str) -> PortRecordError { + PortRecordError { field } +} + +impl fmt::Display for PortRecordError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "invalid remote port record at {}", self.field) + } +} + +impl std::error::Error for PortRecordError {} + +/// The validated document: the records of every workspace, the one edited +/// last first. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PortRecords { + version: u32, + #[serde(default)] + workspaces: Vec, +} + +/// The records of one workspace on one target. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct WorkspaceEntry { + target: Target, + /// Real path of the workspace root on the host. + workspace: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + ports: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + rules: Vec, +} + +impl WorkspaceEntry { + fn is(&self, target: &Target, workspace: &str) -> bool { + self.target == *target && self.workspace == workspace + } + + fn is_empty(&self) -> bool { + self.ports.is_empty() && self.rules.is_empty() + } + + /// Sorts the rows and refuses what an edit never records: a malformed + /// target or path, oversized lists, values an edit would have changed, + /// and a row or rule listed twice. Rows with nothing to remember are + /// dropped. + fn normalize(&mut self) -> Result<(), PortRecordError> { + self.target.validate().map_err(|_| at("target"))?; + if host_path(&self.workspace).is_none() { + return Err(at("workspace")); + } + if self.ports.len() > MAX_PORTS + || self + .ports + .iter() + .any(|record| normalize_port(record.clone()).as_ref() != Ok(record)) + { + return Err(at("ports")); + } + self.ports.retain(|record| !is_blank(record)); + self.ports + .sort_by(|left, right| row_order(left).cmp(&row_order(right))); + if self + .ports + .windows(2) + .any(|pair| row_order(&pair[0]) == row_order(&pair[1])) + { + return Err(at("ports")); + } + if self.rules.len() > MAX_RULES + || self + .rules + .iter() + .any(|rule| normalize_rule(rule.clone()).as_ref() != Ok(rule)) + || self + .rules + .iter() + .enumerate() + .any(|(index, rule)| self.rules[..index].iter().any(|other| other.same(rule))) + { + return Err(at("rules")); + } + Ok(()) + } +} + +impl PortRecords { + /// Reads `document`, or the empty document when there is none yet. + /// + /// Refuses documents over [`MAX_BYTES`], malformed JSON, duplicate keys, + /// unknown fields (`allInterfaces` included), other versions, more than + /// [`MAX_WORKSPACES`] workspaces, a workspace listed twice, and records an + /// edit never writes. Workspaces with nothing to remember are dropped. + pub fn parse(document: Option<&str>) -> Result { + let Some(text) = document else { + return Ok(Self { + version: 1, + workspaces: Vec::new(), + }); + }; + if text.len() > MAX_BYTES { + return Err(at("document")); + } + let mut records: Self = serde_json::from_str(text).map_err(|_| at("document"))?; + if records.version != 1 { + return Err(at("version")); + } + if records.workspaces.len() > MAX_WORKSPACES { + return Err(at("workspaces")); + } + for entry in &mut records.workspaces { + entry.normalize()?; + } + records.workspaces.retain(|entry| !entry.is_empty()); + let workspaces = &records.workspaces; + if workspaces.iter().enumerate().any(|(index, entry)| { + workspaces[..index] + .iter() + .any(|other| other.is(&entry.target, &entry.workspace)) + }) { + return Err(at("workspaces")); + } + Ok(records) + } + + /// 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(|_| at("document"))?; + text.push('\n'); + if text.len() > MAX_BYTES { + return Err(at("document")); + } + Ok(text) + } + + /// What the ports page remembers of the workspace at `real_path` on + /// `target`; nothing when it has no records. + pub fn records( + &self, + target: &Target, + real_path: &str, + ) -> Result { + target.validate().map_err(|_| at("target"))?; + let workspace = host_path(real_path).ok_or(at("workspace"))?; + Ok(self + .workspaces + .iter() + .find(|entry| entry.is(target, workspace)) + .map(|entry| WorkspaceRecords { + ports: entry.ports.clone(), + rules: entry.rules.clone(), + }) + .unwrap_or_default()) + } + + /// Records `record` for its row, replacing what the row had. A record + /// with nothing to remember removes the row. + pub fn set_port( + &mut self, + target: &Target, + real_path: &str, + record: PortRecord, + ) -> Result<(), PortRecordError> { + let record = normalize_port(record)?; + self.update(target, real_path, |entry| { + let position = entry + .ports + .binary_search_by(|row| row_order(row).cmp(&row_order(&record))); + match position { + Ok(index) if is_blank(&record) => { + entry.ports.remove(index); + } + Ok(index) => entry.ports[index] = record, + Err(_) if is_blank(&record) => {} + Err(_) if entry.ports.len() >= MAX_PORTS => return Err(at("ports")), + Err(index) => entry.ports.insert(index, record), + } + Ok(()) + }) + } + + /// Forgets the row of `port` on `host`, any spelling of the row's host + /// accepted. Removing an absent row changes nothing. + pub fn remove_port( + &mut self, + target: &Target, + real_path: &str, + host: Option<&str>, + port: u16, + ) -> Result<(), PortRecordError> { + let host = match host { + Some(host) => row_host(host, "host")?, + None => None, + }; + self.update(target, real_path, |entry| { + entry + .ports + .retain(|record| record.port != port || record.host != host); + Ok(()) + }) + } + + /// Records `rule`, replacing the label of the same rule or adding it last. + pub fn set_rule( + &mut self, + target: &Target, + real_path: &str, + rule: Rule, + ) -> Result<(), PortRecordError> { + let rule = normalize_rule(rule)?; + self.update(target, real_path, |entry| { + match entry.rules.iter().position(|other| other.same(&rule)) { + Some(index) => entry.rules[index] = rule, + None if entry.rules.len() >= MAX_RULES => return Err(at("rules")), + None => entry.rules.push(rule), + } + Ok(()) + }) + } + + /// Forgets the rule that is the same as `rule`. Removing an absent rule + /// changes nothing. + pub fn remove_rule( + &mut self, + target: &Target, + real_path: &str, + rule: Rule, + ) -> Result<(), PortRecordError> { + let rule = normalize_rule(rule)?; + self.update(target, real_path, |entry| { + entry.rules.retain(|other| !other.same(&rule)); + Ok(()) + }) + } + + /// Applies `change` to the records of the workspace at `real_path` on + /// `target`. A change moves the workspace first and removes it once it + /// has nothing left; the workspaces edited longest ago make room. On an + /// error, and when nothing changes, the document stays as it was. + fn update( + &mut self, + target: &Target, + real_path: &str, + change: impl FnOnce(&mut WorkspaceEntry) -> Result<(), PortRecordError>, + ) -> Result<(), PortRecordError> { + target.validate().map_err(|_| at("target"))?; + let workspace = host_path(real_path).ok_or(at("workspace"))?; + let position = self + .workspaces + .iter() + .position(|entry| entry.is(target, workspace)); + let before = match position { + Some(index) => self.workspaces[index].clone(), + None => WorkspaceEntry { + target: target.clone(), + workspace: workspace.into(), + ports: Vec::new(), + rules: Vec::new(), + }, + }; + let mut after = before.clone(); + change(&mut after)?; + if after == before { + return Ok(()); + } + if let Some(index) = position { + self.workspaces.remove(index); + } + if !after.is_empty() { + self.workspaces.insert(0, after); + self.workspaces.truncate(MAX_WORKSPACES); + while self.workspaces.len() > 1 && self.text().is_err() { + self.workspaces.pop(); + } + } + Ok(()) + } +} + +/// The row key of a port: `None` for the host's own loopback address, which +/// `localhost`, `127.0.0.1`, `::1` and the every-interface addresses name; +/// otherwise the host as a forward reaches it. Refused, at `field`, for a +/// host no forward can target. +fn row_host(host: &str, field: &'static str) -> Result, PortRecordError> { + let (canonical, _) = canonical_target(host).ok_or(at(field))?; + Ok((!matches!(canonical.as_str(), "127.0.0.1" | "::1" | "localhost")).then_some(canonical)) +} + +/// The row order: by port, then by host, the loopback row first. +fn row_order(record: &PortRecord) -> (u16, Option<&str>) { + (record.port, record.host.as_deref()) +} + +fn is_blank(record: &PortRecord) -> bool { + record.added.is_none() + && record.label.is_none() + && record.local_port.is_none() + && record.forward_target.is_none() +} + +/// `record` as it is stored: the row's host as its key, the added address +/// without query or fragment, the forward's target as `remote.forwards` +/// lists it, and a confirmation only where one applies. +fn normalize_port(mut record: PortRecord) -> Result { + if record.port == 0 { + return Err(at("port")); + } + record.host = match record.host.as_deref() { + Some(host) => row_host(host, "host")?, + None => None, + }; + if let Some(added) = record.added.take() { + record.added = Some(normalize_added(added, record.port, record.host.as_deref())?); + } + if let Some(label) = &record.label { + validate_label(label)?; + } + if record.local_port == Some(0) { + return Err(at("localPort")); + } + if let Some(target) = record.forward_target.take() { + let (canonical, _) = canonical_target(&target).ok_or(at("forwardTarget"))?; + if row_host(&canonical, "forwardTarget")? != record.host { + return Err(at("forwardTarget")); + } + record.forward_target = Some(canonical); + } + let loopback = record + .host + .as_deref() + .is_none_or(|host| canonical_target(host).is_some_and(|(_, loopback)| loopback)); + record.confirmed_target &= record.forward_target.is_some() && !loopback; + Ok(record) +} + +/// `added` as `remote.parseForwardAddress` reads it back for `port`, on the +/// row `row`, without the query and the fragment of its path: those can +/// carry an access token, such as Jupyter's `?token=`, and stay in the page's +/// memory only. +fn normalize_added( + mut added: AddedAddress, + port: u16, + row: Option<&str>, +) -> Result { + added.path = added.path.and_then(|path| { + let path = path.split(['?', '#']).next().unwrap_or_default(); + (!path.is_empty() && path != "/").then(|| path.to_owned()) + }); + let host = if added.host.contains(':') { + format!("[{}]", added.host) + } else { + added.host.clone() + }; + let path = added.path.as_deref().unwrap_or_default(); + let text = match &added.scheme { + Some(scheme) => format!("{scheme}://{host}:{port}{path}"), + None => format!("{host}:{port}{path}"), + }; + let read = forward_address::parse(&text).map_err(|_| at("added"))?; + let same = read.target_host == added.host + && read.target_port == port + && read.scheme == added.scheme + && read.path == added.path; + if !same || row_host(&added.host, "added")?.as_deref() != row { + return Err(at("added")); + } + Ok(added) +} + +/// `rule` as it is stored: its target as `remote.forwards` lists it, and no +/// listening port for one the host chooses. +fn normalize_rule(rule: Rule) -> Result { + let listen = |port: Option| port.filter(|port| *port != 0); + let label = |label: Option| match label { + Some(label) => validate_label(&label).map(|()| Some(label)), + None => Ok(None), + }; + match rule { + Rule::Host { + listen_port, + target_host, + target_port, + label: name, + } => { + let (target_host, _) = canonical_target(&target_host).ok_or(at("targetHost"))?; + if target_port == 0 { + return Err(at("targetPort")); + } + Ok(Rule::Host { + listen_port: listen(listen_port), + target_host, + target_port, + label: label(name)?, + }) + } + Rule::Reverse { + listen_port, + local_port, + label: name, + } => { + if local_port == 0 { + return Err(at("localPort")); + } + Ok(Rule::Reverse { + listen_port: listen(listen_port), + local_port, + label: label(name)?, + }) + } + } +} + +fn validate_label(label: &str) -> Result<(), PortRecordError> { + let valid = !label.is_empty() + && label.chars().count() <= MAX_LABEL_CHARS + && !label.chars().any(char::is_control); + if valid { + Ok(()) + } else { + Err(at("label")) + } +} + +fn is_false(value: &bool) -> bool { + !*value +} + +#[cfg(test)] +mod tests; diff --git a/rust/crates/remote/src/client/port_records/tests.rs b/rust/crates/remote/src/client/port_records/tests.rs new file mode 100644 index 00000000..cb1effe0 --- /dev/null +++ b/rust/crates/remote/src/client/port_records/tests.rs @@ -0,0 +1,705 @@ +use super::*; +use crate::client::transport::{ContainerEngine, ContainerHop, Hop, SshHop, TransportChain}; +use serde_json::json; + +fn target(hops: Vec, user_id: Option) -> Target { + Target::new(&TransportChain::new(hops), user_id) +} + +fn devbox() -> Target { + target(vec![Hop::Ssh(SshHop::new("dev@box"))], Some(1000)) +} + +fn row(host: Option<&str>, port: u16) -> PortRecord { + PortRecord { + host: host.map(Into::into), + port, + added: None, + label: None, + local_port: None, + forward_target: None, + confirmed_target: false, + } +} + +fn labelled(host: Option<&str>, port: u16, label: &str) -> PortRecord { + PortRecord { + label: Some(label.into()), + ..row(host, port) + } +} + +fn forwarded(host: Option<&str>, port: u16, target: &str, confirmed: bool) -> PortRecord { + PortRecord { + forward_target: Some(target.into()), + confirmed_target: confirmed, + ..row(host, port) + } +} + +fn added(host: &str, scheme: Option<&str>, path: Option<&str>) -> AddedAddress { + AddedAddress { + host: host.into(), + scheme: scheme.map(Into::into), + path: path.map(Into::into), + } +} + +fn host_rule(listen_port: Option, target_host: &str, label: Option<&str>) -> Rule { + Rule::Host { + listen_port, + target_host: target_host.into(), + target_port: 5432, + label: label.map(Into::into), + } +} + +fn reverse_rule(listen_port: Option, local_port: u16) -> Rule { + Rule::Reverse { + listen_port, + local_port, + label: None, + } +} + +fn ports(records: &PortRecords, target: &Target, path: &str) -> Vec { + records.records(target, path).unwrap().ports +} + +/// The document after a round trip through its text, to show what is stored. +fn stored(records: &PortRecords) -> serde_json::Value { + let text = records.text().unwrap(); + assert_eq!(PortRecords::parse(Some(&text)).unwrap(), *records); + serde_json::from_str(&text).unwrap() +} + +#[test] +fn records_never_carry_over_between_hosts_accounts_containers_or_folders() { + let mut records = PortRecords::parse(None).unwrap(); + records + .set_port(&devbox(), "/home/dev/app", labelled(None, 3000, "Web")) + .unwrap(); + assert_eq!( + ports(&records, &devbox(), "/home/dev/app"), + [labelled(None, 3000, "Web")] + ); + + let container = Hop::Container(ContainerHop::new(ContainerEngine::Docker, "web")); + let others = [ + ( + target(vec![Hop::Ssh(SshHop::new("dev@other"))], Some(1000)), + "/home/dev/app", + ), + ( + target(vec![Hop::Ssh(SshHop::new("dev@box"))], Some(0)), + "/home/dev/app", + ), + ( + target( + vec![Hop::Ssh(SshHop::new("dev@box")), container], + Some(1000), + ), + "/home/dev/app", + ), + (devbox(), "/home/dev/app/sub"), + (devbox(), "/home/dev"), + ]; + for (other, path) in &others { + assert_eq!( + records.records(other, path).unwrap(), + WorkspaceRecords::default() + ); + } +} + +#[test] +fn rows_are_keyed_by_the_address_a_forward_reaches() { + let mut records = PortRecords::parse(None).unwrap(); + // Every name of the host's loopback interface and of all its interfaces + // is the same row. + for host in [ + "localhost", + "LOCALHOST", + "127.0.0.1", + "::1", + "0.0.0.0", + "::", + "::ffff:127.0.0.1", + ] { + records + .set_port(&devbox(), "/srv", labelled(Some(host), 3000, host)) + .unwrap(); + assert_eq!( + ports(&records, &devbox(), "/srv"), + [labelled(None, 3000, host)] + ); + } + // Other addresses are rows of their own, in canonical form. + records + .set_port(&devbox(), "/srv", labelled(Some("DB.Internal"), 3000, "db")) + .unwrap(); + records + .set_port( + &devbox(), + "/srv", + labelled(Some("127.0.0.2"), 3000, "second"), + ) + .unwrap(); + records + .set_port( + &devbox(), + "/srv", + labelled(Some("0:0:0:0:0:0:a00:1"), 22, "v6"), + ) + .unwrap(); + assert_eq!( + ports(&records, &devbox(), "/srv"), + [ + labelled(Some("::a00:1"), 22, "v6"), + labelled(None, 3000, "::ffff:127.0.0.1"), + labelled(Some("127.0.0.2"), 3000, "second"), + labelled(Some("db.internal"), 3000, "db"), + ] + ); + // Any spelling removes the row. + records + .remove_port(&devbox(), "/srv", Some("DB.INTERNAL"), 3000) + .unwrap(); + records + .remove_port(&devbox(), "/srv", Some("[::]"), 3000) + .unwrap(); + assert_eq!( + ports(&records, &devbox(), "/srv"), + [ + labelled(Some("::a00:1"), 22, "v6"), + labelled(Some("127.0.0.2"), 3000, "second"), + ] + ); + + for (record, field) in [ + (row(None, 0), "port"), + (labelled(Some("-oProxyCommand"), 1, "x"), "host"), + (labelled(Some("a b"), 1, "x"), "host"), + (labelled(Some(""), 1, "x"), "host"), + ] { + assert_eq!( + records.set_port(&devbox(), "/srv", record), + Err(PortRecordError { field }) + ); + } +} + +#[test] +fn added_addresses_keep_scheme_and_path_but_never_the_query_or_fragment() { + let mut records = PortRecords::parse(None).unwrap(); + let jupyter = PortRecord { + added: Some(added( + "localhost", + Some("http"), + Some("/lab?token=secret#cell"), + )), + ..row(None, 8888) + }; + records.set_port(&devbox(), "/srv", jupyter).unwrap(); + let only_query = PortRecord { + added: Some(added("db.internal", Some("https"), Some("/?token=secret"))), + ..row(Some("db.internal"), 8443) + }; + records.set_port(&devbox(), "/srv", only_query).unwrap(); + let without_scheme = PortRecord { + added: Some(added("localhost", None, Some("/app#top"))), + ..row(None, 3000) + }; + records.set_port(&devbox(), "/srv", without_scheme).unwrap(); + + assert_eq!( + ports(&records, &devbox(), "/srv"), + [ + PortRecord { + added: Some(added("localhost", None, Some("/app"))), + ..row(None, 3000) + }, + PortRecord { + added: Some(added("db.internal", Some("https"), None)), + ..row(Some("db.internal"), 8443) + }, + PortRecord { + added: Some(added("localhost", Some("http"), Some("/lab"))), + ..row(None, 8888) + }, + ] + ); + let text = records.text().unwrap(); + assert!(!text.contains("secret") && !text.contains('?') && !text.contains('#')); + + // A stored query is refused rather than read. + let document = json!({ + "version": 1, + "workspaces": [{ + "target": devbox(), + "workspace": "/srv", + "ports": [{ + "port": 8888, + "added": {"host": "localhost", "scheme": "http", "path": "/lab?token=secret"} + }] + }] + }); + assert_eq!( + PortRecords::parse(Some(&document.to_string())), + Err(PortRecordError { field: "ports" }) + ); +} + +#[test] +fn added_addresses_must_read_back_as_typed_on_their_row() { + let mut records = PortRecords::parse(None).unwrap(); + let ipv6 = PortRecord { + added: Some(added("::1", None, None)), + ..row(None, 3000) + }; + records.set_port(&devbox(), "/srv", ipv6).unwrap(); + let all_interfaces = PortRecord { + added: Some(added("0.0.0.0", Some("http"), None)), + ..row(Some("0.0.0.0"), 80) + }; + records.set_port(&devbox(), "/srv", all_interfaces).unwrap(); + + for added in [ + // Another row's host. + added("db.internal", None, None), + // Not as `remote.parseForwardAddress` reads it back. + added("LOCALHOST", None, None), + added("localhost", Some("HTTP"), None), + added("localhost", Some("http"), Some("lab")), + added("localhost", Some("http"), Some("/a b")), + added("dev@localhost", None, None), + added("[::1]", None, None), + added("", None, None), + added("localhost", Some("1http"), None), + ] { + let record = PortRecord { + added: Some(added), + ..row(None, 3000) + }; + assert_eq!( + records.set_port(&devbox(), "/srv", record), + Err(PortRecordError { field: "added" }) + ); + } +} + +#[test] +fn a_confirmation_is_kept_only_for_a_running_forward_outside_the_hosts_loopback() { + let mut records = PortRecords::parse(None).unwrap(); + records + .set_port( + &devbox(), + "/srv", + forwarded(Some("db.internal"), 5432, "DB.internal", true), + ) + .unwrap(); + // Loopback targets never need one. + records + .set_port(&devbox(), "/srv", forwarded(None, 3000, "0.0.0.0", true)) + .unwrap(); + records + .set_port( + &devbox(), + "/srv", + forwarded(Some("127.0.0.2"), 3000, "127.0.0.2", true), + ) + .unwrap(); + // Without a running forward there is nothing to confirm. + let stopped = PortRecord { + confirmed_target: true, + ..labelled(Some("10.0.0.5"), 80, "Proxy") + }; + records.set_port(&devbox(), "/srv", stopped).unwrap(); + + let restorable: Vec<_> = records.records(&devbox(), "/srv").unwrap().ports; + assert_eq!( + restorable, + [ + labelled(Some("10.0.0.5"), 80, "Proxy"), + forwarded(None, 3000, "127.0.0.1", false), + forwarded(Some("127.0.0.2"), 3000, "127.0.0.2", false), + forwarded(Some("db.internal"), 5432, "db.internal", true), + ] + ); + let workspace = records.records(&devbox(), "/srv").unwrap(); + let targets: Vec<_> = workspace + .restorable() + .map(|(record, target)| (record.port, target)) + .collect(); + assert_eq!( + targets, + [ + (3000, "127.0.0.1"), + (3000, "127.0.0.2"), + (5432, "db.internal") + ] + ); + + // Stopping the forward forgets the confirmation. + records + .set_port(&devbox(), "/srv", labelled(Some("db.internal"), 5432, "DB")) + .unwrap(); + assert_eq!( + records.records(&devbox(), "/srv").unwrap().ports[3], + labelled(Some("db.internal"), 5432, "DB") + ); +} + +#[test] +fn a_forward_target_must_be_the_rows_address() { + let mut records = PortRecords::parse(None).unwrap(); + for (record, field) in [ + (forwarded(None, 3000, "db.internal", true), "forwardTarget"), + ( + forwarded(Some("db.internal"), 3000, "localhost", false), + "forwardTarget", + ), + ( + forwarded(None, 3000, "-oProxyCommand", false), + "forwardTarget", + ), + ( + PortRecord { + local_port: Some(0), + ..forwarded(None, 3000, "localhost", false) + }, + "localPort", + ), + ] { + assert_eq!( + records.set_port(&devbox(), "/srv", record), + Err(PortRecordError { field }) + ); + } + assert_eq!(records, PortRecords::parse(None).unwrap()); +} + +#[test] +fn a_row_with_nothing_to_remember_is_removed() { + let mut records = PortRecords::parse(None).unwrap(); + let chosen = PortRecord { + local_port: Some(13000), + ..row(None, 3000) + }; + records.set_port(&devbox(), "/srv", chosen.clone()).unwrap(); + assert_eq!(ports(&records, &devbox(), "/srv"), [chosen]); + let blank = PortRecord { + confirmed_target: true, + ..row(None, 3000) + }; + records.set_port(&devbox(), "/srv", blank).unwrap(); + assert_eq!(records, PortRecords::parse(None).unwrap()); + assert_eq!(stored(&records), json!({"version": 1, "workspaces": []})); + // Removing what is not there changes nothing. + records.remove_port(&devbox(), "/srv", None, 3000).unwrap(); + records + .remove_rule(&devbox(), "/srv", reverse_rule(None, 3000)) + .unwrap(); + assert_eq!(records, PortRecords::parse(None).unwrap()); + + let long = "x".repeat(MAX_LABEL_CHARS + 1); + for label in ["", "a\nb", long.as_str()] { + assert_eq!( + records.set_port(&devbox(), "/srv", labelled(None, 1, label)), + Err(PortRecordError { field: "label" }) + ); + } + records + .set_port( + &devbox(), + "/srv", + labelled(None, 1, &"界".repeat(MAX_LABEL_CHARS)), + ) + .unwrap(); +} + +#[test] +fn rules_are_the_same_rule_whatever_their_labels_and_keep_their_order() { + let mut records = PortRecords::parse(None).unwrap(); + records + .set_rule(&devbox(), "/srv", host_rule(Some(0), "DB.internal", None)) + .unwrap(); + records + .set_rule(&devbox(), "/srv", reverse_rule(Some(9000), 3000)) + .unwrap(); + records + .set_rule( + &devbox(), + "/srv", + host_rule(None, "db.internal", Some("Database")), + ) + .unwrap(); + records + .set_rule( + &devbox(), + "/srv", + host_rule(Some(15432), "db.internal", None), + ) + .unwrap(); + assert_eq!( + records.records(&devbox(), "/srv").unwrap().rules, + [ + host_rule(None, "db.internal", Some("Database")), + reverse_rule(Some(9000), 3000), + host_rule(Some(15432), "db.internal", None), + ] + ); + records + .remove_rule( + &devbox(), + "/srv", + host_rule(None, "DB.INTERNAL", Some("other")), + ) + .unwrap(); + assert_eq!( + records.records(&devbox(), "/srv").unwrap().rules, + [ + reverse_rule(Some(9000), 3000), + host_rule(Some(15432), "db.internal", None) + ] + ); + assert_eq!( + stored(&records)["workspaces"][0]["rules"], + json!([ + {"kind": "reverse", "listenPort": 9000, "localPort": 3000}, + {"kind": "host", "listenPort": 15432, "targetHost": "db.internal", "targetPort": 5432}, + ]) + ); + + for (rule, field) in [ + (host_rule(None, "-oProxyCommand", None), "targetHost"), + ( + Rule::Host { + listen_port: None, + target_host: "db".into(), + target_port: 0, + label: None, + }, + "targetPort", + ), + (reverse_rule(None, 0), "localPort"), + (host_rule(None, "db", Some("")), "label"), + ] { + assert_eq!( + records.set_rule(&devbox(), "/srv", rule), + Err(PortRecordError { field }) + ); + } +} + +#[test] +fn a_rule_never_records_listening_on_every_host_interface() { + let document = |rule: serde_json::Value| { + json!({ + "version": 1, + "workspaces": [{"target": devbox(), "workspace": "/srv", "rules": [rule]}] + }) + .to_string() + }; + let refused = [ + json!({"kind": "reverse", "localPort": 3000, "allInterfaces": true}), + json!({"kind": "host", "targetHost": "db", "targetPort": 5432, "allInterfaces": false}), + json!({"kind": "host", "targetHost": "db", "targetPort": 5432, "confirmed": true}), + json!({"kind": "local", "localPort": 3000}), + ]; + for rule in refused { + assert_eq!( + PortRecords::parse(Some(&document(rule))), + Err(PortRecordError { field: "document" }) + ); + } + PortRecords::parse(Some(&document( + json!({"kind": "reverse", "localPort": 3000}), + ))) + .unwrap(); +} + +#[test] +fn the_workspace_edited_last_comes_first_and_the_oldest_makes_room() { + let mut records = PortRecords::parse(None).unwrap(); + for index in 0..=MAX_WORKSPACES { + records + .set_port(&devbox(), &format!("/w/{index}"), labelled(None, 3000, "x")) + .unwrap(); + } + let paths = |records: &PortRecords| -> Vec { + records + .workspaces + .iter() + .map(|entry| entry.workspace.clone()) + .collect() + }; + let listed = paths(&records); + assert_eq!(listed.len(), MAX_WORKSPACES); + assert_eq!(listed[0], format!("/w/{MAX_WORKSPACES}")); + assert_eq!(listed[MAX_WORKSPACES - 1], "/w/1"); + + // An edit that changes nothing keeps the order. + records + .set_port(&devbox(), "/w/1", labelled(None, 3000, "x")) + .unwrap(); + assert_eq!(paths(&records), listed); + records + .set_port(&devbox(), "/w/1", labelled(None, 3000, "y")) + .unwrap(); + assert_eq!(paths(&records)[0], "/w/1"); + + // A failed edit changes nothing either. + let before = records.clone(); + records + .set_port(&devbox(), "/w/2", labelled(None, 0, "x")) + .unwrap_err(); + assert_eq!(records, before); + + // Room for the document's size is made the same way. The full workspaces + // are written directly, so that one edit makes room instead of a + // thousand edits filling it. + let label = "界".repeat(MAX_LABEL_CHARS); + let full = |index: usize| WorkspaceEntry { + target: devbox(), + workspace: format!("/big/{index}"), + ports: (1..=MAX_PORTS as u16) + .map(|port| labelled(None, port, &label)) + .collect(), + rules: Vec::new(), + }; + let mut records = PortRecords::parse(None).unwrap(); + while records.text().is_ok() { + records.workspaces.push(full(records.workspaces.len())); + } + let before = paths(&records); + records + .set_port(&devbox(), "/big/0", labelled(None, 1, "edited")) + .unwrap(); + let after = paths(&records); + assert!(records.text().is_ok()); + assert!(after.len() < before.len()); + assert_eq!(after[..], before[..after.len()]); +} + +#[test] +fn a_workspace_holds_a_bounded_number_of_rows_and_rules() { + let mut records = PortRecords::parse(None).unwrap(); + for port in 1..=MAX_PORTS as u16 { + records + .set_port(&devbox(), "/srv", labelled(None, port, "x")) + .unwrap(); + } + assert_eq!( + records.set_port(&devbox(), "/srv", labelled(None, 60000, "x")), + Err(PortRecordError { field: "ports" }) + ); + // Replacing a row still works. + records + .set_port(&devbox(), "/srv", labelled(None, 1, "y")) + .unwrap(); + + for port in 1..=MAX_RULES as u16 { + records + .set_rule(&devbox(), "/srv", reverse_rule(None, port)) + .unwrap(); + } + assert_eq!( + records.set_rule(&devbox(), "/srv", reverse_rule(None, 60000)), + Err(PortRecordError { field: "rules" }) + ); +} + +#[test] +fn targets_and_paths_are_checked_like_trust() { + let mut records = PortRecords::parse(None).unwrap(); + let option = target(vec![Hop::Ssh(SshHop::new("-oProxyCommand=x"))], None); + assert_eq!( + records.set_port(&option, "/srv", labelled(None, 1, "x")), + Err(PortRecordError { field: "target" }) + ); + for path in ["srv", "/srv/../etc", "/srv/", ""] { + assert_eq!( + records.set_port(&devbox(), path, labelled(None, 1, "x")), + Err(PortRecordError { field: "workspace" }) + ); + assert_eq!( + records.records(&devbox(), path), + Err(PortRecordError { field: "workspace" }) + ); + } +} + +#[test] +fn parse_refuses_documents_an_edit_never_writes() { + let entry = + |ports: serde_json::Value| json!({"target": devbox(), "workspace": "/srv", "ports": ports}); + let cases = [ + ("{".to_owned(), "document"), + (json!({"version": 2, "workspaces": []}).to_string(), "version"), + (json!({"version": 1, "extra": true}).to_string(), "document"), + ( + r#"{"version": 1, "version": 1, "workspaces": []}"#.to_owned(), + "document", + ), + ( + json!({"version": 1, "workspaces": [entry(json!([{"host": "LOCALHOST", "port": 1, "label": "x"}]))]}) + .to_string(), + "ports", + ), + ( + json!({"version": 1, "workspaces": [entry(json!([{"port": 1, "label": "x"}, {"port": 1, "label": "y"}]))]}) + .to_string(), + "ports", + ), + ( + json!({"version": 1, "workspaces": [entry(json!([{"port": 1, "label": "x", "confirmedTarget": true}]))]}) + .to_string(), + "ports", + ), + ( + json!({"version": 1, "workspaces": [entry(json!([{"port": 1, "label": "x"}])), entry(json!([{"port": 2, "label": "y"}]))]}) + .to_string(), + "workspaces", + ), + ( + json!({"version": 1, "workspaces": [{"target": devbox(), "workspace": "srv", "ports": [{"port": 1, "label": "x"}]}]}) + .to_string(), + "workspace", + ), + ( + json!({"version": 1, "workspaces": [{"target": {"hops": [{"ssh": {"destination": "-o"}}]}, "workspace": "/srv", "ports": [{"port": 1, "label": "x"}]}]}) + .to_string(), + "target", + ), + ( + json!({"version": 1, "workspaces": [{"target": devbox(), "workspace": "/srv", "rules": [ + {"kind": "reverse", "localPort": 1}, + {"kind": "reverse", "localPort": 1, "label": "again"}, + ]}]}) + .to_string(), + "rules", + ), + (" ".repeat(MAX_BYTES + 1), "document"), + ]; + for (document, field) in cases { + assert_eq!( + PortRecords::parse(Some(&document)), + Err(PortRecordError { field }), + "{field}" + ); + } + + // Rows out of order are sorted, blank rows and empty workspaces dropped. + let document = json!({"version": 1, "workspaces": [ + entry(json!([{"port": 9, "label": "b"}, {"port": 3}, {"port": 1, "label": "a"}])), + {"target": devbox(), "workspace": "/empty"}, + ]}); + let records = PortRecords::parse(Some(&document.to_string())).unwrap(); + assert_eq!( + stored(&records), + json!({"version": 1, "workspaces": [ + entry(json!([{"port": 1, "label": "a"}, {"port": 9, "label": "b"}])), + ]}) + ); +} diff --git a/rust/crates/remote/src/client/trust.rs b/rust/crates/remote/src/client/trust.rs index f119c1df..93b9ebfc 100644 --- a/rust/crates/remote/src/client/trust.rs +++ b/rust/crates/remote/src/client/trust.rs @@ -169,8 +169,9 @@ impl Target { /// Refuses targets no transport chain produces: too many hops, empty, /// oversized or control characters in a field, a destination ssh would /// read as an option, an unknown engine, or a WSL hop that is not first - /// or names a distribution or user `wsl.exe` would not be given. - fn validate(&self) -> Result<(), TrustError> { + /// or names a distribution or user `wsl.exe` would not be given. Port + /// records refuse the same targets. + pub(crate) fn validate(&self) -> Result<(), TrustError> { let field = |value: &str| { !value.is_empty() && value.len() <= MAX_FIELD_BYTES diff --git a/rust/crates/workspace/src/forwards.rs b/rust/crates/workspace/src/forwards.rs index cbd3e135..34f2afcd 100644 --- a/rust/crates/workspace/src/forwards.rs +++ b/rust/crates/workspace/src/forwards.rs @@ -218,7 +218,7 @@ pub fn list(request: ListRequest) -> Result { /// The registered connection, while its session still runs. A session that /// ended already released its forwards, so its connection is forgotten. -fn open(session_id: &str) -> Result, CoreError> { +pub(crate) fn open(session_id: &str) -> Result, CoreError> { let connection = lookup(session_id)?; if connection.session.is_closed() { return Err(forward_error(session_id, ForwardError::SessionClosed)); @@ -227,7 +227,7 @@ fn open(session_id: &str) -> Result, CoreError> { } /// Gives each forward failure its own category. -fn forward_error(session_id: &str, error: ForwardError) -> CoreError { +pub(crate) fn forward_error(session_id: &str, error: ForwardError) -> CoreError { match error { ForwardError::InvalidTarget(field) => { let field = match field { diff --git a/rust/crates/workspace/src/lib.rs b/rust/crates/workspace/src/lib.rs index 30ad89c9..86cff50a 100644 --- a/rust/crates/workspace/src/lib.rs +++ b/rust/crates/workspace/src/lib.rs @@ -17,8 +17,10 @@ //! and owned streaming resources (processes, terminals, watches), //! [`forwards`] keeps the port forwards of the ports page, [`upload`] streams //! 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. +//! what the connection resolves, [`port_records`] keeps what the ports page +//! remembers of each workspace under the same key and restores its forwards, +//! 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. @@ -27,6 +29,7 @@ pub mod forwards; pub mod fs; pub mod host; pub mod motty; +pub mod port_records; pub mod preferences; pub mod probe; mod scope; diff --git a/rust/crates/workspace/src/port_records.rs b/rust/crates/workspace/src/port_records.rs new file mode 100644 index 00000000..41529c25 --- /dev/null +++ b/rust/crates/workspace/src/port_records.rs @@ -0,0 +1,222 @@ +//! `remote.portRecords`, `remote.editPortRecords` and +//! `remote.restoreForwards`: what the ports page remembers of a remote +//! workspace after it closes or the connection drops (design §8, S27, S28). +//! +//! The records live in a machine-local document that the native client reads +//! and publishes atomically, next to the remote preferences. Core keys them +//! like workspace trust, by the open connection's target and the workspace's +//! real path on the host, so another host, account, container or folder never +//! sees them. After a reconnect, `remote.restoreForwards` starts again the +//! local forwards the user left running, each with the confirmation it was +//! given; forwarding rules on the host never start without the user. The +//! rules are in `lithe_remote::client::port_records`. + +use crate::forwards::{forward_error, open}; +use crate::sessions::workspace_key; +use lithe_protocol::{CoreError, ErrorCode}; +use lithe_remote::client::port_records::{ + self, PortRecord, PortRecordError, PortRecords, Rule, WorkspaceRecords, +}; +use lithe_remote::client::{ForwardError, ForwardSpec}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +/// `remote.portRecords` and `remote.restoreForwards`: one open workspace. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct WorkspaceRequest { + /// Current document text; `null` when the source does not exist. + document: Option, + /// Open connection the workspace was opened through. + session_id: String, + /// Absolute host path of the workspace root as opened. + workspace: String, +} + +/// `remote.editPortRecords`: exactly one of `port`, `removePort`, `rule` and +/// `removeRule`. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct EditRequest { + /// Current document text; `null` when the source does not exist. + document: Option, + /// Open connection the workspace was opened through. + session_id: String, + /// Absolute host path of the workspace root as opened. + workspace: String, + /// Replaces what one row remembers; a row with nothing left is removed. + #[serde(default)] + port: Option, + /// Forgets one row. + #[serde(default)] + remove_port: Option, + /// Records a rule, or renames the same rule. + #[serde(default)] + rule: Option, + /// Forgets one rule, whatever its label. + #[serde(default)] + remove_rule: Option, +} + +/// One row: the port on the address it is listed under. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RowRequest { + #[serde(default)] + host: Option, + port: u16, +} + +/// 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: port_records::STORAGE_PATH, + maximum_bytes: port_records::MAX_BYTES, +}; + +/// The change one edit makes. +enum Change { + Port(PortRecord), + RemovePort(RowRequest), + Rule(Rule), + RemoveRule(Rule), +} + +/// Reads what the ports page remembers of one open workspace. +pub fn read(request: WorkspaceRequest) -> Result { + let records = parse(request.document.as_deref())?; + let (target, real_path) = workspace_key(&request.session_id, &request.workspace)?; + let workspace = records + .records(&target, &real_path) + .map_err(invalid_request)?; + Ok(json!({ "records": workspace, "workspace": real_path, "storage": STORAGE })) +} + +/// Applies one change. 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 change = match ( + request.port, + request.remove_port, + request.rule, + request.remove_rule, + ) { + (Some(record), None, None, None) => Change::Port(record), + (None, Some(row), None, None) => Change::RemovePort(row), + (None, None, Some(rule), None) => Change::Rule(rule), + (None, None, None, Some(rule)) => Change::RemoveRule(rule), + _ => return Err(invalid_request(PortRecordError { field: "change" })), + }; + let (target, real_path) = workspace_key(&request.session_id, &request.workspace)?; + let mut after = before.clone(); + match change { + Change::Port(record) => after.set_port(&target, &real_path, record), + Change::RemovePort(row) => { + after.remove_port(&target, &real_path, row.host.as_deref(), row.port) + } + Change::Rule(rule) => after.set_rule(&target, &real_path, rule), + Change::RemoveRule(rule) => after.remove_rule(&target, &real_path, rule), + } + .map_err(invalid_request)?; + let changed = after != before; + let document = if changed { + Some(after.text().map_err(invalid_request)?) + } else { + None + }; + let records = after + .records(&target, &real_path) + .map_err(invalid_request)?; + Ok(json!({ "changed": changed, "document": document, "records": records })) +} + +/// One forward `remote.restoreForwards` started, or why it did not start. +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct Restored { + #[serde(skip_serializing_if = "Option::is_none")] + host: Option, + port: u16, + #[serde(flatten)] + outcome: Outcome, +} + +#[derive(Serialize)] +#[serde(untagged)] +enum Outcome { + Started { + forward: lithe_remote::client::ForwardInfo, + created: bool, + }, + Failed { + error: CoreError, + }, +} + +/// Starts again the local forwards the user left running in the workspace, +/// in row order. Each starts like `remote.startForward`, with the local port +/// the row records and the confirmation it was given; one that fails is +/// reported and the others still start. Rules are not started. +pub fn restore(request: WorkspaceRequest) -> Result { + let records = parse(request.document.as_deref())?; + let (target, real_path) = workspace_key(&request.session_id, &request.workspace)?; + let workspace: WorkspaceRecords = records + .records(&target, &real_path) + .map_err(invalid_request)?; + let connection = open(&request.session_id)?; + let mut forwards = Vec::new(); + for (record, target_host) in workspace.restorable() { + let spec = ForwardSpec { + target_host: target_host.to_owned(), + target_port: record.port, + local_port: Some(record.local_port.unwrap_or(record.port)), + allow_non_loopback_target: record.confirmed_target, + }; + let outcome = match connection.forwards.start(spec) { + Ok((forward, created)) => Outcome::Started { forward, created }, + // Without a session no other forward can start either. + Err(ForwardError::SessionClosed) => { + return Err(forward_error( + &request.session_id, + ForwardError::SessionClosed, + )) + } + Err(error) => Outcome::Failed { + error: forward_error(&request.session_id, error), + }, + }; + forwards.push(Restored { + host: record.host.clone(), + port: record.port, + outcome, + }); + } + Ok(json!({ "forwards": forwards })) +} + +/// 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 { + PortRecords::parse(document).map_err(|error| { + CoreError::new( + ErrorCode::ParseFailed, + "Invalid remote port records document", + ) + .with_details(json!({ "field": error.field }).to_string()) + }) +} + +fn invalid_request(error: PortRecordError) -> CoreError { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid remote port records request", + ) + .with_details(json!({ "field": error.field }).to_string()) +} diff --git a/rust/crates/workspace/src/sessions.rs b/rust/crates/workspace/src/sessions.rs index a2f4a3f6..e15f70d2 100644 --- a/rust/crates/workspace/src/sessions.rs +++ b/rust/crates/workspace/src/sessions.rs @@ -268,6 +268,35 @@ pub(crate) fn lookup(id: &str) -> Result, CoreError> { }) } +/// The key of a workspace's machine-local records, its trust and its port +/// records: the connection's target and the workspace's real path as the host +/// resolves it, so a symbolic link or another spelling of the path never +/// reaches a record of a different folder. `workspace` is the absolute host +/// path the workspace was opened at. +pub(crate) fn workspace_key( + session_id: &str, + workspace: &str, +) -> Result<(Target, String), CoreError> { + if !workspace.starts_with('/') || workspace.contains('\0') { + return Err( + CoreError::new(ErrorCode::InvalidRequest, "Invalid remote workspace path") + .with_details(serde_json::json!({ "field": "workspace" }).to_string()), + ); + } + let connection = lookup(session_id)?; + let real_path = connection + .session + .real_path(workspace) + .map_err(|error| request_error(session_id, error))?; + if lithe_remote::client::trust::host_path(&real_path).is_none() { + return Err(CoreError::new( + ErrorCode::ParseFailed, + "The host returned an invalid real path", + )); + } + Ok((connection.trust_target.clone(), real_path)) +} + /// Removes a connection whose session ended and closes it in the background, /// so the host reconnects instead of retrying a dead session. pub(crate) fn forget(id: &str) { diff --git a/rust/crates/workspace/src/trust.rs b/rust/crates/workspace/src/trust.rs index e196301a..3d972c2c 100644 --- a/rust/crates/workspace/src/trust.rs +++ b/rust/crates/workspace/src/trust.rs @@ -7,7 +7,7 @@ //! host, so a symbolic link or a spelling the host resolves elsewhere never //! reaches a decision. The rules are in `lithe_remote::client::trust`. -use crate::sessions::{lookup, request_error}; +use crate::sessions::workspace_key; use lithe_protocol::{CoreError, ErrorCode}; use lithe_remote::client::trust::{self, Decision, Decisions, List, Target, TrustError}; use serde::{Deserialize, Serialize}; @@ -84,7 +84,7 @@ pub fn state(request: StateRequest) -> Result { match (request.session_id, request.workspace) { (None, None) => {} (Some(session_id), Some(workspace)) => { - let (target, real_path) = resolve(&session_id, &workspace)?; + let (target, real_path) = workspace_key(&session_id, &workspace)?; let workspace_trust = decisions .workspace(&target, &real_path) .map_err(invalid_request)?; @@ -105,7 +105,7 @@ pub fn edit(request: EditRequest) -> Result { let mut after = before.clone(); match (request.decision, request.revoke) { (Some(decision), None) => { - let (target, real_path) = resolve(&decision.session_id, &decision.workspace)?; + let (target, real_path) = workspace_key(&decision.session_id, &decision.workspace)?; after .decide( &target, @@ -132,25 +132,6 @@ pub fn edit(request: EditRequest) -> Result { Ok(json!({ "changed": changed, "document": document, "decisions": after })) } -/// The connection's target and the workspace's real path on the host. -fn resolve(session_id: &str, workspace: &str) -> Result<(Target, String), CoreError> { - if !workspace.starts_with('/') || workspace.contains('\0') { - return Err(invalid_request(TrustError { field: "workspace" })); - } - let connection = lookup(session_id)?; - let real_path = connection - .session - .real_path(workspace) - .map_err(|error| request_error(session_id, error))?; - if trust::host_path(&real_path).is_none() { - return Err(CoreError::new( - ErrorCode::ParseFailed, - "The host returned an invalid real path", - )); - } - Ok((connection.trust_target.clone(), real_path)) -} - /// 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 {