diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 91d900c4..ea1032e6 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -820,6 +820,7 @@ or removing a command fails until the table changes in the same commit. | `remote.startForward` | Forward a local port to a port as the remote host sees it | | `remote.stopForward` | Stop one port forward and close its local port | | `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.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 | @@ -6024,6 +6025,7 @@ owning process). Forwards belong to one connection: | `remote.startForward` | `{ sessionId, targetHost, targetPort, localPort?, allowNonLoopbackTarget? }` | `{ forward, created }` | | `remote.stopForward` | `{ sessionId, forwardId }` | `{ stopped }` | | `remote.forwards` | `{ sessionId }` | `{ forwards }`, by `id` | +| `remote.parseForwardAddress` | `{ text }` | `{ targetHost, targetPort, scheme?, path? }` | A forward is `{ id, localHost, localPort, requestedLocalPort?, localPortChanged, targetHost, targetPort, loopbackTarget, connections }`. @@ -6035,6 +6037,20 @@ localPortChanged, targetHost, targetPort, loopbackTarget, connections }`. same family; `targetHost` in the result is the address sent to the host. A malformed host or port `0` is `invalid_request` with `details.field` (`targetHost` or `targetPort`). +- **Typed address.** `remote.parseForwardAddress` reads what the user typed + into the page, without a connection and without resolving anything: a + port alone (`3000`, on `localhost`), `host:port` with brackets around an + IPv6 address, or a URL `scheme://host[:port][/path][?query][#fragment]`. + A URL without a port uses its scheme's (80 for `http` and `ws`, 443 for + `https` and `wss`); any other scheme must name the port. `targetHost` has + no brackets and names are in lower case; `scheme` and `path` (what follows + the host and port, absent when empty or `/`) come only from a URL or an + address with a path, so the page opens the forwarded address the same + way. A refused address is `invalid_request` with `details` `{ field: + "text", reason }`, where `reason` is `empty`, `tooLong` (over 2048 bytes), + `malformed` (white space or a control character inside), `scheme`, + `credentials` (a user name or password, refused rather than kept), + `host` or `port`. - **Confirmation.** A target outside the host's loopback interface reaches another machine through the host, so it starts only with `allowNonLoopbackTarget: true`, which the native client sets after the diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 1dbaa1a9..708b1e92 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -1018,6 +1018,9 @@ pub enum RemoteCommand { StopForward, /// Lists the running port forwards of one connection (`remote.forwards`). Forwards, + /// Reads a port, `host:port` or URL typed into the ports page + /// (`remote.parseForwardAddress`). + ParseForwardAddress, /// Reads the SSH connections the user saved (`remote.connections`). Connections, /// Saves, removes, imports or records a folder or a connection time on @@ -1604,6 +1607,7 @@ impl CoreCommand { "remote.startForward" => Some(Self::Remote(RemoteCommand::StartForward)), "remote.stopForward" => Some(Self::Remote(RemoteCommand::StopForward)), "remote.forwards" => Some(Self::Remote(RemoteCommand::Forwards)), + "remote.parseForwardAddress" => Some(Self::Remote(RemoteCommand::ParseForwardAddress)), "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 9a5ffb42..8bdf8e22 100644 --- a/rust/crates/core/src/runtime/dispatcher/remote.rs +++ b/rust/crates/core/src/runtime/dispatcher/remote.rs @@ -203,6 +203,18 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option, payload: Valu Err(error) => CoreResponse::failure(id, error), } } + RemoteCommand::ParseForwardAddress => { + match serde_json::from_value(payload) + .map_err(|error| invalid_forward_request(&error)) + .and_then(lithe_workspace::forwards::parse_address) + { + Ok(address) => CoreResponse::success( + id, + serde_json::to_value(address).expect("port forward address should encode"), + ), + Err(error) => CoreResponse::failure(id, error), + } + } RemoteCommand::Connections => { match serde_json::from_value(payload) .map_err(|error| { @@ -320,7 +332,7 @@ fn answer( } } -/// A `remote.*Forward` payload that does not decode. +/// A `remote.*Forward*` payload that does not decode. fn invalid_forward_request(error: &serde_json::Error) -> CoreError { CoreError::new(ErrorCode::InvalidRequest, "Invalid port forward request") .with_details(error.to_string()) diff --git a/rust/crates/core/src/tests/remote_sessions.rs b/rust/crates/core/src/tests/remote_sessions.rs index bab92c04..1caebca8 100644 --- a/rust/crates/core/src/tests/remote_sessions.rs +++ b/rust/crates/core/src/tests/remote_sessions.rs @@ -1278,7 +1278,39 @@ fn connection_window_helpers_answer_through_the_dispatcher() { ); assert_eq!(motty["data"]["unavailable"], "missing", "{motty}"); + let forward = call( + "remote.parseForwardAddress", + json!({"text": "HTTP://Localhost:3000/app?tab=1"}), + ); + assert_eq!( + forward["data"], + json!({"targetHost": "localhost", "targetPort": 3000, "scheme": "http", "path": "/app?tab=1"}), + "{forward}" + ); + let port = call("remote.parseForwardAddress", json!({"text": "8080"})); + assert_eq!( + port["data"], + json!({"targetHost": "localhost", "targetPort": 8080}), + "{port}" + ); + let secret = call( + "remote.parseForwardAddress", + json!({"text": "https://user:secret@example.com"}), + ); + assert_eq!(secret["error"]["code"], "invalid_request", "{secret}"); + let details: Value = + serde_json::from_str(secret["error"]["details"].as_str().unwrap()).unwrap(); + assert_eq!(details, json!({"field": "text", "reason": "credentials"})); + assert!( + !secret.to_string().contains("secret@"), + "a refused address is not echoed" + ); + for (command, payload) in [ + ( + "remote.parseForwardAddress", + json!({"text": "3000", "extra": 1}), + ), ( "remote.effectiveSettings", json!({"connection": {"host": "dev@box"}}), diff --git a/rust/crates/remote/src/client/forward_address.rs b/rust/crates/remote/src/client/forward_address.rs new file mode 100644 index 00000000..5cd53632 --- /dev/null +++ b/rust/crates/remote/src/client/forward_address.rs @@ -0,0 +1,356 @@ +//! Addresses typed into the ports page. +//! +//! The ports page takes a service on the remote host in whichever form the +//! user has it, and turns it into the TCP target a forward reaches: +//! +//! - `3000`: a port on the host's loopback interface, written `localhost`. +//! - `host:port`, with brackets around an IPv6 address, such as `[::1]:3000` +//! or `db.internal:5432`. +//! - A URL, `scheme://host[:port][/path][?query][#fragment]`. Without a port +//! the scheme's own applies: 80 for `http` and `ws`, 443 for `https` and +//! `wss`; any other scheme must name its port. The scheme and what follows +//! the authority are kept, so the page opens the forwarded address with the +//! same path. +//! +//! An address without a scheme may also carry a path, as in +//! `localhost:3000/app`. An authority of digits only is a port in either +//! form, so `http://3000` reaches `localhost:3000`. +//! +//! A URL with a user name or password (`user:secret@host`) is refused rather +//! than stripped: the page shows and keeps the address, and a secret must +//! never end up there (design S12). Hosts are only checked, not resolved; +//! whether the target is the host's own loopback interface, which decides +//! whether the user has to confirm it (design S28), is the forward's rule. +//! +//! Note: .agents/notes/proposed/architecture/2026-10-24-remote-development-workspace-host.md + +use crate::client::forward_set::is_target_host; +use serde::Serialize; +use std::fmt; + +/// Longest address accepted, in bytes, so that a pasted document is refused +/// instead of kept. +pub const MAX_ADDRESS_BYTES: usize = 2048; + +/// Longest URL scheme accepted, in bytes. +const MAX_SCHEME_BYTES: usize = 32; + +/// What a forward reaches, as typed on the ports page. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ForwardAddress { + /// Host as the remote host resolves it: an IP address, an IPv6 one + /// without brackets, or a name in lower case; `localhost` for a port + /// alone. + pub target_host: String, + /// TCP port, 1 to 65535. + pub target_port: u16, + /// URL scheme in lower case, when the address was a URL. + #[serde(skip_serializing_if = "Option::is_none")] + pub scheme: Option, + /// What followed the host and port: path, query and fragment, such as + /// `/app?tab=1`. Absent when nothing or only `/` followed. + #[serde(skip_serializing_if = "Option::is_none")] + pub path: Option, +} + +/// Why an address was refused. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum AddressError { + /// Nothing but white space. + Empty, + /// Longer than [`MAX_ADDRESS_BYTES`]. + TooLong, + /// White space or a control character inside the address. + Malformed, + /// A scheme that is not `letter *(letter / digit / + / - / .)`. + Scheme, + /// A URL with a user name or password. + Credentials, + /// The host is not an IP address or a host name. + Host, + /// The port is missing, `0`, above 65535 or not a number. + Port, +} + +impl AddressError { + /// The reason as the API reports it. + pub fn reason(self) -> &'static str { + match self { + Self::Empty => "empty", + Self::TooLong => "tooLong", + Self::Malformed => "malformed", + Self::Scheme => "scheme", + Self::Credentials => "credentials", + Self::Host => "host", + Self::Port => "port", + } + } +} + +impl fmt::Display for AddressError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "invalid forward address: {}", self.reason()) + } +} + +impl std::error::Error for AddressError {} + +/// Reads an address typed into the ports page; surrounding white space is +/// ignored. +pub fn parse(text: &str) -> Result { + let text = text.trim(); + if text.is_empty() { + return Err(AddressError::Empty); + } + if text.len() > MAX_ADDRESS_BYTES { + return Err(AddressError::TooLong); + } + if text + .chars() + .any(|character| character.is_whitespace() || character.is_control()) + { + return Err(AddressError::Malformed); + } + let (scheme, rest) = match text.split_once("://") { + Some((scheme, rest)) => (Some(parse_scheme(scheme)?), rest), + None => (None, text), + }; + let end = rest.find(['/', '?', '#']).unwrap_or(rest.len()); + let (authority, path) = rest.split_at(end); + if authority.contains('@') { + return Err(AddressError::Credentials); + } + let (target_host, target_port) = parse_authority(authority, scheme.as_deref())?; + let path = (!path.is_empty() && path != "/").then(|| path.to_owned()); + Ok(ForwardAddress { + target_host, + target_port, + scheme, + path, + }) +} + +/// The scheme in lower case, when it is one RFC 3986 allows. +fn parse_scheme(scheme: &str) -> Result { + let mut bytes = scheme.bytes(); + let valid = scheme.len() <= MAX_SCHEME_BYTES + && bytes.next().is_some_and(|byte| byte.is_ascii_alphabetic()) + && bytes.all(|byte| byte.is_ascii_alphanumeric() || b"+-.".contains(&byte)); + if !valid { + return Err(AddressError::Scheme); + } + Ok(scheme.to_ascii_lowercase()) +} + +/// The host and port of `authority`, with `scheme`'s port when it names none. +fn parse_authority(authority: &str, scheme: Option<&str>) -> Result<(String, u16), AddressError> { + if !authority.is_empty() && authority.bytes().all(|byte| byte.is_ascii_digit()) { + return Ok(("localhost".into(), parse_port(authority)?)); + } + let (host, port) = if let Some(rest) = authority.strip_prefix('[') { + let (inner, after) = rest.split_once(']').ok_or(AddressError::Host)?; + // Brackets only ever enclose an IPv6 address. + if inner.parse::().is_err() { + return Err(AddressError::Host); + } + let port = match after { + "" => None, + _ => Some(after.strip_prefix(':').ok_or(AddressError::Host)?), + }; + (inner, port) + } else { + match authority.split_once(':') { + // A second colon is an IPv6 address without brackets, which + // cannot be told apart from its port. + Some((_, port)) if port.contains(':') => return Err(AddressError::Host), + Some((host, port)) => (host, Some(port)), + None => (authority, None), + } + }; + if host.is_empty() || !is_target_host(host) { + return Err(AddressError::Host); + } + let port = match port { + Some(port) => parse_port(port)?, + None => scheme.and_then(default_port).ok_or(AddressError::Port)?, + }; + Ok((host.to_ascii_lowercase(), port)) +} + +/// A port from 1 to 65535, in decimal digits only. +fn parse_port(text: &str) -> Result { + if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) { + return Err(AddressError::Port); + } + match text.parse::() { + Ok(port) if port != 0 => Ok(port), + _ => Err(AddressError::Port), + } +} + +/// The port a URL of `scheme` uses when it names none. +fn default_port(scheme: &str) -> Option { + match scheme { + "http" | "ws" => Some(80), + "https" | "wss" => Some(443), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn address(text: &str) -> ForwardAddress { + parse(text).unwrap_or_else(|error| panic!("{text}: {error}")) + } + + fn target(text: &str) -> (String, u16) { + let address = address(text); + (address.target_host, address.target_port) + } + + #[test] + fn a_port_alone_is_on_the_host_loopback_interface() { + assert_eq!(target("3000"), ("localhost".into(), 3000)); + assert_eq!(target(" 8080\n"), ("localhost".into(), 8080)); + assert_eq!(target("65535"), ("localhost".into(), 65535)); + assert_eq!(parse("0"), Err(AddressError::Port)); + assert_eq!(parse("65536"), Err(AddressError::Port)); + assert_eq!(parse("99999999999999999999"), Err(AddressError::Port)); + } + + #[test] + fn host_and_port_name_addresses_and_host_names() { + assert_eq!(target("127.0.0.1:5432"), ("127.0.0.1".into(), 5432)); + assert_eq!(target("0.0.0.0:8080"), ("0.0.0.0".into(), 8080)); + assert_eq!(target("[::1]:3000"), ("::1".into(), 3000)); + assert_eq!(target("[FE80::1]:3000"), ("fe80::1".into(), 3000)); + assert_eq!(target("DB.Internal:5432"), ("db.internal".into(), 5432)); + assert_eq!(target("api_v2.local:9000"), ("api_v2.local".into(), 9000)); + // A bare IPv6 address cannot be told apart from its port. + assert_eq!(parse("::1:3000"), Err(AddressError::Host)); + assert_eq!(parse("fe80::1"), Err(AddressError::Host)); + assert_eq!(parse("[::1]3000"), Err(AddressError::Host)); + assert_eq!(parse("[127.0.0.1]:80"), Err(AddressError::Host)); + assert_eq!(parse("[::1"), Err(AddressError::Host)); + assert_eq!(parse(":3000"), Err(AddressError::Host)); + assert_eq!(parse("-oProxy:22"), Err(AddressError::Host)); + assert_eq!(parse("db%2Einternal:5432"), Err(AddressError::Host)); + // Without a scheme, a host needs its port. + assert_eq!(parse("localhost"), Err(AddressError::Port)); + assert_eq!(parse("localhost:"), Err(AddressError::Port)); + assert_eq!(parse("localhost:http"), Err(AddressError::Port)); + assert_eq!(parse("localhost:+80"), Err(AddressError::Port)); + } + + #[test] + fn urls_keep_their_scheme_and_path_and_default_the_port() { + assert_eq!( + address("http://localhost:3000/app?tab=1#top"), + ForwardAddress { + target_host: "localhost".into(), + target_port: 3000, + scheme: Some("http".into()), + path: Some("/app?tab=1#top".into()), + } + ); + assert_eq!( + address("HTTPS://Example.com"), + ForwardAddress { + target_host: "example.com".into(), + target_port: 443, + scheme: Some("https".into()), + path: None, + } + ); + assert_eq!(target("http://10.0.0.5/"), ("10.0.0.5".into(), 80)); + assert_eq!(target("ws://[::1]"), ("::1".into(), 80)); + assert_eq!(target("wss://socket.local"), ("socket.local".into(), 443)); + assert_eq!( + address("http://localhost:3000/").path, + None, + "a lone slash opens the same page as none" + ); + assert_eq!( + address("http://localhost:3000?debug").path, + Some("?debug".into()) + ); + assert_eq!( + target("postgres://db.internal:5432/app"), + ("db.internal".into(), 5432) + ); + // A scheme without a default port must name one. + assert_eq!(parse("postgres://db.internal/app"), Err(AddressError::Port)); + assert_eq!(parse("http://"), Err(AddressError::Host)); + assert_eq!(parse("http://:8080"), Err(AddressError::Host)); + assert_eq!(parse("1http://host"), Err(AddressError::Scheme)); + assert_eq!(parse("ht_tp://host"), Err(AddressError::Scheme)); + assert_eq!(parse("://host:80"), Err(AddressError::Scheme)); + } + + #[test] + fn digits_alone_are_a_port_with_or_without_a_scheme() { + assert_eq!(address("http://3000").target_port, 3000); + assert_eq!(address("http://3000").target_host, "localhost"); + assert_eq!( + address("localhost:3000/app").path, + Some("/app".into()), + "an address without a scheme keeps its path" + ); + assert_eq!(address("localhost:3000/app").scheme, None); + } + + #[test] + fn credentials_are_refused_rather_than_kept() { + assert_eq!( + parse("https://user:secret@example.com"), + Err(AddressError::Credentials) + ); + assert_eq!( + parse("postgres://user@db:5432"), + Err(AddressError::Credentials) + ); + assert_eq!(parse("user@db:5432"), Err(AddressError::Credentials)); + // An @ after the authority is part of the path. + assert_eq!( + address("http://localhost:3000/@user").path, + Some("/@user".into()) + ); + } + + #[test] + fn white_space_control_characters_and_size_are_bounded() { + assert_eq!(parse(""), Err(AddressError::Empty)); + assert_eq!(parse(" \t\n"), Err(AddressError::Empty)); + assert_eq!(parse("local host:80"), Err(AddressError::Malformed)); + assert_eq!( + parse("http://localhost:80/a b"), + Err(AddressError::Malformed) + ); + assert_eq!(parse("localhost:80\u{7}"), Err(AddressError::Malformed)); + let long = format!("http://localhost:80/{}", "a".repeat(MAX_ADDRESS_BYTES)); + assert_eq!(parse(&long), Err(AddressError::TooLong)); + let scheme = format!("{}://localhost:80", "h".repeat(MAX_SCHEME_BYTES + 1)); + assert_eq!(parse(&scheme), Err(AddressError::Scheme)); + } + + #[test] + fn reasons_are_distinct() { + let reasons = [ + AddressError::Empty, + AddressError::TooLong, + AddressError::Malformed, + AddressError::Scheme, + AddressError::Credentials, + AddressError::Host, + AddressError::Port, + ] + .map(AddressError::reason); + let mut unique = reasons.to_vec(); + unique.sort_unstable(); + unique.dedup(); + assert_eq!(unique.len(), reasons.len()); + } +} diff --git a/rust/crates/remote/src/client/forward_set.rs b/rust/crates/remote/src/client/forward_set.rs index 0cc280ad..a4886621 100644 --- a/rust/crates/remote/src/client/forward_set.rs +++ b/rust/crates/remote/src/client/forward_set.rs @@ -400,6 +400,12 @@ fn is_host_name(host: &str) -> bool { .all(|byte| byte.is_ascii_alphanumeric() || b"-_.".contains(&byte)) } +/// True for a host a forward can target: an IP address, IPv6 in brackets or +/// not, or a host name. +pub(crate) fn is_target_host(host: &str) -> bool { + TargetHost::parse(host).is_ok() +} + /// 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 c2466767..81c0e6d3 100644 --- a/rust/crates/remote/src/client/mod.rs +++ b/rust/crates/remote/src/client/mod.rs @@ -13,6 +13,8 @@ //! routes each resource's events to its subscriber. //! - [`api`] offers typed operations and resource handles on a session. //! - [`forward`] forwards local ports through tunnels. +//! - [`forward_address`] reads the addresses typed into the ports page: +//! ports, `host:port` and URLs. //! - [`forward_set`] keeps the forwards of one session for the ports page, //! confirms targets outside the host and releases them with the session. //! - [`connection_log`] records one connection's lifecycle in the v2 log, @@ -38,6 +40,7 @@ mod command; pub mod connection_log; pub mod connections; pub mod forward; +pub mod forward_address; pub mod forward_set; pub mod launch; #[cfg(feature = "motty")] @@ -52,6 +55,7 @@ pub use api::{SpawnSpec, TerminalSpec, WriteOptions}; pub use bootstrap::{ArtifactError, ServerArtifact, ServerTarget}; pub use connection_log::{ConnectionKind, ConnectionLog}; pub use forward::PortForward; +pub use forward_address::{AddressError, ForwardAddress}; pub use forward_set::{ForwardError, ForwardInfo, ForwardSet, ForwardSpec, TargetField}; pub use session::{ClientError, ConnectOptions, Event, RemoteSession, ResumeMode}; pub use transport::{ContainerEngine, ContainerHop, Hop, SshHop, TransportChain, TransportError}; diff --git a/rust/crates/workspace/src/forwards.rs b/rust/crates/workspace/src/forwards.rs index 5ea77ac4..d4925140 100644 --- a/rust/crates/workspace/src/forwards.rs +++ b/rust/crates/workspace/src/forwards.rs @@ -1,5 +1,7 @@ //! `remote.startForward`, `remote.stopForward` and `remote.forwards`: the //! port forwards of one open connection, as the ports page manages them. +//! `remote.parseForwardAddress` reads what the user typed into the page, a +//! port, `host:port` or a URL, without a connection. //! //! Each connection owns its forwards. Closing the connection, or losing it, //! closes every local port it opened (design S29). Which targets need the @@ -11,7 +13,9 @@ use crate::sessions::{forget, lookup, Connection}; use lithe_protocol::{CoreError, ErrorCode}; use lithe_remote::client::forward_set::MAX_FORWARDS; -use lithe_remote::client::{ForwardError, ForwardInfo, ForwardSpec, TargetField}; +use lithe_remote::client::{ + forward_address, ForwardAddress, ForwardError, ForwardInfo, ForwardSpec, TargetField, +}; use serde::{Deserialize, Serialize}; use serde_json::json; use std::sync::Arc; @@ -33,6 +37,13 @@ pub struct StartRequest { allow_non_loopback_target: bool, } +/// `remote.parseForwardAddress`: an address typed into the ports page. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct AddressRequest { + text: String, +} + /// `remote.stopForward`. #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -90,6 +101,15 @@ pub fn start(request: StartRequest) -> Result { Ok(Started { forward, created }) } +/// Reads an address typed into the ports page into the target of a forward. +/// Nothing is resolved or contacted. +pub fn parse_address(request: AddressRequest) -> Result { + forward_address::parse(&request.text).map_err(|error| { + CoreError::new(ErrorCode::InvalidRequest, "Invalid port forward address") + .with_details(json!({ "field": "text", "reason": error.reason() }).to_string()) + }) +} + /// Stops one forward and closes its local port. pub fn stop(request: StopRequest) -> Result { let connection = open(&request.session_id)?;