Skip to content

Commit 9ac01fa

Browse files
committed
fix(remote): enforce trust, filesystem and session identity boundaries
1 parent 0598008 commit 9ac01fa

33 files changed

Lines changed: 1954 additions & 216 deletions

‎rust/contracts/remote-workspace-protocol-v1.md‎

Lines changed: 70 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ clients. Design rationale lives in
1313
| --- | --- |
1414
| `lithe-remote-server --stdio` | Ends with the connection, terminating everything it started. |
1515
| `lithe-remote-server --connect <key> [--state-dir <dir>]` | Persistent: relays to the daemon of session `<key>`, starting it if needed. |
16+
| `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. |
1617

1718
`<key>` is 1–64 characters from `[A-Za-z0-9._-]`. The daemon keeps its
1819
socket, lock and log under `<dir>` (default `$HOME/.lithe-server`) in
@@ -50,6 +51,11 @@ Other clients should do the same.
5051
bytes of UTF-8 JSON. Frames larger than 16 MiB are rejected.
5152
3. Closing the client-to-server stream is a disconnect.
5253

54+
The reference server bounds response serialization to the frame limit. A result
55+
that exceeds it becomes a `TOO_LARGE` error for that request, and subsequent
56+
responses remain usable. Event producers bound their own batches; events cannot
57+
be replaced by a request error and are never silently discarded by the writer.
58+
5359
All traffic, including tunnels, uses this stream. The server listens on a
5460
network port only for a forwarding rule the user added (`listener.open`, see
5561
"Listeners"); such a port belongs to the connection that opened it and
@@ -126,7 +132,7 @@ subscribe before creating the resource.
126132
| `fs.stat` | `path` | metadata of the path itself (links not followed) |
127133
| `fs.readDir` | `path` | `entries` sorted by name byte order, `skippedNonUtf8` |
128134
| `fs.readFile` | `path`, `offset`, `length` (≤ 8 MiB) | `data`, `eof`, `metadata`; only a regular file is read |
129-
| `fs.writeFile` | `path`, `data` (≤ 8 MiB), `expected?`, `overwrite`, `createParents` | metadata after the write |
135+
| `fs.writeFile` | `path`, `data` (≤ 8 MiB), `expected?`, `overwrite`, `createParents`, `root?` | metadata after the write |
130136
| `fs.createDir` | `path`, `recursive`, `mode?` (at most `0o7777`) | `null` |
131137
| `fs.remove` | `path`, `recursive` | `null`; links are removed, never followed |
132138
| `fs.rename` | `from`, `to`, `overwrite` | `null` |
@@ -168,6 +174,15 @@ subscribe before creating the resource.
168174
opened file, so a FIFO without a writer never holds the request and a path
169175
replaced between `fs.stat` and the read is still checked. A directory fails
170176
with `IS_A_DIRECTORY`; sockets, FIFOs and devices fail with `UNSUPPORTED`.
177+
Metadata includes optional `revision`, an opaque identity incorporating the
178+
host's file identity, size and precise modification/change timestamps. Clients
179+
compare it exactly and return it in `expected`; they must not interpret its
180+
encoding. Older servers may omit it.
181+
182+
`fs.readDir` examines at most 20,000 directory entries, including names that are
183+
not UTF-8, and bounds serialized entries below the frame limit with space for
184+
the response envelope. Exceeding either budget returns `TOO_LARGE` rather than
185+
a successful partial listing. Recursive indexes should use `walk.start`.
171186

172187
`fs.copy` refuses, with `INVALID_REQUEST`, to copy a file onto itself —
173188
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
184199
without usable trash storage returns an error and retains the original entry;
185200
it does not fall back to permanent deletion.
186201

187-
`fs.writeFile` replaces the file atomically through a temporary sibling and
188-
writes through symbolic links. With `expected` (`size`, `modifiedMs`) it fails
189-
with `CONFLICT` unless the file still matches; without it, an existing file is
190-
only replaced when `overwrite` is set. A write with neither `expected` nor
191-
`overwrite` only creates: when two such writes race, exactly one succeeds and
192-
the other fails with `ALREADY_EXISTS`. When a file is replaced, the temporary
193-
file never has broader permissions than the original.
202+
`fs.writeFile` replaces the file atomically through a temporary sibling. With
203+
`expected` (`size`, `modifiedMs`, optional `revision`) it fails with `CONFLICT`
204+
unless the file still matches; without it, an existing file is only replaced
205+
when `overwrite` is set. The revision catches an inode replacement or precise
206+
timestamp change even when size and millisecond modification time are unchanged.
207+
A write with neither `expected` nor `overwrite` publishes by atomic no-replace
208+
linking: a concurrently created destination is retained and the write fails
209+
with `ALREADY_EXISTS`. A replacement's temporary file is created with permissions
210+
no broader than the original, before any content is written.
211+
212+
The optional `root` requires the `guardedWrites` feature. Editor clients send
213+
their workspace root and refuse an older server instead of retrying without the
214+
boundary. The requested path must be lexically below that root with no `..`
215+
components. The server resolves the root, opens it through directory handles,
216+
and opens each descendant directory without following symbolic links. The leaf
217+
must not be a symbolic link either. Missing descendants are created only with
218+
`createParents` and are reopened without following links. Staging and publication
219+
use the same parent handle; refused boundary or symlink crossings return
220+
`PERMISSION_DENIED`. Without `root`, explicit general host writes retain their
221+
ability to write outside a workspace and through an existing leaf link.
222+
223+
Cooperating Lithe daemons serialize writes to the same directory with a
224+
five-second advisory-lock deadline. The server rechecks the version after
225+
staging and syncing, immediately before publication. POSIX rename provides no
226+
version-based compare-and-swap: an external writer that ignores this lock can
227+
still change a file between that final check and replacement. Directory handles
228+
also do not sandbox a hostile same-user process that moves an already-open
229+
directory outside the root. These are limits of conflict and path protection,
230+
not guarantees of isolation from the remote account itself. Failed saves reclaim
231+
their temporary files; a crash can leave one behind.
194232

195233
Hosts advertising `features: ["upload", ...]` accept staged uploads without
196234
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
274312

275313
`watch.changed` batches are coalesced and sorted by path. With `overflow`
276314
changes were lost and the client must rescan the watched tree.
315+
The reference backend queue retains at most 2,048 changes and 1 MiB of raw
316+
path bytes without blocking the native watcher. Pressure clears those changes
317+
and preserves an overflow marker, watch-limit notice and root-removal notice.
318+
Coalesced batches hold at most 5,000 distinct changes and 1 MiB of path bytes
319+
before JSON escaping; a larger batch becomes an empty overflow batch.
320+
321+
`walk.entries` batches hold at most 2,000 entries and 1 MiB of relative-path
322+
bytes before JSON escaping. A single path beyond that budget ends the walk with
323+
`truncated: true`; it is not sent as an oversized event.
277324

278325
## Listeners
279326

@@ -390,6 +437,21 @@ than reaching an older one.
390437

391438
## Server identity
392439

440+
`--target-identity --state-dir <dir>` prints 64 hexadecimal characters derived
441+
from a random marker, the current numeric user ID and the canonical state root.
442+
The marker is `target-identity-v1` in the private state directory, created as
443+
an owner-only regular file without following symbolic links and published
444+
without replacing another launcher's marker. Later launches validate ownership,
445+
permissions and length before reading it. This is persistent account-local
446+
state, not a secret or hardware identity: copying the marker to a clone with
447+
the same account and path also copies that identity.
448+
449+
The reference bootstrap prints `LITHE-TARGET <identity>` after installation
450+
and waits for a session key on the same authenticated stream before executing
451+
`--connect`. The client combines this marker with the actual OpenSSH identity
452+
and explicit route before selecting any previously stored key or token. The
453+
marker does not replace SSH host-key authentication.
454+
393455
`lithe-remote-server --identity` prints one JSON line with `serverVersion`,
394456
`protocolVersion` and `sha256` of the executable itself. A binary is never
395457
trusted to report its own hash: bootstrappers reuse an installed server only

‎rust/contracts/rust-core-api.md‎

Lines changed: 48 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6140,7 +6140,8 @@ and `{ stage: "installed", uploaded }` once the server is in place, where
61406140
failed attempt stops after the last stage reached, so a host without a
61416141
matching build stops after `platformChecked`. The result is `{ status, session,
61426142
host, diagnostics }`; `session` is `{ id, uploaded, hostName, userName,
6143-
homeDirectory, windowsInterop, sessionKey, sessionToken, resumed, keptPrograms }`
6143+
homeDirectory, windowsInterop, sessionKey, sessionToken, sessionBinding?,
6144+
resumeConsumed, resumed, keptPrograms }`
61446145
and is set only for `connected`. A host without a matching build is
61456146
`unsupportedPlatform` and nothing is uploaded. `windowsInterop` is the host
61466147
capability of the same name from the remote workspace protocol: `true` or
@@ -6152,7 +6153,16 @@ The server runs a persistent session (`--connect <sessionKey>`, with
61526153
connection. `sessionKey` names that session and `sessionToken` is the secret
61536154
that attaches to it again; the client stores the token like a password and
61546155
never logs it. To attach to a session an earlier connection kept, pass
6155-
`resume: { key, token }` with the values it returned. `resumed` tells whether
6156+
`resume: { key, token, binding? }` with the values it returned. The opaque
6157+
64-hexadecimal `sessionBinding` binds the explicit transport chain, the actual
6158+
OpenSSH-authenticated host name, port, account, peer address and host-key
6159+
fingerprint, and the final server's account-local state identity. Before sending
6160+
an old key or token, the same connection must produce an identical binding.
6161+
Legacy records without a binding, a changed target, or unavailable evidence
6162+
start a fresh session without sending the old credentials. `resumeConsumed`
6163+
tells the native credential store whether Core attempted those credentials;
6164+
only then may it remove the old record. A mismatched record remains available
6165+
for the original target. `resumed` tells whether
61566166
this connection attached to it; `keptPrograms` lists the processes and
61576167
terminals it still runs, as `remote.runningPrograms` does, and is empty for
61586168
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
61626172
characters or not made of ASCII letters, digits, `.`, `_` and `-`, or a token
61636173
that is empty, longer than 128 characters or not hexadecimal, is
61646174
`invalid_request` with `{ field: "resume", reason: "invalid" }`, before
6165-
OpenSSH or `wsl.exe` starts.
6175+
OpenSSH or `wsl.exe` starts. A present binding must be 64 hexadecimal characters.
6176+
6177+
OpenSSH supplies identity evidence on the actual connection, with connection
6178+
multiplexing disabled; Core does not pre-read `ssh -G` or weaken the user's
6179+
host-key policy. ProxyCommand and ProxyJump connections remain usable, but
6180+
unverifiable evidence gives no reusable `sessionBinding` and no automatic
6181+
credential recovery. Such a connection also receives a fresh trust identity.
6182+
The current private `-E` evidence file bounds reads to 64 KiB but does not bound
6183+
OpenSSH's writes; correcting this resource lifetime remains a release blocker.
61666184

61676185
Instead of `connection`, the request may name a WSL distribution on this
61686186
Windows machine as `wsl: { distribution, user? }`, where `distribution` is a
@@ -6247,8 +6265,8 @@ gone. Requests over it take `sessionId`:
62476265
| Command | Request | Result |
62486266
| --- | --- | --- |
62496267
| `remote.readDir` | `{ sessionId, path }` | the remote protocol's `fs.readDir` result |
6250-
| `remote.readFile` | `{ sessionId, path }` | `{ data (base64), size, modifiedMs }`; files over 16 MiB are `not_supported` |
6251-
| `remote.writeFile` | `{ sessionId, path, data, expected? }` | `{ status: "saved", size, modifiedMs }` or `{ status: "conflict" }` |
6268+
| `remote.readFile` | `{ sessionId, path }` | `{ data (base64), size, modifiedMs, revision? }`; files over 16 MiB are `not_supported` |
6269+
| `remote.writeFile` | `{ sessionId, path, data, expected?, root? }` | `{ status: "saved", size, modifiedMs, revision? }` or `{ status: "conflict" }` |
62526270
| `remote.hostRequest` | `{ sessionId, method, params }` | the finite host method's result, including JSON `null` |
62536271
| `remote.hostInfo` | `{ sessionId }` | the original connection's handshake `host`, including OS, architecture, home and features |
62546272
| `remote.uploadFile` | `{ sessionId, sourcePath, path, sha256, mode }` | verified `{ size, sha256 }` |
@@ -6261,12 +6279,31 @@ gone. Requests over it take `sessionId`:
62616279
| `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 |
62626280

62636281
`remote.writeFile` replaces the file atomically on the host. With
6264-
`expected` (`{ size, modifiedMs }` from the read) a changed file is a
6282+
`expected` (`{ size, modifiedMs, revision? }` from the read) a changed file is a
62656283
`conflict`; without it the file must not exist yet. A missing path is
62666284
`workspace_not_found`, a denied one `permission_denied`. A broken connection
62676285
fails with `connection_closed` and is forgotten, so the host reconnects; an
62686286
unknown or closed `sessionId` is also `connection_closed`.
62696287

6288+
Editor saves send `root`, the workspace's absolute host root. The host must
6289+
advertise `guardedWrites`; otherwise Core returns `not_supported` without
6290+
sending an unscoped write. Descendant directory and leaf symlinks, path escapes
6291+
and `..` are refused. General explicit host writes without `root` retain their
6292+
existing outside-workspace and leaf-link behavior. The opaque `revision` is
6293+
returned unchanged from the opened host file and compared exactly. Cooperating
6294+
Lithe daemons serialize saves and recheck after staging; an external writer
6295+
that ignores their advisory lock still has the final check-to-rename window.
6296+
See the [remote protocol](remote-workspace-protocol-v1.md) for the path and
6297+
conflict-protection limits.
6298+
6299+
`remote.readFile` applies a cumulative 16 MiB decoded-content limit and a
6300+
120-second overall read deadline, with each chunk limited to 30 seconds.
6301+
Cancellation is checked between chunks and at most every 50 ms while waiting
6302+
for a reply; dropping a pending chunk withdraws unsent work and ignores late
6303+
replies without closing the connection. The read validates chunk progress, EOF
6304+
and file revisions, rejecting a changed file instead of returning mixed content.
6305+
It does not perform a preliminary uncancellable `stat` outside that deadline.
6306+
62706307
`remote.hostRequest` accepts finite filesystem, environment and port queries,
62716308
`server.state` (what still runs, with the `label` given at start, so the host
62726309
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
64516488
decisions are separate and never carry over. They are keyed by the
64526489
connection's **target** and the workspace's **real path** on the host:
64536490

6454-
- The target is `{ hops, userId? }`. Each hop keeps only what chooses where
6491+
- The target is `{ hops, userId?, identity? }`. Each hop keeps only what chooses where
64556492
it ends: `{ ssh: { destination, port?, portOption?, user?, proxyJump? } }`
64566493
(the first `Port`, `User` and `ProxyJump` options, as ssh uses them) or
64576494
`{ container: { engine, program, container, user? } }`. Keys, timeouts,
64586495
keep-alive, working directories and environment are not part of it.
6459-
`userId` is the server's numeric account from `server.hello`. Targets match
6496+
`userId` is the server's numeric account from `server.hello`. `identity` is
6497+
the verified session binding described above, or a fresh connection-local
6498+
identity when that binding is unavailable. Legacy targets without it remain
6499+
readable and revocable but cannot authorize new connections. Targets match
64606500
exactly: another host, account, port, route or container asks again, and so
64616501
does a spelling that may reach the same account, such as `dev@box` against
64626502
`box` with `User=dev`.

‎rust/crates/diagnostics/src/catalog_generated.rs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1542,6 +1542,19 @@ pub static EVENTS: &[EventMetadata] = &[
15421542
rate: 60,
15431543
owner: "lithe-core",
15441544
},
1545+
EventMetadata {
1546+
id: "remote.session.identity_rejected",
1547+
channel: "remote",
1548+
level: LogLevel::Warn,
1549+
message: "Remote identity could not authorize automatic session recovery",
1550+
fields: &[
1551+
FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Controlled identity category without host names, fingerprints or credentials", reason: None },
1552+
FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "Identity validation or resume binding stage", reason: None },
1553+
],
1554+
span: None,
1555+
rate: 60,
1556+
owner: "lithe-core",
1557+
},
15451558
EventMetadata {
15461559
id: "remote.session.state_failed",
15471560
channel: "remote",

‎rust/crates/git-host/src/authentication.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ mod unix;
1818
#[cfg(unix)]
1919
use unix as channel;
2020
#[cfg(windows)]
21-
mod windows;
21+
pub(crate) mod windows;
2222
#[cfg(windows)]
2323
use windows as channel;
2424
#[cfg(test)]

‎rust/crates/git-host/src/authentication/windows.rs‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,25 @@ const CREATE_ATTEMPTS: usize = 4;
5151
/// How long the helper waits for a free pipe instance.
5252
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
5353

54+
/// Creates a directory with the same protected owner-only DACL as AskPass.
55+
pub(crate) fn private_directory(path: &std::path::Path) -> io::Result<()> {
56+
use windows_sys::Win32::Storage::FileSystem::CreateDirectoryW;
57+
let descriptor = Descriptor::owner_only(&CurrentUser::query()?)?;
58+
let attributes = SECURITY_ATTRIBUTES {
59+
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
60+
lpSecurityDescriptor: descriptor.0 .0,
61+
bInheritHandle: 0,
62+
};
63+
let path = wide(path.as_os_str());
64+
// SAFETY: both the NUL-terminated path and security descriptor outlive
65+
// this call; CreateDirectoryW copies the descriptor into the directory.
66+
if unsafe { CreateDirectoryW(path.as_ptr(), &attributes) } == 0 {
67+
Err(io::Error::last_os_error())
68+
} else {
69+
Ok(())
70+
}
71+
}
72+
5473
/// Listening pipe for one session. Dropping it closes the last listening
5574
/// instance, which removes the pipe name once accepted instances close too.
5675
pub(super) struct Listener {

‎rust/crates/git-host/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ pub mod failure_log;
1010

1111
pub mod authentication;
1212
pub mod configuration;
13+
pub mod private_directory;
1314

1415
use std::fs::{File, OpenOptions};
1516
use std::io::{self, Read, Seek, SeekFrom, Write};
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
//! Fresh owner-only directories for short-lived native helper evidence.
2+
3+
use rand::RngCore;
4+
use std::io;
5+
use std::path::{Path, PathBuf};
6+
7+
/// Owns a fresh directory, removed after its caller has stopped the helper.
8+
pub struct PrivateDirectory(PathBuf);
9+
10+
impl PrivateDirectory {
11+
/// Creates one directory in the platform temporary directory. No shared
12+
/// cache, installed resource or user preference is changed.
13+
pub fn new() -> io::Result<Self> {
14+
let mut bytes = [0u8; 16];
15+
rand::rngs::OsRng
16+
.try_fill_bytes(&mut bytes)
17+
.map_err(io::Error::other)?;
18+
let suffix: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
19+
let path = std::env::temp_dir().join(format!("lithe-evidence-{suffix}"));
20+
create(&path)?;
21+
Ok(Self(path))
22+
}
23+
24+
/// Private parent for caller-owned evidence files.
25+
pub fn path(&self) -> &Path {
26+
&self.0
27+
}
28+
}
29+
30+
impl Drop for PrivateDirectory {
31+
fn drop(&mut self) {
32+
crate::failure_log::cleanup(
33+
"vcs.host.cleanup_failed",
34+
"evidence_cleanup",
35+
std::fs::remove_dir_all(&self.0),
36+
);
37+
}
38+
}
39+
40+
#[cfg(unix)]
41+
fn create(path: &Path) -> io::Result<()> {
42+
use std::os::unix::fs::DirBuilderExt;
43+
std::fs::DirBuilder::new().mode(0o700).create(path)
44+
}
45+
46+
#[cfg(windows)]
47+
fn create(path: &Path) -> io::Result<()> {
48+
crate::authentication::windows::private_directory(path)
49+
}

0 commit comments

Comments
 (0)