From 524873c6a1e79cac0f517d849cecc412a4c6605a Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 21 Nov 2026 02:34:49 +0800 Subject: [PATCH 1/3] =?UTF-8?q?feat(remote):=20=E8=BF=9C=E7=A8=8B=E5=B7=A5?= =?UTF-8?q?=E4=BD=9C=E5=8C=BA=E4=BF=A1=E4=BB=BB=E6=8C=89=E7=9B=AE=E6=A0=87?= =?UTF-8?q?=E4=B8=8E=E4=B8=BB=E6=9C=BA=E7=9C=9F=E5=AE=9E=E8=B7=AF=E5=BE=84?= =?UTF-8?q?=E8=AE=B0=E5=BD=95=EF=BC=88S01/S02/S04=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 lithe_remote::client::trust:信任键是连接目标加工作区在主机上的 真实路径。目标只保留决定落点的字段(SSH 目的地、端口、User/Port/ ProxyJump 选项,容器引擎、程序、容器名、用户,以及主机账号 uid), IdentityFile、超时、工作目录、环境变量不参与;换主机、账号、别名、端口、 跳板或容器后一律重新询问,本地信任与远程信任互不继承。 - 信任位置只覆盖本目标,永远不提供 `/`,也没有“全部信任”;同一路径不能 同时信任与不信任;决策文件有大小、目标数、条目数、跳数、字段长度上限, 重复键、未知字段、未知版本都按解析失败处理,失败时不改动任何内容。 - 新增 remote.workspaceTrust / remote.editWorkspaceTrust:Core 通过打开的 连接解析真实路径后再查或记录决策,符号链接和主机解析到别处的写法拿不到 别的工作区的决策;返回 projectCodeAllowed,供构建、运行、测试计划使用。 决策文件只存在本机用户偏好目录(toolchains/remote-trust.json),由原生 客户端原子写入,不写到主机;没有变化的编辑返回 null 文档。撤销不需要连接。 - 协议:HostCapabilities 新增 userId(内核给出的数字账号,不取环境变量), 旧服务端不返回该字段,升级后需重新确认一次。 - 为挂接连接与命令,改动超出 remote crate:workspace 的连接记录信任目标、 新增 trust 模块;core 新增两个命令与分发;rust-core-api.md 与远程协议 文档同步。 --- .../contracts/remote-workspace-protocol-v1.md | 7 +- rust/contracts/rust-core-api.md | 75 ++ rust/crates/core/src/protocol/command.rs | 8 + .../core/src/runtime/dispatcher/remote.rs | 30 + rust/crates/core/src/tests/remote_sessions.rs | 140 +++ rust/crates/remote/src/client/mod.rs | 3 + rust/crates/remote/src/client/transport.rs | 2 +- rust/crates/remote/src/client/trust.rs | 996 ++++++++++++++++++ rust/crates/remote/src/protocol/methods.rs | 4 + rust/crates/remote/src/server/platform/mod.rs | 1 + rust/crates/workspace/src/lib.rs | 6 +- rust/crates/workspace/src/sessions.rs | 8 +- rust/crates/workspace/src/test_support.rs | 8 +- rust/crates/workspace/src/trust.rs | 172 +++ 14 files changed, 1453 insertions(+), 7 deletions(-) create mode 100644 rust/crates/remote/src/client/trust.rs create mode 100644 rust/crates/workspace/src/trust.rs diff --git a/rust/contracts/remote-workspace-protocol-v1.md b/rust/contracts/remote-workspace-protocol-v1.md index c86eeecc..02008d0c 100644 --- a/rust/contracts/remote-workspace-protocol-v1.md +++ b/rust/contracts/remote-workspace-protocol-v1.md @@ -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`, diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 90b5fbc1..592aceb0 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -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 | @@ -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 diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index dc2f8820..6fedbf7a 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -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)] @@ -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)), diff --git a/rust/crates/core/src/runtime/dispatcher/remote.rs b/rust/crates/core/src/runtime/dispatcher/remote.rs index dea8adff..ae14e0c1 100644 --- a/rust/crates/core/src/runtime/dispatcher/remote.rs +++ b/rust/crates/core/src/runtime/dispatcher/remote.rs @@ -136,6 +136,36 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option, 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::(payload) { Ok(request) => CoreResponse::success( diff --git a/rust/crates/core/src/tests/remote_sessions.rs b/rust/crates/core/src/tests/remote_sessions.rs index 0ae6388c..b8a49172 100644 --- a/rust/crates/core/src/tests/remote_sessions.rs +++ b/rust/crates/core/src/tests/remote_sessions.rs @@ -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" + ); +} diff --git a/rust/crates/remote/src/client/mod.rs b/rust/crates/remote/src/client/mod.rs index bc0b6700..7418923e 100644 --- a/rust/crates/remote/src/client/mod.rs +++ b/rust/crates/remote/src/client/mod.rs @@ -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. @@ -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}; diff --git a/rust/crates/remote/src/client/transport.rs b/rust/crates/remote/src/client/transport.rs index 1492e181..0e79c5c8 100644 --- a/rust/crates/remote/src/client/transport.rs +++ b/rust/crates/remote/src/client/transport.rs @@ -143,7 +143,7 @@ pub enum ContainerEngine { } impl ContainerEngine { - fn name(self) -> &'static str { + pub(crate) fn name(self) -> &'static str { match self { Self::Docker => "docker", Self::Podman => "podman", diff --git a/rust/crates/remote/src/client/trust.rs b/rust/crates/remote/src/client/trust.rs new file mode 100644 index 00000000..3e48d5cc --- /dev/null +++ b/rust/crates/remote/src/client/trust.rs @@ -0,0 +1,996 @@ +//! Machine-local trust of remote workspaces (design S01 to S04). +//! +//! A remote workspace is trusted, kept in safe mode, or not decided yet, as a +//! local one is, but a decision never carries over to another place: +//! +//! - It is keyed by the [`Target`], the hops that reach the host and the +//! numeric account the server runs as, together with the workspace's real +//! path as the host resolves it (`fs.realPath`). Local workspaces, other +//! hosts, other accounts and other ports never inherit it, and a symbolic +//! link opens the decision of the folder it points to. +//! - It is stored only on the local machine, in the document at +//! [`STORAGE_PATH`] below the platform's user-preference directory. The host +//! keeps no marker, because project files and other users can change it. +//! - A trusted location covers the workspaces below it on its own target only, +//! and a host's root folder is never offered as one. +//! - Nothing trusts every remote location at once. +//! +//! This module validates, decides and merges. The caller resolves the target +//! and the real path over an open session, so a key is never a path the host +//! did not resolve. The platform adapter reads the document and publishes +//! edits atomically. + +use crate::client::transport::{Hop, TransportChain}; +use serde::{Deserialize, Serialize}; +use std::fmt; + +/// Document location below the platform's user-preference directory, next to +/// the trust of local workspaces in `toolchains/global.json`. +pub const STORAGE_PATH: &str = "toolchains/remote-trust.json"; + +/// Largest accepted document, in bytes. +pub const MAX_BYTES: usize = 256 * 1024; + +/// Targets with decisions. +const MAX_TARGETS: usize = 64; + +/// Entries of each list of one target, as for local workspaces. +const MAX_ENTRIES: usize = 256; + +/// Hops of one target. +const MAX_HOPS: usize = 8; + +/// Longest hop field, in bytes. +const MAX_FIELD_BYTES: usize = 1024; + +/// Longest connection name kept for display, in characters. +const MAX_LABEL_CHARS: usize = 128; + +/// Longest host path, in bytes: Linux `PATH_MAX`. +const MAX_PATH_BYTES: usize = 4096; + +/// Where a remote workspace lives, apart from its path. +/// +/// Two workspaces share decisions only when every field is equal, compared +/// exactly. Spellings that may reach the same account differently, such as +/// `dev@box` and `box` with `User=dev`, ask again instead of guessing. +#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Target { + /// The hops that choose the host, outermost first. + pub hops: Vec, + /// Numeric account the server runs as, from `server.hello`. It tells + /// apart accounts that the SSH configuration chooses without the hop + /// naming them. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub user_id: Option, +} + +/// The fields of one hop that choose where it ends. Keys, timeouts, +/// keep-alive, working directories and environment do not, so changing them +/// keeps the decisions. +#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub enum TargetHop { + /// An SSH hop. + Ssh(SshTarget), + /// An `exec` into a container. + Container(ContainerTarget), +} + +/// SSH hop fields that choose the host, the account and the route. +#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SshTarget { + /// Destination as the hop gives it: `host`, `user@host` or an alias. + pub destination: String, + /// Port passed as `-p`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub port: Option, + /// Value of the first `Port` option; ssh uses the first value of an option. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub port_option: Option, + /// Value of the first `User` option. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub user: Option, + /// Value of the first `ProxyJump` option. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub proxy_jump: Option, +} + +/// Container hop fields that choose the engine, the container and the account. +#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ContainerTarget { + /// `docker` or `podman`. + pub engine: String, + /// Engine CLI executable. Docker-compatible CLIs reach different daemons. + pub program: String, + /// Container name or id. + pub container: String, + /// `user`, `uid` or `user:group` given to `exec`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub user: Option, +} + +impl Target { + /// The target of a session opened through `chain` to a server running as + /// the numeric account `user_id`. + pub fn new(chain: &TransportChain, user_id: Option) -> Self { + let hops = chain + .hops + .iter() + .map(|hop| match hop { + Hop::Ssh(hop) => { + let option = |name: &str| { + hop.options + .iter() + .find(|(key, _)| key.eq_ignore_ascii_case(name)) + .map(|(_, value)| value.clone()) + }; + TargetHop::Ssh(SshTarget { + destination: hop.destination.clone(), + port: hop.port, + port_option: option("Port"), + user: option("User"), + proxy_jump: option("ProxyJump"), + }) + } + Hop::Container(hop) => TargetHop::Container(ContainerTarget { + engine: hop.engine.name().into(), + program: hop.program.clone(), + container: hop.container.clone(), + user: hop.user.clone(), + }), + }) + .collect(); + Self { hops, user_id } + } + + /// 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, or an unknown engine. + fn validate(&self) -> Result<(), TrustError> { + let field = |value: &str| { + !value.is_empty() + && value.len() <= MAX_FIELD_BYTES + && !value.chars().any(char::is_control) + }; + let optional = |value: &Option| value.as_deref().is_none_or(field); + let valid = self.hops.len() <= MAX_HOPS + && self.hops.iter().all(|hop| match hop { + TargetHop::Ssh(hop) => { + field(&hop.destination) + && !hop.destination.starts_with('-') + && optional(&hop.port_option) + && optional(&hop.user) + && optional(&hop.proxy_jump) + } + TargetHop::Container(hop) => { + matches!(hop.engine.as_str(), "docker" | "podman") + && field(&hop.program) + && field(&hop.container) + && optional(&hop.user) + } + }); + if valid { + Ok(()) + } else { + Err(TrustError::at("target")) + } + } +} + +/// A workspace's trust: `trusted` lets project code run, `distrusted` is a +/// recorded choice of safe mode, and `unknown` means the user was not asked. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum TrustState { + /// Project code may run. + Trusted, + /// The user chose safe mode for this workspace. + Distrusted, + /// No decision applies; the workspace stays in safe mode. + Unknown, +} + +/// The trust of one remote workspace. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceTrust { + /// The decision that applies. + pub state: TrustState, + /// The real path the decision is keyed by. + pub workspace: String, + /// The trusted location that trusts the workspace, when the state comes + /// from one. + pub location: Option, + /// The folder a trust prompt may offer to trust with the workspace: its + /// parent, unless that is the host's root. + pub offered_location: Option, +} + +/// One explicit decision on a workspace. +#[derive(Clone, Copy, Debug)] +pub struct Decision<'a> { + /// `true` lets project code run; `false` records safe mode. + pub trusted: bool, + /// Also trusts the offered location. Refused with `trusted: false` and for + /// a workspace whose parent is the host's root. + pub location: bool, + /// Connection name shown with the target's decisions; the previous name + /// stays when absent. Never part of the key. + pub label: Option<&'a str>, +} + +/// One list of a target's decisions. +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub enum List { + /// Workspaces whose project code may run. + TrustedWorkspaces, + /// Workspaces kept in safe mode. + DistrustedWorkspaces, + /// Folders whose workspaces, at any depth, are trusted unless distrusted + /// themselves. + TrustedLocations, +} + +/// Why a document, a target, a path or a decision was refused. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct TrustError { + /// The offending field, for example `document`, `workspace` or `location`. + pub field: &'static str, +} + +impl TrustError { + fn at(field: &'static str) -> Self { + Self { field } + } +} + +impl fmt::Display for TrustError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + formatter, + "invalid remote workspace trust at {}", + self.field + ) + } +} + +impl std::error::Error for TrustError {} + +/// The validated document: the decisions of every target, sorted by target. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Decisions { + version: u32, + #[serde(default)] + targets: Vec, +} + +/// Decisions on the workspaces of one target. Each list is sorted and holds +/// distinct real paths. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct TargetDecisions { + target: Target, + #[serde(default, skip_serializing_if = "Option::is_none")] + label: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + trusted_workspaces: Vec, + /// An explicit decision on a workspace wins over a location containing it. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + distrusted_workspaces: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + trusted_locations: Vec, +} + +impl TargetDecisions { + fn new(target: Target) -> Self { + Self { + target, + label: None, + trusted_workspaces: Vec::new(), + distrusted_workspaces: Vec::new(), + trusted_locations: Vec::new(), + } + } + + fn is_empty(&self) -> bool { + self.trusted_workspaces.is_empty() + && self.distrusted_workspaces.is_empty() + && self.trusted_locations.is_empty() + } + + fn list_mut(&mut self, list: List) -> &mut Vec { + match list { + List::TrustedWorkspaces => &mut self.trusted_workspaces, + List::DistrustedWorkspaces => &mut self.distrusted_workspaces, + List::TrustedLocations => &mut self.trusted_locations, + } + } + + /// Sorts the lists and refuses what a decision never records: malformed + /// or duplicate paths, oversized lists, the root as a location, and a + /// workspace that is both trusted and distrusted. + fn normalize(&mut self) -> Result<(), TrustError> { + self.target.validate()?; + if let Some(label) = &self.label { + validate_label(label)?; + } + for (list, field) in [ + (&mut self.trusted_workspaces, "trustedWorkspaces"), + (&mut self.distrusted_workspaces, "distrustedWorkspaces"), + (&mut self.trusted_locations, "trustedLocations"), + ] { + list.sort(); + let malformed = list.iter().any(|path| host_path(path).is_none()); + let duplicate = list.windows(2).any(|pair| pair[0] == pair[1]); + if list.len() > MAX_ENTRIES || malformed || duplicate { + return Err(TrustError::at(field)); + } + } + if self + .trusted_locations + .iter() + .any(|location| location == "/") + { + return Err(TrustError::at("trustedLocations")); + } + if self + .trusted_workspaces + .iter() + .any(|workspace| contains(&self.distrusted_workspaces, workspace)) + { + return Err(TrustError::at("distrustedWorkspaces")); + } + Ok(()) + } + + fn within_bounds(&self) -> Result<(), TrustError> { + for (list, field) in [ + (&self.trusted_workspaces, "trustedWorkspaces"), + (&self.distrusted_workspaces, "distrustedWorkspaces"), + (&self.trusted_locations, "trustedLocations"), + ] { + if list.len() > MAX_ENTRIES { + return Err(TrustError::at(field)); + } + } + Ok(()) + } +} + +impl Decisions { + /// Reads `document`, or the empty document when there is none yet. + /// + /// Refuses documents over [`MAX_BYTES`], malformed JSON, duplicate keys, + /// unknown fields, other versions, more than 64 targets, a target listed + /// twice, and lists a decision never records. Targets without decisions + /// are dropped. + pub fn parse(document: Option<&str>) -> Result { + let Some(text) = document else { + return Ok(Self { + version: 1, + targets: Vec::new(), + }); + }; + if text.len() > MAX_BYTES { + return Err(TrustError::at("document")); + } + let mut decisions: Self = + serde_json::from_str(text).map_err(|_| TrustError::at("document"))?; + if decisions.version != 1 { + return Err(TrustError::at("version")); + } + if decisions.targets.len() > MAX_TARGETS { + return Err(TrustError::at("targets")); + } + for entry in &mut decisions.targets { + entry.normalize()?; + } + decisions.targets.retain(|entry| !entry.is_empty()); + decisions + .targets + .sort_by(|left, right| left.target.cmp(&right.target)); + if decisions + .targets + .windows(2) + .any(|pair| pair[0].target == pair[1].target) + { + return Err(TrustError::at("targets")); + } + Ok(decisions) + } + + /// 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(|_| TrustError::at("document"))?; + text.push('\n'); + if text.len() > MAX_BYTES { + return Err(TrustError::at("document")); + } + Ok(text) + } + + /// The trust of the workspace at `real_path` on `target`, as IntelliJ IDEA + /// orders it: an explicit decision on the workspace first, then a trusted + /// location of the same target containing it. + pub fn workspace( + &self, + target: &Target, + real_path: &str, + ) -> Result { + let workspace = host_path(real_path).ok_or(TrustError::at("workspace"))?; + let (state, location) = match self.entry(target) { + Some(entry) if contains(&entry.trusted_workspaces, workspace) => { + (TrustState::Trusted, None) + } + Some(entry) if contains(&entry.distrusted_workspaces, workspace) => { + (TrustState::Distrusted, None) + } + Some(entry) => match entry + .trusted_locations + .iter() + .find(|location| within(workspace, location)) + { + Some(location) => (TrustState::Trusted, Some(location.clone())), + None => (TrustState::Unknown, None), + }, + None => (TrustState::Unknown, None), + }; + Ok(WorkspaceTrust { + state, + workspace: workspace.into(), + location, + offered_location: offered_location(workspace), + }) + } + + /// Records `decision` on the workspace at `real_path` on `target`, + /// keeping every other decision. Trusting moves the workspace out of the + /// distrusted list and safe mode moves it out of the trusted one. On an + /// error nothing changes. + pub fn decide( + &mut self, + target: &Target, + real_path: &str, + decision: Decision<'_>, + ) -> Result<(), TrustError> { + target.validate()?; + let workspace = host_path(real_path) + .ok_or(TrustError::at("workspace"))? + .to_owned(); + if let Some(label) = decision.label { + validate_label(label)?; + } + let offered = if decision.location { + if !decision.trusted { + return Err(TrustError::at("location")); + } + Some(offered_location(&workspace).ok_or(TrustError::at("location"))?) + } else { + None + }; + let position = self + .targets + .binary_search_by(|entry| entry.target.cmp(target)); + let mut entry = match position { + Ok(index) => self.targets[index].clone(), + Err(_) if self.targets.len() >= MAX_TARGETS => { + return Err(TrustError::at("targets")); + } + Err(_) => TargetDecisions::new(target.clone()), + }; + if decision.trusted { + remove(&mut entry.distrusted_workspaces, &workspace); + insert(&mut entry.trusted_workspaces, workspace); + } else { + remove(&mut entry.trusted_workspaces, &workspace); + insert(&mut entry.distrusted_workspaces, workspace); + } + if let Some(offered) = offered { + insert(&mut entry.trusted_locations, offered); + } + if let Some(label) = decision.label { + entry.label = Some(label.into()); + } + entry.within_bounds()?; + match position { + Ok(index) => self.targets[index] = entry, + Err(index) => self.targets.insert(index, entry), + } + Ok(()) + } + + /// Removes `path` from one list of `target`'s decisions, and the target + /// once it has none left. Removing an absent entry changes nothing. + pub fn revoke(&mut self, target: &Target, list: List, path: &str) -> Result<(), TrustError> { + target.validate()?; + let path = host_path(path).ok_or(TrustError::at("path"))?; + if let Ok(index) = self + .targets + .binary_search_by(|entry| entry.target.cmp(target)) + { + let entry = &mut self.targets[index]; + remove(entry.list_mut(list), path); + if entry.is_empty() { + self.targets.remove(index); + } + } + Ok(()) + } + + fn entry(&self, target: &Target) -> Option<&TargetDecisions> { + self.targets + .binary_search_by(|entry| entry.target.cmp(target)) + .ok() + .map(|index| &self.targets[index]) + } +} + +/// `path` when it is an absolute, normalized host path, the form of an +/// `fs.realPath` result: it starts with `/`, has no empty, `.` or `..` +/// component, ends without `/` unless it is `/`, contains no NUL and is at +/// most 4096 bytes long. +pub fn host_path(path: &str) -> Option<&str> { + let normalized = path.len() <= MAX_PATH_BYTES + && !path.contains('\0') + && (path == "/" + || path.strip_prefix('/').is_some_and(|rest| { + rest.split('/') + .all(|component| !component.is_empty() && component != "." && component != "..") + })); + normalized.then_some(path) +} + +/// Whether `workspace` is `location` or below it. +fn within(workspace: &str, location: &str) -> bool { + workspace + .strip_prefix(location) + .is_some_and(|rest| rest.is_empty() || rest.starts_with('/')) +} + +/// The parent of `workspace`, unless that is the host's root, which would +/// trust every project on the host. +fn offered_location(workspace: &str) -> Option { + let (parent, _) = workspace.rsplit_once('/')?; + (!parent.is_empty()).then(|| parent.to_owned()) +} + +fn validate_label(label: &str) -> Result<(), TrustError> { + let valid = !label.is_empty() + && label.chars().count() <= MAX_LABEL_CHARS + && !label.chars().any(char::is_control); + if valid { + Ok(()) + } else { + Err(TrustError::at("label")) + } +} + +fn contains(list: &[String], path: &str) -> bool { + list.binary_search_by(|entry| entry.as_str().cmp(path)) + .is_ok() +} + +fn insert(list: &mut Vec, path: String) { + if let Err(index) = list.binary_search(&path) { + list.insert(index, path); + } +} + +fn remove(list: &mut Vec, path: &str) { + if let Ok(index) = list.binary_search_by(|entry| entry.as_str().cmp(path)) { + list.remove(index); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::client::transport::{ContainerEngine, ContainerHop, SshHop}; + use serde_json::json; + + fn ssh(destination: &str) -> SshHop { + SshHop::new(destination) + } + + fn target(hops: Vec, user_id: Option) -> Target { + Target::new(&TransportChain::new(hops), user_id) + } + + fn devbox() -> Target { + target(vec![Hop::Ssh(ssh("dev@box"))], Some(1000)) + } + + fn trust(decisions: &mut Decisions, target: &Target, path: &str, location: bool) { + decisions + .decide( + target, + path, + Decision { + trusted: true, + location, + label: Some("Dev box"), + }, + ) + .unwrap(); + } + + fn state(decisions: &Decisions, target: &Target, path: &str) -> TrustState { + decisions.workspace(target, path).unwrap().state + } + + #[test] + fn decisions_never_carry_over_between_hosts_accounts_ports_or_containers() { + let mut decisions = Decisions::parse(None).unwrap(); + trust(&mut decisions, &devbox(), "/home/dev/app", false); + assert_eq!( + state(&decisions, &devbox(), "/home/dev/app"), + TrustState::Trusted + ); + + let with_port = SshHop { + port: Some(2222), + ..ssh("dev@box") + }; + let option = |name: &str, value: &str| SshHop { + options: vec![(name.into(), value.into())], + ..ssh("dev@box") + }; + let others = [ + target(vec![Hop::Ssh(ssh("dev@other"))], Some(1000)), + target(vec![Hop::Ssh(ssh("ops@box"))], Some(1000)), + target(vec![Hop::Ssh(ssh("box"))], Some(1000)), + target(vec![Hop::Ssh(with_port)], Some(1000)), + target(vec![Hop::Ssh(option("Port", "2222"))], Some(1000)), + target(vec![Hop::Ssh(option("User", "root"))], Some(1000)), + target(vec![Hop::Ssh(option("ProxyJump", "bastion"))], Some(1000)), + target(vec![Hop::Ssh(ssh("dev@box"))], Some(0)), + target(vec![Hop::Ssh(ssh("dev@box"))], None), + target( + vec![ + Hop::Ssh(ssh("dev@box")), + Hop::Container(ContainerHop::new(ContainerEngine::Docker, "api")), + ], + Some(1000), + ), + target(Vec::new(), Some(1000)), + ]; + for other in &others { + assert_ne!(other, &devbox()); + assert_eq!( + state(&decisions, other, "/home/dev/app"), + TrustState::Unknown, + "{other:?}" + ); + } + assert_eq!( + state(&decisions, &devbox(), "/home/dev/other"), + TrustState::Unknown + ); + } + + #[test] + fn targets_keep_only_the_fields_that_choose_where_a_hop_ends() { + let hop = SshHop { + program: "/opt/ssh".into(), + port: Some(22), + options: vec![ + ("ConnectTimeout".into(), "5".into()), + ("user".into(), "dev".into()), + ("User".into(), "root".into()), + ("IdentityFile".into(), "~/.ssh/id".into()), + ], + ..ssh("box") + }; + let mut container = ContainerHop::new(ContainerEngine::Podman, "api"); + container.user = Some("1000:1000".into()); + container.working_directory = Some("/srv".into()); + container + .environment + .insert("TOKEN".into(), "secret".into()); + let built = target(vec![Hop::Ssh(hop), Hop::Container(container)], Some(7)); + assert_eq!( + serde_json::to_value(&built).unwrap(), + json!({ + "hops": [ + {"ssh": {"destination": "box", "port": 22, "user": "dev"}}, + {"container": {"engine": "podman", "program": "podman", "container": "api", "user": "1000:1000"}} + ], + "userId": 7 + }) + ); + + let keep_alive = SshHop { + options: vec![("ServerAliveInterval".into(), "30".into())], + ..ssh("dev@box") + }; + assert_eq!(target(vec![Hop::Ssh(keep_alive)], Some(1000)), devbox()); + } + + #[test] + fn a_trusted_location_covers_its_own_target_only_and_never_the_host_root() { + let mut decisions = Decisions::parse(None).unwrap(); + trust(&mut decisions, &devbox(), "/srv/projects/app", true); + let deep = decisions + .workspace(&devbox(), "/srv/projects/other/service") + .unwrap(); + assert_eq!(deep.state, TrustState::Trusted); + assert_eq!(deep.location.as_deref(), Some("/srv/projects")); + assert_eq!( + deep.offered_location.as_deref(), + Some("/srv/projects/other") + ); + assert_eq!( + state(&decisions, &devbox(), "/srv/projects-old/app"), + TrustState::Unknown + ); + assert_eq!(state(&decisions, &devbox(), "/srv"), TrustState::Unknown); + let elsewhere = target(vec![Hop::Ssh(ssh("dev@other"))], Some(1000)); + assert_eq!( + state(&decisions, &elsewhere, "/srv/projects/app"), + TrustState::Unknown + ); + + let top = decisions.workspace(&devbox(), "/srv").unwrap(); + assert_eq!(top.offered_location, None); + assert_eq!( + decisions + .workspace(&devbox(), "/") + .unwrap() + .offered_location, + None + ); + let before = decisions.clone(); + for (path, trusted) in [("/srv", true), ("/srv/projects/app", false)] { + let refused = decisions.decide( + &devbox(), + path, + Decision { + trusted, + location: true, + label: None, + }, + ); + assert_eq!(refused, Err(TrustError::at("location")), "{path}"); + } + assert_eq!(decisions, before); + } + + #[test] + fn an_explicit_decision_wins_over_a_location_and_moves_between_lists() { + let mut decisions = Decisions::parse(None).unwrap(); + trust(&mut decisions, &devbox(), "/srv/projects/app", true); + let keep_safe = Decision { + trusted: false, + location: false, + label: None, + }; + decisions + .decide(&devbox(), "/srv/projects/untrusted", keep_safe) + .unwrap(); + assert_eq!( + state(&decisions, &devbox(), "/srv/projects/untrusted"), + TrustState::Distrusted + ); + decisions + .decide(&devbox(), "/srv/projects/app", keep_safe) + .unwrap(); + assert_eq!( + state(&decisions, &devbox(), "/srv/projects/app"), + TrustState::Distrusted + ); + trust(&mut decisions, &devbox(), "/srv/projects/untrusted", false); + let text = decisions.text().unwrap(); + let document: serde_json::Value = serde_json::from_str(&text).unwrap(); + assert_eq!( + document["targets"][0]["trustedWorkspaces"], + json!(["/srv/projects/untrusted"]) + ); + assert_eq!( + document["targets"][0]["distrustedWorkspaces"], + json!(["/srv/projects/app"]) + ); + assert_eq!(document["targets"][0]["label"], "Dev box"); + assert_eq!(Decisions::parse(Some(&text)).unwrap(), decisions); + } + + #[test] + fn revoking_removes_entries_and_empty_targets_and_ignores_absent_ones() { + let mut decisions = Decisions::parse(None).unwrap(); + trust(&mut decisions, &devbox(), "/srv/projects/app", true); + decisions + .revoke(&devbox(), List::TrustedLocations, "/srv/projects") + .unwrap(); + assert_eq!( + state(&decisions, &devbox(), "/srv/projects/other"), + TrustState::Unknown + ); + let unchanged = decisions.clone(); + decisions + .revoke(&devbox(), List::DistrustedWorkspaces, "/srv/projects/app") + .unwrap(); + let elsewhere = target(vec![Hop::Ssh(ssh("dev@other"))], Some(1000)); + decisions + .revoke(&elsewhere, List::TrustedWorkspaces, "/srv/projects/app") + .unwrap(); + assert_eq!(decisions, unchanged); + decisions + .revoke(&devbox(), List::TrustedWorkspaces, "/srv/projects/app") + .unwrap(); + assert_eq!(decisions, Decisions::parse(None).unwrap()); + assert_eq!( + decisions.revoke(&devbox(), List::TrustedWorkspaces, "srv"), + Err(TrustError::at("path")) + ); + } + + #[test] + fn documents_refuse_ambiguous_malformed_and_oversized_content() { + let entry = |extra: serde_json::Value| { + let mut entry = + json!({"target": {"hops": [{"ssh": {"destination": "dev@box"}}], "userId": 1000}}); + for (key, value) in extra.as_object().unwrap() { + entry[key] = value.clone(); + } + entry + }; + let document = + |targets: Vec| json!({"version": 1, "targets": targets}).to_string(); + let refused = [ + ("{\"version\":1,\"version\":1}".to_owned(), "document"), + ( + json!({"version": 1, "trustAll": true}).to_string(), + "document", + ), + (json!({"version": 2}).to_string(), "version"), + ( + document(vec![entry(json!({"trustedWorkspaces": ["/a/b", "/a/b"]}))]), + "trustedWorkspaces", + ), + ( + document(vec![entry(json!({"trustedWorkspaces": ["a/b"]}))]), + "trustedWorkspaces", + ), + ( + document(vec![entry(json!({"trustedWorkspaces": ["/a/../b"]}))]), + "trustedWorkspaces", + ), + ( + document(vec![entry(json!({"trustedWorkspaces": ["/a/"]}))]), + "trustedWorkspaces", + ), + ( + document(vec![entry(json!({"trustedLocations": ["/"]}))]), + "trustedLocations", + ), + ( + document(vec![entry( + json!({"trustedWorkspaces": ["/a"], "distrustedWorkspaces": ["/a"]}), + )]), + "distrustedWorkspaces", + ), + ( + document(vec![entry( + json!({"label": "Dev\nbox", "trustedWorkspaces": ["/a"]}), + )]), + "label", + ), + ( + document(vec![ + entry(json!({"trustedWorkspaces": ["/a"]})), + entry(json!({"trustedWorkspaces": ["/b"]})), + ]), + "targets", + ), + ( + document(vec![ + json!({"target": {"hops": [{"ssh": {"destination": "-oProxyCommand=x"}}]}, "trustedWorkspaces": ["/a"]}), + ]), + "target", + ), + ( + document(vec![ + json!({"target": {"hops": [{"container": {"engine": "lxc", "program": "lxc", "container": "a"}}]}, "trustedWorkspaces": ["/a"]}), + ]), + "target", + ), + ( + format!( + "{{\"version\":1,\"targets\":[],\"x\":\"{}\"}}", + "a".repeat(MAX_BYTES) + ), + "document", + ), + ]; + for (text, field) in refused { + assert_eq!( + Decisions::parse(Some(&text)), + Err(TrustError::at(field)), + "{}", + &text[..text.len().min(200)] + ); + } + + let unsorted = document(vec![ + entry(json!({"trustedWorkspaces": ["/b", "/a"]})), + json!({"target": {"hops": []}, "label": "Unused"}), + ]); + let decisions = Decisions::parse(Some(&unsorted)).unwrap(); + let normalized: serde_json::Value = + serde_json::from_str(&decisions.text().unwrap()).unwrap(); + assert_eq!(normalized["targets"].as_array().unwrap().len(), 1); + assert_eq!( + normalized["targets"][0]["trustedWorkspaces"], + json!(["/a", "/b"]) + ); + } + + #[test] + fn lists_and_targets_stay_within_their_bounds() { + let mut decisions = Decisions::parse(None).unwrap(); + for index in 0..MAX_ENTRIES { + trust(&mut decisions, &devbox(), &format!("/w/{index}"), false); + } + let full = decisions.clone(); + let decision = Decision { + trusted: true, + location: false, + label: None, + }; + assert_eq!( + decisions.decide(&devbox(), "/w/extra", decision), + Err(TrustError::at("trustedWorkspaces")) + ); + assert_eq!(decisions, full); + + let mut decisions = Decisions::parse(None).unwrap(); + for index in 0..MAX_TARGETS { + let host = target(vec![Hop::Ssh(ssh(&format!("dev@host{index}")))], Some(1000)); + decisions.decide(&host, "/w", decision).unwrap(); + } + let extra = target(vec![Hop::Ssh(ssh("dev@extra"))], Some(1000)); + assert_eq!( + decisions.decide(&extra, "/w", decision), + Err(TrustError::at("targets")) + ); + assert_eq!( + decisions.decide( + &devbox(), + "/w", + Decision { + label: Some(&"x".repeat(MAX_LABEL_CHARS + 1)), + ..decision + } + ), + Err(TrustError::at("label")) + ); + } + + #[test] + fn host_paths_must_be_absolute_and_normalized() { + for path in ["/", "/home/dev", "/srv/my project", "/a/.hidden"] { + assert_eq!(host_path(path), Some(path)); + } + let long = format!("/{}", "a".repeat(MAX_PATH_BYTES)); + for path in [ + "", + "home", + "//srv", + "/srv/", + "/srv//a", + "/srv/./a", + "/srv/..", + "/a\0b", + long.as_str(), + ] { + assert_eq!(host_path(path), None, "{path:?}"); + } + } +} diff --git a/rust/crates/remote/src/protocol/methods.rs b/rust/crates/remote/src/protocol/methods.rs index da28b0ff..572e3be7 100644 --- a/rust/crates/remote/src/protocol/methods.rs +++ b/rust/crates/remote/src/protocol/methods.rs @@ -353,6 +353,10 @@ pub struct HostCapabilities { pub host_name: String, /// Account the server runs as; `None` when the host cannot name it. pub user_name: Option, + /// Numeric id of that account, from the kernel rather than the + /// environment. `None` from servers that predate it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub user_id: Option, /// Home directory of that account; `None` when it is not set. pub home_directory: Option, /// Login shell of the remote user, used for terminals and for resolving diff --git a/rust/crates/remote/src/server/platform/mod.rs b/rust/crates/remote/src/server/platform/mod.rs index 4b67879c..79a4154e 100644 --- a/rust/crates/remote/src/server/platform/mod.rs +++ b/rust/crates/remote/src/server/platform/mod.rs @@ -65,6 +65,7 @@ pub(crate) fn host_capabilities() -> HostCapabilities { arch: std::env::consts::ARCH.into(), host_name: unix::host_name(), user_name: account.user_name, + user_id: Some(unix::current_uid()), home_directory: account.home_directory, default_shell: account.shell, path_separator: "/".into(), diff --git a/rust/crates/workspace/src/lib.rs b/rust/crates/workspace/src/lib.rs index b8ed089b..e257aead 100644 --- a/rust/crates/workspace/src/lib.rs +++ b/rust/crates/workspace/src/lib.rs @@ -10,8 +10,9 @@ //! The session side owns the long-lived connections: [`probe`] checks that a //! saved SSH connection reaches a usable host, [`sessions`] opens and keeps the //! connections, [`host`] forwards finite requests and owned streaming resources -//! (processes, terminals, watches), and [`upload`] streams a verified file to -//! the host. Domain semantics stay in their engines (Git, build, language +//! (processes, terminals, watches), [`upload`] streams a verified file to +//! the host, and [`trust`] keys remote workspace trust by what the connection +//! resolves. Domain semantics stay in their engines (Git, build, language //! servers); this crate only supplies the IO boundary. pub mod fs; @@ -21,6 +22,7 @@ mod scope; pub mod sessions; #[cfg(feature = "test-support")] pub mod test_support; +pub mod trust; pub mod upload; pub use scope::{ diff --git a/rust/crates/workspace/src/sessions.rs b/rust/crates/workspace/src/sessions.rs index bf01b321..20338cf1 100644 --- a/rust/crates/workspace/src/sessions.rs +++ b/rust/crates/workspace/src/sessions.rs @@ -12,6 +12,7 @@ use lithe_git_host::ProcessTree; use lithe_protocol::{CoreError, ErrorCode}; use lithe_remote::client::launch::{launch, launch_command, LaunchError, Launched}; use lithe_remote::client::session::{ClientError, ConnectOptions}; +use lithe_remote::client::trust::Target; use lithe_remote::client::{ ConnectionKind, ConnectionLog, Hop, RemoteSession, ServerArtifact, ServerTarget, TransportChain, }; @@ -99,6 +100,9 @@ pub struct Connection { pub session: RemoteSession, /// Git executable path and version found on the host, once resolved. pub git_tool: Mutex>, + /// Where the connection ends, the key of its workspaces' trust together + /// with their real paths. Fixed when the connection opens. + pub(crate) trust_target: Target, pub(crate) transport: ConnectionTransport, } @@ -294,7 +298,8 @@ fn connect_logged( if let Some(program) = ssh_program { hop.program = program.into(); } - let argv = TransportChain::new(vec![Hop::Ssh(hop)]) + let chain = TransportChain::new(vec![Hop::Ssh(hop)]); + let argv = chain .command(&launch_command( request.install_root.as_deref(), &["--stdio"], @@ -552,6 +557,7 @@ fn connect_logged( Arc::new(Connection { session, git_tool: Mutex::new(None), + trust_target: Target::new(&chain, capabilities.user_id), transport: ConnectionTransport::Ssh { child: Mutex::new(child), tree, diff --git a/rust/crates/workspace/src/test_support.rs b/rust/crates/workspace/src/test_support.rs index 2f6e7b20..09fa4c7a 100644 --- a/rust/crates/workspace/src/test_support.rs +++ b/rust/crates/workspace/src/test_support.rs @@ -2,17 +2,21 @@ //! against an in-process host server instead of an SSH child. use crate::sessions::{lookup, nonce, registry, Connection, ConnectionTransport}; -use lithe_remote::client::RemoteSession; +use lithe_remote::client::trust::Target; +use lithe_remote::client::{RemoteSession, TransportChain}; use std::sync::{Arc, Mutex}; -/// Registers `session` as a connected host and returns its session id. +/// Registers `session` as a connected host and returns its session id. Its +/// trust target has no hops, only the account the server reports. pub fn register_in_process(session: RemoteSession) -> String { let id = nonce(); + let trust_target = Target::new(&TransportChain::local(), session.hello().host.user_id); registry().lock().unwrap().insert( id.clone(), Arc::new(Connection { session, git_tool: Mutex::new(None), + trust_target, transport: ConnectionTransport::InProcess, }), ); diff --git a/rust/crates/workspace/src/trust.rs b/rust/crates/workspace/src/trust.rs new file mode 100644 index 00000000..e196301a --- /dev/null +++ b/rust/crates/workspace/src/trust.rs @@ -0,0 +1,172 @@ +//! `remote.workspaceTrust` and `remote.editWorkspaceTrust`: whether a remote +//! workspace may run project code (design S01 to S04). +//! +//! Decisions live in a machine-local document that the native client reads +//! and publishes atomically, as for local workspaces. Core resolves every key +//! over the open connection, its target and the workspace's real path on the +//! 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 lithe_protocol::{CoreError, ErrorCode}; +use lithe_remote::client::trust::{self, Decision, Decisions, List, Target, TrustError}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +/// `remote.workspaceTrust`: the decisions, and the trust of one workspace +/// when `sessionId` and `workspace` are both given. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct StateRequest { + /// Current document text; `null` when the source does not exist. + document: Option, + /// Open connection the workspace was opened through. + #[serde(default)] + session_id: Option, + /// Absolute host path of the workspace root as opened. + #[serde(default)] + workspace: Option, +} + +/// `remote.editWorkspaceTrust`: exactly one of `decision` and `revoke`. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct EditRequest { + /// Current document text; `null` when the source does not exist. + document: Option, + /// Records a decision on an open workspace. + #[serde(default)] + decision: Option, + /// Removes one entry, also for a target that is not connected. + #[serde(default)] + revoke: Option, +} + +/// One decision on the workspace at `workspace` over `sessionId`. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct DecisionRequest { + session_id: String, + workspace: String, + trusted: bool, + #[serde(default)] + location: bool, + #[serde(default)] + label: Option, +} + +/// One entry of the document to remove, as `remote.workspaceTrust` lists it. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RevokeRequest { + target: Target, + list: List, + path: String, +} + +/// 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: trust::STORAGE_PATH, + maximum_bytes: trust::MAX_BYTES, +}; + +/// Reads the document and, when asked, the trust of one open workspace. +pub fn state(request: StateRequest) -> Result { + let decisions = parse(request.document.as_deref())?; + let mut result = json!({ "document": decisions, "storage": STORAGE }); + match (request.session_id, request.workspace) { + (None, None) => {} + (Some(session_id), Some(workspace)) => { + let (target, real_path) = resolve(&session_id, &workspace)?; + let workspace_trust = decisions + .workspace(&target, &real_path) + .map_err(invalid_request)?; + result["projectCodeAllowed"] = + json!(workspace_trust.state == trust::TrustState::Trusted); + result["workspaceTrust"] = json!(workspace_trust); + result["workspaceTrust"]["target"] = json!(target); + } + _ => return Err(invalid_request(TrustError { field: "workspace" })), + } + Ok(result) +} + +/// Applies one decision or removal. 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 mut after = before.clone(); + match (request.decision, request.revoke) { + (Some(decision), None) => { + let (target, real_path) = resolve(&decision.session_id, &decision.workspace)?; + after + .decide( + &target, + &real_path, + Decision { + trusted: decision.trusted, + location: decision.location, + label: decision.label.as_deref(), + }, + ) + .map_err(invalid_request)?; + } + (None, Some(revoke)) => after + .revoke(&revoke.target, revoke.list, &revoke.path) + .map_err(invalid_request)?, + _ => return Err(invalid_request(TrustError { field: "decision" })), + } + let changed = after != before; + let document = if changed { + Some(after.text().map_err(invalid_request)?) + } else { + None + }; + 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 { + Decisions::parse(document).map_err(|error| { + CoreError::new( + ErrorCode::ParseFailed, + "Invalid remote workspace trust document", + ) + .with_details(json!({ "field": error.field }).to_string()) + }) +} + +fn invalid_request(error: TrustError) -> CoreError { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid remote workspace trust request", + ) + .with_details(json!({ "field": error.field }).to_string()) +} From 0ddb5611b88a7044dbeb01a9dbdbfb684e5f922e Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 21 Nov 2026 02:53:38 +0800 Subject: [PATCH 2/3] =?UTF-8?q?fix(remote):=20=E8=B0=83=E8=AF=95=E6=9E=84?= =?UTF-8?q?=E5=BB=BA=E4=BC=98=E5=8C=96=20sha2=EF=BC=8C=E6=8C=81=E4=B9=85?= =?UTF-8?q?=E4=BC=9A=E8=AF=9D=E6=B5=8B=E8=AF=95=E5=9C=A8=E9=AB=98=E8=B4=9F?= =?UTF-8?q?=E8=BD=BD=E4=B8=8B=E4=B8=8D=E5=86=8D=E8=B6=85=E6=97=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 持久会话的代理和 daemon 都对服务端可执行文件算 SHA-256 来命名会话。 调试构建的服务端约 40 MB,未优化的 sha2 空闲时要约 1.4 秒,CPU 被占满时 约 7 秒,一次连接算两遍就超过测试的 10 秒握手上限,persistence 的 12 个 测试会成片失败(#138 之前的 43e3f27 同样复现,属于既有问题)。 - 工作区根 Cargo.toml 只对 dev profile 的 sha2 开 opt-level 3:空闲 74 ms、 满载 369 ms;persistence 一轮从约 15 秒降到约 4 秒。发布构建不受影响。 --- rust/Cargo.toml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 6d952b72..a2179605 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -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 From 24be6aa61a4f9e0b59f242d8c0ed94f95a64463c Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 21 Nov 2026 02:53:38 +0800 Subject: [PATCH 3/3] =?UTF-8?q?fix(remote):=20=E6=8F=A1=E6=89=8B=E5=A4=B1?= =?UTF-8?q?=E8=B4=A5=E6=97=B6=E7=AD=89=E4=BC=A0=E8=BE=93=E7=9A=84=E6=A0=87?= =?UTF-8?q?=E5=87=86=E9=94=99=E8=AF=AF=E8=AF=BB=E5=AE=8C=E5=86=8D=E7=BB=99?= =?UTF-8?q?=E5=87=BA=E8=AF=8A=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 传输进程写完错误信息立刻退出时,客户端看到退出后马上读尾部缓冲, 读 stderr 的线程可能还没把管道里最后的内容读进来,诊断里就缺了 “not found” 这类原因(a_missing_server_reports_the_transport_output 在 Linux 上三轮挂两轮)。 - 标准错误尾部改为带“已读到结尾”标记的 StderrTail;握手失败时先等传输 退出,再在同一个 2 秒宽限内等读到结尾。传输留下的进程一直占着管道时, 到期就用已有内容,不会多等。 - 补两个单测:读到结尾后内容完整;只保留最后 8 KiB,期限已过时立即返回。 --- rust/crates/remote/src/client/session.rs | 158 ++++++++++++++++++----- 1 file changed, 129 insertions(+), 29 deletions(-) diff --git a/rust/crates/remote/src/client/session.rs b/rust/crates/remote/src/client/session.rs index 389e9b05..50c4fb3b 100644 --- a/rust/crates/remote/src/client/session.rs +++ b/rust/crates/remote/src/client/session.rs @@ -343,11 +343,73 @@ pub struct RemoteSession { /// Sequence number of the latest event received. last_seq: Arc, child: Mutex>, - stderr_tail: Arc>>, + stderr_tail: Arc, hello: Option, log: ConnectionLog, } +/// The last [`STDERR_TAIL_BYTES`] of the transport's standard error, and +/// whether its reader has reached the end of the stream. +#[derive(Default)] +struct StderrTail { + state: Mutex, + ended: Condvar, +} + +#[derive(Default)] +struct TailState { + bytes: VecDeque, + ended: bool, +} + +impl StderrTail { + /// A tail with no stream behind it, for sessions without a transport. + fn finished() -> Self { + Self { + state: Mutex::new(TailState { + bytes: VecDeque::new(), + ended: true, + }), + ended: Condvar::new(), + } + } + + fn push(&self, bytes: &[u8]) { + let mut state = lock(&self.state); + state.bytes.extend(bytes); + let excess = state.bytes.len().saturating_sub(STDERR_TAIL_BYTES); + state.bytes.drain(..excess); + } + + fn finish(&self) { + lock(&self.state).ended = true; + self.ended.notify_all(); + } + + /// Waits until the reader reaches the end of the stream or `deadline` + /// passes. A process the transport left running can hold the stream open + /// after the transport itself exited. + fn wait_for_end(&self, deadline: Instant) { + let mut state = lock(&self.state); + while !state.ended { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return; + } + state = match self.ended.wait_timeout(state, remaining) { + Ok((state, _)) => state, + Err(poisoned) => poisoned.into_inner().0, + }; + } + } + + fn text(&self) -> String { + let state = lock(&self.state); + let bytes: Vec = state.bytes.iter().copied().collect(); + String::from_utf8_lossy(&bytes).trim().to_owned() + } +} + /// An owned request waiter. Dropping it withdraws unsent work and ignores late /// replies, without closing the session or its other resources. pub struct PendingRequest { @@ -414,14 +476,17 @@ impl RemoteSession { })?; let stdin = child.stdin.take().expect("stdin is piped"); let stdout = child.stdout.take().expect("stdout is piped"); - let stderr_tail = Arc::new(Mutex::new(VecDeque::new())); - if let Some(stderr) = child.stderr.take() { - if let Err(error) = keep_tail(stderr, Arc::clone(&stderr_tail)) { - abandon(Some(child)); - let error = ClientError::Spawn(error); - log.connect_failed("connect", &error.failure_category(), "remote"); - return Err(error); + let stderr_tail = Arc::new(StderrTail::default()); + match child.stderr.take() { + Some(stderr) => { + if let Err(error) = keep_tail(stderr, Arc::clone(&stderr_tail)) { + abandon(Some(child)); + let error = ClientError::Spawn(error); + log.connect_failed("connect", &error.failure_category(), "remote"); + return Err(error); + } } + None => stderr_tail.finish(), } Self::establish( stdout, @@ -440,7 +505,14 @@ impl RemoteSession { options: &ConnectOptions, ) -> Result<(Self, Receiver), ClientError> { let log = options.log_or_begin(ConnectionKind::Streams); - Self::establish(reader, Box::new(writer), None, Arc::default(), options, log) + Self::establish( + reader, + Box::new(writer), + None, + Arc::new(StderrTail::finished()), + options, + log, + ) } /// Completes the handshake and records its outcome in `log`. @@ -448,7 +520,7 @@ impl RemoteSession { reader: impl Read + Send + 'static, writer: Box, child: Option, - stderr_tail: Arc>>, + stderr_tail: Arc, options: &ConnectOptions, log: ConnectionLog, ) -> Result<(Self, Receiver), ClientError> { @@ -464,7 +536,7 @@ impl RemoteSession { reader: impl Read + Send + 'static, writer: Box, child: Option, - stderr_tail: Arc>>, + stderr_tail: Arc, options: &ConnectOptions, log: ConnectionLog, ) -> Result<(Self, Receiver), ClientError> { @@ -525,8 +597,7 @@ impl RemoteSession { Ok(Ok(())) => {} Ok(Err(FrameError::PreambleNotFound { noise })) => { let mut output = String::from_utf8_lossy(&noise).trim().to_owned(); - session.wait_for_transport_exit(SHUTDOWN_GRACE); - let stderr = session.diagnostics(); + let stderr = session.final_diagnostics(); if !stderr.is_empty() { output = format!("{output}\n{stderr}").trim().to_owned(); } @@ -535,9 +606,8 @@ impl RemoteSession { }); } Ok(Err(_)) | Err(mpsc::RecvTimeoutError::Disconnected) => { - session.wait_for_transport_exit(SHUTDOWN_GRACE); return Err(ClientError::Disconnected { - diagnostics: session.diagnostics(), + diagnostics: session.final_diagnostics(), }); } Err(mpsc::RecvTimeoutError::Timeout) => return Err(ClientError::Timeout), @@ -707,9 +777,18 @@ impl RemoteSession { } fn diagnostics(&self) -> String { - let tail = lock(&self.stderr_tail); - let bytes: Vec = tail.iter().copied().collect(); - String::from_utf8_lossy(&bytes).trim().to_owned() + self.stderr_tail.text() + } + + /// Diagnostics of a transport that ended the stream. The transport's exit + /// and the end of its standard error share one grace: a message written + /// just before exiting can still be in the pipe when the exit is seen. + fn final_diagnostics(&self) -> String { + let deadline = Instant::now() + SHUTDOWN_GRACE; + if self.wait_for_transport_exit(SHUTDOWN_GRACE) { + self.stderr_tail.wait_for_end(deadline); + } + self.diagnostics() } /// Waits up to `grace` for the transport process to exit, so its final @@ -915,25 +994,18 @@ fn close(pending: &Mutex) { } } -fn keep_tail( - mut stderr: impl Read + Send + 'static, - tail: Arc>>, -) -> io::Result<()> { +fn keep_tail(mut stderr: impl Read + Send + 'static, tail: Arc) -> io::Result<()> { thread::Builder::new() .name("remote-stderr".into()) .spawn(move || { let mut buffer = [0_u8; 4096]; loop { match stderr.read(&mut buffer) { - Ok(0) | Err(_) => return, - Ok(read) => { - let mut tail = lock(&tail); - tail.extend(&buffer[..read]); - let excess = tail.len().saturating_sub(STDERR_TAIL_BYTES); - tail.drain(..excess); - } + Ok(0) | Err(_) => break, + Ok(read) => tail.push(&buffer[..read]), } } + tail.finish(); }) .map(drop) } @@ -997,6 +1069,34 @@ mod tests { .is_resource_already_gone()); } + #[test] + fn the_stderr_tail_is_complete_once_its_reader_reaches_the_end() { + let tail = Arc::new(StderrTail::default()); + keep_tail( + io::Cursor::new(b"lithe-remote-server: not found\n".to_vec()), + Arc::clone(&tail), + ) + .unwrap(); + tail.wait_for_end(Instant::now() + Duration::from_secs(10)); + assert!(lock(&tail.state).ended); + assert_eq!(tail.text(), "lithe-remote-server: not found"); + } + + #[test] + fn the_stderr_tail_keeps_its_last_bytes_and_stops_waiting_at_the_deadline() { + let tail = StderrTail::default(); + tail.push(&vec![b'a'; STDERR_TAIL_BYTES]); + tail.push(b"end"); + let text = tail.text(); + assert_eq!(text.len(), STDERR_TAIL_BYTES); + assert!(text.ends_with("aend"), "{}", &text[text.len() - 8..]); + // A stream that stays open ends the wait at its deadline, here + // already passed. + tail.wait_for_end(Instant::now()); + assert!(!lock(&tail.state).ended); + assert!(lock(&StderrTail::finished().state).ended); + } + fn waiter(outgoing: Arc, payload: Vec) -> (PendingRequest, SyncSender) { let (sender, reply) = mpsc::sync_channel(1); let pending = Arc::new(Mutex::new(Pending::default()));