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
88 changes: 87 additions & 1 deletion rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -6270,7 +6273,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.

Expand Down Expand Up @@ -6347,6 +6351,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
Expand Down
12 changes: 12 additions & 0 deletions rust/crates/core/src/protocol/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -1630,6 +1639,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)),
Expand Down
18 changes: 18 additions & 0 deletions rust/crates/core/src/runtime/dispatcher/remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,24 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option<String>, 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| {
Expand Down
1 change: 1 addition & 0 deletions rust/crates/core/src/runtime/request_trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,7 @@ mod tests {
"remote.startForward",
"remote.startHostForward",
"remote.startReverseForward",
"remote.restoreForwards",
"remote.runningPrograms",
"remote.endPrograms",
"debug.launch",
Expand Down
204 changes: 204 additions & 0 deletions rust/crates/core/src/tests/remote_sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1359,6 +1359,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::<Value>(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.
Expand Down
9 changes: 9 additions & 0 deletions rust/crates/remote/src/client/forward_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading
Loading