Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion rust/contracts/application-boundary.md
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,9 @@ meaning; `lithe_protocol::ErrorCode` documents when it is reported:
- `encoding_unmappable`
- `cancelled`
- `timed_out`
- `connection_closed`
- `connection_closed`: the remote connection the request names closed or was lost
- `forward_target_not_confirmed`: a port forward reaches another machine through the remote host and the user has not confirmed it
- `forward_limit_reached`: the remote connection keeps the most port forwards it allows
- `remote_server_invalid`: the server build `remote.connect` would send cannot
be read or is not the build its SHA-256 names
- `unknown`
Expand Down
2 changes: 1 addition & 1 deletion rust/contracts/remote-workspace-protocol-v1.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ subscribe before creating the resource.
| `tunnel.write` | `tunnelId`, `data` | `null`; `BUSY` when the peer stops reading |
| `tunnel.shutdownWrite` | `tunnelId` | `null`; queued data is sent, then the write side is shut down; replies keep arriving |
| `tunnel.close` | `tunnelId` | `null`; aborts both directions, queued data is discarded |
| `ports.listening` | — | sorted `ports` (`address`, `port`) |
| `ports.listening` | — | `ports` sorted by `address` and `port`, one entry for each: `address`, `port`, and `pid` and `process` (the command name) when the server's user can inspect the owning process |

`fs.copy` refuses, with `INVALID_REQUEST`, to copy a file onto itself —
directly, through a symbolic link in either direction or onto a hard link —
Expand Down
50 changes: 50 additions & 0 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -816,6 +816,9 @@ or removing a command fails until the table changes in the same commit.
| `remote.hostInfo` | Return cached handshake capabilities of one connection |
| `remote.workspaceTrust` | Read remote workspace trust decisions and one open workspace's trust |
| `remote.editWorkspaceTrust` | Record or remove one remote workspace trust decision |
| `remote.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.connections` | Read the SSH connections the user saved |
| `remote.editConnections` | Save, remove or record a folder on one saved SSH connection |
| `git.historyRewritePreview` | Review undo, message edit, squash, or drop with complete messages, eligibility, and an immutable checkout expectation |
Expand Down Expand Up @@ -5859,6 +5862,53 @@ persistent disconnect retains them until explicit release, shutdown or idle expi
Forced server termination recovery remains unsupported, rather than risking
deletion of inputs used by surviving processes.

#### Remote port forwards

The ports page forwards a local port to a TCP port as the remote host sees
it. It lists candidates with `remote.hostRequest` and `ports.listening`
(`{ ports: [{ address, port, pid?, process? }] }`, one entry for each address
and port; `pid` and `process` only when the server's user can inspect the
owning process). Forwards belong to one connection:

| Command | Request | Result |
| --- | --- | --- |
| `remote.startForward` | `{ sessionId, targetHost, targetPort, localPort?, allowNonLoopbackTarget? }` | `{ forward, created }` |
| `remote.stopForward` | `{ sessionId, forwardId }` | `{ stopped }` |
| `remote.forwards` | `{ sessionId }` | `{ forwards }`, by `id` |

A forward is `{ id, localHost, localPort, requestedLocalPort?,
localPortChanged, targetHost, targetPort, loopbackTarget, connections }`.

- **Target.** `targetHost` is an IP address (IPv6 with or without brackets)
or a host name the remote host resolves, such as `localhost`. A wildcard
address (`0.0.0.0`, `::`), as `ports.listening` reports a program that
listens on every interface, becomes the host's loopback address of the
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`).
- **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
user confirmed that target. Without it the request fails with
`forward_target_not_confirmed` and nothing starts. `loopbackTarget` tells
the two apart in the list.
- **Local port.** The forward listens on `127.0.0.1`. `localPort` (absent or
`0` for a free one) is used when no local program accepts connections on
it, on `127.0.0.1` or `::1`; otherwise the forward listens on a free port,
`requestedLocalPort` keeps the asked one and `localPortChanged` is `true`.
A local port that cannot be opened at all is `unknown` with
`details.io`.
- **Once per target.** Starting a target that already has a forward returns
that forward with `created: false`, so a repeated click opens no second
local port. A connection keeps at most 64 forwards; one more is
`forward_limit_reached` with `details.maximum`.
- **Lifetime.** `remote.stopForward` closes the local port; connections it
already accepted run until either side closes them, and an unknown id
returns `stopped: false`. `remote.disconnect`, `remote.closeAll` and a
lost connection close every local port of the connection. Requests on a
connection whose session ended are `connection_closed` and forget it, as
for the other commands. `connections` counts accepted local connections.

#### Remote workspace trust

A remote workspace is trusted, kept in safe mode or undecided, as a local
Expand Down
10 changes: 10 additions & 0 deletions rust/crates/core/src/protocol/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1009,6 +1009,13 @@ pub enum RemoteCommand {
/// Records or removes one remote workspace trust decision
/// (`remote.editWorkspaceTrust`).
EditWorkspaceTrust,
/// Forwards a local port to a port as the remote host sees it
/// (`remote.startForward`).
StartForward,
/// Stops one port forward and closes its local port (`remote.stopForward`).
StopForward,
/// Lists the running port forwards of one connection (`remote.forwards`).
Forwards,
/// Reads the SSH connections the user saved (`remote.connections`).
Connections,
/// Saves, removes or records a folder on one saved SSH connection
Expand Down Expand Up @@ -1578,6 +1585,9 @@ impl CoreCommand {
"remote.hostInfo" => Some(Self::Remote(RemoteCommand::HostInfo)),
"remote.workspaceTrust" => Some(Self::Remote(RemoteCommand::WorkspaceTrust)),
"remote.editWorkspaceTrust" => Some(Self::Remote(RemoteCommand::EditWorkspaceTrust)),
"remote.startForward" => Some(Self::Remote(RemoteCommand::StartForward)),
"remote.stopForward" => Some(Self::Remote(RemoteCommand::StopForward)),
"remote.forwards" => Some(Self::Remote(RemoteCommand::Forwards)),
"remote.connections" => Some(Self::Remote(RemoteCommand::Connections)),
"remote.editConnections" => Some(Self::Remote(RemoteCommand::EditConnections)),
"git.historyRewritePreview" => Some(Self::Git(GitCommand::HistoryRewritePreview)),
Expand Down
45 changes: 44 additions & 1 deletion rust/crates/core/src/runtime/dispatcher/remote.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
//! `remote.*` commands: probing, authentication, connections, files and processes.
//! `remote.*` commands: probing, authentication, connections, files,
//! processes and port forwards.

use crate::protocol::{CoreError, CoreResponse, ErrorCode, RemoteCommand};
use serde_json::{json, Value};
Expand Down Expand Up @@ -166,6 +167,42 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option<String>, payload: Valu
Err(error) => CoreResponse::failure(id, error),
}
}
RemoteCommand::StartForward => {
match serde_json::from_value(payload)
.map_err(|error| invalid_forward_request(&error))
.and_then(lithe_workspace::forwards::start)
{
Ok(started) => CoreResponse::success(
id,
serde_json::to_value(started).expect("port forward result should encode"),
),
Err(error) => CoreResponse::failure(id, error),
}
}
RemoteCommand::StopForward => {
match serde_json::from_value(payload)
.map_err(|error| invalid_forward_request(&error))
.and_then(lithe_workspace::forwards::stop)
{
Ok(stopped) => CoreResponse::success(
id,
serde_json::to_value(stopped).expect("port forward result should encode"),
),
Err(error) => CoreResponse::failure(id, error),
}
}
RemoteCommand::Forwards => {
match serde_json::from_value(payload)
.map_err(|error| invalid_forward_request(&error))
.and_then(lithe_workspace::forwards::list)
{
Ok(forwards) => CoreResponse::success(
id,
serde_json::to_value(forwards).expect("port forward list should encode"),
),
Err(error) => CoreResponse::failure(id, error),
}
}
RemoteCommand::Connections => {
match serde_json::from_value(payload)
.map_err(|error| {
Expand Down Expand Up @@ -239,3 +276,9 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option<String>, payload: Valu
}
}
}

/// 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())
}
4 changes: 4 additions & 0 deletions rust/crates/core/src/runtime/request_trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,8 @@ pub(crate) fn is_hot(method: &str) -> bool {
// and active runs probe their process tree's listening ports periodically.
|| method == "processMemory.summarize"
|| method == "process.listeningPorts"
// The ports page refreshes its forwards' connection counts while shown.
|| method == "remote.forwards"
}

/// Explicit host provenance wins; Git provenance covers hosts that send only that.
Expand Down Expand Up @@ -278,6 +280,7 @@ mod tests {
"debug.transport.handle",
"processMemory.summarize",
"process.listeningPorts",
"remote.forwards",
] {
assert!(is_hot(method), "{method}");
}
Expand All @@ -288,6 +291,7 @@ mod tests {
"file.write",
"lsp.startServer",
"remote.connect",
"remote.startForward",
"debug.launch",
] {
assert!(!is_hot(method), "{method}");
Expand Down
159 changes: 159 additions & 0 deletions rust/crates/core/src/tests/remote_sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1248,3 +1248,162 @@ fn remote_workspace_trust_keys_the_host_real_path_on_the_connected_target() {
"unknown"
);
}

// The ports page: a forward reaches a program listening on the host's
// wildcard address, a second click returns the same forward, a target on
// another machine waits for the user's confirmation, and every failure keeps
// its own category.
#[test]
fn remote_port_forwards_start_once_per_target_and_end_with_the_connection() {
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};

let host = HostFixture::new();
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let echo = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
stream.set_read_timeout(Some(STEP)).unwrap();
let mut buffer = [0_u8; 5];
stream.read_exact(&mut buffer).unwrap();
stream.write_all(&buffer).unwrap();
});
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 start = |payload: Value| {
let mut payload = payload;
payload["sessionId"] = json!(host.id);
call("remote.startForward", payload)
};

let started = ok(start(json!({"targetHost": "0.0.0.0", "targetPort": port})));
assert_eq!(started["created"], true, "{started}");
let forward = started["forward"].clone();
assert_eq!(forward["targetHost"], "127.0.0.1", "{started}");
assert_eq!(forward["loopbackTarget"], true, "{started}");
assert_eq!(forward["localHost"], "127.0.0.1", "{started}");
assert_eq!(forward["localPortChanged"], false, "{started}");
assert!(forward.get("requestedLocalPort").is_none(), "{started}");
// The wildcard and the loopback address name one target.
let again = ok(start(
json!({"targetHost": "127.0.0.1", "targetPort": port}),
));
assert_eq!(again["created"], false, "{again}");
assert_eq!(again["forward"]["id"], forward["id"], "{again}");

let local_port = u16::try_from(forward["localPort"].as_u64().unwrap()).unwrap();
let mut local = TcpStream::connect(("127.0.0.1", local_port)).unwrap();
local.set_read_timeout(Some(STEP)).unwrap();
local.write_all(b"ports").unwrap();
let mut answer = [0_u8; 5];
local.read_exact(&mut answer).unwrap();
assert_eq!(&answer, b"ports");
drop(local);
echo.join().unwrap();

let listed = ok(call("remote.forwards", json!({"sessionId": host.id})));
assert_eq!(listed["forwards"].as_array().unwrap().len(), 1, "{listed}");
assert_eq!(listed["forwards"][0]["id"], forward["id"], "{listed}");

// A database on the host's network starts only once confirmed.
let elsewhere = json!({"targetHost": "192.0.2.10", "targetPort": 5432});
assert_eq!(
error(start(elsewhere.clone()))["code"],
"forward_target_not_confirmed"
);
let mut confirmed = elsewhere;
confirmed["allowNonLoopbackTarget"] = json!(true);
let outside = ok(start(confirmed));
assert_eq!(outside["forward"]["loopbackTarget"], false, "{outside}");

for (payload, field) in [
(
json!({"targetHost": "127.0.0.1", "targetPort": 0}),
"targetPort",
),
(
json!({"targetHost": "-oProxyCommand", "targetPort": 22}),
"targetHost",
),
] {
let refused = error(start(payload));
assert_eq!(refused["code"], "invalid_request", "{refused}");
let details: Value = serde_json::from_str(refused["details"].as_str().unwrap()).unwrap();
assert_eq!(details["field"], field, "{refused}");
}
assert_eq!(
error(start(
json!({"targetHost": "127.0.0.1", "targetPort": 70_000})
))["code"],
"invalid_request"
);

// The connection keeps a bounded number of forwards; a target that
// already has one still answers at the limit.
let running = ok(call("remote.forwards", json!({"sessionId": host.id})))["forwards"]
.as_array()
.unwrap()
.len();
let limit = lithe_remote::client::forward_set::MAX_FORWARDS;
for target in (1..).filter(|target| *target != port).take(limit - running) {
ok(start(
json!({"targetHost": "127.0.0.1", "targetPort": target}),
));
}
let full = error(start(json!({"targetHost": "::1", "targetPort": 1})));
assert_eq!(full["code"], "forward_limit_reached", "{full}");
let details: Value = serde_json::from_str(full["details"].as_str().unwrap()).unwrap();
assert_eq!(details["maximum"], limit, "{full}");
assert_eq!(
ok(start(
json!({"targetHost": "127.0.0.1", "targetPort": port})
))["created"],
false
);

let stop = |forward_id: &Value| {
call(
"remote.stopForward",
json!({"sessionId": host.id, "forwardId": forward_id}),
)
};
assert_eq!(ok(stop(&forward["id"]))["stopped"], true);
assert_eq!(ok(stop(&forward["id"]))["stopped"], false);
assert_eq!(
error(call(
"remote.forwards",
json!({"sessionId": test_support::unique_id()})
))["code"],
"connection_closed"
);

// A connection whose session ended released its forwards and is
// forgotten, so the ports page reconnects instead of listing nothing.
test_support::drop_link(&host.id);
for _ in 0..2 {
assert_eq!(
error(call("remote.forwards", json!({"sessionId": host.id})))["code"],
"connection_closed"
);
}
assert_eq!(
error(start(
json!({"targetHost": "127.0.0.1", "targetPort": port})
))["code"],
"connection_closed"
);
}
8 changes: 8 additions & 0 deletions rust/crates/protocol/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ pub enum ErrorCode {
/// A long-lived connection the request names is closed or was lost; the
/// caller can reconnect and retry.
ConnectionClosed,
/// `remote.startForward` names a target outside the remote host's
/// loopback interface without `allowNonLoopbackTarget`. Nothing started;
/// the caller asks the user to confirm that target and repeats the
/// request with the flag.
ForwardTargetNotConfirmed,
/// `remote.startForward` found the connection at its forward limit
/// (`details.maximum`); stopping a forward makes room.
ForwardLimitReached,
/// `remote.connect` reached a host whose server build the request names,
/// but the local file could not be read or its SHA-256 is not the one the
/// request gives for it. Nothing was installed on the host; the
Expand Down
Loading
Loading