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
22 changes: 18 additions & 4 deletions rust/contracts/application-boundary.md
Original file line number Diff line number Diff line change
Expand Up @@ -381,21 +381,35 @@ or remote failures. The shape is pinned by

## Error Codes

Use stable categories rather than platform error strings:
Use stable categories rather than platform error strings. Each code has one
meaning; `lithe_protocol::ErrorCode` documents when it is reported:

- `git_branch_not_merged`
- `git_branch_changed`
- `git_untrusted_workspace`: the workspace is not trusted, so Git did not start
- `invalid_request`
- `workspace_not_found`
- `permission_denied`
- `not_supported`
- `runtime_missing`
- `process_start_failed`
- `process_failed`
- `git_branch_exists`
- `git_branch_not_merged`
- `git_branch_changed`
- `git_checkout_changed`
- `git_authentication_failed`
- `git_worktree_not_registered`
- `git_worktree_primary`
- `git_worktree_current`
- `git_worktree_locked`
- `git_worktree_has_changes`
- `git_commit_author_invalid`
- `git_untrusted_workspace`: the workspace is not trusted, so Git did not start
- `parse_failed`
- `encoding_unmappable`
- `cancelled`
- `timed_out`
- `connection_closed`
- `remote_server_invalid`: the server build `remote.connect` would send cannot
be read or is not the build its SHA-256 names
- `unknown`

GitHub authorization is independent of a Lithe account. Device Flow is the
Expand Down
6 changes: 6 additions & 0 deletions rust/contracts/remote-workspace-protocol-v1.md
Original file line number Diff line number Diff line change
Expand Up @@ -322,3 +322,9 @@ belong to the remote user and are not writable by the group or other users.
On a host without a hash tool, a fresh upload is accepted when its size
matches and `--identity` reports the expected hash, and it is uploaded again
on every connection instead of being reused.

The expected hash is never computed from the file about to be sent: the
application ships it in a manifest signed with the builds, and the
bootstrapper reads the build once, compares it with that hash and sends the
same bytes. A build that cannot be read or differs is refused before anything
reaches the host (`remote_server_invalid` from `remote.connect`).
28 changes: 21 additions & 7 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -5700,17 +5700,31 @@ and `uptimeSeconds`.

#### Remote connections that stay open

`remote.connect` takes `{ connection, servers: [{ target, path }],
`remote.connect` takes `{ connection, servers: [{ target, path, sha256 }],
serverVersion, installRoot? }`. `servers` are the read-only server builds the
host ships, by Rust target; `installRoot` defaults to `$HOME/.lithe-server`.
One OpenSSH process probes the host, keeps an installed server whose
`--identity` reports the same SHA-256 or uploads the matching build through
the same stream, and starts it, so the user authenticates once. Prompts are
relayed as for `remote.probe`. The result is `{ status, session, host,
diagnostics }`; `session` is `{ id, uploaded, hostName, userName,
host ships, by Rust target; `sha256` is the build's SHA-256 as 64 hexadecimal
digits, taken from the manifest the application ships and signs with the
builds, never computed from the file Core is about to send. `installRoot`
defaults to `$HOME/.lithe-server`. One OpenSSH process probes the host, then
Core reads the build for the host's platform once and compares it with its
`sha256`; the bytes it checked are the bytes it sends. The host keeps an
installed server only when its own `sha256sum` or `shasum` computes that
SHA-256; otherwise it receives the build through the same stream, checks it
the same way (a host with neither tool checks the size and `--identity`, and
never reuses that upload), and starts it, so the user authenticates once.
Prompts are relayed as for `remote.probe`. The result is `{ status, session,
host, diagnostics }`; `session` is `{ id, uploaded, hostName, userName,
homeDirectory }` and is set only for `connected`. A host without a matching
build is `unsupportedPlatform` and nothing is uploaded.

A malformed connection, an unknown `target` or a `sha256` that is not 64
hexadecimal digits is `invalid_request`, before OpenSSH starts. A missing
`ssh` is `runtime_missing`. When the build for the host's platform cannot be
read or its SHA-256 differs, the attempt ends as `remote_server_invalid`
without sending anything; `details` says which of the two happened and, for a
mismatch, the SHA-256 Core computed, but never the path. Cancellation and the
five-minute bound are `cancelled` and `timed_out`.

Core keeps an open connection until `remote.disconnect` (`{ sessionId }`,
returning `{ closed }`) or until the host process exits; ending it terminates
the OpenSSH process tree. `remote.closeAll` (no payload, returning
Expand Down
5 changes: 5 additions & 0 deletions rust/crates/protocol/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ pub enum ErrorCode {
/// A long-lived connection the request names is closed or was lost; the
/// caller can reconnect and retry.
ConnectionClosed,
/// `remote.connect` reached a host whose server build the request names,
/// but the local file could not be read or its SHA-256 is not the one the
/// request gives for it. Nothing was installed on the host; the
/// application's copy of the build is damaged or was replaced.
RemoteServerInvalid,
/// A failure does not fit a more stable cross-platform category.
Unknown,
}
Expand Down
204 changes: 183 additions & 21 deletions rust/crates/remote/src/client/bootstrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@
//! directory, so clients of different releases can share a host.

use sha2::{Digest, Sha256};
use std::fs::File;
use std::fmt;
use std::io;
use std::path::PathBuf;
use std::path::Path;
use std::sync::Arc;

const PROBE_BEGIN: &str = "LITHE-PROBE-BEGIN";
const PROBE_END: &str = "LITHE-PROBE-END";
Expand Down Expand Up @@ -92,37 +93,113 @@ impl ServerTarget {
}
}

/// A server binary available on the local machine.
/// A server binary held in memory together with its identity.
///
/// The bytes are read once. The SHA-256 sent to the host, the bytes uploaded
/// and the bytes checked against the caller's expected hash are therefore the
/// same: replacing the file after the check changes nothing that is sent.
#[derive(Clone, Debug)]
pub struct ServerArtifact {
/// Platform the binary runs on.
pub target: ServerTarget,
/// Location of the binary on the local machine.
pub path: PathBuf,
/// Server version, the first part of the install directory name.
pub version: String,
/// Lowercase hex SHA-256 of the binary; the host must compute the same hash.
pub sha256: String,
target: ServerTarget,
version: String,
sha256: String,
binary: Arc<[u8]>,
}

impl ServerArtifact {
/// Describes a binary on disk, hashing it.
pub fn from_file(
/// Reads the binary at `path` and accepts it only when its SHA-256 is
/// `expected_sha256`. The expected hash must come from something the
/// local file cannot change, for example a manifest built and signed
/// together with the application; then a binary replaced on the local
/// disk is refused instead of being uploaded to the host.
pub fn read_verified(
target: ServerTarget,
path: PathBuf,
path: &Path,
version: impl Into<String>,
) -> io::Result<Self> {
let mut hasher = Sha256::new();
io::copy(&mut File::open(&path)?, &mut hasher)?;
Ok(Self {
expected_sha256: &str,
) -> Result<Self, ArtifactError> {
if !crate::protocol::methods::is_sha256_hex(expected_sha256) {
return Err(ArtifactError::InvalidHash);
}
let binary = std::fs::read(path).map_err(ArtifactError::Io)?;
let artifact = Self::from_bytes(target, binary, version);
if !artifact.sha256.eq_ignore_ascii_case(expected_sha256) {
return Err(ArtifactError::Mismatch {
actual: artifact.sha256,
});
}
Ok(artifact)
}

/// Describes bytes the caller already holds, hashing them. Suits callers
/// that produced the binary themselves, such as tests that build it.
pub fn from_bytes(
target: ServerTarget,
binary: impl Into<Arc<[u8]>>,
version: impl Into<String>,
) -> Self {
let binary = binary.into();
Self {
target,
path,
version: version.into(),
sha256: crate::protocol::methods::encode_hex(&hasher.finalize()),
})
sha256: crate::protocol::methods::encode_hex(&Sha256::digest(&binary)),
binary,
}
}

/// Platform the binary runs on.
pub fn target(&self) -> ServerTarget {
self.target
}

/// Server version, the first part of the install directory name.
pub fn version(&self) -> &str {
&self.version
}

/// Lowercase hex SHA-256 of [`Self::binary`]; the host must compute the
/// same hash before it runs the server.
pub fn sha256(&self) -> &str {
&self.sha256
}

/// The bytes uploaded when the host has no matching server installed.
pub fn binary(&self) -> &[u8] {
&self.binary
}
}

/// Why [`ServerArtifact::read_verified`] refused a binary.
#[derive(Debug)]
pub enum ArtifactError {
/// The expected SHA-256 is not 64 hexadecimal digits.
InvalidHash,
/// The binary could not be read.
Io(io::Error),
/// The binary's SHA-256 is not the expected one.
Mismatch {
/// Lowercase hex SHA-256 of the bytes that were read.
actual: String,
},
}

impl fmt::Display for ArtifactError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidHash => {
formatter.write_str("the expected SHA-256 is not 64 hexadecimal digits")
}
Self::Io(error) => write!(formatter, "the server binary could not be read: {error}"),
Self::Mismatch { actual } => write!(
formatter,
"the server binary does not match the expected SHA-256; its SHA-256 is {actual}"
),
}
}
}

impl std::error::Error for ArtifactError {}

/// What the probe reported about the end of a chain.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProbeReport {
Expand Down Expand Up @@ -290,6 +367,91 @@ LITHE-PROBE-BEGIN\nLinux\nx86_64\n/root\nLITHE-PROBE-END\n";
assert_eq!(mac.cpu_count, None);
}

/// A private file removed when the test ends, also after a failed assertion.
struct TempFile(std::path::PathBuf);

impl TempFile {
fn new(name: &str, contents: &[u8]) -> Self {
let path = std::env::temp_dir().join(format!(
"lithe-remote-artifact-{name}-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
std::fs::write(&path, contents).unwrap();
Self(path)
}
}

impl Drop for TempFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}

const BINARY: &[u8] = b"server build";

fn sha256_of(bytes: &[u8]) -> String {
crate::protocol::methods::encode_hex(&Sha256::digest(bytes))
}

// The hash sent to the host and the bytes uploaded are the ones checked,
// so replacing the file after the check does not change the upload.
#[test]
fn a_verified_binary_keeps_the_bytes_that_were_checked() {
let file = TempFile::new("keeps", BINARY);
let expected = sha256_of(BINARY).to_ascii_uppercase();
let artifact =
ServerArtifact::read_verified(ServerTarget::LinuxX86_64, &file.0, "1.0.0", &expected)
.unwrap();
std::fs::write(&file.0, b"replaced afterwards").unwrap();
assert_eq!(artifact.binary(), BINARY);
assert_eq!(artifact.sha256(), sha256_of(BINARY));
assert_eq!(artifact.target(), ServerTarget::LinuxX86_64);
assert_eq!(artifact.version(), "1.0.0");
}

#[test]
fn a_binary_that_differs_from_the_expected_hash_is_refused() {
let file = TempFile::new("differs", b"replaced build");
let refused = ServerArtifact::read_verified(
ServerTarget::LinuxAarch64,
&file.0,
"1.0.0",
&sha256_of(BINARY),
);
assert!(
matches!(&refused, Err(ArtifactError::Mismatch { actual })
if *actual == sha256_of(b"replaced build")),
"{refused:?}"
);
}

// A malformed expectation is refused before the file is read, so it can
// never be compared against, or confused with, a missing file.
#[test]
fn a_malformed_expected_hash_is_refused_before_reading() {
let missing = std::env::temp_dir().join("lithe-remote-artifact-never-created");
for expected in [
String::new(),
"0".repeat(63),
format!("{}g", "0".repeat(63)),
] {
assert!(matches!(
ServerArtifact::read_verified(ServerTarget::LinuxX86_64, &missing, "1", &expected),
Err(ArtifactError::InvalidHash)
));
}
assert!(matches!(
ServerArtifact::read_verified(
ServerTarget::LinuxX86_64,
&missing,
"1",
&"0".repeat(64)
),
Err(ArtifactError::Io(error)) if error.kind() == io::ErrorKind::NotFound
));
}

// The probe crosses SSH hops through the transport's quoting, which
// rejects these characters instead of escaping them.
#[test]
Expand Down
4 changes: 2 additions & 2 deletions rust/crates/remote/src/client/connection_log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,8 +217,8 @@ impl ConnectionLog {
"reused"
};
let mut fields = vec![
("target", json!(artifact.target.rust_target())),
("server_version", json!(artifact.version)),
("target", json!(artifact.target().rust_target())),
("server_version", json!(artifact.version())),
("action", json!(action)),
("verification", json!(deployment.verification.as_str())),
("duration_ms", millis(duration)),
Expand Down
Loading
Loading