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
6 changes: 6 additions & 0 deletions rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,9 @@ strip = true
lto = true
codegen-units = 1
opt-level = "s"

# Unoptimized SHA-256 needs over a second for the 40 MB debug remote server,
# which hashes itself in both its proxy and its daemon. On a busy machine that
# alone outlasted the tests' handshake bound; optimized, it takes milliseconds.
[profile.dev.package.sha2]
opt-level = 3
7 changes: 6 additions & 1 deletion rust/contracts/remote-workspace-protocol-v1.md
Original file line number Diff line number Diff line change
Expand Up @@ -279,13 +279,18 @@ connection with the same key starts a fresh session.
## Host capabilities

`server.hello` returns `host` with `os` (`linux` / `macos`), `arch`
(`x86_64` / `aarch64`), `hostName`, `userName`, `homeDirectory`,
(`x86_64` / `aarch64`), `hostName`, `userName`, `userId`, `homeDirectory`,
`defaultShell`, `pathSeparator`, `process.orphanProtection`
(`parentDeathSignal` / `serverShutdown`), `watch.backend`
(`inotify` / `fsevents`), `watch.directoryLimit` and the sorted `features`
list. Clients branch on these facts, never on `os` alone, and check
`features` before calling optional methods.

`userName` comes from the server's environment when it is set, so it is for
display only. `userId` is the numeric account from the kernel; clients key
per-account state, such as workspace trust, by it. Servers that predate it omit
the field.

## Error codes

`PROTOCOL_MISMATCH`, `INVALID_SESSION_TOKEN`, `INVALID_REQUEST`,
Expand Down
75 changes: 75 additions & 0 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -814,6 +814,8 @@ or removing a command fails until the table changes in the same commit.
| `remote.runWatch` | Own a host watch and relays changes until cancellation or root removal |
| `remote.uploadFile` | Stream a native source into integrity-checked host file staging |
| `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 |
| `git.historyRewritePreview` | Review undo, message edit, squash, or drop with complete messages, eligibility, and an immutable checkout expectation |
| `git.remotes` | Return configured fetch remote names and URLs |
| `git.tags` | Return tag names, tag object IDs, target IDs, dates, and annotations |
Expand Down Expand Up @@ -5754,6 +5756,79 @@ 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 workspace trust

A remote workspace is trusted, kept in safe mode or undecided, as a local
one is (see "Global SDK registrations without an open project"), but its
decisions are separate and never carry over. They are keyed by the
connection's **target** and the workspace's **real path** on the host:

- The target is `{ hops, userId? }`. Each hop keeps only what chooses where
it ends: `{ ssh: { destination, port?, portOption?, user?, proxyJump? } }`
(the first `Port`, `User` and `ProxyJump` options, as ssh uses them) or
`{ container: { engine, program, container, user? } }`. Keys, timeouts,
keep-alive, working directories and environment are not part of it.
`userId` is the server's numeric account from `server.hello`. Targets match
exactly: another host, account, port, route or container asks again, and so
does a spelling that may reach the same account, such as `dev@box` against
`box` with `User=dev`.
- The real path is the host's `fs.realPath` of the workspace root, so a
symbolic link opens the decision of the folder it points to.
- Local workspaces never inherit remote decisions and the reverse; a
"trust every workspace" setting applies to local workspaces only.

`remote.workspaceTrust` accepts `{ document: string|null, sessionId?,
workspace? }`; `sessionId` and `workspace` (an absolute host path as opened)
come together. It returns `{ document, storage: { relativePath:
"toolchains/remote-trust.json", maximumBytes: 262144 }, projectCodeAllowed?,
workspaceTrust? }`, where `document` is the validated
`{ version: 1, targets: [{ target, label?, trustedWorkspaces?,
distrustedWorkspaces?, trustedLocations? }] }`, sorted by target. With a
workspace, `workspaceTrust` is `{ state, workspace, location, offeredLocation,
target }` and `projectCodeAllowed` is `state == "trusted"`. As for local
workspaces, an explicit decision applies first, then a trusted location of
the same target containing the real path. `offeredLocation` is the parent
folder, or `null` when that is `/`: a host's root is never offered and never
accepted as a location.

`remote.editWorkspaceTrust` accepts `{ document, decision }` or
`{ document, revoke }`:

- `decision: { sessionId, workspace, trusted, location?, label? }` resolves
the target and the real path over the session, like `remote.workspaceTrust`,
and records one decision: `trusted: true` moves the workspace to
`trustedWorkspaces`, `false` to `distrustedWorkspaces`, and `location: true`
also adds `offeredLocation` to `trustedLocations`. `location` with
`trusted: false`, or without an offered location, is rejected. `label` is
the connection name shown with the target's decisions (at most 128
characters, no control characters); it never affects matching.
- `revoke: { target, list, path }` removes one entry, where `list` is
`trustedWorkspaces`, `distrustedWorkspaces` or `trustedLocations`, and works
without a connection to the target. A target without entries is dropped;
removing an absent entry changes nothing.

The result is `{ changed, document: string|null, decisions }`. An unchanged
edit returns a `null` document and must not create a source. There is no
operation that trusts every remote workspace or host.

Bounds: 256 KiB per document, 64 targets, 256 entries per list, 8 hops, and
normalized absolute host paths of at most 4096 bytes (no empty, `.` or `..`
component, no trailing `/`). A document that cannot be decoded, has duplicate
keys, unknown fields, another version, a target listed twice, the same path
trusted and distrusted, or `/` as a location is `parse_failed` with
`details.field`; a malformed request, a refused decision 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, never on the host, in a workspace or in an installed package: a
marker on the host could be written by the project or other users. They retain
the exact bytes, verify them before atomic publication and reread after Save,
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.

### Git patch discovery and rebase amendment preconditions

`git.patchExport` accepts optional `metadataOnly` (default false). In metadata
Expand Down
8 changes: 8 additions & 0 deletions rust/crates/core/src/protocol/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1003,6 +1003,12 @@ pub enum RemoteCommand {
UploadFile,
/// Returns cached handshake capabilities of one connection.
HostInfo,
/// Reads remote workspace trust decisions, and one open workspace's
/// trust (`remote.workspaceTrust`).
WorkspaceTrust,
/// Records or removes one remote workspace trust decision
/// (`remote.editWorkspaceTrust`).
EditWorkspaceTrust,
}

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -1565,6 +1571,8 @@ impl CoreCommand {
"remote.runWatch" => Some(Self::Remote(RemoteCommand::RunWatch)),
"remote.uploadFile" => Some(Self::Remote(RemoteCommand::UploadFile)),
"remote.hostInfo" => Some(Self::Remote(RemoteCommand::HostInfo)),
"remote.workspaceTrust" => Some(Self::Remote(RemoteCommand::WorkspaceTrust)),
"remote.editWorkspaceTrust" => Some(Self::Remote(RemoteCommand::EditWorkspaceTrust)),
"git.historyRewritePreview" => Some(Self::Git(GitCommand::HistoryRewritePreview)),
"git.remotes" => Some(Self::Git(GitCommand::Remotes)),
"git.tags" => Some(Self::Git(GitCommand::Tags)),
Expand Down
30 changes: 30 additions & 0 deletions rust/crates/core/src/runtime/dispatcher/remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,36 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option<String>, payload: Valu
Err(error) => CoreResponse::failure(id, error),
}
}
RemoteCommand::WorkspaceTrust => {
match serde_json::from_value(payload)
.map_err(|error| {
CoreError::new(
ErrorCode::InvalidRequest,
"Invalid remote workspace trust request",
)
.with_details(error.to_string())
})
.and_then(lithe_workspace::trust::state)
{
Ok(value) => CoreResponse::success(id, value),
Err(error) => CoreResponse::failure(id, error),
}
}
RemoteCommand::EditWorkspaceTrust => {
match serde_json::from_value(payload)
.map_err(|error| {
CoreError::new(
ErrorCode::InvalidRequest,
"Invalid remote workspace trust request",
)
.with_details(error.to_string())
})
.and_then(lithe_workspace::trust::edit)
{
Ok(value) => CoreResponse::success(id, value),
Err(error) => CoreResponse::failure(id, error),
}
}
RemoteCommand::Disconnect => {
match serde_json::from_value::<lithe_workspace::sessions::DisconnectRequest>(payload) {
Ok(request) => CoreResponse::success(
Expand Down
140 changes: 140 additions & 0 deletions rust/crates/core/src/tests/remote_sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1108,3 +1108,143 @@ fn plugin_protocol_maps_owned_uris_without_rewriting_source_text() {
assert_eq!(mapped["params"]["paths"], request["params"]["paths"]);
assert_eq!(mapped["params"]["uri"], local);
}

#[test]
fn remote_workspace_trust_keys_the_host_real_path_on_the_connected_target() {
use std::os::unix::fs::MetadataExt;
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();
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 code = |response: Value| -> Value {
assert_eq!(response["ok"], false, "{response}");
response["error"]["code"].clone()
};
let state = |document: &Value, workspace: &std::path::Path| {
call(
"remote.workspaceTrust",
json!({"document": document, "sessionId": host.id, "workspace": workspace}),
)
};
let decide = |document: &Value, decision: Value| {
call(
"remote.editWorkspaceTrust",
json!({"document": document, "decision": decision}),
)
};
let real = json!(project);

// A link opens the decision of the folder it points to, on this target.
let unknown = ok(state(&Value::Null, &link));
assert_eq!(
unknown["storage"],
json!({"relativePath": "toolchains/remote-trust.json", "maximumBytes": 262_144})
);
assert_eq!(unknown["projectCodeAllowed"], false, "{unknown}");
let trust = &unknown["workspaceTrust"];
assert_eq!(trust["state"], "unknown", "{unknown}");
assert_eq!(trust["workspace"], real, "{unknown}");
assert_eq!(
trust["offeredLocation"],
json!(host.root.join("host/projects"))
);
let target = trust["target"].clone();
let uid = std::fs::metadata(&project).unwrap().uid();
assert_eq!(target, json!({"hops": [], "userId": uid}), "{unknown}");
assert_eq!(
ok(call("remote.workspaceTrust", json!({"document": null}))),
json!({"document": {"version": 1, "targets": []}, "storage": unknown["storage"]})
);

let decision =
json!({"sessionId": host.id, "workspace": link, "trusted": true, "label": "Fixture"});
let decided = ok(decide(&Value::Null, decision.clone()));
assert_eq!(decided["changed"], true, "{decided}");
assert_eq!(
decided["decisions"]["targets"][0]["trustedWorkspaces"],
json!([real])
);
let document = decided["document"].clone();
assert!(document.is_string(), "{decided}");
let repeated = ok(decide(&document, decision));
assert_eq!(repeated["changed"], false, "{repeated}");
assert!(repeated["document"].is_null(), "{repeated}");

let trusted = ok(state(&document, &project));
assert_eq!(trusted["projectCodeAllowed"], true, "{trusted}");
assert_eq!(trusted["workspaceTrust"]["state"], "trusted");
assert_eq!(
ok(state(&document, &sibling))["workspaceTrust"]["state"],
"unknown"
);

// Each failure keeps its own category.
assert_eq!(
code(state(&document, &host.root.join("host/missing"))),
"workspace_not_found"
);
assert_eq!(
code(state(&document, std::path::Path::new("projects/app"))),
"invalid_request"
);
assert_eq!(
code(call(
"remote.workspaceTrust",
json!({"document": document, "sessionId": host.id})
)),
"invalid_request"
);
assert_eq!(
code(state(&json!("{\"version\":1,\"trustAll\":true}"), &project)),
"parse_failed"
);
assert_eq!(
code(decide(
&document,
json!({"sessionId": host.id, "workspace": project, "trusted": false, "location": true})
)),
"invalid_request"
);
assert_eq!(
code(decide(
&document,
json!({"sessionId": test_support::unique_id(), "workspace": project, "trusted": true})
)),
"connection_closed"
);
assert_eq!(
code(call(
"remote.editWorkspaceTrust",
json!({"document": document})
)),
"invalid_request"
);

// Removing an entry needs no connection to its target.
let revoked = ok(call(
"remote.editWorkspaceTrust",
json!({"document": document, "revoke": {"target": target,
"list": "trustedWorkspaces", "path": project}}),
));
assert_eq!(revoked["changed"], true, "{revoked}");
assert_eq!(revoked["decisions"]["targets"], json!([]), "{revoked}");
assert_eq!(
ok(state(&revoked["document"], &link))["workspaceTrust"]["state"],
"unknown"
);
}
3 changes: 3 additions & 0 deletions rust/crates/remote/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
//! - [`forward`] forwards local ports through tunnels.
//! - [`connection_log`] records one connection's lifecycle in the v2 log,
//! 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.
//!
//! The transport layer deliberately knows nothing about files or processes.
//! Supporting a new kind of remote means adding a hop, not new capabilities.
Expand All @@ -28,6 +30,7 @@ pub mod forward;
pub mod launch;
pub mod session;
pub mod transport;
pub mod trust;

pub use api::{SpawnSpec, TerminalSpec, WriteOptions};
pub use bootstrap::{ServerArtifact, ServerTarget};
Expand Down
Loading
Loading