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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 70 additions & 8 deletions rust/contracts/remote-workspace-protocol-v1.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <key> [--state-dir <dir>]` | Persistent: relays to the daemon of session `<key>`, starting it if needed. |
| `lithe-remote-server --target-identity --state-dir <dir>` | Prints the non-secret identity of the final account's server state before a client chooses a session key. |

`<key>` is 1–64 characters from `[A-Za-z0-9._-]`. The daemon keeps its
socket, lock and log under `<dir>` (default `$HOME/.lithe-server`) in
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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` |
Expand Down Expand Up @@ -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 —
Expand All @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -390,6 +437,21 @@ than reaching an older one.

## Server identity

`--target-identity --state-dir <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 <identity>` 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
Expand Down
56 changes: 48 additions & 8 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -6152,7 +6153,16 @@ The server runs a persistent session (`--connect <sessionKey>`, 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
Expand All @@ -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
Expand Down Expand Up @@ -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 }` |
Expand All @@ -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
Expand Down Expand Up @@ -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`.
Expand Down
13 changes: 13 additions & 0 deletions rust/crates/diagnostics/src/catalog_generated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion rust/crates/git-host/src/authentication.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down
19 changes: 19 additions & 0 deletions rust/crates/git-host/src/authentication/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<SECURITY_ATTRIBUTES>() 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 {
Expand Down
1 change: 1 addition & 0 deletions rust/crates/git-host/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down
49 changes: 49 additions & 0 deletions rust/crates/git-host/src/private_directory.rs
Original file line number Diff line number Diff line change
@@ -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<Self> {
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)
}
Loading
Loading