diff --git a/rust/contracts/remote-workspace-protocol-v1.md b/rust/contracts/remote-workspace-protocol-v1.md index d9dab27e..2152f6c3 100644 --- a/rust/contracts/remote-workspace-protocol-v1.md +++ b/rust/contracts/remote-workspace-protocol-v1.md @@ -13,6 +13,7 @@ clients. Design rationale lives in | --- | --- | | `lithe-remote-server --stdio` | Ends with the connection, terminating everything it started. | | `lithe-remote-server --connect [--state-dir ]` | Persistent: relays to the daemon of session ``, starting it if needed. | +| `lithe-remote-server --target-identity --state-dir ` | Prints the non-secret identity of the final account's server state before a client chooses a session key. | `` is 1–64 characters from `[A-Za-z0-9._-]`. The daemon keeps its socket, lock and log under `` (default `$HOME/.lithe-server`) in @@ -50,6 +51,11 @@ Other clients should do the same. bytes of UTF-8 JSON. Frames larger than 16 MiB are rejected. 3. Closing the client-to-server stream is a disconnect. +The reference server bounds response serialization to the frame limit. A result +that exceeds it becomes a `TOO_LARGE` error for that request, and subsequent +responses remain usable. Event producers bound their own batches; events cannot +be replaced by a request error and are never silently discarded by the writer. + All traffic, including tunnels, uses this stream. The server listens on a network port only for a forwarding rule the user added (`listener.open`, see "Listeners"); such a port belongs to the connection that opened it and @@ -126,7 +132,7 @@ subscribe before creating the resource. | `fs.stat` | `path` | metadata of the path itself (links not followed) | | `fs.readDir` | `path` | `entries` sorted by name byte order, `skippedNonUtf8` | | `fs.readFile` | `path`, `offset`, `length` (≤ 8 MiB) | `data`, `eof`, `metadata`; only a regular file is read | -| `fs.writeFile` | `path`, `data` (≤ 8 MiB), `expected?`, `overwrite`, `createParents` | metadata after the write | +| `fs.writeFile` | `path`, `data` (≤ 8 MiB), `expected?`, `overwrite`, `createParents`, `root?` | metadata after the write | | `fs.createDir` | `path`, `recursive`, `mode?` (at most `0o7777`) | `null` | | `fs.remove` | `path`, `recursive` | `null`; links are removed, never followed | | `fs.rename` | `from`, `to`, `overwrite` | `null` | @@ -168,6 +174,15 @@ subscribe before creating the resource. opened file, so a FIFO without a writer never holds the request and a path replaced between `fs.stat` and the read is still checked. A directory fails with `IS_A_DIRECTORY`; sockets, FIFOs and devices fail with `UNSUPPORTED`. +Metadata includes optional `revision`, an opaque identity incorporating the +host's file identity, size and precise modification/change timestamps. Clients +compare it exactly and return it in `expected`; they must not interpret its +encoding. Older servers may omit it. + +`fs.readDir` examines at most 20,000 directory entries, including names that are +not UTF-8, and bounds serialized entries below the frame limit with space for +the response envelope. Exceeding either budget returns `TOO_LARGE` rather than +a successful partial listing. Recursive indexes should use `walk.start`. `fs.copy` refuses, with `INVALID_REQUEST`, to copy a file onto itself — directly, through a symbolic link in either direction or onto a hard link — @@ -184,13 +199,36 @@ the remote account, never to the client placeholder or installation. A host without usable trash storage returns an error and retains the original entry; it does not fall back to permanent deletion. -`fs.writeFile` replaces the file atomically through a temporary sibling and -writes through symbolic links. With `expected` (`size`, `modifiedMs`) it fails -with `CONFLICT` unless the file still matches; without it, an existing file is -only replaced when `overwrite` is set. A write with neither `expected` nor -`overwrite` only creates: when two such writes race, exactly one succeeds and -the other fails with `ALREADY_EXISTS`. When a file is replaced, the temporary -file never has broader permissions than the original. +`fs.writeFile` replaces the file atomically through a temporary sibling. With +`expected` (`size`, `modifiedMs`, optional `revision`) it fails with `CONFLICT` +unless the file still matches; without it, an existing file is only replaced +when `overwrite` is set. The revision catches an inode replacement or precise +timestamp change even when size and millisecond modification time are unchanged. +A write with neither `expected` nor `overwrite` publishes by atomic no-replace +linking: a concurrently created destination is retained and the write fails +with `ALREADY_EXISTS`. A replacement's temporary file is created with permissions +no broader than the original, before any content is written. + +The optional `root` requires the `guardedWrites` feature. Editor clients send +their workspace root and refuse an older server instead of retrying without the +boundary. The requested path must be lexically below that root with no `..` +components. The server resolves the root, opens it through directory handles, +and opens each descendant directory without following symbolic links. The leaf +must not be a symbolic link either. Missing descendants are created only with +`createParents` and are reopened without following links. Staging and publication +use the same parent handle; refused boundary or symlink crossings return +`PERMISSION_DENIED`. Without `root`, explicit general host writes retain their +ability to write outside a workspace and through an existing leaf link. + +Cooperating Lithe daemons serialize writes to the same directory with a +five-second advisory-lock deadline. The server rechecks the version after +staging and syncing, immediately before publication. POSIX rename provides no +version-based compare-and-swap: an external writer that ignores this lock can +still change a file between that final check and replacement. Directory handles +also do not sandbox a hostile same-user process that moves an already-open +directory outside the root. These are limits of conflict and path protection, +not guarantees of isolation from the remote account itself. Failed saves reclaim +their temporary files; a crash can leave one behind. Hosts advertising `features: ["upload", ...]` accept staged uploads without increasing the frame limit. Upload IDs are server-assigned and owned by the @@ -274,6 +312,15 @@ environment and caches it for the session. `process.spawn` with `watch.changed` batches are coalesced and sorted by path. With `overflow` changes were lost and the client must rescan the watched tree. +The reference backend queue retains at most 2,048 changes and 1 MiB of raw +path bytes without blocking the native watcher. Pressure clears those changes +and preserves an overflow marker, watch-limit notice and root-removal notice. +Coalesced batches hold at most 5,000 distinct changes and 1 MiB of path bytes +before JSON escaping; a larger batch becomes an empty overflow batch. + +`walk.entries` batches hold at most 2,000 entries and 1 MiB of relative-path +bytes before JSON escaping. A single path beyond that budget ends the walk with +`truncated: true`; it is not sent as an oversized event. ## Listeners @@ -390,6 +437,21 @@ than reaching an older one. ## Server identity +`--target-identity --state-dir ` prints 64 hexadecimal characters derived +from a random marker, the current numeric user ID and the canonical state root. +The marker is `target-identity-v1` in the private state directory, created as +an owner-only regular file without following symbolic links and published +without replacing another launcher's marker. Later launches validate ownership, +permissions and length before reading it. This is persistent account-local +state, not a secret or hardware identity: copying the marker to a clone with +the same account and path also copies that identity. + +The reference bootstrap prints `LITHE-TARGET ` after installation +and waits for a session key on the same authenticated stream before executing +`--connect`. The client combines this marker with the actual OpenSSH identity +and explicit route before selecting any previously stored key or token. The +marker does not replace SSH host-key authentication. + `lithe-remote-server --identity` prints one JSON line with `serverVersion`, `protocolVersion` and `sha256` of the executable itself. A binary is never trusted to report its own hash: bootstrappers reuse an installed server only diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 030e608d..98d273ba 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -6140,7 +6140,8 @@ and `{ stage: "installed", uploaded }` once the server is in place, where failed attempt stops after the last stage reached, so a host without a matching build stops after `platformChecked`. The result is `{ status, session, host, diagnostics }`; `session` is `{ id, uploaded, hostName, userName, -homeDirectory, windowsInterop, sessionKey, sessionToken, resumed, keptPrograms }` +homeDirectory, windowsInterop, sessionKey, sessionToken, sessionBinding?, +resumeConsumed, resumed, keptPrograms }` and is set only for `connected`. A host without a matching build is `unsupportedPlatform` and nothing is uploaded. `windowsInterop` is the host capability of the same name from the remote workspace protocol: `true` or @@ -6152,7 +6153,16 @@ The server runs a persistent session (`--connect `, with connection. `sessionKey` names that session and `sessionToken` is the secret that attaches to it again; the client stores the token like a password and never logs it. To attach to a session an earlier connection kept, pass -`resume: { key, token }` with the values it returned. `resumed` tells whether +`resume: { key, token, binding? }` with the values it returned. The opaque +64-hexadecimal `sessionBinding` binds the explicit transport chain, the actual +OpenSSH-authenticated host name, port, account, peer address and host-key +fingerprint, and the final server's account-local state identity. Before sending +an old key or token, the same connection must produce an identical binding. +Legacy records without a binding, a changed target, or unavailable evidence +start a fresh session without sending the old credentials. `resumeConsumed` +tells the native credential store whether Core attempted those credentials; +only then may it remove the old record. A mismatched record remains available +for the original target. `resumed` tells whether this connection attached to it; `keptPrograms` lists the processes and terminals it still runs, as `remote.runningPrograms` does, and is empty for a new session. When the host refuses the token, because the session ended @@ -6162,7 +6172,15 @@ user authenticates again but is never locked out; that connection reports characters or not made of ASCII letters, digits, `.`, `_` and `-`, or a token that is empty, longer than 128 characters or not hexadecimal, is `invalid_request` with `{ field: "resume", reason: "invalid" }`, before -OpenSSH or `wsl.exe` starts. +OpenSSH or `wsl.exe` starts. A present binding must be 64 hexadecimal characters. + +OpenSSH supplies identity evidence on the actual connection, with connection +multiplexing disabled; Core does not pre-read `ssh -G` or weaken the user's +host-key policy. ProxyCommand and ProxyJump connections remain usable, but +unverifiable evidence gives no reusable `sessionBinding` and no automatic +credential recovery. Such a connection also receives a fresh trust identity. +The current private `-E` evidence file bounds reads to 64 KiB but does not bound +OpenSSH's writes; correcting this resource lifetime remains a release blocker. Instead of `connection`, the request may name a WSL distribution on this Windows machine as `wsl: { distribution, user? }`, where `distribution` is a @@ -6247,8 +6265,8 @@ gone. Requests over it take `sessionId`: | Command | Request | Result | | --- | --- | --- | | `remote.readDir` | `{ sessionId, path }` | the remote protocol's `fs.readDir` result | -| `remote.readFile` | `{ sessionId, path }` | `{ data (base64), size, modifiedMs }`; files over 16 MiB are `not_supported` | -| `remote.writeFile` | `{ sessionId, path, data, expected? }` | `{ status: "saved", size, modifiedMs }` or `{ status: "conflict" }` | +| `remote.readFile` | `{ sessionId, path }` | `{ data (base64), size, modifiedMs, revision? }`; files over 16 MiB are `not_supported` | +| `remote.writeFile` | `{ sessionId, path, data, expected?, root? }` | `{ status: "saved", size, modifiedMs, revision? }` or `{ status: "conflict" }` | | `remote.hostRequest` | `{ sessionId, method, params }` | the finite host method's result, including JSON `null` | | `remote.hostInfo` | `{ sessionId }` | the original connection's handshake `host`, including OS, architecture, home and features | | `remote.uploadFile` | `{ sessionId, sourcePath, path, sha256, mode }` | verified `{ size, sha256 }` | @@ -6261,12 +6279,31 @@ gone. Requests over it take `sessionId`: | `remote.endPrograms` | `{ sessionId, programs? }` | `{ ended }`: every running process gets `SIGTERM` for its process session and every terminal hangs up, or only those `programs` (`[{ kind, id }]` as `remote.runningPrograms` listed them) names; one that ended in the meantime or is not running is not counted, one that ignores the signal is still listed | `remote.writeFile` replaces the file atomically on the host. With -`expected` (`{ size, modifiedMs }` from the read) a changed file is a +`expected` (`{ size, modifiedMs, revision? }` from the read) a changed file is a `conflict`; without it the file must not exist yet. A missing path is `workspace_not_found`, a denied one `permission_denied`. A broken connection fails with `connection_closed` and is forgotten, so the host reconnects; an unknown or closed `sessionId` is also `connection_closed`. +Editor saves send `root`, the workspace's absolute host root. The host must +advertise `guardedWrites`; otherwise Core returns `not_supported` without +sending an unscoped write. Descendant directory and leaf symlinks, path escapes +and `..` are refused. General explicit host writes without `root` retain their +existing outside-workspace and leaf-link behavior. The opaque `revision` is +returned unchanged from the opened host file and compared exactly. Cooperating +Lithe daemons serialize saves and recheck after staging; an external writer +that ignores their advisory lock still has the final check-to-rename window. +See the [remote protocol](remote-workspace-protocol-v1.md) for the path and +conflict-protection limits. + +`remote.readFile` applies a cumulative 16 MiB decoded-content limit and a +120-second overall read deadline, with each chunk limited to 30 seconds. +Cancellation is checked between chunks and at most every 50 ms while waiting +for a reply; dropping a pending chunk withdraws unsent work and ignores late +replies without closing the connection. The read validates chunk progress, EOF +and file revisions, rejecting a changed file instead of returning mixed content. +It does not perform a preliminary uncancellable `stat` outside that deadline. + `remote.hostRequest` accepts finite filesystem, environment and port queries, `server.state` (what still runs, with the `label` given at start, so the host can ask before closing a window), plus controls of existing processes and @@ -6451,12 +6488,15 @@ 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 +- The target is `{ hops, userId?, identity? }`. 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 + `userId` is the server's numeric account from `server.hello`. `identity` is + the verified session binding described above, or a fresh connection-local + identity when that binding is unavailable. Legacy targets without it remain + readable and revocable but cannot authorize new connections. 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`. diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index 22b84afd..11e4ac3f 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -1542,6 +1542,19 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 60, owner: "lithe-core", }, + EventMetadata { + id: "remote.session.identity_rejected", + channel: "remote", + level: LogLevel::Warn, + message: "Remote identity could not authorize automatic session recovery", + fields: &[ + FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Controlled identity category without host names, fingerprints or credentials", reason: None }, + FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "Identity validation or resume binding stage", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, EventMetadata { id: "remote.session.state_failed", channel: "remote", diff --git a/rust/crates/git-host/src/authentication.rs b/rust/crates/git-host/src/authentication.rs index 554e08df..68e4fb34 100644 --- a/rust/crates/git-host/src/authentication.rs +++ b/rust/crates/git-host/src/authentication.rs @@ -18,7 +18,7 @@ mod unix; #[cfg(unix)] use unix as channel; #[cfg(windows)] -mod windows; +pub(crate) mod windows; #[cfg(windows)] use windows as channel; #[cfg(test)] diff --git a/rust/crates/git-host/src/authentication/windows.rs b/rust/crates/git-host/src/authentication/windows.rs index 61f5c614..0f76fd77 100644 --- a/rust/crates/git-host/src/authentication/windows.rs +++ b/rust/crates/git-host/src/authentication/windows.rs @@ -51,6 +51,25 @@ const CREATE_ATTEMPTS: usize = 4; /// How long the helper waits for a free pipe instance. const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); +/// Creates a directory with the same protected owner-only DACL as AskPass. +pub(crate) fn private_directory(path: &std::path::Path) -> io::Result<()> { + use windows_sys::Win32::Storage::FileSystem::CreateDirectoryW; + let descriptor = Descriptor::owner_only(&CurrentUser::query()?)?; + let attributes = SECURITY_ATTRIBUTES { + nLength: std::mem::size_of::() as u32, + lpSecurityDescriptor: descriptor.0 .0, + bInheritHandle: 0, + }; + let path = wide(path.as_os_str()); + // SAFETY: both the NUL-terminated path and security descriptor outlive + // this call; CreateDirectoryW copies the descriptor into the directory. + if unsafe { CreateDirectoryW(path.as_ptr(), &attributes) } == 0 { + Err(io::Error::last_os_error()) + } else { + Ok(()) + } +} + /// Listening pipe for one session. Dropping it closes the last listening /// instance, which removes the pipe name once accepted instances close too. pub(super) struct Listener { diff --git a/rust/crates/git-host/src/lib.rs b/rust/crates/git-host/src/lib.rs index 9609add5..d3f26b86 100644 --- a/rust/crates/git-host/src/lib.rs +++ b/rust/crates/git-host/src/lib.rs @@ -10,6 +10,7 @@ pub mod failure_log; pub mod authentication; pub mod configuration; +pub mod private_directory; use std::fs::{File, OpenOptions}; use std::io::{self, Read, Seek, SeekFrom, Write}; diff --git a/rust/crates/git-host/src/private_directory.rs b/rust/crates/git-host/src/private_directory.rs new file mode 100644 index 00000000..4ef9da24 --- /dev/null +++ b/rust/crates/git-host/src/private_directory.rs @@ -0,0 +1,49 @@ +//! Fresh owner-only directories for short-lived native helper evidence. + +use rand::RngCore; +use std::io; +use std::path::{Path, PathBuf}; + +/// Owns a fresh directory, removed after its caller has stopped the helper. +pub struct PrivateDirectory(PathBuf); + +impl PrivateDirectory { + /// Creates one directory in the platform temporary directory. No shared + /// cache, installed resource or user preference is changed. + pub fn new() -> io::Result { + let mut bytes = [0u8; 16]; + rand::rngs::OsRng + .try_fill_bytes(&mut bytes) + .map_err(io::Error::other)?; + let suffix: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect(); + let path = std::env::temp_dir().join(format!("lithe-evidence-{suffix}")); + create(&path)?; + Ok(Self(path)) + } + + /// Private parent for caller-owned evidence files. + pub fn path(&self) -> &Path { + &self.0 + } +} + +impl Drop for PrivateDirectory { + fn drop(&mut self) { + crate::failure_log::cleanup( + "vcs.host.cleanup_failed", + "evidence_cleanup", + std::fs::remove_dir_all(&self.0), + ); + } +} + +#[cfg(unix)] +fn create(path: &Path) -> io::Result<()> { + use std::os::unix::fs::DirBuilderExt; + std::fs::DirBuilder::new().mode(0o700).create(path) +} + +#[cfg(windows)] +fn create(path: &Path) -> io::Result<()> { + crate::authentication::windows::private_directory(path) +} diff --git a/rust/crates/remote/src/bin/lithe-remote-server.rs b/rust/crates/remote/src/bin/lithe-remote-server.rs index 9bca438d..229db9f9 100644 --- a/rust/crates/remote/src/bin/lithe-remote-server.rs +++ b/rust/crates/remote/src/bin/lithe-remote-server.rs @@ -4,7 +4,7 @@ //! - `--connect `: relay standard streams to the persistent session //! ``, starting its daemon when needed. This is what transports run. //! - `--daemon `: the persistent session itself, started by `--connect`. -//! - `--identity`, `--version`, `--print-environment`: helpers for the +//! - `--identity`, `--target-identity`, `--version`, `--print-environment`: helpers for the //! bootstrapper and for environment resolution. //! //! Nothing but protocol bytes may reach standard output in `--stdio` and @@ -15,7 +15,7 @@ use std::io::{self, Write}; use std::path::PathBuf; use std::process::ExitCode; -const USAGE: &str = "usage: lithe-remote-server --stdio | --connect [--state-dir ] | --daemon [--state-dir ] | --identity | --version | --print-environment"; +const USAGE: &str = "usage: lithe-remote-server --stdio | --connect [--state-dir ] | --daemon [--state-dir ] | --target-identity --state-dir | --identity | --version | --print-environment"; fn main() -> ExitCode { let arguments: Vec = std::env::args().skip(1).collect(); @@ -34,6 +34,9 @@ fn main() -> ExitCode { .map_err(io::Error::from) .and_then(|()| writeln!(stdout)) }), + ["--target-identity", "--state-dir", root] => { + lithe_remote::server::print_target_identity(std::path::Path::new(root)) + } ["--version"] => writeln!(io::stdout(), "{}", env!("CARGO_PKG_VERSION")), ["--print-environment"] => lithe_remote::server::print_environment(), _ => { diff --git a/rust/crates/remote/src/client/api.rs b/rust/crates/remote/src/client/api.rs index 7b121eb7..befb072e 100644 --- a/rust/crates/remote/src/client/api.rs +++ b/rust/crates/remote/src/client/api.rs @@ -50,6 +50,8 @@ pub struct WriteOptions { pub overwrite: bool, /// Create missing parent directories first. pub create_parents: bool, + /// Optional editor boundary; every descendant directory must be a real directory. + pub root: Option, } /// What to run in [`RemoteSession::spawn`]. @@ -209,20 +211,74 @@ impl RemoteSession { /// Reads a whole file in chunks. Fails with `CONFLICT` when the file /// changes while it is being read, rather than returning a mixture. pub fn read_file(&self, path: &str) -> Result<(Vec, FileMetadata), ClientError> { + self.read_file_with_budget(path, usize::MAX, None, || false) + } + + /// Reads within a cumulative byte budget and one overall deadline. Cancellation + /// is observed between chunks and at most every 50 ms while a reply is pending. + pub fn read_file_limited( + &self, + path: &str, + limit: usize, + timeout: Duration, + cancelled: impl FnMut() -> bool, + ) -> Result<(Vec, FileMetadata), ClientError> { + let deadline = Instant::now().checked_add(timeout).ok_or_else(|| { + ClientError::Protocol("the read deadline cannot be represented".into()) + })?; + self.read_file_with_budget(path, limit, Some(deadline), cancelled) + } + + fn read_file_with_budget( + &self, + path: &str, + limit: usize, + deadline: Option, + mut cancelled: impl FnMut() -> bool, + ) -> Result<(Vec, FileMetadata), ClientError> { let mut content = Vec::new(); let mut first: Option = None; loop { - let chunk: ReadFileResult = self.call( + if cancelled() { + return Err(ClientError::Cancelled); + } + let remaining = deadline.map_or(REQUEST_TIMEOUT, |deadline| { + deadline.saturating_duration_since(Instant::now()) + }); + if remaining.is_zero() { + return Err(ClientError::Timeout); + } + let length = MAX_TRANSFER_BYTES + .min(limit.saturating_sub(content.len()).saturating_add(1) as u64); + let pending = self.begin_request_value( methods::FS_READ_FILE, - &ReadFileParams { + serde_json::to_value(ReadFileParams { path: path.into(), offset: content.len() as u64, - length: MAX_TRANSFER_BYTES, - }, + length, + }) + .expect("read parameters serialize"), + remaining.min(REQUEST_TIMEOUT), )?; + let chunk: ReadFileResult = loop { + if cancelled() { + return Err(ClientError::Cancelled); + } + if let Some(value) = pending.poll(Duration::from_millis(50))? { + break serde_json::from_value(value) + .map_err(|error| ClientError::Protocol(error.to_string()))?; + } + }; + if chunk.metadata.size > limit as u64 { + return Err(ClientError::Remote(RemoteError::new( + ErrorCode::TooLarge, + "the file exceeds the read budget", + ))); + } if let Some(first) = &first { if first.size != chunk.metadata.size || first.modified_ms != chunk.metadata.modified_ms + || first.revision != chunk.metadata.revision { return Err(ClientError::Remote(RemoteError::new( ErrorCode::Conflict, @@ -230,7 +286,25 @@ impl RemoteSession { ))); } } - content.extend(decode(&chunk.data)?); + let bytes = decode(&chunk.data)?; + let total = content + .len() + .checked_add(bytes.len()) + .ok_or_else(|| ClientError::Protocol("invalid read size".into()))?; + if total > limit { + return Err(ClientError::Remote(RemoteError::new( + ErrorCode::TooLarge, + "the file exceeds the read budget", + ))); + } + if bytes.len() as u64 > length + || total as u64 > chunk.metadata.size + || chunk.eof != (total as u64 == chunk.metadata.size) + || (bytes.is_empty() && !chunk.eof) + { + return Err(ClientError::Protocol("invalid read progress".into())); + } + content.extend_from_slice(&bytes); let eof = chunk.eof; first.get_or_insert(chunk.metadata); if eof { @@ -246,6 +320,18 @@ impl RemoteSession { content: &[u8], options: WriteOptions, ) -> Result { + if options.root.is_some() + && !self + .hello() + .host + .features + .contains(&methods::Feature::GuardedWrites) + { + return Err(ClientError::Remote(RemoteError::new( + ErrorCode::Unsupported, + "the server does not support scoped saves", + ))); + } self.call( methods::FS_WRITE_FILE, &WriteFileParams { @@ -254,6 +340,7 @@ impl RemoteSession { expected: options.expected, overwrite: options.overwrite, create_parents: options.create_parents, + root: options.root, }, ) } diff --git a/rust/crates/remote/src/client/launch.rs b/rust/crates/remote/src/client/launch.rs index 301eb43b..9f39f4b9 100644 --- a/rust/crates/remote/src/client/launch.rs +++ b/rust/crates/remote/src/client/launch.rs @@ -107,6 +107,50 @@ pub fn launch_command(root: Option<&str>, server_arguments: &[&str]) -> Vec) -> Vec { + let mut command = launch_command(root, &[]); + command[2] = LAUNCH_SCRIPT.replace( + "shift; exec \"$exe\" \"$@\"", + "target=$(\"$exe\" --target-identity --state-dir \"$root\") || exit 95; echo \"LITHE-TARGET $target\"; read key || exit 96; exec \"$exe\" --connect \"$key\" --state-dir \"$root\"", + ); + command +} + +/// Installs the server, reads its account-local identity and lets the caller +/// select a fresh or previously bound key before the daemon is contacted. +pub fn launch_bound( + output: &mut impl Read, + input: &mut impl Write, + artifact_for: impl FnOnce(&ProbeReport) -> Option, + log: &ConnectionLog, + stage: impl FnMut(Stage), + select_key: impl FnOnce(&str) -> String, +) -> Result { + let launched = launch(output, input, artifact_for, log, stage)?; + let line = read_line(output, 128)? + .ok_or_else(|| LaunchError::Protocol("missing target identity".into()))?; + let text = std::str::from_utf8(&line) + .map_err(|_| LaunchError::Protocol("invalid target identity".into()))?; + let identity = text + .strip_prefix("LITHE-TARGET ") + .filter(|value| crate::protocol::methods::is_sha256_hex(value)) + .ok_or_else(|| LaunchError::Protocol("invalid target identity".into()))?; + let key = select_key(identity); + if key.is_empty() + || key.len() > 64 + || !key + .bytes() + .all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c)) + { + return Err(LaunchError::Protocol("invalid session key".into())); + } + writeln!(input, "{key}").map_err(LaunchError::Io)?; + input.flush().map_err(LaunchError::Io)?; + Ok(launched) +} + /// What happened before the server took over the stream. #[derive(Clone, Debug, Eq, PartialEq)] pub struct Launched { diff --git a/rust/crates/remote/src/client/mod.rs b/rust/crates/remote/src/client/mod.rs index 22606796..b8a51157 100644 --- a/rust/crates/remote/src/client/mod.rs +++ b/rust/crates/remote/src/client/mod.rs @@ -69,6 +69,7 @@ pub mod prompt; mod routes; pub mod session; pub mod ssh_config; +pub mod ssh_identity; pub mod transport; pub mod trust; pub mod wsl; diff --git a/rust/crates/remote/src/client/session.rs b/rust/crates/remote/src/client/session.rs index d7ee07f9..36bf5b4c 100644 --- a/rust/crates/remote/src/client/session.rs +++ b/rust/crates/remote/src/client/session.rs @@ -133,6 +133,8 @@ pub enum ClientError { }, /// No response arrived in time. A late response is discarded. Timeout, + /// The caller cancelled an operation; its pending request is withdrawn. + Cancelled, /// The peer sent something that is not this protocol. Protocol(String), } @@ -150,6 +152,7 @@ impl fmt::Display for ClientError { write!(formatter, "the remote connection closed: {diagnostics}") } Self::Timeout => formatter.write_str("the remote server did not answer in time"), + Self::Cancelled => formatter.write_str("the remote operation was cancelled"), Self::Protocol(message) => write!(formatter, "remote protocol error: {message}"), } } @@ -163,6 +166,7 @@ impl ClientError { pub fn failure_category(&self) -> String { match self { Self::Timeout => "timeout".into(), + Self::Cancelled => "cancelled".into(), Self::Disconnected { .. } => "closed".into(), Self::Transport(_) => "transport".into(), Self::Spawn(_) => "spawn".into(), @@ -1198,6 +1202,31 @@ mod tests { assert_eq!(lock(&outgoing.state).frames.len(), 1); } + #[test] + fn cancelling_a_whole_file_read_withdraws_the_pending_chunk() { + // No transport thread: the queued request deterministically marks the + // first pending poll, after which the caller cancels without a reply. + let session = RemoteSession { + outgoing: Arc::default(), + pending: Arc::default(), + routes: Arc::default(), + next_request: Arc::new(AtomicU64::new(0)), + next_resource: AtomicU64::new(1), + position: EventPosition::default(), + child: Mutex::new(None), + stderr_tail: Arc::new(StderrTail::finished()), + hello: None, + log: ConnectionLog::begin(ConnectionKind::Ssh), + }; + let result = session.read_file_limited("/file", 1024, Duration::from_secs(1), || { + !lock(&session.outgoing.state).frames.is_empty() + }); + assert!(matches!(result, Err(ClientError::Cancelled)), "{result:?}"); + assert!(lock(&session.pending).waiting.is_empty()); + assert!(lock(&session.outgoing.state).frames.is_empty()); + assert!(!session.is_closed()); + } + #[test] fn dropping_a_queued_request_withdraws_only_its_frame() { let outgoing = Arc::new(Outgoing::default()); diff --git a/rust/crates/remote/src/client/ssh_identity.rs b/rust/crates/remote/src/client/ssh_identity.rs new file mode 100644 index 00000000..7f389f54 --- /dev/null +++ b/rust/crates/remote/src/client/ssh_identity.rs @@ -0,0 +1,202 @@ +//! Identity evidence from the actual OpenSSH process, never from `ssh -G`. +//! +//! The caller captures OpenSSH's own `-E` log in an owner-only directory. +//! Remote banners, command stderr and proxy stderr cannot write this channel. +//! Only source-tagged records of the locally spawned PID are considered. An +//! unfamiliar format, a proxy route or incomplete evidence has no reusable +//! identity; callers must use a connection-local trust key and send no token. + +use serde::Serialize; +use sha2::{Digest, Sha256}; + +/// Maximum evidence read for one connection. Overflow fails closed. +pub const MAX_BYTES: usize = 64 * 1024; + +/// Overrides only logging and connection multiplexing, never host-key policy. +pub const OPTIONS: &[&str] = &[ + "ControlMaster=no", + "ControlPath=none", + "FingerprintHash=sha256", + "LogLevel=ERROR", + "LogVerbose=sshconnect.c:ssh_login():*,sshconnect.c:verify_host_key():*,sshconnect.c:ssh_connect_direct():*,sshconnect.c:ssh_proxy_connect():*,sshconnect.c:ssh_proxy_fdpass_connect():*,sshconnect2.c:ssh_userauth2():*", +]; + +/// Validated facts from one successfully authenticated direct connection. +#[derive(Debug, Eq, PartialEq, Serialize)] +pub struct Identity { + host: String, + port: u16, + user: String, + host_key: String, + peer: String, +} + +/// Reads only OpenSSH's own records for `pid`. Success must follow both the +/// selected host key and account, on a direct socket. It proves which key +/// OpenSSH accepted under the user's existing host-key policy. +pub fn parse(bytes: &[u8], pid: u32) -> Option { + if bytes.len() > MAX_BYTES { + return None; + } + let text = std::str::from_utf8(bytes).ok()?; + let pid_value = pid.to_string(); + let mut account = None; + let mut key = None; + let mut peer = None; + let mut authenticated = false; + for line in text.lines() { + let Some((tag, remainder)) = line.split_once(" (") else { + continue; + }; + let Some((origin, message)) = remainder.split_once("): ") else { + continue; + }; + let origin_pid = origin.strip_prefix("pid=").or_else(|| { + // Apple's OpenSSH also tags the binary path in its local log. + let (binary, pid) = origin.strip_prefix("bin=")?.rsplit_once(", pid=")?; + (binary.starts_with('/') && field(binary)).then_some(pid) + }); + if origin_pid != Some(pid_value.as_str()) { + continue; + } + let tag = tag.strip_prefix("debug1: ").unwrap_or(tag); + let Some((function, line_number)) = tag.rsplit_once(':') else { + continue; + }; + if line_number.is_empty() || !line_number.bytes().all(|c| c.is_ascii_digit()) { + continue; + } + match function { + "sshconnect.c:ssh_proxy_connect()" | "sshconnect.c:ssh_proxy_fdpass_connect()" => { + return None + } + "sshconnect.c:ssh_connect_direct()" if message.starts_with("Connecting to ") => { + let address = message.strip_prefix("Connecting to ")?.strip_suffix('.')?; + let (address, port) = address.rsplit_once(" port ")?; + let (_, ip) = address.rsplit_once(" [")?; + let ip = ip.strip_suffix(']')?.parse::().ok()?; + peer = Some((ip.to_string(), port.parse::().ok()?)); + } + "sshconnect.c:ssh_login()" if message.starts_with("Authenticating to ") => { + if account.is_some() { + return None; + } + let (address, user) = message + .strip_prefix("Authenticating to ")? + .rsplit_once(" as '")?; + let user = user.strip_suffix('\'')?; + let (host, port) = address.rsplit_once(':')?; + if !field(host) || !field(user) { + return None; + } + account = Some((host.to_owned(), port.parse::().ok()?, user.to_owned())); + } + "sshconnect.c:verify_host_key()" if !authenticated => { + let value = message + .strip_prefix("Server host key: ") + .or_else(|| message.strip_prefix("Server host certificate: ")); + if let Some(value) = value { + let mut fields = value.split_whitespace(); + let kind = fields.next()?; + let fingerprint = fields.next()?.trim_end_matches(','); + if !field(kind) + || !fingerprint + .strip_prefix("SHA256:")? + .bytes() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'+' | b'/' | b'=')) + || !(50..=51).contains(&fingerprint.len()) + { + return None; + } + if key.replace(format!("{kind} {fingerprint}")).is_some() { + return None; + } + } + } + "sshconnect2.c:ssh_userauth2()" if message.starts_with("Authenticated to ") => { + if authenticated + || key.is_none() + || account.is_none() + || message.contains("(via proxy)") + { + return None; + } + authenticated = true; + } + _ => {} + } + } + let (host, port, user) = account?; + let (peer, peer_port) = peer?; + if !authenticated || port == 0 || peer_port != port { + return None; + } + Some(Identity { + host, + port, + user, + host_key: key?, + peer, + }) +} + +fn field(value: &str) -> bool { + !value.is_empty() && value.len() <= 1024 && !value.chars().any(|c| c.is_control() || c == '\\') +} + +/// Domain-separated digest of canonical structured identity facts. It is +/// opaque storage identity, never a credential or a replacement for SSH. +pub fn digest(value: &impl Serialize) -> String { + let mut hasher = Sha256::new(); + hasher.update(b"lithe.remote.identity.v1\0"); + hasher.update(serde_json::to_vec(value).expect("identity fields serialize")); + crate::protocol::methods::encode_hex(&hasher.finalize()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn evidence() -> String { + format!("debug1: sshconnect.c:ssh_connect_direct():10 (pid=7): Connecting to box [127.0.0.1] port 22.\n\ + debug1: sshconnect.c:ssh_login():20 (pid=7): Authenticating to box:22 as 'dev'\n\ + debug1: sshconnect.c:verify_host_key():30 (pid=7): Server host key: ssh-ed25519 SHA256:{}\n\ + sshconnect2.c:ssh_userauth2():40 (pid=7): Authenticated to box ([127.0.0.1]:22) using \"publickey\".\n", "a".repeat(43)) + } + + #[test] + fn accepts_only_complete_actual_process_evidence() { + let text = evidence(); + let identity = parse(text.as_bytes(), 7).unwrap(); + assert_eq!( + parse( + text.replace("(pid=7)", "(bin=/usr/bin/ssh, pid=7)") + .as_bytes(), + 7 + ), + Some(identity) + ); + let identity = parse(text.as_bytes(), 7).unwrap(); + assert_eq!(identity.host, "box"); + assert_eq!(identity.user, "dev"); + assert!(parse(text.as_bytes(), 8).is_none()); + assert!(parse(text.split("sshconnect2.c").next().unwrap().as_bytes(), 7).is_none()); + assert!(parse(text.replace(" (pid=7)", "").as_bytes(), 7).is_none()); + assert!(parse( + text.replace("([127.0.0.1]:22)", "(via proxy)").as_bytes(), + 7 + ) + .is_none()); + assert!(parse(format!("{text}{}", "x".repeat(MAX_BYTES)).as_bytes(), 7).is_none()); + for changed in [ + text.replace("'dev'", "'ops'"), + text.replace(&"a".repeat(43), &"b".repeat(43)), + text.replace("box", "other"), + ] { + assert_ne!( + digest(&identity), + digest(&parse(changed.as_bytes(), 7).unwrap()) + ); + } + } +} diff --git a/rust/crates/remote/src/client/trust.rs b/rust/crates/remote/src/client/trust.rs index 93b9ebfc..0819ddfd 100644 --- a/rust/crates/remote/src/client/trust.rs +++ b/rust/crates/remote/src/client/trust.rs @@ -64,6 +64,10 @@ pub struct Target { /// naming them. #[serde(default, skip_serializing_if = "Option::is_none")] pub user_id: Option, + /// Actual authenticated target digest, or a connection-local digest when + /// reusable evidence is unavailable. Absent only in legacy records. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub identity: Option, } /// The fields of one hop that choose where it ends. Keys, timeouts, @@ -163,7 +167,11 @@ impl Target { }), }) .collect(); - Self { hops, user_id } + Self { + hops, + user_id, + identity: None, + } } /// Refuses targets no transport chain produces: too many hops, empty, @@ -178,7 +186,11 @@ impl Target { && !value.chars().any(char::is_control) }; let optional = |value: &Option| value.as_deref().is_none_or(field); - let valid = self.hops.len() <= MAX_HOPS + let valid = self + .identity + .as_deref() + .is_none_or(crate::protocol::methods::is_sha256_hex) + && self.hops.len() <= MAX_HOPS && self.hops.iter().enumerate().all(|(index, hop)| match hop { TargetHop::Ssh(hop) => { field(&hop.destination) @@ -634,6 +646,27 @@ mod tests { target(vec![Hop::Ssh(ssh("dev@box"))], Some(1000)) } + #[test] + fn authenticated_targets_do_not_inherit_alias_only_decisions() { + let legacy = devbox(); + let mut decisions = Decisions::parse(None).unwrap(); + trust(&mut decisions, &legacy, "/srv/app", false); + let bound = |identity: &str| { + let mut value = serde_json::to_value(&legacy).unwrap(); + value["identity"] = json!(identity); + serde_json::from_value::(value).unwrap() + }; + let first = bound(&"a".repeat(64)); + let rebound = bound(&"b".repeat(64)); + assert_eq!(state(&decisions, &first, "/srv/app"), TrustState::Unknown); + trust(&mut decisions, &first, "/srv/app", false); + assert_eq!(state(&decisions, &first, "/srv/app"), TrustState::Trusted); + assert_eq!(state(&decisions, &rebound, "/srv/app"), TrustState::Unknown); + let reloaded = Decisions::parse(Some(&decisions.text().unwrap())).unwrap(); + assert_eq!(state(&reloaded, &first, "/srv/app"), TrustState::Trusted); + assert_eq!(state(&reloaded, &rebound, "/srv/app"), TrustState::Unknown); + } + fn trust(decisions: &mut Decisions, target: &Target, path: &str, location: bool) { decisions .decide( diff --git a/rust/crates/remote/src/failure_log.rs b/rust/crates/remote/src/failure_log.rs index cd96e74f..fb862532 100644 --- a/rust/crates/remote/src/failure_log.rs +++ b/rust/crates/remote/src/failure_log.rs @@ -149,6 +149,7 @@ pub(crate) fn client_category(error: &crate::client::session::ClientError) -> St use crate::client::session::ClientError; match error { ClientError::Timeout => "timeout".into(), + ClientError::Cancelled => "cancelled".into(), ClientError::Disconnected { .. } => "closed".into(), ClientError::Transport(_) => "transport".into(), ClientError::Spawn(error) => format!("{:?}", error.kind()), diff --git a/rust/crates/remote/src/protocol/methods.rs b/rust/crates/remote/src/protocol/methods.rs index 2c802b51..8d05c67b 100644 --- a/rust/crates/remote/src/protocol/methods.rs +++ b/rust/crates/remote/src/protocol/methods.rs @@ -480,6 +480,8 @@ pub enum WatchBackend { pub enum Feature { /// `fs.*` methods. Filesystem, + /// Scoped editor saves with precise revisions and directory-handle publication. + GuardedWrites, /// Bounded staged uploads with SHA-256 and atomic no-replace publication. Upload, /// Session-owned private run directories reclaimed when the session ends. @@ -634,6 +636,9 @@ pub struct FileMetadata { /// stay exact in JavaScript numbers, which a future TypeScript client /// relies on. pub modified_ms: Option, + /// Opaque host file identity and nanosecond timestamps; absent on older servers. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub revision: Option, /// No write permission bit is set. pub readonly: bool, /// Permission bits (`0o755` style), for executable markers and @@ -707,10 +712,14 @@ pub struct FileVersion { pub size: u64, /// Modification time in milliseconds the client last saw. pub modified_ms: Option, + /// Opaque revision returned with the content; compared exactly when supplied. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub revision: Option, } /// Parameters of `fs.writeFile`. The file is replaced atomically through a -/// temporary sibling, and writes go through symbolic links. +/// temporary sibling. Scoped editor writes refuse symbolic links; explicit +/// unscoped host writes retain leaf-link behavior. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WriteFileParams { @@ -729,6 +738,10 @@ pub struct WriteFileParams { /// Create missing parent directories first. #[serde(default)] pub create_parents: bool, + /// Optional absolute workspace boundary. Descendant symlinks and `..` are refused. + /// Requires `guardedWrites`; clients must not silently retry without it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub root: Option, } /// Parameters of `fs.createDir`. diff --git a/rust/crates/remote/src/server/connection.rs b/rust/crates/remote/src/server/connection.rs index b9e6993f..67c0b6be 100644 --- a/rust/crates/remote/src/server/connection.rs +++ b/rust/crates/remote/src/server/connection.rs @@ -7,7 +7,7 @@ //! complete in any order; `process.kill` and `terminal.close` are among them //! because finding every member of a session scans the process table. -use crate::protocol::frame::{read_frame, write_frame}; +use crate::protocol::frame::{read_frame, write_frame, MAX_FRAME_BYTES}; use crate::protocol::methods::{ self, AckParams, HelloParams, HelloResult, ResumeParams, ResumeResult, SessionInfo, }; @@ -496,12 +496,54 @@ mod tests; fn write_loop(mut output: impl Write, receiver: Receiver) -> io::Result<()> { while let Ok(Outgoing::Message(message)) = receiver.recv() { - let payload = serde_json::to_vec(&message).map_err(io::Error::from)?; + let mut payload = Vec::new(); + if let Err(error) = serde_json::to_writer(FrameBuffer(&mut payload), &message) { + if payload.len() < MAX_FRAME_BYTES { + return Err(io::Error::from(error)); + } + match message { + Message::Response { id, .. } => { + payload = serde_json::to_vec(&Message::failure( + id, + RemoteError::new( + ErrorCode::TooLarge, + "the response exceeds the frame limit", + ), + )) + .map_err(io::Error::from)?; + } + _ => { + // Events have no request id for a recoverable error response. + // Their producers must bound batches; never silently discard one. + return Err(io::Error::from(error)); + } + } + } write_frame(&mut output, &payload).map_err(|error| io::Error::other(error.to_string()))?; } Ok(()) } +/// Stops serialization before an oversized response allocates another full frame. +struct FrameBuffer<'a>(&'a mut Vec); + +impl Write for FrameBuffer<'_> { + fn write(&mut self, bytes: &[u8]) -> io::Result { + let remaining = MAX_FRAME_BYTES - self.0.len(); + self.0 + .extend_from_slice(&bytes[..bytes.len().min(remaining)]); + if bytes.len() > remaining { + Err(io::Error::other("frame budget exceeded")) + } else { + Ok(bytes.len()) + } + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + pub(crate) fn respond(id: u64, reply: Result) -> Message { match reply { Ok(result) => Message::success(id, result), diff --git a/rust/crates/remote/src/server/connection/tests.rs b/rust/crates/remote/src/server/connection/tests.rs index 897c48f5..715ffe2c 100644 --- a/rust/crates/remote/src/server/connection/tests.rs +++ b/rust/crates/remote/src/server/connection/tests.rs @@ -6,6 +6,29 @@ use std::time::Instant; const STEP: Duration = Duration::from_secs(5); +// An oversized result must fail only its request; the next reply still arrives. +#[test] +fn oversized_response_preserves_the_writer_for_the_next_request() { + let (send, receive) = mpsc::sync_channel(3); + send.send(Outgoing::Message(Message::success( + 1, + json!("x".repeat(crate::protocol::frame::MAX_FRAME_BYTES)), + ))) + .unwrap(); + send.send(Outgoing::Message(Message::success(2, json!({})))) + .unwrap(); + send.send(Outgoing::Close).unwrap(); + let mut bytes = Vec::new(); + write_loop(&mut bytes, receive).unwrap(); + let mut input = std::io::Cursor::new(bytes); + let first: Message = serde_json::from_slice(&read_frame(&mut input).unwrap().unwrap()).unwrap(); + assert!( + matches!(first, Message::Response { id: 1, error: Some(error), .. } if error.code == ErrorCode::TooLarge) + ); + let next: Message = serde_json::from_slice(&read_frame(&mut input).unwrap().unwrap()).unwrap(); + assert_eq!(next, Message::success(2, json!({}))); +} + #[test] fn cancellation_waits_for_process_terminal_and_watch_publication() { let root = WatchRoot::new(); diff --git a/rust/crates/remote/src/server/daemon.rs b/rust/crates/remote/src/server/daemon.rs index dcea8d4f..1c5b7e5f 100644 --- a/rust/crates/remote/src/server/daemon.rs +++ b/rust/crates/remote/src/server/daemon.rs @@ -151,7 +151,7 @@ fn daemon_name(key: &str, executable_sha256: &str) -> String { /// Creates `path` with mode 0700, or verifies an existing one is a real /// directory owned by the user that nobody else can write to. -fn private_directory(path: &Path) -> io::Result<()> { +pub(super) fn private_directory(path: &Path) -> io::Result<()> { match fs::DirBuilder::new() .recursive(true) .mode(0o700) diff --git a/rust/crates/remote/src/server/fs.rs b/rust/crates/remote/src/server/fs.rs index 8a730ca4..c51b00f2 100644 --- a/rust/crates/remote/src/server/fs.rs +++ b/rust/crates/remote/src/server/fs.rs @@ -2,19 +2,20 @@ //! //! The server acts with the remote user's own permissions, exactly like the //! shell the user could open over the same transport. It therefore does not -//! confine paths to the workspace; the client decides which paths it shows. +//! confine general host operations to a workspace; editor saves explicitly +//! carry a root and refuse descendant symbolic links at publication. use crate::protocol::methods::{ - self, decode_bytes, encode_bytes, CopyParams, CopyResult, CreateDirParams, DirectoryEntry, - FileKind, FileMetadata, PathParams, ReadDirResult, ReadFileParams, ReadFileResult, - RealPathResult, RemoveParams, RenameParams, SetPermissionsParams, VolumeInfo, WriteFileParams, + self, encode_bytes, CopyParams, CopyResult, CreateDirParams, DirectoryEntry, FileKind, + FileMetadata, PathParams, ReadDirResult, ReadFileParams, ReadFileResult, RealPathResult, + RemoveParams, RenameParams, SetPermissionsParams, VolumeInfo, WriteFileParams, MAX_TRANSFER_BYTES, }; use crate::protocol::{ErrorCode, RemoteError}; use crate::server::{parse, platform, to_value}; use serde_json::{json, Value}; -use std::fs::{self, File, OpenOptions}; -use std::io::{self, Read, Seek, SeekFrom, Write}; +use std::fs::{self, OpenOptions}; +use std::io::{self, Read, Seek, SeekFrom}; use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; @@ -22,6 +23,13 @@ use std::time::UNIX_EPOCH; static TEMPORARY_FILE_COUNTER: AtomicU64 = AtomicU64::new(0); +/// Bounds synchronous listings; recursive indexes use streaming walk batches. +const MAX_DIRECTORY_ENTRIES: usize = 20_000; +/// Reserve framing and result-envelope space around serialized entries. +const DIRECTORY_ENVELOPE_BYTES: usize = 1024; + +mod guarded_write; + pub(crate) fn handle(method: &str, params: Value) -> Result { match method { methods::FS_STAT => { @@ -125,6 +133,7 @@ fn describe(path: &Path, metadata: &fs::Metadata) -> FileMetadata { .ok() .and_then(|time| time.duration_since(UNIX_EPOCH).ok()) .and_then(|duration| i64::try_from(duration.as_millis()).ok()), + revision: Some(revision(metadata)), readonly: metadata.permissions().readonly(), mode: metadata.mode() & 0o7777, symlink_target, @@ -135,6 +144,19 @@ fn describe(path: &Path, metadata: &fs::Metadata) -> FileMetadata { } } +fn revision(metadata: &fs::Metadata) -> String { + format!( + "{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}", + metadata.dev(), + metadata.ino(), + metadata.len(), + metadata.mtime(), + metadata.mtime_nsec(), + metadata.ctime(), + metadata.ctime_nsec() + ) +} + pub(crate) fn kind_of(file_type: &fs::FileType) -> FileKind { if file_type.is_symlink() { FileKind::Symlink @@ -148,11 +170,29 @@ pub(crate) fn kind_of(file_type: &fs::FileType) -> FileKind { } fn read_dir(params: PathParams) -> Result { + read_dir_bounded( + params, + MAX_DIRECTORY_ENTRIES, + crate::protocol::frame::MAX_FRAME_BYTES - DIRECTORY_ENVELOPE_BYTES, + ) +} + +fn read_dir_bounded( + params: PathParams, + max_entries: usize, + max_bytes: usize, +) -> Result { let path = host_path(¶ms.path)?; let listing = fs::read_dir(&path).map_err(|error| io_error(error, ¶ms.path))?; let mut entries = Vec::new(); let mut skipped_non_utf8 = 0; + let mut bytes = 0; + let mut examined = 0; for entry in listing { + examined += 1; + if examined > max_entries { + return Err(too_large(examined as u64)); + } let entry = entry.map_err(|error| io_error(error, ¶ms.path))?; let Ok(name) = entry.file_name().into_string() else { skipped_non_utf8 += 1; @@ -163,10 +203,18 @@ fn read_dir(params: PathParams) -> Result { let Ok(metadata) = fs::symlink_metadata(entry.path()) else { continue; }; - entries.push(DirectoryEntry { + let described = DirectoryEntry { metadata: describe(&entry.path(), &metadata), name, - }); + }; + bytes += serde_json::to_vec(&described) + .expect("directory entries serialize") + .len() + + 1; + if bytes > max_bytes { + return Err(too_large(bytes as u64)); + } + entries.push(described); } entries.sort_by(|left, right| left.name.cmp(&right.name)); Ok(ReadDirResult { @@ -226,111 +274,7 @@ fn read_file(params: ReadFileParams) -> Result { /// link itself intact. The rename gives the file a new inode, which breaks /// hard links, the same trade-off other editors' safe-write mode makes. fn write_file(params: WriteFileParams) -> Result { - let data = decode_bytes(¶ms.data) - .map_err(|error| RemoteError::new(ErrorCode::InvalidRequest, error.to_string()))?; - if data.len() as u64 > MAX_TRANSFER_BYTES { - return Err(too_large(data.len() as u64)); - } - let requested = host_path(¶ms.path)?; - let target = match fs::symlink_metadata(&requested) { - Ok(metadata) if metadata.file_type().is_symlink() => { - fs::canonicalize(&requested).map_err(|error| io_error(error, ¶ms.path))? - } - _ => requested, - }; - let current = match fs::metadata(&target) { - Ok(metadata) => Some(metadata), - Err(error) if error.kind() == io::ErrorKind::NotFound => None, - Err(error) => return Err(io_error(error, ¶ms.path)), - }; - if let Some(metadata) = ¤t { - if metadata.is_dir() { - return Err(RemoteError::new( - ErrorCode::IsADirectory, - "cannot replace a directory with a file", - )); - } - } - match (¶ms.expected, ¤t) { - (Some(expected), Some(metadata)) => { - let found = describe(&target, metadata); - if found.size != expected.size || found.modified_ms != expected.modified_ms { - return Err(RemoteError::new( - ErrorCode::Conflict, - "the file changed since it was read", - ) - .with_details(json!({ "size": found.size, "modifiedMs": found.modified_ms }))); - } - } - (Some(_), None) => { - return Err(RemoteError::new( - ErrorCode::Conflict, - "the file was deleted since it was read", - )) - } - (None, Some(_)) if !params.overwrite => { - return Err(RemoteError::new( - ErrorCode::AlreadyExists, - "the file already exists", - )) - } - _ => {} - } - - let parent = target - .parent() - .ok_or_else(|| RemoteError::new(ErrorCode::InvalidPath, "cannot write the root"))?; - if params.create_parents { - fs::create_dir_all(parent).map_err(|error| io_error(error, ¶ms.path))?; - } - let name = target - .file_name() - .map(|name| name.to_string_lossy().into_owned()) - .unwrap_or_default(); - let temporary = parent.join(format!( - ".{name}.lithe-{}-{}.tmp", - std::process::id(), - TEMPORARY_FILE_COUNTER.fetch_add(1, Ordering::Relaxed) - )); - // Without `expected` or `overwrite` the request only creates. The - // existence check above cannot protect the commit from a concurrent - // creation of the same path, so the commit itself must refuse to replace. - let create_only = params.expected.is_none() && !params.overwrite; - let written = write_temporary(&temporary, &data, current.as_ref()).and_then(|()| { - if create_only { - platform::rename_no_replace(&temporary, &target) - } else { - fs::rename(&temporary, &target) - } - }); - if let Err(error) = written { - let _ = fs::remove_file(&temporary); - return Err(io_error(error, ¶ms.path)); - } - stat(&target, ¶ms.path) -} - -/// Writes the replacement content. When a file is replaced, the temporary -/// file is created with at most the original's permission bits, so content -/// of an owner-only file is never readable by other users through the -/// temporary name; the umask can only remove bits, and the exact original -/// mode is restored before the rename publishes the file. -fn write_temporary(path: &Path, data: &[u8], replaced: Option<&fs::Metadata>) -> io::Result<()> { - let mut file = create_temporary(path, replaced)?; - file.write_all(data)?; - if let Some(metadata) = replaced { - file.set_permissions(metadata.permissions())?; - } - file.sync_all() -} - -fn create_temporary(path: &Path, replaced: Option<&fs::Metadata>) -> io::Result { - let mode = replaced.map_or(0o666, |metadata| metadata.permissions().mode() & 0o777); - OpenOptions::new() - .write(true) - .create_new(true) - .mode(mode) - .open(path) + guarded_write::write(params) } fn create_dir(params: CreateDirParams) -> Result<(), RemoteError> { @@ -615,6 +559,89 @@ pub(crate) fn io_error(error: io::Error, path: &str) -> RemoteError { #[cfg(test)] mod tests { use super::*; + use crate::protocol::methods::decode_bytes; + use std::fs::File; + + #[test] + fn directory_listing_stops_at_entry_and_serialized_byte_budgets() { + let directory = std::env::temp_dir().join(format!( + "lithe-list-budget-{}-{}", + std::process::id(), + TEMPORARY_FILE_COUNTER.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&directory).unwrap(); + let _cleanup = RemoveOnDrop(directory.clone()); + fs::write(directory.join("one"), b"1").unwrap(); + fs::write(directory.join("two"), b"2").unwrap(); + let params = || PathParams { + path: directory.to_str().unwrap().into(), + }; + assert_eq!( + read_dir_bounded(params(), 1, 4096).unwrap_err().code, + ErrorCode::TooLarge + ); + assert_eq!( + read_dir_bounded(params(), 10, 1).unwrap_err().code, + ErrorCode::TooLarge + ); + assert_eq!( + read_dir_bounded(params(), 10, 4096).unwrap().entries.len(), + 2 + ); + } + + #[test] + fn scoped_save_refuses_a_symlink_in_a_parent_directory() { + let directory = std::env::temp_dir().join(format!( + "lithe-scoped-save-{}", + TEMPORARY_FILE_COUNTER.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(directory.join("workspace")).unwrap(); + fs::create_dir_all(directory.join("outside")).unwrap(); + let _cleanup = RemoveOnDrop(directory.clone()); + std::os::unix::fs::symlink(directory.join("outside"), directory.join("workspace/link")) + .unwrap(); + let result = write_file( + serde_json::from_value(json!({ + "path": directory.join("workspace/link/new"), "root": directory.join("workspace"), + "data": encode_bytes(b"must stay inside") + })) + .unwrap(), + ); + assert!(result.is_err(), "scoped save followed a parent symlink"); + assert!(!directory.join("outside/new").exists()); + } + + #[test] + fn precise_revision_detects_same_size_and_restored_modification_time() { + let directory = std::env::temp_dir().join(format!( + "lithe-revision-save-{}", + TEMPORARY_FILE_COUNTER.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&directory).unwrap(); + let _cleanup = RemoveOnDrop(directory.clone()); + let path = directory.join("file"); + fs::write(&path, b"old").unwrap(); + let before = fs::metadata(&path).unwrap(); + let observed = describe(&path, &before); + let replacement = directory.join("replacement"); + fs::write(&replacement, b"new").unwrap(); + File::options() + .write(true) + .open(&replacement) + .unwrap() + .set_times(fs::FileTimes::new().set_modified(before.modified().unwrap())) + .unwrap(); + fs::rename(replacement, &path).unwrap(); + let result = write_file( + serde_json::from_value(json!({"path": path, + "data": encode_bytes(b"mine"), "expected": {"size": observed.size, + "modifiedMs": observed.modified_ms, "revision": observed.revision}})) + .unwrap(), + ); + assert_eq!(result.unwrap_err().code, ErrorCode::Conflict); + assert_eq!(fs::read(path).unwrap(), b"new"); + } #[test] fn link_metadata_reports_target_permissions_not_symlink_permissions() { @@ -640,28 +667,6 @@ mod tests { ); } - // Other users must not be able to open the temporary file while it holds - // the new content of an owner-only file; tightening the mode afterwards - // would not revoke a descriptor they already opened. - #[test] - fn temporary_file_for_an_owner_only_file_starts_owner_only() { - let directory = std::env::temp_dir().join(format!( - "lithe-remote-fs-mode-{}-{}", - std::process::id(), - TEMPORARY_FILE_COUNTER.fetch_add(1, Ordering::Relaxed) - )); - fs::create_dir_all(&directory).unwrap(); - let _cleanup = RemoveOnDrop(directory.clone()); - let original = directory.join("secret"); - fs::write(&original, b"old").unwrap(); - fs::set_permissions(&original, fs::Permissions::from_mode(0o600)).unwrap(); - let replaced = fs::metadata(&original).unwrap(); - - let temporary = directory.join("secret.tmp"); - let file = create_temporary(&temporary, Some(&replaced)).unwrap(); - assert_eq!(file.metadata().unwrap().permissions().mode() & 0o777, 0o600); - } - fn read_whole(path: &Path) -> Result { read_file(ReadFileParams { path: path.to_str().unwrap().to_owned(), diff --git a/rust/crates/remote/src/server/fs/guarded_write.rs b/rust/crates/remote/src/server/fs/guarded_write.rs new file mode 100644 index 00000000..fba8f733 --- /dev/null +++ b/rust/crates/remote/src/server/fs/guarded_write.rs @@ -0,0 +1,417 @@ +//! Directory-handle saves. A scoped path never follows a descendant symlink, +//! and cooperating daemons serialize saves before checking the expected revision. +//! External writers do not take this lock: POSIX rename has no revision CAS, +//! so the final recheck reduces, but cannot eliminate, their last syscall window. + +use super::{describe, host_path, io_error, too_large, TEMPORARY_FILE_COUNTER}; +use crate::protocol::methods::{ + decode_bytes, FileMetadata, FileVersion, WriteFileParams, MAX_TRANSFER_BYTES, +}; +use crate::protocol::{ErrorCode, RemoteError}; +use std::ffi::{CStr, CString, OsStr}; +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Write}; +use std::os::fd::{AsRawFd, FromRawFd}; +use std::os::unix::ffi::OsStrExt; +use std::os::unix::fs::OpenOptionsExt; +use std::path::{Component, Path}; +use std::sync::atomic::Ordering; +use std::time::{Duration, Instant}; + +pub(super) fn write(params: WriteFileParams) -> Result { + write_before_commit(params, || {}) +} + +fn write_before_commit( + params: WriteFileParams, + before_commit: impl FnOnce(), +) -> Result { + let data = decode_bytes(¶ms.data) + .map_err(|error| RemoteError::new(ErrorCode::InvalidRequest, error.to_string()))?; + if data.len() as u64 > MAX_TRANSFER_BYTES { + return Err(too_large(data.len() as u64)); + } + let requested = host_path(¶ms.path)?; + let boundary = params.root.as_deref().map(host_path).transpose()?; + let (parent, name) = if let Some(root) = &boundary { + let relative = requested.strip_prefix(root).map_err(|_| denied())?; + if relative + .components() + .any(|part| !matches!(part, Component::Normal(_))) + { + return Err(denied()); + } + let name = relative.file_name().ok_or_else(denied)?; + let root = fs::canonicalize(root).map_err(|error| io_error(error, ¶ms.path))?; + let mut parent = open_directory(&root).map_err(|error| io_error(error, ¶ms.path))?; + for part in relative.parent().unwrap_or(Path::new("")).components() { + let Component::Normal(part) = part else { + return Err(denied()); + }; + let name = c_name(part)?; + let opened = open_at( + &parent, + &name, + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW, + 0, + ); + parent = match opened { + Err(error) if params.create_parents && error.kind() == io::ErrorKind::NotFound => { + // SAFETY: parent is open and name is one NUL-terminated component. + if unsafe { libc::mkdirat(parent.as_raw_fd(), name.as_ptr(), 0o777) } != 0 { + let error = io::Error::last_os_error(); + if error.kind() != io::ErrorKind::AlreadyExists { + return Err(io_error(error, ¶ms.path)); + } + } + // Another creator may have won: re-open without following links. + open_at( + &parent, + &name, + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW, + 0, + ) + } + result => result, + } + .map_err(|error| scoped_error(error, ¶ms.path))?; + } + (parent, c_name(name)?) + } else { + // General host operations retain their explicit ability to write outside + // a workspace and through an existing leaf link. + let target = if fs::symlink_metadata(&requested).is_ok_and(|metadata| metadata.is_symlink()) + { + fs::canonicalize(&requested).map_err(|error| io_error(error, ¶ms.path))? + } else { + requested.clone() + }; + let parent = target.parent().ok_or_else(denied)?; + if params.create_parents { + fs::create_dir_all(parent).map_err(|error| io_error(error, ¶ms.path))?; + } + let parent = fs::canonicalize(parent).map_err(|error| io_error(error, ¶ms.path))?; + ( + open_directory(&parent).map_err(|error| io_error(error, ¶ms.path))?, + c_name(target.file_name().ok_or_else(denied)?)?, + ) + }; + lock_parent(&parent).map_err(|error| io_error(error, ¶ms.path))?; + let current = metadata_at(&parent, &name).map_err(|error| scoped_error(error, ¶ms.path))?; + check_expected(¶ms, current.as_ref())?; + let temporary = CString::new(format!( + ".lithe-{}-{}.tmp", + std::process::id(), + TEMPORARY_FILE_COUNTER.fetch_add(1, Ordering::Relaxed) + )) + .expect("temporary name has no NUL"); + let mut file = create_temporary(&parent, &temporary, current.as_ref()) + .map_err(|error| io_error(error, ¶ms.path))?; + let cleanup = Temporary { + parent: &parent, + name: &temporary, + }; + file.write_all(&data) + .and_then(|()| { + if let Some(metadata) = ¤t { + // SAFETY: file owns a live fd; mode_t retains each host's native width. + if unsafe { libc::fchmod(file.as_raw_fd(), metadata.mode & 0o7777) } != 0 { + return Err(io::Error::last_os_error()); + } + } + file.sync_all() + }) + .map_err(|error| io_error(error, ¶ms.path))?; + before_commit(); + let latest = metadata_at(&parent, &name).map_err(|error| scoped_error(error, ¶ms.path))?; + check_expected(¶ms, latest.as_ref())?; + if current.as_ref().map(|stamp| &stamp.revision) != latest.as_ref().map(|stamp| &stamp.revision) + { + return Err(conflict()); + } + let create_only = params.expected.is_none() && !params.overwrite; + if create_only { + // A hard-link publication is atomic no-replace on both host platforms. + // Both names refer to the same synchronized inode until cleanup unlinks + // the temporary name; no check-then-rename fallback can overwrite it. + // SAFETY: parent owns a live directory fd and both C strings outlive the call. + let status = unsafe { + libc::linkat( + parent.as_raw_fd(), + temporary.as_ptr(), + parent.as_raw_fd(), + name.as_ptr(), + 0, + ) + }; + if status != 0 { + return Err(io_error(io::Error::last_os_error(), ¶ms.path)); + } + } else { + // SAFETY: both names are single components relative to the live parent fd. + let status = unsafe { + libc::renameat( + parent.as_raw_fd(), + temporary.as_ptr(), + parent.as_raw_fd(), + name.as_ptr(), + ) + }; + if status != 0 { + return Err(io_error(io::Error::last_os_error(), ¶ms.path)); + } + } + drop(cleanup); + let saved = file + .metadata() + .map_err(|error| io_error(error, ¶ms.path))?; + Ok(describe(&requested, &saved)) +} + +fn check_expected(params: &WriteFileParams, found: Option<&Stamp>) -> Result<(), RemoteError> { + if found.is_some_and(|metadata| metadata.mode & libc::S_IFMT == libc::S_IFDIR) { + return Err(RemoteError::new( + ErrorCode::IsADirectory, + "cannot replace a directory", + )); + } + match (¶ms.expected, found) { + (Some(expected), Some(metadata)) if matches_version(expected, metadata) => Ok(()), + (Some(_), _) => Err(conflict()), + (None, Some(_)) if !params.overwrite => Err(RemoteError::new( + ErrorCode::AlreadyExists, + "the file already exists", + )), + _ => Ok(()), + } +} + +fn matches_version(expected: &FileVersion, observed: &Stamp) -> bool { + expected.size == observed.size + && expected.modified_ms == observed.modified_ms + && expected + .revision + .as_ref() + .is_none_or(|expected| expected == &observed.revision) +} + +fn conflict() -> RemoteError { + RemoteError::new(ErrorCode::Conflict, "the file changed since it was read") +} +fn denied() -> RemoteError { + RemoteError::new( + ErrorCode::PermissionDenied, + "the save path crosses the workspace boundary or a symbolic link", + ) +} +fn scoped_error(error: io::Error, path: &str) -> RemoteError { + if matches!(error.raw_os_error(), Some(libc::ELOOP | libc::ENOTDIR)) { + denied() + } else { + io_error(error, path) + } +} + +fn c_name(name: &OsStr) -> Result { + CString::new(name.as_bytes()).map_err(|_| denied()) +} + +fn open_directory(path: &Path) -> io::Result { + let mut directory = OpenOptions::new() + .read(true) + .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC) + .open("/")?; + for part in path.components() { + match part { + Component::RootDir => {} + Component::Normal(name) => { + let name = CString::new(name.as_bytes()).map_err(io::Error::other)?; + directory = open_at( + &directory, + &name, + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW, + 0, + )?; + } + _ => return Err(io::Error::from(io::ErrorKind::InvalidInput)), + } + } + Ok(directory) +} + +fn open_at(parent: &File, name: &CStr, flags: i32, mode: libc::mode_t) -> io::Result { + // SAFETY: name is NUL-terminated, parent remains open, and a successful fd + // is transferred exactly once into File. CLOEXEC prevents child inheritance. + let fd = unsafe { + libc::openat( + parent.as_raw_fd(), + name.as_ptr(), + flags | libc::O_CLOEXEC, + mode as libc::c_uint, + ) + }; + if fd < 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: openat returned a new owned fd. + Ok(unsafe { File::from_raw_fd(fd) }) +} + +/// Metadata read without requiring read access or opening a FIFO/device. +struct Stamp { + size: u64, + modified_ms: Option, + revision: String, + mode: libc::mode_t, +} + +fn metadata_at(parent: &File, name: &CStr) -> io::Result> { + let mut raw = std::mem::MaybeUninit::::uninit(); + // SAFETY: raw is writable storage for a stat, name is NUL-terminated, and + // parent stays live. AT_SYMLINK_NOFOLLOW observes the entry itself. + if unsafe { + libc::fstatat( + parent.as_raw_fd(), + name.as_ptr(), + raw.as_mut_ptr(), + libc::AT_SYMLINK_NOFOLLOW, + ) + } != 0 + { + let error = io::Error::last_os_error(); + return if error.kind() == io::ErrorKind::NotFound { + Ok(None) + } else { + Err(error) + }; + } + // SAFETY: fstatat initialized raw after returning success. + let raw = unsafe { raw.assume_init() }; + if raw.st_mode & libc::S_IFMT == libc::S_IFLNK { + return Err(io::Error::from_raw_os_error(libc::ELOOP)); + } + Ok(Some(Stamp { + size: raw.st_size as u64, + modified_ms: raw + .st_mtime + .checked_mul(1000) + .and_then(|seconds| seconds.checked_add(raw.st_mtime_nsec / 1_000_000)) + .filter(|milliseconds| *milliseconds >= 0), + revision: format!( + "{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}", + raw.st_dev, + raw.st_ino, + raw.st_size, + raw.st_mtime, + raw.st_mtime_nsec, + raw.st_ctime, + raw.st_ctime_nsec + ), + mode: raw.st_mode, + })) +} + +fn create_temporary(parent: &File, name: &CStr, replaced: Option<&Stamp>) -> io::Result { + let mode = replaced.map_or(0o666, |metadata| metadata.mode & 0o777); + open_at( + parent, + name, + libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW, + mode, + ) +} + +fn lock_parent(parent: &File) -> io::Result<()> { + let deadline = Instant::now() + Duration::from_secs(5); + loop { + // SAFETY: flock operates on the live directory fd. Closing it releases + // the lock, including on every error and unwinding path. + if unsafe { libc::flock(parent.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 { + return Ok(()); + } + let error = io::Error::last_os_error(); + if error.kind() != io::ErrorKind::WouldBlock || Instant::now() >= deadline { + return Err(error); + } + std::thread::sleep(Duration::from_millis(5)); + } +} + +/// Removes unpublished data, or the extra link of a newly published file. +struct Temporary<'a> { + parent: &'a File, + name: &'a CStr, +} +impl Drop for Temporary<'_> { + fn drop(&mut self) { + // SAFETY: both borrowed values outlive this guard; unlinkat follows no links. + if unsafe { libc::unlinkat(self.parent.as_raw_fd(), self.name.as_ptr(), 0) } != 0 { + let error = io::Error::last_os_error(); + if error.kind() != io::ErrorKind::NotFound { + eprintln!( + "lithe-remote-server: temporary save cleanup failed: {:?}", + error.kind() + ); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::protocol::methods::encode_bytes; + use serde_json::json; + + struct RemoveOnDrop(std::path::PathBuf); + impl Drop for RemoveOnDrop { + fn drop(&mut self) { + if let Err(error) = fs::remove_dir_all(&self.0) { + eprintln!("test directory cleanup failed: {error}"); + } + } + } + + #[test] + fn save_rechecks_changes_after_staging_and_reclaims_its_temporary() { + let directory = std::env::temp_dir().join(format!( + "lithe-save-commit-{}-{}", + std::process::id(), + TEMPORARY_FILE_COUNTER.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&directory).unwrap(); + let _cleanup = RemoveOnDrop(directory.clone()); + let path = directory.join("file"); + fs::write(&path, b"old").unwrap(); + let observed = describe(&path, &fs::metadata(&path).unwrap()); + let params = serde_json::from_value(json!({"path": path, "data": encode_bytes(b"mine"), + "expected": {"size": observed.size, "modifiedMs": observed.modified_ms, "revision": observed.revision}})).unwrap(); + let result = write_before_commit(params, || { + fs::write(&path, b"the external writer wins").unwrap(); + }); + assert_eq!(result.unwrap_err().code, ErrorCode::Conflict); + assert_eq!(fs::read(&path).unwrap(), b"the external writer wins"); + assert_eq!(fs::read_dir(directory).unwrap().count(), 1); + } + + #[test] + fn temporary_file_for_owner_only_content_is_private_at_creation() { + let directory = std::env::temp_dir().join(format!( + "lithe-save-mode-{}-{}", + std::process::id(), + TEMPORARY_FILE_COUNTER.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&directory).unwrap(); + let _cleanup = RemoveOnDrop(directory.clone()); + let parent = open_directory(&fs::canonicalize(&directory).unwrap()).unwrap(); + let stamp = Stamp { + size: 0, + modified_ms: None, + revision: String::new(), + mode: 0o600, + }; + let file = create_temporary(&parent, c"temporary", Some(&stamp)).unwrap(); + use std::os::unix::fs::MetadataExt; + assert_eq!(file.metadata().unwrap().mode() & 0o777, 0o600); + } +} diff --git a/rust/crates/remote/src/server/mod.rs b/rust/crates/remote/src/server/mod.rs index 6ce842ce..f41df3c3 100644 --- a/rust/crates/remote/src/server/mod.rs +++ b/rust/crates/remote/src/server/mod.rs @@ -33,6 +33,7 @@ mod resources; mod run_directory; mod session; mod spawner; +mod target_identity; mod terminal; mod threads; mod tunnel; @@ -42,6 +43,7 @@ mod watch; pub use daemon::{run_daemon, run_proxy, PersistentOptions}; pub use environment::print_environment; +pub use target_identity::print as print_target_identity; use crate::protocol::methods::ServerIdentity; use crate::protocol::{ErrorCode, RemoteError, PROTOCOL_VERSION}; diff --git a/rust/crates/remote/src/server/platform/mod.rs b/rust/crates/remote/src/server/platform/mod.rs index 0ecf1c32..27f6ea70 100644 --- a/rust/crates/remote/src/server/platform/mod.rs +++ b/rust/crates/remote/src/server/platform/mod.rs @@ -53,6 +53,7 @@ pub(crate) fn host_capabilities() -> HostCapabilities { let account = unix::current_account(); let mut features = vec![ Feature::Filesystem, + Feature::GuardedWrites, Feature::Upload, Feature::RunDirectories, Feature::Walk, diff --git a/rust/crates/remote/src/server/target_identity.rs b/rust/crates/remote/src/server/target_identity.rs new file mode 100644 index 00000000..a9870d9a --- /dev/null +++ b/rust/crates/remote/src/server/target_identity.rs @@ -0,0 +1,70 @@ +//! Account-local identity of the actual server state, before any session token. + +use super::{daemon::private_directory, platform}; +use crate::protocol::methods::encode_hex; +use sha2::{Digest, Sha256}; +use std::fs::{self, OpenOptions}; +use std::io::{self, Read, Write}; +use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; +use std::path::Path; + +/// Prints a non-secret stable identity of this account's server state. A +/// new host, default account or container state gets a different identity. +/// The file is published without replacement so concurrent launches agree. +pub fn print(root: &Path) -> io::Result<()> { + private_directory(root)?; + let identity_path = root.join("target-identity-v1"); + let temporary = root.join(format!(".target-identity-{}", std::process::id())); + let mut created_temporary = false; + let result = (|| { + if !identity_path.exists() { + let mut random = [0u8; 32]; + fs::File::open("/dev/urandom")?.read_exact(&mut random)?; + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(&temporary)?; + created_temporary = true; + file.write_all(encode_hex(&random).as_bytes())?; + file.sync_all()?; + match fs::hard_link(&temporary, &identity_path) { + Ok(()) => {} + // log-exempt: Expected absence: the publication slot is already occupied; all launchers read that same identity below. + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {} + Err(error) => return Err(error), + } + } + let mut file = OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) + .open(&identity_path)?; + let metadata = file.metadata()?; + if !metadata.is_file() + || metadata.uid() != platform::current_uid() + || metadata.mode() & 0o077 != 0 + || metadata.len() != 64 + { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "invalid target identity file", + )); + } + let mut bytes = [0u8; 64]; + file.read_exact(&mut bytes)?; + if !bytes.iter().all(u8::is_ascii_hexdigit) { + return Err(io::Error::other("invalid target identity")); + } + let mut digest = Sha256::new(); + digest.update(b"lithe.server.target.v1\0"); + digest.update(bytes); + digest.update(platform::current_uid().to_be_bytes()); + digest.update(fs::canonicalize(root)?.as_os_str().as_encoded_bytes()); + writeln!(io::stdout(), "{}", encode_hex(&digest.finalize())) + })(); + if created_temporary { + fs::remove_file(&temporary)?; + } + result +} diff --git a/rust/crates/remote/src/server/walk.rs b/rust/crates/remote/src/server/walk.rs index f90973a3..f9791937 100644 --- a/rust/crates/remote/src/server/walk.rs +++ b/rust/crates/remote/src/server/walk.rs @@ -24,6 +24,9 @@ use std::sync::Arc; /// small enough to keep each frame far below the size limit. const BATCH_ENTRIES: usize = 2000; +/// Relative path bytes per batch; JSON can escape each byte into six bytes. +const BATCH_PATH_BYTES: usize = 1024 * 1024; + pub(crate) struct WalkTable { registry: Registry, } @@ -141,6 +144,7 @@ impl Walker { unreadable_directories: 0, }; let mut batch = Vec::with_capacity(BATCH_ENTRIES); + let mut batch_bytes = 0; // Each stack frame is a directory's remaining, reverse-sorted // children, so popping yields name order depth-first. let mut stack: Vec> = Vec::new(); @@ -161,18 +165,31 @@ impl Walker { done.truncated = true; break; } + if relative.len() > BATCH_PATH_BYTES { + // A single entry can exceed the budget even in an empty + // batch. Report a partial walk instead of emitting a frame + // the writer cannot serialize. + done.truncated = true; + break; + } done.total += 1; let descend = kind == FileKind::Directory && !path .file_name() .and_then(|name| name.to_str()) .is_some_and(|name| self.excludes.contains(name)); + if batch_bytes + relative.len() > BATCH_PATH_BYTES { + self.flush(session, &mut batch); + batch_bytes = 0; + } + batch_bytes += relative.len(); batch.push(WalkEntry { path: relative.clone(), kind, }); if batch.len() >= BATCH_ENTRIES { self.flush(session, &mut batch); + batch_bytes = 0; } if descend { match self.children(&path, &relative, &mut done) { diff --git a/rust/crates/remote/src/server/watch.rs b/rust/crates/remote/src/server/watch.rs index f29f425f..1b85cea4 100644 --- a/rust/crates/remote/src/server/watch.rs +++ b/rust/crates/remote/src/server/watch.rs @@ -20,10 +20,10 @@ use crate::server::session::Session; use crate::server::threads::Parked; use crate::server::{parse, to_value}; use serde_json::Value; -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::path::{Path, PathBuf}; -use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; -use std::sync::Arc; +use std::sync::mpsc::{RecvTimeoutError, SendError}; +use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant}; const QUIET_PERIOD: Duration = Duration::from_millis(50); @@ -33,6 +33,15 @@ const MAX_BATCH_DELAY: Duration = Duration::from_millis(250); /// a rescan is cheaper for the client than applying individual changes. const MAX_BATCH_CHANGES: usize = 5000; +/// Path bytes before JSON escaping (at most sixfold). Leaves frame headroom +/// for change kinds and the envelope even for control characters in names. +const MAX_BATCH_PATH_BYTES: usize = 1024 * 1024; + +/// Backend pressure is bounded separately from the coalesced event frame. +const MAX_RAW_CHANGES: usize = 2048; +const MAX_RAW_PATH_BYTES: usize = 1024 * 1024; +const MAX_LIMIT_MESSAGE_CHARS: usize = 1024; + /// A change as reported by a backend, before coalescing. pub(crate) enum RawEvent { Change(PathBuf, ChangeKind), @@ -76,8 +85,142 @@ impl Excludes { } } -/// Receives raw events from a backend thread. -pub(crate) type Sink = Sender; +/// Nonblocking backend queue. Control events survive a full change queue. +pub(crate) struct Sink(Arc); + +pub(crate) struct RawReceiver(Arc); + +struct RawQueue { + state: Mutex, + ready: Condvar, +} + +/// Change paths are bounded by both count and bytes; overflow is sticky until read. +struct RawState { + changes: VecDeque<(PathBuf, ChangeKind)>, + bytes: usize, + overflow: bool, + limit: Option, + root_removed: bool, + closed: bool, + receiving: bool, +} + +fn raw_channel() -> (Sink, RawReceiver) { + let queue = Arc::new(RawQueue { + state: Mutex::new(RawState { + changes: VecDeque::new(), + bytes: 0, + overflow: false, + limit: None, + root_removed: false, + closed: false, + receiving: true, + }), + ready: Condvar::new(), + }); + (Sink(Arc::clone(&queue)), RawReceiver(queue)) +} + +impl Sink { + pub(crate) fn send(&self, event: RawEvent) -> Result<(), SendError> { + let mut state = crate::server::lock(&self.0.state); + if !state.receiving { + return Err(SendError(event)); + } + match event { + RawEvent::Change(path, kind) if !state.overflow => { + let bytes = path.as_os_str().len(); + if state.changes.len() >= MAX_RAW_CHANGES + || state.bytes.saturating_add(bytes) > MAX_RAW_PATH_BYTES + { + state.changes.clear(); + state.bytes = 0; + state.overflow = true; + } else { + state.bytes += bytes; + state.changes.push_back((path, kind)); + } + } + RawEvent::Change(..) => {} + RawEvent::Overflow => { + state.changes.clear(); + state.bytes = 0; + state.overflow = true; + } + RawEvent::LimitReached(message) => { + state.limit = Some(message.chars().take(MAX_LIMIT_MESSAGE_CHARS).collect()); + } + RawEvent::RootRemoved => state.root_removed = true, + } + self.0.ready.notify_one(); + Ok(()) + } +} + +impl Drop for Sink { + fn drop(&mut self) { + crate::server::lock(&self.0.state).closed = true; + self.0.ready.notify_one(); + } +} + +impl RawReceiver { + fn recv(&self) -> Result { + self.receive(None) + } + + fn recv_timeout(&self, timeout: Duration) -> Result { + self.receive(Some(Instant::now() + timeout)) + } + + fn receive(&self, deadline: Option) -> Result { + let mut state = crate::server::lock(&self.0.state); + loop { + if std::mem::take(&mut state.overflow) { + return Ok(RawEvent::Overflow); + } + if let Some((path, kind)) = state.changes.pop_front() { + state.bytes -= path.as_os_str().len(); + return Ok(RawEvent::Change(path, kind)); + } + if let Some(message) = state.limit.take() { + return Ok(RawEvent::LimitReached(message)); + } + if std::mem::take(&mut state.root_removed) { + return Ok(RawEvent::RootRemoved); + } + if state.closed { + return Err(RecvTimeoutError::Disconnected); + } + state = if let Some(deadline) = deadline { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return Err(RecvTimeoutError::Timeout); + } + self.0 + .ready + .wait_timeout(state, remaining) + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .0 + } else { + self.0 + .ready + .wait(state) + .unwrap_or_else(|poisoned| poisoned.into_inner()) + }; + } + } +} + +impl Drop for RawReceiver { + fn drop(&mut self) { + let mut state = crate::server::lock(&self.0.state); + state.receiving = false; + state.changes.clear(); + state.bytes = 0; + } +} pub(crate) struct WatchTable { registry: Registry, @@ -157,12 +300,12 @@ impl WatchTable { let watch_id = params.watch_id; let coalescer = { let session = Arc::clone(session); - Parked::start("remote-watch", move |raw: Receiver| { + Parked::start("remote-watch", move |raw: RawReceiver| { coalesce(raw, |batch| deliver(&session, watch_id, batch)); })? }; let excludes = Arc::new(Excludes::new(root.clone(), params.exclude_names)); - let (sink, raw) = mpsc::channel(); + let (sink, raw) = raw_channel(); let (backend, watched_directories) = watcher::start(root, ¶ms.root, excludes, sink)?; self.registry.insert( watch_id, @@ -216,6 +359,7 @@ fn deliver(session: &Session, watch_id: u64, delivery: Delivery) { #[derive(Default)] struct Batch { changes: BTreeMap, + bytes: usize, overflow: bool, } @@ -232,9 +376,13 @@ impl Batch { (Some(ChangeKind::Deleted), ChangeKind::Created) => ChangeKind::Modified, (_, kind) => kind, }; + if !self.changes.contains_key(&path) { + self.bytes = self.bytes.saturating_add(path.as_os_str().len()); + } self.changes.insert(path, merged); - if self.changes.len() > MAX_BATCH_CHANGES { + if self.changes.len() > MAX_BATCH_CHANGES || self.bytes > MAX_BATCH_PATH_BYTES { self.changes.clear(); + self.bytes = 0; self.overflow = true; } } @@ -258,7 +406,7 @@ impl Batch { } /// Merges raw events into batches until the backend closes the channel. -pub(crate) fn coalesce(raw: Receiver, mut deliver: impl FnMut(Delivery)) { +pub(crate) fn coalesce(raw: RawReceiver, mut deliver: impl FnMut(Delivery)) { let mut batch = Batch::default(); loop { // Wait for the first event of a batch without a deadline. @@ -272,6 +420,7 @@ pub(crate) fn coalesce(raw: Receiver, mut deliver: impl FnMut(Delivery Some(RawEvent::Change(path, kind)) => batch.add(path, kind), Some(RawEvent::Overflow) => { batch.changes.clear(); + batch.bytes = 0; batch.overflow = true; } Some(RawEvent::LimitReached(message)) => { @@ -317,6 +466,50 @@ pub(crate) fn coalesce(raw: Receiver, mut deliver: impl FnMut(Delivery mod tests { use super::*; + #[test] + fn raw_backpressure_preserves_overflow_and_root_removal() { + let (sender, receiver) = raw_channel(); + for index in 0..=MAX_RAW_CHANGES { + sender + .send(RawEvent::Change( + format!("/w/{index}").into(), + ChangeKind::Modified, + )) + .unwrap(); + } + sender + .send(RawEvent::LimitReached("watch limit".into())) + .unwrap(); + sender.send(RawEvent::RootRemoved).unwrap(); + drop(sender); + let mut deliveries = Vec::new(); + coalesce(receiver, |delivery| deliveries.push(delivery)); + assert!(deliveries + .iter() + .any(|delivery| matches!(delivery, Delivery::Changes { overflow: true, .. }))); + assert!(deliveries + .iter() + .any(|delivery| matches!(delivery, Delivery::Error(WatchErrorCode::LimitReached, _)))); + assert!(matches!( + deliveries.last(), + Some(Delivery::Error(WatchErrorCode::RootRemoved, _)) + )); + } + + #[test] + fn a_batch_with_long_paths_requires_a_rescan_before_it_exceeds_the_frame_budget() { + let mut batch = Batch::default(); + for index in 0..300 { + batch.add( + format!("/w/{index}/{}", "x".repeat(4096)).into(), + ChangeKind::Modified, + ); + } + assert!( + matches!(batch.take(), Some(Delivery::Changes { changes, overflow: true }) if changes.is_empty()) + ); + } + fn changes_of(deliveries: &[Delivery]) -> Vec<(String, ChangeKind)> { deliveries .iter() @@ -335,7 +528,7 @@ mod tests { // `modified` and one `created`, not the raw sequence. #[test] fn bursts_merge_into_one_sorted_batch() { - let (sender, receiver) = mpsc::channel(); + let (sender, receiver) = raw_channel(); for (path, kind) in [ ("/w/b.txt", ChangeKind::Deleted), ("/w/a.txt", ChangeKind::Created), @@ -358,7 +551,7 @@ mod tests { #[test] fn lost_events_turn_the_batch_into_an_overflow() { - let (sender, receiver) = mpsc::channel(); + let (sender, receiver) = raw_channel(); sender .send(RawEvent::Change("/w/a".into(), ChangeKind::Created)) .unwrap(); diff --git a/rust/crates/remote/tests/server.rs b/rust/crates/remote/tests/server.rs index cb91f3ad..4251336a 100644 --- a/rust/crates/remote/tests/server.rs +++ b/rust/crates/remote/tests/server.rs @@ -29,6 +29,111 @@ fn code(result: Result) -> ErrorCode { } } +#[test] +fn limited_file_reads_enforce_bytes_deadline_and_cancellation() { + let root = TempDir::new("limited-read"); + let path = root.join("file"); + std::fs::write(&path, b"a small file").unwrap(); + let (session, _events) = connect(); + assert_eq!( + code(session.read_file_limited(&path, 3, STEP_TIMEOUT, || false)), + ErrorCode::TooLarge + ); + assert!(matches!( + session.read_file_limited(&path, 100, STEP_TIMEOUT, || true), + Err(ClientError::Cancelled) + )); + assert!(matches!( + session.read_file_limited(&path, 100, std::time::Duration::ZERO, || false), + Err(ClientError::Timeout) + )); + assert_eq!( + session + .read_file_limited(&path, 100, STEP_TIMEOUT, || false) + .unwrap() + .0, + b"a small file" + ); + assert!(session.ping().is_ok()); + session.shutdown(STEP_TIMEOUT); +} + +#[test] +fn scoped_saves_keep_regular_files_inside_and_refuse_parent_and_leaf_links() { + let root = TempDir::new("scoped-save"); + std::fs::create_dir(root.join("workspace")).unwrap(); + std::fs::create_dir(root.join("outside")).unwrap(); + std::os::unix::fs::symlink(root.join("outside"), root.join("workspace/link")).unwrap(); + std::fs::write(root.join("outside/file"), b"outside").unwrap(); + std::os::unix::fs::symlink(root.join("outside/file"), root.join("workspace/leaf")).unwrap(); + let (session, _events) = connect(); + for path in [ + root.join("workspace/link/file"), + root.join("workspace/leaf"), + root.join("workspace/../outside/file"), + ] { + assert_eq!( + code(session.write_file( + &path, + b"mine", + WriteOptions { + root: Some(root.join("workspace")), + overwrite: true, + ..WriteOptions::default() + } + )), + ErrorCode::PermissionDenied + ); + } + let path = root.join("workspace/file"); + let metadata = session + .write_file( + &path, + b"one", + WriteOptions { + root: Some(root.join("workspace")), + ..WriteOptions::default() + }, + ) + .unwrap(); + session + .write_file( + &path, + b"two", + WriteOptions { + root: Some(root.join("workspace")), + expected: Some(FileVersion { + size: metadata.size, + modified_ms: metadata.modified_ms, + revision: metadata.revision, + }), + ..WriteOptions::default() + }, + ) + .unwrap(); + assert_eq!(std::fs::read(path).unwrap(), b"two"); + session + .write_file( + &root.join("workspace/new/nested/file"), + b"created", + WriteOptions { + root: Some(root.join("workspace")), + create_parents: true, + ..WriteOptions::default() + }, + ) + .unwrap(); + assert_eq!( + std::fs::read(root.join("workspace/new/nested/file")).unwrap(), + b"created" + ); + assert_eq!( + std::fs::read(root.join("outside/file")).unwrap(), + b"outside" + ); + session.shutdown(STEP_TIMEOUT); +} + #[test] fn staged_upload_checks_order_digest_and_atomic_no_replace_publication() { let root = TempDir::new("staged-upload"); @@ -342,6 +447,7 @@ fn files_are_written_atomically_and_guarded_against_concurrent_changes() { expected: Some(FileVersion { size: created.size, modified_ms: created.modified_ms, + revision: created.revision.clone(), }), ..WriteOptions::default() }; diff --git a/rust/crates/workspace/src/fs.rs b/rust/crates/workspace/src/fs.rs index d51ff5b9..878bfd91 100644 --- a/rust/crates/workspace/src/fs.rs +++ b/rust/crates/workspace/src/fs.rs @@ -318,6 +318,7 @@ impl Read for File { let observed = methods::FileVersion { size: result.metadata.size, modified_ms: result.metadata.modified_ms, + revision: result.metadata.revision.clone(), }; if version.as_ref().is_some_and(|first| *first != observed) { return Err(io::Error::new( @@ -429,7 +430,7 @@ pub fn append(path_value: &Path, bytes: &[u8]) -> io::Result<()> { content.extend_from_slice(bytes); check_write_size(content.len() as u64)?; rpc::(&host, methods::FS_WRITE_FILE, json!({"path": remote, "data": methods::encode_bytes(&content), - "expected": previous.map(|value| methods::FileVersion { size: value.size, modified_ms: value.modified_ms })})).map(|_| ()) + "expected": previous.map(|value| methods::FileVersion { size: value.size, modified_ms: value.modified_ms, revision: value.revision })})).map(|_| ()) } None => { use std::io::Write; diff --git a/rust/crates/workspace/src/lib.rs b/rust/crates/workspace/src/lib.rs index 5c931bf1..f155736d 100644 --- a/rust/crates/workspace/src/lib.rs +++ b/rust/crates/workspace/src/lib.rs @@ -43,6 +43,7 @@ mod resumption; mod scope; pub mod sessions; pub mod ssh_configuration; +mod ssh_evidence; #[cfg(feature = "test-support")] pub mod test_support; pub mod trust; diff --git a/rust/crates/workspace/src/sessions.rs b/rust/crates/workspace/src/sessions.rs index 8df4cfb1..df7bb89e 100644 --- a/rust/crates/workspace/src/sessions.rs +++ b/rust/crates/workspace/src/sessions.rs @@ -26,8 +26,11 @@ use crate::programs::RunningProgram; use lithe_git_host::ProcessTree; use lithe_protocol::{CoreError, ErrorCode}; use lithe_remote::client::connections::{ConnectionError, Reason, SshConnection}; -use lithe_remote::client::launch::{launch, launch_command, LaunchError, Launched, Stage}; +use lithe_remote::client::launch::{ + bound_launch_command, launch_bound, LaunchError, Launched, Stage, +}; use lithe_remote::client::session::{ClientError, ConnectOptions, ResumeMode}; +use lithe_remote::client::ssh_identity; use lithe_remote::client::trust::Target; use lithe_remote::client::{ wsl, ArtifactError, ConnectionKind, ConnectionLog, ContainerConnection, ForwardSet, Hop, @@ -114,13 +117,17 @@ pub struct ConnectRequest { } /// A persistent session `remote.connect` returned earlier. -#[derive(Deserialize)] +#[derive(Clone, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct ResumeInput { /// [`OpenedSession::session_key`]. key: String, /// [`OpenedSession::session_token`]; a secret. token: SessionToken, + /// Opaque identity returned with this token. Legacy records are never + /// sent automatically, even when their saved connection id matches. + #[serde(default)] + binding: Option, } /// Longest session key, which the server limits too. @@ -144,7 +151,7 @@ impl ResumeInput { let token_valid = !token.is_empty() && token.len() <= MAX_SESSION_TOKEN_CHARS && token.chars().all(|c| c.is_ascii_hexdigit()); - if key_valid && token_valid { + if key_valid && token_valid && self.binding.as_deref().is_none_or(methods::is_sha256_hex) { return Ok(()); } Err(crate::connections::invalid_request(ConnectionError { @@ -173,6 +180,11 @@ pub struct OpenedSession { /// Secret a later `resume` presents; the client stores it like a /// password and never logs it. session_token: Option, + /// Reusable verified identity; absent when only this connection is known. + session_binding: Option, + /// The supplied resume belonged to this verified target and was tried. + /// A mismatched or legacy record remains in the native secret store. + resume_consumed: bool, /// Whether this connection attached to the session `resume` named. /// `false` after a `resume` means that session had ended, or belonged /// to another client, and a new one started. @@ -649,6 +661,13 @@ pub(crate) fn connect_with( // The session under that key belongs to another client, or replaced // the one the token was issued for. result = connect_logged(&request, None, client, program, &log, &mut refused); + if let Ok(ConnectResult { + session: Some(session), + .. + }) = &mut result + { + session.resume_consumed = true; + } } match &result { Ok(result) => { @@ -691,11 +710,6 @@ fn connect_logged( if let Some(resume) = resume { resume.check()?; } - let session_key = resume.map_or_else(nonce, |resume| resume.key.clone()); - let mut server_arguments = vec!["--connect", session_key.as_str()]; - if let Some(root) = request.install_root.as_deref() { - server_arguments.extend(["--state-dir", root]); - } // Only the build for the host's platform is read and checked, once the // probe reports it; here the targets and hashes are just validated. let servers = request @@ -722,15 +736,27 @@ fn connect_logged( let _connecting = ConnectingGuard::enter(); let chain = TransportChain::new(chain_hops(request, program)?); - let argv = chain - .command(&launch_command( - request.install_root.as_deref(), - &server_arguments, - )) + let evidence = if client == Client::Ssh { + Some(crate::ssh_evidence::Evidence::new().map_err(|error| { + CoreError::new( + ErrorCode::ProcessStartFailed, + "Could not prepare SSH identity evidence", + ) + .with_details(error.to_string()) + })?) + } else { + None + }; + let evidence = Arc::new(Mutex::new(evidence)); + let mut argv = chain + .command(&bound_launch_command(request.install_root.as_deref())) .map_err(|error| { CoreError::new(ErrorCode::InvalidRequest, client.invalid()) .with_details(error.to_string()) })?; + if let Some(evidence) = evidence.lock().unwrap_or_else(|p| p.into_inner()).as_ref() { + argv.splice(1..1, evidence.arguments()); + } let (program, arguments) = argv.split_first().expect("a hop always produces a command"); let mut process = Command::new(program); process @@ -773,6 +799,7 @@ fn connect_logged( CoreError::new(ErrorCode::ProcessStartFailed, client.supervise_failed()) .with_details(error.to_string()) })?; + let ssh_pid = child.id(); let stderr_tail = Arc::new(Mutex::new(VecDeque::new())); let stderr_reader = Mutex::new( child @@ -791,6 +818,9 @@ fn connect_logged( // its stages over. let (stage_sender, stages) = mpsc::channel(); let launch_log = log.clone(); + let resume_for_launch = resume.cloned(); + let chain_target = Target::new(&chain, None); + let evidence_for_launch = Arc::clone(&evidence); std::thread::spawn(move || { let artifact_for = |report: &lithe_remote::client::bootstrap::ProbeReport| { let target = report.target()?; @@ -810,7 +840,8 @@ fn connect_logged( } } }; - let result = launch( + let mut selected = None; + let result = launch_bound( &mut output, &mut input, artifact_for, @@ -819,16 +850,42 @@ fn connect_logged( // log-exempt: User cancellation: abandon drops the stage receiver before killing the SSH tree. let _ = stage_sender.send(stage); }, + |server_identity| { + let actual = evidence_for_launch + .lock() + .unwrap_or_else(|p| p.into_inner()) + .as_mut() + .and_then(|evidence| evidence.identity(ssh_pid)); + let binding = if client == Client::Ssh && actual.is_none() { + None + } else { + Some(ssh_identity::digest(&( + &chain_target, + actual, + server_identity, + ))) + }; + let consumed = resume_for_launch + .as_ref() + .is_some_and(|resume| resume_matches(resume, binding.as_deref())); + let key = if consumed { + resume_for_launch.as_ref().unwrap().key.clone() + } else { + nonce() + }; + selected = Some((key.clone(), binding, consumed)); + key + }, ); // log-exempt: User cancellation: abandon drops the launch receiver before killing the SSH tree. - let _ = finished.send((result, output, input)); + let _ = finished.send((result, output, input, selected)); }); let deadline = Instant::now() + CONNECT_DEADLINE; let abandon = |error: CoreError, child: &mut Child| { reap(&tree, child); Err(error) }; - let (result, output, input) = loop { + let (result, output, input, selected) = loop { if let Err(error) = lithe_protocol::cancellation::check() { return abandon(error, &mut child); } @@ -895,12 +952,15 @@ fn connect_logged( ); } } - let bytes: Vec = tail + let mut bytes: Vec = tail .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .iter() .copied() .collect(); + if let Some(evidence) = evidence.lock().unwrap_or_else(|p| p.into_inner()).as_mut() { + bytes.extend(evidence.diagnostics()); + } bytes }; let failed = @@ -971,6 +1031,8 @@ fn connect_logged( } }; let Launched { report, uploaded } = launched; + let (session_key, session_binding, resume_consumed) = + selected.expect("bound launch selects a key before returning"); let host = ProbedHost { server_target: report.target().map(ServerTarget::rust_target), system: report.system, @@ -980,7 +1042,9 @@ fn connect_logged( }; let options = ConnectOptions { handshake_timeout: HANDSHAKE_TIMEOUT, - session_token: resume.map(|resume| resume.token.clone()), + session_token: resume + .filter(|_| resume_consumed) + .map(|resume| resume.token.clone()), // Events start only after process events are parked below, so the // ones a resumed session replays wait for `remote.attachProcess`. resume: ResumeMode::Deferred, @@ -990,7 +1054,7 @@ fn connect_logged( let (session, events) = match RemoteSession::from_streams(output, input, &options) { Ok(value) => value, Err(error) => { - *refused = resume.is_some() + *refused = resume_consumed && matches!( &error, ClientError::Remote(remote) @@ -1052,6 +1116,27 @@ fn connect_logged( Vec::new() }; let id = nonce(); + let mut trust_target = Target::new(&chain, capabilities.user_id); + trust_target.identity = Some( + session_binding + .clone() + .unwrap_or_else(|| ssh_identity::digest(&nonce())), + ); + if session_binding.is_none() { + lithe_diagnostics::core_events::recovery_failed( + "remote.session.identity_rejected", + "identity", + "unverified_route", + "ssh", + ); + } else if resume.is_some() && !resume_consumed { + lithe_diagnostics::core_events::recovery_failed( + "remote.session.identity_rejected", + "resume", + "binding_mismatch", + "core", + ); + } registry() .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) @@ -1059,7 +1144,7 @@ fn connect_logged( id.clone(), Arc::new(Connection::new( session, - Target::new(&chain, capabilities.user_id), + trust_target, ConnectionTransport::Process { child: Mutex::new(child), tree, @@ -1081,6 +1166,8 @@ fn connect_logged( windows_interop: capabilities.windows_interop, session_key, session_token: info.session_token, + session_binding, + resume_consumed, resumed: info.resumed, kept_programs, }), @@ -1089,6 +1176,39 @@ fn connect_logged( }) } +/// A saved connection id is only a lookup hint, never authority to send a +/// token. Both sides must name the same verified identity before writing. +fn resume_matches(resume: &ResumeInput, binding: Option<&str>) -> bool { + binding.is_some() && resume.binding.as_deref() == binding +} + +#[cfg(test)] +mod identity_tests { + use super::*; + + #[test] + fn legacy_changed_and_unverified_targets_never_receive_tokens() { + let fixture: serde_json::Value = serde_json::from_str(include_str!( + "../../../fixtures/remote/session-binding-v1.json" + )) + .unwrap(); + for case in fixture["cases"].as_array().unwrap() { + let resume = ResumeInput { + key: fixture["session"]["sessionKey"].as_str().unwrap().into(), + token: SessionToken::new(fixture["session"]["sessionToken"].as_str().unwrap()), + binding: case["binding"].as_str().map(str::to_owned), + }; + resume.check().unwrap(); + assert_eq!( + resume_matches(&resume, case["actual"].as_str()), + case["consumed"].as_bool().unwrap(), + "{}", + case["id"] + ); + } + } +} + /// `remote.readDir`: one directory on a connected host. #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -1130,31 +1250,34 @@ pub struct ReadFileRequest { /// The version identifies the read for a later conflict-checked write. pub fn read_file(request: ReadFileRequest) -> Result { let connection = lookup(&request.session_id)?; - let metadata = connection - .session - .stat(&request.path) - .map_err(|error| request_error(&request.session_id, error))?; - if metadata.size > MAX_EDIT_BYTES { - return Err( - CoreError::new(ErrorCode::NotSupported, "The file is too large to open") - .with_details(format!("{} bytes", metadata.size)), - ); + // The read reports metadata from its opened file. A separate stat would + // race that open and wait outside the read's cancellation and deadline. + let mut stopped = None; + let read = connection.session.read_file_limited( + &request.path, + MAX_EDIT_BYTES as usize, + Duration::from_secs(120), + || { + stopped = lithe_protocol::cancellation::check().err(); + stopped.is_some() + }, + ); + if let Some(error) = stopped { + return Err(error); } - let (content, metadata) = connection - .session - .read_file(&request.path) - .map_err(|error| request_error(&request.session_id, error))?; - // The file may have grown since `stat`. - if content.len() as u64 > MAX_EDIT_BYTES { - return Err( + let (content, metadata) = read.map_err(|error| { + if matches!(&error, ClientError::Remote(remote) if remote.code == RemoteErrorCode::TooLarge) + { CoreError::new(ErrorCode::NotSupported, "The file is too large to open") - .with_details(format!("{} bytes", content.len())), - ); - } + } else { + request_error(&request.session_id, error) + } + })?; Ok(serde_json::json!({ "data": methods::encode_bytes(&content), "size": metadata.size, "modifiedMs": metadata.modified_ms, + "revision": metadata.revision, })) } @@ -1170,6 +1293,9 @@ pub struct WriteFileRequest { /// the result is `conflict`; when absent, the file must not exist yet. #[serde(default)] expected: Option, + /// Editor workspace boundary; absent for explicit general host writes. + #[serde(default)] + root: Option, } /// Saves a file atomically on the host: `{ status: "saved", size, @@ -1177,6 +1303,19 @@ pub struct WriteFileRequest { /// read or, for a new file, when one appeared. pub fn write_file(request: WriteFileRequest) -> Result { let connection = lookup(&request.session_id)?; + if request.root.is_some() + && !connection + .session + .hello() + .host + .features + .contains(&methods::Feature::GuardedWrites) + { + return Err(CoreError::new( + ErrorCode::NotSupported, + "The host server does not support scoped saves", + )); + } let content = methods::decode_bytes(&request.data).map_err(|error| { CoreError::new( ErrorCode::InvalidRequest, @@ -1188,6 +1327,7 @@ pub fn write_file(request: WriteFileRequest) -> Result Result Result CoreError { ErrorCode::TimedOut, "The remote host did not answer in time", ), + ClientError::Cancelled => { + CoreError::new(ErrorCode::Cancelled, "The remote operation was cancelled") + } ClientError::Disconnected { diagnostics } => { // A broken connection cannot recover. forget(session_id); diff --git a/rust/crates/workspace/src/ssh_evidence.rs b/rust/crates/workspace/src/ssh_evidence.rs new file mode 100644 index 00000000..fed584a8 --- /dev/null +++ b/rust/crates/workspace/src/ssh_evidence.rs @@ -0,0 +1,88 @@ +//! Owner-only, bounded evidence from the actual local OpenSSH process. + +use lithe_git_host::private_directory::PrivateDirectory; +use lithe_remote::client::ssh_identity::{self, Identity}; +use std::fs::{File, OpenOptions}; +use std::io::{self, Read, Seek}; +use std::path::PathBuf; + +/// The helper only writes a private log; it is never parsed as shell code. +pub(crate) struct Evidence { + file: File, + path: PathBuf, + _directory: PrivateDirectory, +} + +impl Evidence { + pub(crate) fn new() -> io::Result { + let directory = PrivateDirectory::new()?; + let path = directory.path().join("ssh.log"); + let file = lithe_platform::fs::owner_only_file( + OpenOptions::new().read(true).write(true).create_new(true), + ) + .open(&path)?; + Ok(Self { + file, + path, + _directory: directory, + }) + } + + /// Inserted before all hop options. OpenSSH reads the user's routing and + /// host-key policy normally; these flags only capture its own evidence. + pub(crate) fn arguments(&self) -> Vec { + let mut arguments = vec!["-E".into(), self.path.to_string_lossy().into_owned()]; + for option in ssh_identity::OPTIONS { + arguments.extend(["-o".into(), (*option).into()]); + } + arguments + } + + pub(crate) fn identity(&mut self, pid: u32) -> Option { + let read = (|| -> io::Result> { + self.file.rewind()?; + let mut bytes = Vec::new(); + self.file + .by_ref() + .take(ssh_identity::MAX_BYTES as u64 + 1) + .read_to_end(&mut bytes)?; + Ok(bytes) + })(); + match read { + Ok(bytes) => ssh_identity::parse(&bytes, pid), + Err(error) => { + lithe_diagnostics::core_events::recovery_failed( + "remote.session.diagnostics_failed", + "identity_read", + &format!("{:?}", error.kind()), + "io", + ); + None + } + } + } + + pub(crate) fn diagnostics(&mut self) -> Vec { + let result = (|| -> io::Result> { + self.file.rewind()?; + let mut bytes = Vec::new(); + self.file + .by_ref() + .take(ssh_identity::MAX_BYTES as u64) + .read_to_end(&mut bytes)?; + Ok(bytes) + })(); + match result { + Ok(bytes) => bytes, + Err(error) => { + lithe_diagnostics::core_events::recovery_failed( + "remote.session.diagnostics_failed", + "identity_diagnostics", + &format!("{:?}", error.kind()), + "io", + ); + Vec::new() + } + } + } +} diff --git a/rust/fixtures/remote/session-binding-v1.json b/rust/fixtures/remote/session-binding-v1.json new file mode 100644 index 00000000..38b491d0 --- /dev/null +++ b/rust/fixtures/remote/session-binding-v1.json @@ -0,0 +1,18 @@ +{ + "protocolVersion": 1, + "session": { + "id": "fixture-session", + "sessionKey": "fixture-key", + "sessionToken": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "sessionBinding": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "resumeConsumed": true, + "resumed": true, + "keptPrograms": [] + }, + "cases": [ + { "id": "legacy", "binding": null, "actual": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "consumed": false }, + { "id": "same-target", "binding": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "actual": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "consumed": true }, + { "id": "unverified", "binding": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "actual": null, "consumed": false }, + { "id": "changed-target", "binding": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "actual": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", "consumed": false } + ] +} diff --git a/rust/logging/events/remote.json b/rust/logging/events/remote.json index 9f5bdc33..7e26910d 100644 --- a/rust/logging/events/remote.json +++ b/rust/logging/events/remote.json @@ -2,6 +2,18 @@ "version": 1, "root": "remote", "events": [ + { + "id": "remote.session.identity_rejected", + "channel": "remote", + "level": "warn", + "message": "Remote identity could not authorize automatic session recovery", + "fields": { + "stage": {"type": "token", "required": true, "description": "Identity validation or resume binding stage"}, + "error": {"type": "error", "required": true, "description": "Controlled identity category without host names, fingerprints or credentials"} + }, + "rate": 60, + "owner": "lithe-core" + }, { "id": "remote.process.cleanup_failed", "channel": "remote",