From 213c6c70974ef7e58033111adcd3ee605f39025a Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 21 Nov 2026 00:13:49 +0800 Subject: [PATCH] =?UTF-8?q?feat(remote):=20=E8=BF=9C=E7=A8=8B=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E7=94=9F=E5=91=BD=E5=91=A8=E6=9C=9F=E5=86=99=E5=85=A5?= =?UTF-8?q?=E6=97=A5=E5=BF=97=20v2=EF=BC=88S34=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Lithe-IDEA#2231 S34:每次远程连接用随机连接 id 标识,按日志目录 记录连接、认证结果、上传与校验、部署、转发、中断和清理,不记录 主机、用户名、路径、远端输出、令牌或认证回答。 - client/connection_log.rs:ConnectionLog 跟踪一次连接,状态按 打开 → 关闭中 → 断开 → 释放推进,同一连接的每个结局只记一次; ended 区分 shutdown、lost、detached、closed。 - launch:安装步骤(mkdir/write/verify/rename)失败时记录分类, 部署结果区分上传与复用、sha256 与身份校验,上传时才记字节数。 - session:常驻会话记录 transport、persistent、resumed;读循环 结束时记录中断原因,Drop 时记录清理结果。 - forward:开始时记录本地端口、绑定范围和目标类型,移除时记录 接受的连接数和持续时间;转发失败事件带上连接 id。 - workspace/sessions.rs:探测结果映射为互不重复的失败分类 (probe/authentication/network/connect),取消不算失败。 - 日志目录 remote.json 新增对应事件并重新生成 catalog_generated.rs。 - 测试 tests/connection_log.rs:用 Core 的日志目录校验每条记录, 覆盖上传与复用、校验失败、常驻会话分离与恢复、远端被杀、端口 转发、握手失败、连接前取消,并断言记录里没有路径、HOME、用户名、 主机地址、令牌和远端输出。lithe-diagnostics 只作为 dev-dependency。 --- rust/Cargo.lock | 1 + .../diagnostics/src/catalog_generated.rs | 150 +++++++ rust/crates/remote/Cargo.toml | 9 + .../remote/src/client/connection_log.rs | 420 ++++++++++++++++++ rust/crates/remote/src/client/forward.rs | 33 +- rust/crates/remote/src/client/launch.rs | 324 ++++++++++++-- rust/crates/remote/src/client/mod.rs | 4 + rust/crates/remote/src/client/session.rs | 130 +++++- rust/crates/remote/src/failure_log.rs | 73 ++- rust/crates/remote/tests/connection_log.rs | 386 ++++++++++++++++ rust/crates/remote/tests/server.rs | 20 +- rust/crates/workspace/src/probe/tests.rs | 24 + rust/crates/workspace/src/sessions.rs | 51 ++- rust/logging/events/remote.json | 236 ++++++++++ 14 files changed, 1775 insertions(+), 86 deletions(-) create mode 100644 rust/crates/remote/src/client/connection_log.rs create mode 100644 rust/crates/remote/tests/connection_log.rs diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 408e367e..6d33e415 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1466,6 +1466,7 @@ version = "0.1.0" dependencies = [ "base64", "libc", + "lithe-diagnostics", "serde", "serde_json", "sha2", diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index ac34d354..d79abe9c 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -1281,12 +1281,111 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 60, owner: "lithe-core", }, + EventMetadata { + id: "remote.connection.cleaned", + channel: "remote", + level: LogLevel::Info, + message: "Remote connection {ended}", + fields: &[ + FieldMetadata { name: "connection", field_type: FieldType::Id, required: true, description: "Random per-connection log identifier that correlates this connection's lines; never a host, user name or session token", reason: None }, + FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Lifetime of the established connection from the completed handshake until release", reason: None }, + FieldMetadata { name: "ended", field_type: FieldType::Token, required: true, description: "How the session was released: shutdown, closed (stdio server ended with the client), detached (daemon kept running) or lost", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "remote.connection.connect.failed", + channel: "remote", + level: LogLevel::Warn, + message: "Remote connection failed", + fields: &[ + FieldMetadata { name: "connection", field_type: FieldType::Id, required: true, description: "Random per-connection log identifier that correlates this connection's lines; never a host, user name or session token", reason: None }, + FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Monotonic time from remote.connection.connect.started to remote.connection.connect.failed, encoded in milliseconds", reason: None }, + FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Failure that ended the remote.connection.connect operation, retaining its error code and domain without unredacted private details", reason: None }, + FieldMetadata { name: "outcome", field_type: FieldType::Token, required: false, description: "How the attempt ended without a failure: connected, or cancelled by the user before the session opened", reason: None }, + FieldMetadata { name: "persistent", field_type: FieldType::Bool, required: false, description: "Whether the server is a persistent daemon session that survives this client disconnecting", reason: None }, + FieldMetadata { name: "resumed", field_type: FieldType::Bool, required: false, description: "Whether this connection reattached to an existing persistent session, i.e. a reconnect", reason: None }, + FieldMetadata { name: "server_version", field_type: FieldType::Version, required: false, description: "Version the remote server reported in server.hello once the handshake succeeded", reason: None }, + FieldMetadata { name: "stage", field_type: FieldType::Token, required: false, description: "Connection step that failed: probe, artifact, deploy, handshake, authentication, network or connect", reason: None }, + FieldMetadata { name: "transport", field_type: FieldType::Token, required: true, description: "How the client reached the server: ssh, command (any spawned transport chain) or streams (caller-supplied pipes)", reason: None }, + ], + span: Some(SpanPhase::Failed), + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "remote.connection.connect.finished", + channel: "remote", + level: LogLevel::Info, + message: "Remote connection finished", + fields: &[ + FieldMetadata { name: "connection", field_type: FieldType::Id, required: true, description: "Random per-connection log identifier that correlates this connection's lines; never a host, user name or session token", reason: None }, + FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Monotonic time from remote.connection.connect.started to remote.connection.connect.finished, encoded in milliseconds", reason: None }, + FieldMetadata { name: "outcome", field_type: FieldType::Token, required: false, description: "How the attempt ended without a failure: connected, or cancelled by the user before the session opened", reason: None }, + FieldMetadata { name: "persistent", field_type: FieldType::Bool, required: false, description: "Whether the server is a persistent daemon session that survives this client disconnecting", reason: None }, + FieldMetadata { name: "resumed", field_type: FieldType::Bool, required: false, description: "Whether this connection reattached to an existing persistent session, i.e. a reconnect", reason: None }, + FieldMetadata { name: "server_version", field_type: FieldType::Version, required: false, description: "Version the remote server reported in server.hello once the handshake succeeded", reason: None }, + FieldMetadata { name: "stage", field_type: FieldType::Token, required: false, description: "Connection step that failed: probe, artifact, deploy, handshake, authentication, network or connect", reason: None }, + FieldMetadata { name: "transport", field_type: FieldType::Token, required: true, description: "How the client reached the server: ssh, command (any spawned transport chain) or streams (caller-supplied pipes)", reason: None }, + ], + span: Some(SpanPhase::Finished), + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "remote.connection.connect.started", + channel: "remote", + level: LogLevel::Debug, + message: "Remote connection started", + fields: &[ + FieldMetadata { name: "connection", field_type: FieldType::Id, required: true, description: "Random per-connection log identifier that correlates this connection's lines; never a host, user name or session token", reason: None }, + FieldMetadata { name: "outcome", field_type: FieldType::Token, required: false, description: "How the attempt ended without a failure: connected, or cancelled by the user before the session opened", reason: None }, + FieldMetadata { name: "persistent", field_type: FieldType::Bool, required: false, description: "Whether the server is a persistent daemon session that survives this client disconnecting", reason: None }, + FieldMetadata { name: "resumed", field_type: FieldType::Bool, required: false, description: "Whether this connection reattached to an existing persistent session, i.e. a reconnect", reason: None }, + FieldMetadata { name: "server_version", field_type: FieldType::Version, required: false, description: "Version the remote server reported in server.hello once the handshake succeeded", reason: None }, + FieldMetadata { name: "stage", field_type: FieldType::Token, required: false, description: "Connection step that failed: probe, artifact, deploy, handshake, authentication, network or connect", reason: None }, + FieldMetadata { name: "transport", field_type: FieldType::Token, required: true, description: "How the client reached the server: ssh, command (any spawned transport chain) or streams (caller-supplied pipes)", reason: None }, + ], + span: Some(SpanPhase::Started), + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "remote.connection.interrupted", + channel: "remote", + level: LogLevel::Warn, + message: "Remote connection interrupted: {cause}", + fields: &[ + FieldMetadata { name: "cause", field_type: FieldType::Token, required: true, description: "Why the server stream ended without a shutdown request: eof, protocol, overflow, or an I/O error kind", reason: None }, + FieldMetadata { name: "connection", field_type: FieldType::Id, required: true, description: "Random per-connection log identifier that correlates this connection's lines; never a host, user name or session token", reason: None }, + FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Time the connection had been established before the stream ended unexpectedly", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "remote.connection.shell_started", + channel: "remote", + level: LogLevel::Info, + message: "Remote shell answered the probe for {target}", + fields: &[ + FieldMetadata { name: "connection", field_type: FieldType::Id, required: true, description: "Random per-connection log identifier that correlates this connection's lines; never a host, user name or session token", reason: None }, + FieldMetadata { name: "target", field_type: FieldType::Token, required: true, description: "Server build target matching the probed system, e.g. x86_64-unknown-linux-musl, or unsupported; authentication has succeeded", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, EventMetadata { id: "remote.forward.accept_failed", channel: "remote", level: LogLevel::Warn, message: "Port forward accept failed", fields: &[ + FieldMetadata { name: "connection", field_type: FieldType::Id, required: false, description: "Random per-connection log identifier of the forward's session; never a host, user name or session token", reason: None }, FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Fixed summary and stable failure category from remote.forward.accept_failed; never error display text", reason: None }, FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "Controlled remote.forward.accept_failed operation stage; excludes paths and peer input", reason: None }, ], @@ -1300,6 +1399,7 @@ pub static EVENTS: &[EventMetadata] = &[ level: LogLevel::Warn, message: "Forwarded connection failed", fields: &[ + FieldMetadata { name: "connection", field_type: FieldType::Id, required: false, description: "Random per-connection log identifier of the forward's session; never a host, user name or session token", reason: None }, FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Fixed summary and stable failure category from remote.forward.connection_failed; never error display text", reason: None }, FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "Controlled remote.forward.connection_failed operation stage; excludes paths and peer input", reason: None }, ], @@ -1307,6 +1407,38 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 12, owner: "lithe-core", }, + EventMetadata { + id: "remote.forward.removed", + channel: "remote", + level: LogLevel::Info, + message: "Port forward on local port {local_port} removed", + fields: &[ + FieldMetadata { name: "connection", field_type: FieldType::Id, required: true, description: "Random per-connection log identifier that correlates this connection's lines; never a host, user name or session token", reason: None }, + FieldMetadata { name: "connections", field_type: FieldType::Int, required: true, description: "Number of local connections the forward accepted during its lifetime", reason: None }, + FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Time from starting the forward until its acceptor stopped", reason: None }, + FieldMetadata { name: "local_port", field_type: FieldType::Int, required: true, description: "Local TCP port the forward stopped listening on", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "remote.forward.started", + channel: "remote", + level: LogLevel::Info, + message: "Port forward started on local port {local_port}", + fields: &[ + FieldMetadata { name: "bind_scope", field_type: FieldType::Token, required: true, description: "Whether the local listener is bound to loopback only or to a network-reachable address", reason: None }, + FieldMetadata { name: "connection", field_type: FieldType::Id, required: true, description: "Random per-connection log identifier that correlates this connection's lines; never a host, user name or session token", reason: None }, + FieldMetadata { name: "local_port", field_type: FieldType::Int, required: true, description: "Local TCP port the forward listens on, after the system chose one for port 0", reason: None }, + FieldMetadata { name: "remote_port", field_type: FieldType::Int, required: false, description: "Remote TCP port the forward reaches; absent for unix sockets, and the remote host is never logged", reason: None }, + FieldMetadata { name: "target_kind", field_type: FieldType::Token, required: true, description: "Remote endpoint family the forward opens: tcp for host and port, unix for a socket path", reason: None }, + FieldMetadata { name: "target_scope", field_type: FieldType::Token, required: false, description: "Whether the remote TCP host is a loopback name or address, or another network host", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, EventMetadata { id: "remote.process.cleanup_failed", channel: "remote", @@ -1332,6 +1464,24 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 60, owner: "lithe-core", }, + EventMetadata { + id: "remote.server.deploy_finished", + channel: "remote", + level: LogLevel::Info, + message: "Remote server {action} after {verification} verification", + fields: &[ + FieldMetadata { name: "action", field_type: FieldType::Token, required: true, description: "Deployment result: reused when the private installed binary already matched, uploaded otherwise", reason: None }, + FieldMetadata { name: "bytes", field_type: FieldType::Bytes, required: false, description: "Size of the server binary sent over the connection; present only when it was uploaded", reason: None }, + FieldMetadata { name: "connection", field_type: FieldType::Id, required: true, description: "Random per-connection log identifier that correlates this connection's lines; never a host, user name or session token", reason: None }, + FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Time from sending the install request until the remote confirmed the installed binary", reason: None }, + FieldMetadata { name: "server_version", field_type: FieldType::Version, required: true, description: "Version of the bundled server artifact the client offered for this deployment", reason: None }, + FieldMetadata { name: "target", field_type: FieldType::Token, required: true, description: "Server build target that was installed or reused, e.g. aarch64-unknown-linux-musl", reason: None }, + FieldMetadata { name: "verification", field_type: FieldType::Token, required: true, description: "How the remote checked the binary: sha256 computed by the host's own tool, or identity (matching size and self-reported identity) when the host has no hash tool", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, EventMetadata { id: "remote.session.cleanup_failed", channel: "remote", diff --git a/rust/crates/remote/Cargo.toml b/rust/crates/remote/Cargo.toml index b06223a2..44b8c162 100644 --- a/rust/crates/remote/Cargo.toml +++ b/rust/crates/remote/Cargo.toml @@ -30,6 +30,11 @@ sha2 = { version = "0.10", optional = true } libc = { version = "0.2", optional = true } trash = { version = "5.2.6", default-features = false, features = ["chrono"], optional = true } +# Tests check every lifecycle fact against the log catalog Core validates with. +# Only tests use it: the server and the client stay free of Core crates. +[dev-dependencies] +lithe-diagnostics = { path = "../diagnostics" } + [[bin]] name = "lithe-remote-server" path = "src/bin/lithe-remote-server.rs" @@ -62,3 +67,7 @@ required-features = ["client", "server"] [[test]] name = "persistence" required-features = ["client", "server"] + +[[test]] +name = "connection_log" +required-features = ["client", "server"] diff --git a/rust/crates/remote/src/client/connection_log.rs b/rust/crates/remote/src/client/connection_log.rs new file mode 100644 index 00000000..ab50affa --- /dev/null +++ b/rust/crates/remote/src/client/connection_log.rs @@ -0,0 +1,420 @@ +//! Connection lifecycle facts (design S34). +//! +//! One [`ConnectionLog`] follows one connection attempt from its first step +//! until its session is released. Every fact carries the same `connection` +//! value, a random identifier made for this attempt, so all lines of one +//! connection can be read together. The application maps it to the +//! connection's display name; hosts, user names, home directories, paths, +//! prompts, answers and session tokens never enter these facts, so an exported +//! log names no host or user. +//! +//! An attempt records, in order: +//! +//! 1. `remote.connection.connect.started` when it begins; +//! 2. `remote.connection.shell_started` once authentication succeeded and the +//! remote shell answered the probe; +//! 3. `remote.server.deploy_finished` after the installed server was reused, +//! or uploaded and verified; +//! 4. exactly one of `remote.connection.connect.finished` (connected or +//! cancelled) and `remote.connection.connect.failed`; +//! 5. `remote.connection.interrupted` when an established stream ends without +//! a shutdown request; +//! 6. `remote.connection.cleaned` when the established session is released. +//! +//! Port forwards over the session add `remote.forward.started` and +//! `remote.forward.removed`. +//! +//! Several layers can see the same failure: the launch script, the protocol +//! handshake, and the caller that owns the SSH process. Each reports the most +//! specific stage it knows, and only the first outcome of an attempt is kept, +//! so an attempt never records two outcomes. + +use crate::client::bootstrap::{ServerArtifact, ServerTarget}; +use crate::client::launch::{Deployment, LaunchError}; +use crate::failure_log; +use crate::protocol::methods::{encode_hex, HelloResult, TunnelTarget}; +use serde_json::{json, Value}; +use std::collections::hash_map::RandomState; +use std::fmt; +use std::hash::BuildHasher; +use std::net::{IpAddr, SocketAddr}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering}; +use std::sync::{Arc, OnceLock}; +use std::time::{Duration, Instant}; + +pub(crate) const CONNECT_STARTED: &str = "remote.connection.connect.started"; +pub(crate) const CONNECT_FINISHED: &str = "remote.connection.connect.finished"; +pub(crate) const CONNECT_FAILED: &str = "remote.connection.connect.failed"; +pub(crate) const SHELL_STARTED: &str = "remote.connection.shell_started"; +pub(crate) const DEPLOY_FINISHED: &str = "remote.server.deploy_finished"; +pub(crate) const INTERRUPTED: &str = "remote.connection.interrupted"; +pub(crate) const CLEANED: &str = "remote.connection.cleaned"; +pub(crate) const FORWARD_STARTED: &str = "remote.forward.started"; +pub(crate) const FORWARD_REMOVED: &str = "remote.forward.removed"; + +// Session states only move forward, in this order. + +/// The session is established, or not yet. +const OPEN: u8 = 0; +/// The client asked the server to shut down; the stream ending is expected. +const SHUTTING_DOWN: u8 = 1; +/// The stream ended without a shutdown request. +const LOST: u8 = 2; +/// The session was released and `remote.connection.cleaned` is settled. +const RELEASED: u8 = 3; + +/// How the client reaches the server. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ConnectionKind { + /// An SSH connection owned by the caller. + Ssh, + /// A transport chain [`crate::client::RemoteSession::connect`] spawns. + Command, + /// Streams the caller supplies to + /// [`crate::client::RemoteSession::from_streams`]. + Streams, +} + +impl ConnectionKind { + fn as_str(self) -> &'static str { + match self { + Self::Ssh => "ssh", + Self::Command => "command", + Self::Streams => "streams", + } + } +} + +/// Lifecycle log of one connection attempt. Clones share the attempt, so the +/// caller, the launch and the session record into the same lines. +#[derive(Clone)] +pub struct ConnectionLog(Arc); + +struct Inner { + id: String, + kind: ConnectionKind, + started: Instant, + settled: AtomicBool, + connected: OnceLock, + state: AtomicU8, +} + +impl fmt::Debug for ConnectionLog { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "ConnectionLog({})", self.0.id) + } +} + +impl ConnectionLog { + /// Starts the log of a new attempt and records + /// `remote.connection.connect.started`. + pub fn begin(kind: ConnectionKind) -> Self { + let log = Self(Arc::new(Inner { + id: random_id(), + kind, + started: Instant::now(), + settled: AtomicBool::new(false), + connected: OnceLock::new(), + state: AtomicU8::new(OPEN), + })); + log.emit_connect(CONNECT_STARTED, vec![]); + log + } + + /// The `connection` value of every fact of this attempt: 16 random hex + /// digits that only correlate log lines. It is not a session id or a + /// capability. + pub fn id(&self) -> &str { + &self.0.id + } + + /// Records that the attempt failed at `stage` with a stable category, + /// unless an outcome is already recorded. `stage` is one of `probe`, + /// `artifact`, `deploy`, `handshake`, `authentication`, `network` and + /// `connect`; `code` and `domain` are controlled vocabulary, never error + /// text or peer output. + pub fn connect_failed(&self, stage: &'static str, code: &str, domain: &'static str) { + if self.settle() { + self.emit_connect( + CONNECT_FAILED, + vec![ + ("stage", json!(stage)), + ("error", json!("Remote connection failed")), + ("error_code", json!(code)), + ("error_domain", json!(domain)), + ("duration_ms", millis(self.0.started.elapsed())), + ], + ); + } + } + + /// Records that the user cancelled the attempt before the session opened, + /// unless an outcome is already recorded. Cancellation is not a failure. + pub fn connect_cancelled(&self) { + if self.settle() { + self.emit_connect( + CONNECT_FINISHED, + vec![ + ("outcome", json!("cancelled")), + ("duration_ms", millis(self.0.started.elapsed())), + ], + ); + } + } + + /// Records the completed handshake. The session's lifetime starts here. + pub(crate) fn connected(&self, hello: &HelloResult) { + if !self.settle() { + return; + } + let now = *self.0.connected.get_or_init(Instant::now); + let mut fields = vec![ + ("outcome", json!("connected")), + ("persistent", json!(hello.session.persistent)), + ("resumed", json!(hello.session.resumed)), + ("duration_ms", millis(now - self.0.started)), + ]; + // The version is peer output; one the catalog would refuse is left out + // instead of losing the whole fact. + if is_version(&hello.server_version) { + fields.push(("server_version", json!(hello.server_version))); + } + self.emit_connect(CONNECT_FINISHED, fields); + } + + /// Records a launch failure at `stage`. A shell that never answered the + /// probe is left to the caller, which knows from the SSH process whether + /// authentication, the host key or the network failed. + pub(crate) fn launch_failed(&self, stage: &'static str, error: &LaunchError) { + if stage == "probe" && matches!(error, LaunchError::NoShell) { + return; + } + let domain = match error { + LaunchError::Io(_) => "io", + _ => "remote", + }; + self.connect_failed(stage, &error.failure_category(), domain); + } + + /// Records that the remote shell answered the probe, so authentication + /// succeeded. `target` is `None` when no server build fits the host. + pub(crate) fn shell_started(&self, target: Option) { + let target = target.map_or("unsupported", ServerTarget::rust_target); + self.emit(SHELL_STARTED, vec![("target", json!(target))]); + } + + /// Records how the server was put in place on the host. + pub(crate) fn deployed( + &self, + artifact: &ServerArtifact, + deployment: &Deployment, + bytes: usize, + duration: Duration, + ) { + let action = if deployment.uploaded { + "uploaded" + } else { + "reused" + }; + let mut fields = vec![ + ("target", json!(artifact.target.rust_target())), + ("server_version", json!(artifact.version)), + ("action", json!(action)), + ("verification", json!(deployment.verification.as_str())), + ("duration_ms", millis(duration)), + ]; + if deployment.uploaded { + fields.push(("bytes", json!(bytes))); + } + self.emit(DEPLOY_FINISHED, fields); + } + + /// Marks that the client asked the server to shut down, so the stream + /// ending afterwards is not an interruption. A session already lost or + /// released keeps that state. + pub(crate) fn shutdown_requested(&self) { + self.0.state.fetch_max(SHUTTING_DOWN, Ordering::AcqRel); + } + + /// Records that the server stream ended with `cause`, a controlled token. + /// Nothing is recorded after a shutdown request or release, or before the + /// handshake completed, whose failure the handshake records itself. + pub(crate) fn stream_ended(&self, cause: &str) { + if self + .0 + .state + .compare_exchange(OPEN, LOST, Ordering::AcqRel, Ordering::Acquire) + .is_err() + { + return; + } + if let Some(connected) = self.0.connected.get() { + self.emit( + INTERRUPTED, + vec![ + ("cause", json!(cause)), + ("duration_ms", millis(connected.elapsed())), + ], + ); + } + } + + /// Records the release of an established session once. `persistent` + /// sessions keep running on the host after this client leaves. + pub(crate) fn released(&self, persistent: bool) { + let previous = self.0.state.swap(RELEASED, Ordering::AcqRel); + let Some(connected) = self.0.connected.get() else { + return; + }; + let ended = match previous { + RELEASED => return, + SHUTTING_DOWN => "shutdown", + LOST => "lost", + _ if persistent => "detached", + _ => "closed", + }; + self.emit( + CLEANED, + vec![ + ("ended", json!(ended)), + ("duration_ms", millis(connected.elapsed())), + ], + ); + } + + /// Records a forward listening on `local` for `target`. The remote host + /// and socket path stay out: only the port and whether the host is a + /// loopback name or address are recorded. + pub(crate) fn forward_started(&self, local: SocketAddr, target: &TunnelTarget) { + let mut fields = vec![ + ("local_port", json!(local.port())), + ("bind_scope", json!(scope(local.ip().is_loopback()))), + ]; + match target { + TunnelTarget::Tcp { host, port } => { + fields.push(("target_kind", json!("tcp"))); + fields.push(("remote_port", json!(port))); + fields.push(("target_scope", json!(scope(is_loopback_host(host))))); + } + TunnelTarget::Unix { .. } => fields.push(("target_kind", json!("unix"))), + } + self.emit(FORWARD_STARTED, fields); + } + + /// Records a forward that stopped after accepting `connections`. + pub(crate) fn forward_removed(&self, local_port: u16, connections: u64, duration: Duration) { + self.emit( + FORWARD_REMOVED, + vec![ + ("local_port", json!(local_port)), + ("connections", json!(connections)), + ("duration_ms", millis(duration)), + ], + ); + } + + /// True for the first outcome of the attempt. + fn settle(&self) -> bool { + !self.0.settled.swap(true, Ordering::AcqRel) + } + + fn emit(&self, event: &str, mut fields: Vec<(&'static str, Value)>) { + fields.push(("connection", json!(self.0.id))); + failure_log::record(event, &fields); + } + + /// The connect span also names the transport; the other facts identify + /// the attempt by `connection` alone. + fn emit_connect(&self, event: &str, mut fields: Vec<(&'static str, Value)>) { + fields.push(("transport", json!(self.0.kind.as_str()))); + self.emit(event, fields); + } +} + +fn millis(duration: Duration) -> Value { + json!(u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)) +} + +fn scope(loopback: bool) -> &'static str { + if loopback { + "loopback" + } else { + "network" + } +} + +fn is_loopback_host(host: &str) -> bool { + let unbracketed = host + .strip_prefix('[') + .and_then(|rest| rest.strip_suffix(']')) + .unwrap_or(host); + host.eq_ignore_ascii_case("localhost") + || unbracketed + .parse::() + .is_ok_and(|address| address.is_loopback()) +} + +/// Mirrors the catalog's `version` type: 1 to 64 ASCII letters, digits and `._+-`. +fn is_version(value: &str) -> bool { + !value.is_empty() + && value.len() <= 64 + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"._+-".contains(&byte)) +} + +/// 64 bits from the standard library's randomly keyed hasher. The counter +/// keeps two attempts in one process apart even if the keys repeated. +fn random_id() -> String { + static ATTEMPTS: AtomicU64 = AtomicU64::new(0); + let value = + RandomState::new().hash_one((ATTEMPTS.fetch_add(1, Ordering::Relaxed), std::process::id())); + encode_hex(&value.to_be_bytes()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn identifiers_are_distinct_lowercase_hex() { + let first = random_id(); + let second = random_id(); + assert_eq!(first.len(), 16); + assert!(first + .bytes() + .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())); + assert_ne!(first, second); + } + + #[test] + fn loopback_hosts_are_recognized_without_resolving_names() { + for host in [ + "localhost", + "LOCALHOST", + "127.0.0.1", + "127.8.9.1", + "::1", + "[::1]", + ] { + assert!(is_loopback_host(host), "{host}"); + } + for host in [ + "0.0.0.0", + "10.0.0.1", + "example.com", + "localhost.example.com", + "[::2]", + ] { + assert!(!is_loopback_host(host), "{host}"); + } + } + + #[test] + fn server_versions_outside_the_catalog_vocabulary_are_left_out() { + assert!(is_version("0.8.11+build.3")); + assert!(!is_version("")); + assert!(!is_version("1.0 beta")); + assert!(!is_version(&"1".repeat(65))); + } +} diff --git a/rust/crates/remote/src/client/forward.rs b/rust/crates/remote/src/client/forward.rs index f372041a..ed802c31 100644 --- a/rust/crates/remote/src/client/forward.rs +++ b/rust/crates/remote/src/client/forward.rs @@ -4,13 +4,18 @@ //! opens its own tunnel to the remote target and copies bytes both ways, so //! `http://127.0.0.1:` in a browser reaches a server that only //! listens on the remote machine's loopback interface. +//! +//! Starting and removing a forward are recorded in the session's +//! [`ConnectionLog`] with the local port and the number of accepted +//! connections; the remote host and socket path are not recorded. use crate::client::api::TunnelEvent; +use crate::client::connection_log::ConnectionLog; use crate::client::session::{ClientError, RemoteSession}; use crate::protocol::methods::TunnelTarget; use std::io::{self, Read, Write}; use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream}; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant}; @@ -30,6 +35,10 @@ pub struct PortForward { local_address: SocketAddr, stopping: Arc, acceptor: Option>, + /// Local connections accepted so far. + accepted: Arc, + started: Instant, + log: ConnectionLog, } impl PortForward { @@ -43,8 +52,14 @@ impl PortForward { let listener = TcpListener::bind(bind)?; let local_address = listener.local_addr()?; let stopping = Arc::new(AtomicBool::new(false)); + let accepted = Arc::new(AtomicU64::new(0)); + let log = session.connection_log().clone(); + let started = Instant::now(); let acceptor = { let stopping = Arc::clone(&stopping); + let accepted = Arc::clone(&accepted); + let log = log.clone(); + let target = target.clone(); thread::Builder::new() .name("remote-forward".into()) .spawn(move || { @@ -57,6 +72,7 @@ impl PortForward { Err(error) => { forward_failed( "remote.forward.accept_failed", + &log, "accept", &format!("{:?}", error.kind()), "io", @@ -68,14 +84,17 @@ impl PortForward { continue; } }; + accepted.fetch_add(1, Ordering::Relaxed); let session = Arc::clone(&session); let target = target.clone(); + let log = log.clone(); thread::spawn(move || { if let Err(error) = bridge(&session, connection, target) { if let Some(category) = crate::failure_log::bridge_category(&error) { forward_failed( "remote.forward.connection_failed", + &log, "bridge", &category, "remote", @@ -87,10 +106,14 @@ impl PortForward { } })? }; + log.forward_started(local_address, &target); Ok(Self { local_address, stopping, acceptor: Some(acceptor), + accepted, + started, + log, }) } @@ -126,6 +149,11 @@ impl Drop for PortForward { "thread", ); } + self.log.forward_removed( + self.local_address.port(), + self.accepted.load(Ordering::Relaxed), + self.started.elapsed(), + ); } } @@ -219,6 +247,7 @@ fn permit_failure(last: &mut Option, now: Instant) -> bool { fn forward_failed( event: &str, + log: &ConnectionLog, stage: &'static str, code: &str, domain: &'static str, @@ -229,7 +258,7 @@ fn forward_failed( Instant::now(), ); if permitted { - crate::failure_log::failed(event, stage, code, domain); + crate::failure_log::failed_for(event, log.id(), stage, code, domain); } } diff --git a/rust/crates/remote/src/client/launch.rs b/rust/crates/remote/src/client/launch.rs index 780a766f..5b21defe 100644 --- a/rust/crates/remote/src/client/launch.rs +++ b/rust/crates/remote/src/client/launch.rs @@ -7,12 +7,18 @@ //! 2. the client picks the artifact for it and sends one line naming its //! version, SHA-256 and size; //! 3. the shell checks that the install directories are private to the -//! remote user, then keeps an installed binary whose SHA-256 it computes -//! itself, or receives exactly `size` bytes, installs them under a -//! temporary name and verifies them before renaming them into place; +//! remote user, then either keeps an installed binary whose SHA-256 it +//! computes itself and answers `LITHE-INSTALL-PRESENT`, or answers +//! `LITHE-INSTALL-NEEDED`, receives exactly `size` bytes under a temporary +//! name, verifies them, renames them into place and answers +//! `LITHE-INSTALL-DONE` with how it verified them; a failed step answers +//! `LITHE-INSTALL-FAILED` with the step instead; //! 4. the shell `exec`s the server, whose preamble starts the protocol on the //! same stream, ready for [`crate::client::RemoteSession::from_streams`]. //! +//! The steps are recorded in the attempt's [`ConnectionLog`]: the probe +//! answer, the deployment and any failure with its stage. +//! //! An installed binary is never trusted to report its own hash. When the host //! has neither `sha256sum` nor `shasum`, every connection uploads the binary //! again instead. The install root, `bin` and the version directory must not @@ -24,11 +30,14 @@ //! `!` (see [`crate::client::transport`]). use crate::client::bootstrap::{parse_probe, ProbeReport, ServerArtifact, INSTALL_HASH_PREFIX}; +use crate::client::connection_log::ConnectionLog; use std::fmt; use std::io::{self, Read, Write}; +use std::time::Instant; const INSTALL_PRESENT: &str = "LITHE-INSTALL-PRESENT"; const INSTALL_NEEDED: &str = "LITHE-INSTALL-NEEDED"; +const INSTALL_DONE: &str = "LITHE-INSTALL-DONE"; const INSTALL_UNSAFE: &str = "LITHE-INSTALL-UNSAFE"; const INSTALL_FAILED: &str = "LITHE-INSTALL-FAILED"; const PROBE_END: &str = "LITHE-PROBE-END"; @@ -48,7 +57,12 @@ const NOISE_LIMIT: usize = 64 * 1024; /// owned by someone else or writable by others, and accepts a missing one; /// - `digest` prints the SHA-256 computed by the host's own tool, or nothing; /// - `reusable` accepts an installed binary only when it is a private regular -/// file whose computed SHA-256 is exactly the expected one. +/// file whose computed SHA-256 is exactly the expected one; +/// - `fail` removes a partial upload and answers the failed step. +/// +/// Without a hash tool, an upload is accepted when its size matches and the +/// binary reports the expected identity (`checked=identity`); it is still +/// never reused, because `reusable` requires a computed hash. const LAUNCH_SCRIPT: &str = concat!( crate::client::bootstrap::host_details_script!(), "echo LITHE-PROBE-BEGIN; uname -s; uname -m; echo \"$HOME\"; echo LITHE-PROBE-END; ", @@ -67,14 +81,15 @@ const LAUNCH_SCRIPT: &str = concat!( "else return 1; fi; echo \"$1\"; }; ", "reusable() { [ -L \"$exe\" ] && return 1; [ -f \"$exe\" ] || return 1; inspect \"$exe\"; ", "[ \"$owner\" = \"$uid\" ] || return 1; shared && return 1; [ \"$(digest \"$exe\")\" = \"$sha\" ]; }; ", - "fail() { [ -z \"$tmp\" ] || rm -f \"$tmp\"; echo LITHE-INSTALL-FAILED >&2; exit \"$1\"; }; ", + "fail() { [ -z \"$tmp\" ] || rm -f \"$tmp\"; echo \"LITHE-INSTALL-FAILED $2\"; exit \"$1\"; }; ", "guarded; if reusable; then echo LITHE-INSTALL-PRESENT; else ", - "umask 077; mkdir -p \"$dir\" || { echo LITHE-INSTALL-FAILED; exit 92; }; guarded; ", + "umask 077; mkdir -p \"$dir\" || fail 92 mkdir; guarded; ", "echo LITHE-INSTALL-NEEDED; tmp=\"$dir/.upload.$$\"; ", - "head -c \"$size\" > \"$tmp\" && chmod 700 \"$tmp\" || fail 92; got=$(digest \"$tmp\"); ", - "if [ -n \"$got\" ]; then [ \"$got\" = \"$sha\" ] || fail 93; ", - "else [ $(wc -c < \"$tmp\") -eq \"$size\" ] && \"$tmp\" --identity 2>/dev/null | grep -q \"$sha\" || fail 93; fi; ", - "mv -f \"$tmp\" \"$exe\" || fail 92; fi; shift; exec \"$exe\" \"$@\"" + "head -c \"$size\" > \"$tmp\" && chmod 700 \"$tmp\" || fail 92 write; got=$(digest \"$tmp\"); ", + "if [ -n \"$got\" ]; then checked=sha256; [ \"$got\" = \"$sha\" ] || fail 93 verify; ", + "else checked=identity; [ $(wc -c < \"$tmp\") -eq \"$size\" ] && \"$tmp\" --identity 2>/dev/null | grep -q \"$sha\" || fail 93 verify; fi; ", + "mv -f \"$tmp\" \"$exe\" || fail 92 rename; echo \"LITHE-INSTALL-DONE $checked\"; fi; ", + "shift; exec \"$exe\" \"$@\"" ); /// Command to run at the end of a chain. `root` overrides the install root, @@ -115,22 +130,100 @@ pub enum UnsafeReason { } impl UnsafeReason { + const ALL: [Self; 4] = [ + Self::SymbolicLink, + Self::NotADirectory, + Self::OwnedByOtherUser, + Self::WritableByOthers, + ]; + + /// The word the script answers with. + fn as_str(self) -> &'static str { + match self { + Self::SymbolicLink => "symlink", + Self::NotADirectory => "type", + Self::OwnedByOtherUser => "owner", + Self::WritableByOthers => "writable", + } + } + fn parse(word: &str) -> Option { - Some(match word { - "symlink" => Self::SymbolicLink, - "type" => Self::NotADirectory, - "owner" => Self::OwnedByOtherUser, - "writable" => Self::WritableByOthers, - _ => return None, - }) + Self::ALL.into_iter().find(|reason| reason.as_str() == word) + } +} + +/// Install step that failed on the host. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum InstallStep { + /// Creating the version directory, for example under a read-only home. + CreateDirectory, + /// Writing the received bytes to the temporary file. + Write, + /// The received bytes did not match the expected SHA-256, or, on a host + /// without a hash tool, the expected size and identity. + Verify, + /// Moving the verified file into place. + Rename, +} + +impl InstallStep { + const ALL: [Self; 4] = [ + Self::CreateDirectory, + Self::Write, + Self::Verify, + Self::Rename, + ]; + + /// The word the script answers with. + fn as_str(self) -> &'static str { + match self { + Self::CreateDirectory => "mkdir", + Self::Write => "write", + Self::Verify => "verify", + Self::Rename => "rename", + } + } + + fn parse(word: &str) -> Option { + Self::ALL.into_iter().find(|step| step.as_str() == word) + } +} + +/// How the server was put in place on the host. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) struct Deployment { + /// Whether the binary was sent over this connection. + pub(crate) uploaded: bool, + /// How the host checked the binary it runs. + pub(crate) verification: Verification, +} + +/// How the host checked the binary. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum Verification { + /// The host computed the SHA-256 with its own tool. A reused binary is + /// always checked this way. + Sha256, + /// The host has no hash tool: the upload's size matched and the binary + /// reported the expected identity. + Identity, +} + +impl Verification { + /// Log token of the check. + pub(crate) fn as_str(self) -> &'static str { + match self { + Self::Sha256 => "sha256", + Self::Identity => "identity", + } } } /// Why [`launch`] could not start the server. #[derive(Debug)] pub enum LaunchError { - /// The stream ended before the shell reported its platform, usually - /// because the connection or authentication failed. + /// The stream ended before the shell answered, usually because the + /// connection or authentication failed. NoShell, /// The caller has no artifact for the reported platform. NoArtifact(Box), @@ -142,9 +235,9 @@ pub enum LaunchError { /// Which check failed. reason: UnsafeReason, }, - /// The host could not create the install directory, for example because - /// the home directory is read-only; SSH's standard error says why. - InstallFailed, + /// An install step failed on the host, for example because the home + /// directory is read-only; SSH's standard error says why. + InstallFailed(InstallStep), /// The shell answered something other than this script's protocol. Protocol(String), /// The connection's stream failed. @@ -173,9 +266,14 @@ impl fmt::Display for LaunchError { "refusing to install the remote server: {path:?} {problem}" ) } - Self::InstallFailed => { - formatter.write_str("the remote server install directory could not be created") - } + Self::InstallFailed(step) => formatter.write_str(match step { + InstallStep::CreateDirectory => { + "the remote server install directory could not be created" + } + InstallStep::Write => "the remote server upload could not be written", + InstallStep::Verify => "the uploaded remote server failed verification", + InstallStep::Rename => "the verified remote server could not be moved into place", + }), Self::Protocol(message) => write!(formatter, "unexpected remote output: {message}"), Self::Io(error) => write!(formatter, "remote stream failed: {error}"), } @@ -184,14 +282,52 @@ impl fmt::Display for LaunchError { impl std::error::Error for LaunchError {} +impl LaunchError { + /// Stable category for logs. It never contains remote output or paths. + pub fn failure_category(&self) -> String { + match self { + Self::NoShell => "no-shell".into(), + Self::NoArtifact(_) => "no-artifact".into(), + Self::UnsafeInstall { reason, .. } => format!("unsafe-{}", reason.as_str()), + Self::InstallFailed(step) => format!("install-{}", step.as_str()), + Self::Protocol(_) => "protocol".into(), + Self::Io(error) => format!("{:?}", error.kind()), + } + } +} + /// Drives the script on a started connection. `output` is read one byte at /// a time so that nothing after the script's lines is consumed; the session /// reads the rest. Blocking reads end when the caller closes the connection. +/// +/// `log` receives the probe answer, the deployment and failures with their +/// stage. Two failures are left to the caller, which knows more: a shell that +/// never answered the probe, whose cause the SSH process tells, and +/// [`LaunchError::NoArtifact`], which the caller's `artifact_for` decided. pub fn launch( output: &mut impl Read, input: &mut impl Write, artifact_for: impl FnOnce(&ProbeReport) -> Option, + log: &ConnectionLog, ) -> Result { + let report = probe(output).inspect_err(|error| log.launch_failed("probe", error))?; + log.shell_started(report.target()); + let artifact = + artifact_for(&report).ok_or_else(|| LaunchError::NoArtifact(Box::new(report.clone())))?; + let (binary, name) = + read_artifact(&artifact).inspect_err(|error| log.launch_failed("artifact", error))?; + let started = Instant::now(); + let deployment = deploy(output, input, &artifact, &binary, &name) + .inspect_err(|error| log.launch_failed("deploy", error))?; + log.deployed(&artifact, &deployment, binary.len(), started.elapsed()); + Ok(Launched { + report, + uploaded: deployment.uploaded, + }) +} + +/// Reads the probe block, skipping output before it such as a login banner. +fn probe(output: &mut impl Read) -> Result { let mut probe_output = Vec::new(); loop { let line = read_line(output, NOISE_LIMIT.saturating_sub(probe_output.len()))? @@ -202,9 +338,12 @@ pub fn launch( break; } } - let report = parse_probe(&probe_output).ok_or(LaunchError::NoShell)?; - let artifact = - artifact_for(&report).ok_or_else(|| LaunchError::NoArtifact(Box::new(report.clone())))?; + parse_probe(&probe_output).ok_or(LaunchError::NoShell) +} + +/// Reads the binary and checks the fields sent to the shell. Returns the +/// bytes and the version directory name. +fn read_artifact(artifact: &ServerArtifact) -> Result<(Vec, String), LaunchError> { let binary = std::fs::read(&artifact.path).map_err(LaunchError::Io)?; let name = format!( "{}-{}", @@ -222,6 +361,18 @@ pub fn launch( ))); } } + Ok((binary, name)) +} + +/// Sends the install request, then the binary when the shell needs it, and +/// reads how the shell put the server in place. +fn deploy( + output: &mut impl Read, + input: &mut impl Write, + artifact: &ServerArtifact, + binary: &[u8], + name: &str, +) -> Result { writeln!( input, "{} {} {} {name}", @@ -231,26 +382,49 @@ pub fn launch( ) .and_then(|()| input.flush()) .map_err(LaunchError::Io)?; - - let answer = read_line(output, NOISE_LIMIT)?.ok_or(LaunchError::NoShell)?; - let answer = String::from_utf8_lossy(&answer).trim_end().to_owned(); - let uploaded = match answer.as_str() { - INSTALL_PRESENT => false, + match answer(output)?.as_str() { + INSTALL_PRESENT => Ok(Deployment { + uploaded: false, + verification: Verification::Sha256, + }), INSTALL_NEEDED => { input - .write_all(&binary) + .write_all(binary) .and_then(|()| input.flush()) .map_err(LaunchError::Io)?; - true - } - INSTALL_FAILED => return Err(LaunchError::InstallFailed), - other => { - return Err( - unsafe_install(other).unwrap_or_else(|| LaunchError::Protocol(other.to_owned())) - ) + let verification = installed(&answer(output)?)?; + Ok(Deployment { + uploaded: true, + verification, + }) } - }; - Ok(Launched { report, uploaded }) + other => Err(refusal(other)), + } +} + +/// Reads one answer line of the script. +fn answer(output: &mut impl Read) -> Result { + let line = read_line(output, NOISE_LIMIT)?.ok_or(LaunchError::NoShell)?; + Ok(String::from_utf8_lossy(&line).trim_end().to_owned()) +} + +/// Reads `LITHE-INSTALL-DONE ` after an upload. +fn installed(answer: &str) -> Result { + match answer + .strip_prefix(INSTALL_DONE) + .and_then(|rest| rest.strip_prefix(' ')) + { + Some("sha256") => Ok(Verification::Sha256), + Some("identity") => Ok(Verification::Identity), + _ => Err(refusal(answer)), + } +} + +/// The error for an answer that is not the expected next step. +fn refusal(answer: &str) -> LaunchError { + unsafe_install(answer) + .or_else(|| install_failed(answer)) + .unwrap_or_else(|| LaunchError::Protocol(answer.to_owned())) } /// Reads `LITHE-INSTALL-UNSAFE `; the path may contain spaces. @@ -263,6 +437,12 @@ fn unsafe_install(answer: &str) -> Option { }) } +/// Reads `LITHE-INSTALL-FAILED `. +fn install_failed(answer: &str) -> Option { + let step = answer.strip_prefix(INSTALL_FAILED)?.strip_prefix(' ')?; + InstallStep::parse(step).map(LaunchError::InstallFailed) +} + /// Reads up to a newline. `None` at end of stream before any byte. fn read_line(output: &mut impl Read, limit: usize) -> Result>, LaunchError> { let mut line = Vec::new(); @@ -316,4 +496,62 @@ mod tests { assert!(unsafe_install("LITHE-INSTALL-UNSAFEsymlink /x").is_none()); assert!(unsafe_install("LITHE-INSTALL-PRESENT").is_none()); } + + #[test] + fn upload_answers_name_the_check_or_the_failed_step() { + assert_eq!( + installed("LITHE-INSTALL-DONE sha256").unwrap(), + Verification::Sha256 + ); + assert_eq!( + installed("LITHE-INSTALL-DONE identity").unwrap(), + Verification::Identity + ); + for (answer, step) in [ + ("LITHE-INSTALL-FAILED mkdir", InstallStep::CreateDirectory), + ("LITHE-INSTALL-FAILED write", InstallStep::Write), + ("LITHE-INSTALL-FAILED verify", InstallStep::Verify), + ("LITHE-INSTALL-FAILED rename", InstallStep::Rename), + ] { + let error = installed(answer).unwrap_err(); + assert!( + matches!(error, LaunchError::InstallFailed(found) if found == step), + "{answer}" + ); + assert_eq!( + error.failure_category(), + format!("install-{}", step.as_str()) + ); + } + for answer in [ + "LITHE-INSTALL-DONE", + "LITHE-INSTALL-DONE md5", + "LITHE-INSTALL-FAILED", + "LITHE-INSTALL-FAILED other", + ] { + assert!( + matches!(installed(answer), Err(LaunchError::Protocol(_))), + "{answer}" + ); + } + } + + // Categories reach the log, so none carries remote output or a path. + #[test] + fn failure_categories_carry_no_remote_text() { + let unsafe_install = LaunchError::UnsafeInstall { + path: "/home/dev/.lithe-server".into(), + reason: UnsafeReason::OwnedByOtherUser, + }; + assert_eq!(unsafe_install.failure_category(), "unsafe-owner"); + assert_eq!( + LaunchError::Protocol("banner from dev@box".into()).failure_category(), + "protocol" + ); + assert_eq!( + LaunchError::Io(io::Error::new(io::ErrorKind::BrokenPipe, "/home/dev")) + .failure_category(), + "BrokenPipe" + ); + } } diff --git a/rust/crates/remote/src/client/mod.rs b/rust/crates/remote/src/client/mod.rs index 0c39a043..bc0b6700 100644 --- a/rust/crates/remote/src/client/mod.rs +++ b/rust/crates/remote/src/client/mod.rs @@ -11,6 +11,8 @@ //! routes each resource's events to its subscriber. //! - [`api`] offers typed operations and resource handles on a session. //! - [`forward`] forwards local ports through tunnels. +//! - [`connection_log`] records one connection's lifecycle in the v2 log, +//! identified by a random id instead of the host or user name. //! //! The transport layer deliberately knows nothing about files or processes. //! Supporting a new kind of remote means adding a hop, not new capabilities. @@ -21,6 +23,7 @@ pub mod api; pub mod bootstrap; #[cfg(all(test, unix))] mod command; +pub mod connection_log; pub mod forward; pub mod launch; pub mod session; @@ -28,6 +31,7 @@ pub mod transport; pub use api::{SpawnSpec, TerminalSpec, WriteOptions}; pub use bootstrap::{ServerArtifact, ServerTarget}; +pub use connection_log::{ConnectionKind, ConnectionLog}; pub use forward::PortForward; pub use session::{ClientError, ConnectOptions, Event, RemoteSession, ResumeMode}; pub use transport::{ContainerEngine, ContainerHop, Hop, SshHop, TransportChain, TransportError}; diff --git a/rust/crates/remote/src/client/session.rs b/rust/crates/remote/src/client/session.rs index a6a23113..2a8c5b25 100644 --- a/rust/crates/remote/src/client/session.rs +++ b/rust/crates/remote/src/client/session.rs @@ -13,7 +13,11 @@ //! A writer thread owns the outgoing stream. Requests queue their frames for //! it, so a peer that stops reading blocks only that thread, and every request //! still ends at its own deadline. +//! +//! The session records its lifecycle in a [`ConnectionLog`]: the handshake +//! outcome, a stream that ends without a shutdown request, and the release. +use crate::client::connection_log::{ConnectionKind, ConnectionLog}; use crate::client::transport::{TransportChain, TransportError}; use crate::protocol::frame::{read_frame, skip_preamble, write_frame}; use crate::protocol::methods::{ @@ -183,6 +187,10 @@ pub struct ConnectOptions { pub session_token: Option, /// When event delivery starts. pub resume: ResumeMode, + /// Log of an attempt the caller began before the session, for example + /// to record the launch over its own SSH connection. `None` begins a new + /// one for this session. + pub log: Option, } /// When event delivery starts after the handshake. @@ -208,10 +216,20 @@ impl Default for ConnectOptions { idle_timeout: None, session_token: None, resume: ResumeMode::Immediately { after_seq: None }, + log: None, } } } +impl ConnectOptions { + /// The caller's log, or a new one for a connection of `kind`. + fn log_or_begin(&self, kind: ConnectionKind) -> ConnectionLog { + self.log + .clone() + .unwrap_or_else(|| ConnectionLog::begin(kind)) + } +} + /// Frames waiting for the writer thread. #[derive(Default)] struct OutgoingState { @@ -327,6 +345,7 @@ pub struct RemoteSession { child: Mutex>, stderr_tail: Arc>>, hello: Option, + log: ConnectionLog, } /// An owned request waiter. Dropping it withdraws unsent work and ignores late @@ -389,26 +408,24 @@ impl RemoteSession { server_command: &[String], options: &ConnectOptions, ) -> Result<(Self, Receiver), ClientError> { - let command = chain - .command(server_command) - .map_err(ClientError::Transport)?; - let (program, arguments) = command - .split_first() - .ok_or_else(|| ClientError::Protocol("empty server command".into()))?; - let mut child = Command::new(program) - .args(arguments) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .map_err(ClientError::Spawn)?; + let log = options.log_or_begin(ConnectionKind::Command); + let mut child = spawn(chain, server_command).inspect_err(|error| { + log.connect_failed("connect", &error.failure_category(), "remote") + })?; let stdin = child.stdin.take().expect("stdin is piped"); let stdout = child.stdout.take().expect("stdout is piped"); let stderr_tail = Arc::new(Mutex::new(VecDeque::new())); if let Some(stderr) = child.stderr.take() { keep_tail(stderr, Arc::clone(&stderr_tail)); } - Self::establish(stdout, Box::new(stdin), Some(child), stderr_tail, options) + Self::establish( + stdout, + Box::new(stdin), + Some(child), + stderr_tail, + options, + log, + ) } /// Uses existing streams, for example an in-process server in tests. @@ -417,15 +434,34 @@ impl RemoteSession { writer: impl Write + Send + 'static, options: &ConnectOptions, ) -> Result<(Self, Receiver), ClientError> { - Self::establish(reader, Box::new(writer), None, Arc::default(), options) + let log = options.log_or_begin(ConnectionKind::Streams); + Self::establish(reader, Box::new(writer), None, Arc::default(), options, log) } + /// Completes the handshake and records its outcome in `log`. fn establish( reader: impl Read + Send + 'static, writer: Box, child: Option, stderr_tail: Arc>>, options: &ConnectOptions, + log: ConnectionLog, + ) -> Result<(Self, Receiver), ClientError> { + let result = Self::handshake(reader, writer, child, stderr_tail, options, log.clone()); + match &result { + Ok((session, _)) => log.connected(session.hello()), + Err(error) => log.connect_failed("handshake", &error.failure_category(), "remote"), + } + result + } + + fn handshake( + reader: impl Read + Send + 'static, + writer: Box, + child: Option, + stderr_tail: Arc>>, + options: &ConnectOptions, + log: ConnectionLog, ) -> Result<(Self, Receiver), ClientError> { let deadline = Instant::now() + options.handshake_timeout; let pending = Arc::new(Mutex::new(Pending::default())); @@ -451,6 +487,7 @@ impl RemoteSession { outgoing: Arc::clone(&outgoing), next_request: Arc::clone(&next_request), last_seq: Arc::clone(&last_seq), + log: log.clone(), }; thread::Builder::new() .name("remote-reader".into()) @@ -467,6 +504,7 @@ impl RemoteSession { child: Mutex::new(child), stderr_tail, hello: None, + log, }; match ready.recv_timeout(deadline.saturating_duration_since(Instant::now())) { @@ -535,6 +573,12 @@ impl RemoteSession { self.hello.as_ref().expect("set by establish") } + /// Lifecycle log of this connection; port forwards and the caller record + /// into it under the same `connection` id. + pub fn connection_log(&self) -> &ConnectionLog { + &self.log + } + /// Returns a resource id that is unused in this session, also across /// reconnections. pub fn allocate_id(&self) -> u64 { @@ -594,6 +638,11 @@ impl RemoteSession { timeout: Duration, ) -> Result { let deadline = Instant::now() + timeout; + if method == methods::SERVER_SHUTDOWN { + // Marked before sending, so the stream ending afterwards is not an + // interruption. + self.log.shutdown_requested(); + } let id = self.next_request.fetch_add(1, Ordering::Relaxed) + 1; let (reply_sender, reply) = mpsc::sync_channel(1); { @@ -669,6 +718,13 @@ impl RemoteSession { impl Drop for RemoteSession { fn drop(&mut self) { + // Released before the stream closes, so the end of the stream that + // closing causes is not recorded as an interruption. + let persistent = self + .hello + .as_ref() + .is_some_and(|hello| hello.session.persistent); + self.log.released(persistent); // The writer thread then drops standard input, which is the server's // disconnect signal. A writer blocked on a peer that stopped reading // is released when the transport is killed below. @@ -698,6 +754,33 @@ struct ReaderContext { outgoing: Arc, next_request: Arc, last_seq: Arc, + log: ConnectionLog, +} + +/// Starts the transport command of `chain`. +fn spawn(chain: &TransportChain, server_command: &[String]) -> Result { + let command = chain + .command(server_command) + .map_err(ClientError::Transport)?; + let (program, arguments) = command + .split_first() + .ok_or_else(|| ClientError::Protocol("empty server command".into()))?; + Command::new(program) + .args(arguments) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(ClientError::Spawn) +} + +/// Log token for why the server stream ended; never peer bytes. +fn stream_end_cause(error: &FrameError) -> String { + match error { + FrameError::UnexpectedEof => "eof".into(), + FrameError::Io(error) => format!("{:?}", error.kind()), + FrameError::TooLarge(_) | FrameError::PreambleNotFound { .. } => "protocol".into(), + } } fn read_loop( @@ -712,6 +795,7 @@ fn read_loop( outgoing, next_request, last_seq, + log, } = context; let mut reader = BufReader::new(reader); if let Err(error) = skip_preamble(&mut reader, PREAMBLE_NOISE_LIMIT) { @@ -723,7 +807,12 @@ fn read_loop( // log-exempt: User cancellation: the connecting caller already ended the handshake and no longer waits for the ready notification. let _ = ready.send(Ok(())); let mut acknowledged = 0; - while let Ok(Some(frame)) = read_frame(&mut reader) { + let cause = loop { + let frame = match read_frame(&mut reader) { + Ok(Some(frame)) => frame, + Ok(None) => break "eof".to_owned(), + Err(error) => break stream_end_cause(&error), + }; match serde_json::from_slice::(&frame) { Ok(Message::Response { id, result, error }) => { let waiter = lock(&pending).waiting.remove(&id); @@ -738,7 +827,7 @@ fn read_loop( } Ok(Message::Event { event, params, seq }) => { if !route(&routes, &events, Event { event, params, seq }) { - break; + break "overflow".to_owned(); } if let Some(seq) = seq { last_seq.store(seq, Ordering::Release); @@ -749,9 +838,12 @@ fn read_loop( } } } - Ok(Message::Request { .. }) | Err(_) => break, + Ok(Message::Request { .. }) | Err(_) => break "protocol".to_owned(), } - } + }; + // Recorded before waiting requests fail, so an owner that drops the + // session on that failure finds the session already marked lost. + log.stream_ended(&cause); close(&pending); // Ending every subscription tells consumers the stream is gone. lock(&routes).clear(); diff --git a/rust/crates/remote/src/failure_log.rs b/rust/crates/remote/src/failure_log.rs index ea3d85d0..961a2949 100644 --- a/rust/crates/remote/src/failure_log.rs +++ b/rust/crates/remote/src/failure_log.rs @@ -1,16 +1,37 @@ -//! Injected scalar failure facts; the owning Core supplies the only log writer. +//! Injected scalar log facts; the owning Core supplies the only log writer. +//! +//! Two families cross this hook: failure facts (`stage` plus a fixed error +//! summary and stable category) and connection lifecycle facts from +//! [`crate::client::connection_log`]. Both carry only controlled vocabulary, +//! counts and durations, never hosts, user names, paths, prompts, answers or +//! session tokens. use serde_json::{json, Value}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::OnceLock; -/// Complete catalog surface emitted by this adapter. +/// Failure facts emitted by this adapter. Every one accepts exactly `stage` +/// and `error`; the forward failures also accept an optional `connection`. pub const EVENTS: &[&str] = &[ "remote.client.operation_failed", "remote.forward.accept_failed", "remote.forward.connection_failed", ]; +/// Connection lifecycle facts emitted through the same hook (S34). Each has +/// its own fields; see `rust/logging/events/remote.json`. +pub const LIFECYCLE_EVENTS: &[&str] = &[ + "remote.connection.connect.started", + "remote.connection.connect.finished", + "remote.connection.connect.failed", + "remote.connection.shell_started", + "remote.server.deploy_finished", + "remote.connection.interrupted", + "remote.connection.cleaned", + "remote.forward.started", + "remote.forward.removed", +]; + /// Borrowed scalar fields; callers supply only fixed summaries and stable categories. pub type Fields<'a> = &'a [(&'static str, Value)]; /// Process-owned callback; no file writer or dependency on Core lives here. @@ -48,26 +69,50 @@ pub fn uninstalled_count() -> u64 { } /// No error display text is accepted: only caller-controlled categories cross the hook. pub(crate) fn failed(event: &str, stage: &'static str, code: &str, domain: &'static str) { - HOOK.failed(event, stage, code, domain); + HOOK.failed(event, None, stage, code, domain); +} +/// Like [`failed`], for failure events that also accept the random +/// `connection` log id of the session they belong to. +pub(crate) fn failed_for( + event: &str, + connection: &str, + stage: &'static str, + code: &str, + domain: &'static str, +) { + HOOK.failed(event, Some(connection), stage, code, domain); +} +/// Emits one lifecycle fact. Callers build every field from controlled +/// vocabulary, counts and durations. +pub(crate) fn record(event: &str, fields: Fields<'_>) { + HOOK.emit(event, fields); } impl Hook { - fn failed(&self, event: &str, stage: &'static str, code: &str, domain: &'static str) { - self.emit( - event, - &[ - ("stage", json!(stage)), - ("error", json!("Helper operation failed")), - ("error_code", json!(code)), - ("error_domain", json!(domain)), - ], - ); + fn failed( + &self, + event: &str, + connection: Option<&str>, + stage: &'static str, + code: &str, + domain: &'static str, + ) { + let mut fields = vec![ + ("stage", json!(stage)), + ("error", json!("Helper operation failed")), + ("error_code", json!(code)), + ("error_domain", json!(domain)), + ]; + if let Some(connection) = connection { + fields.push(("connection", json!(connection))); + } + self.emit(event, &fields); } fn teardown(&self, event: &str, stage: &'static str, result: std::io::Result) { match result { Ok(_) => {} // log-exempt: Expected absence: the peer already disconnected, so no connection is left to close or write to. Err(error) if disconnected_io(error.kind()) => {} - Err(error) => self.failed(event, stage, &format!("{:?}", error.kind()), "io"), + Err(error) => self.failed(event, None, stage, &format!("{:?}", error.kind()), "io"), } } } diff --git a/rust/crates/remote/tests/connection_log.rs b/rust/crates/remote/tests/connection_log.rs new file mode 100644 index 00000000..680ee722 --- /dev/null +++ b/rust/crates/remote/tests/connection_log.rs @@ -0,0 +1,386 @@ +//! Connection lifecycle facts (design S34) recorded while a real server is +//! installed, connected, forwarded through and released over the local +//! transport. +//! +//! Every fact must pass the log catalog Core validates with, the facts of one +//! attempt share its `connection` id, and no fact names a path, a host +//! address, a session token or diagnostics the remote printed. + +mod support; + +use lithe_diagnostics::core_events; +use lithe_remote::client::launch::{launch, launch_command, InstallStep, LaunchError, Launched}; +use lithe_remote::client::session::ConnectOptions; +use lithe_remote::client::{ + ConnectionKind, ConnectionLog, PortForward, RemoteSession, ServerArtifact, TransportChain, +}; +use lithe_remote::protocol::methods::TunnelTarget; +use serde_json::Value; +use std::collections::BTreeMap; +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; +use std::sync::{Arc, Condvar, Mutex}; +use std::thread; +use support::{options, Daemon, TempDir, SERVER, STEP_TIMEOUT}; + +const STARTED: &str = "remote.connection.connect.started"; +const FINISHED: &str = "remote.connection.connect.finished"; +const FAILED: &str = "remote.connection.connect.failed"; +const SHELL: &str = "remote.connection.shell_started"; +const DEPLOYED: &str = "remote.server.deploy_finished"; +const INTERRUPTED: &str = "remote.connection.interrupted"; +const CLEANED: &str = "remote.connection.cleaned"; +const FORWARD_STARTED: &str = "remote.forward.started"; +const FORWARD_REMOVED: &str = "remote.forward.removed"; + +type Fact = (String, BTreeMap); + +/// Every fact this test process recorded. Tests run in parallel, so each +/// reads only the facts of its own attempts, by `connection` id. +static FACTS: Mutex> = Mutex::new(Vec::new()); +static RECORDED: Condvar = Condvar::new(); + +fn sink(event: &str, fields: &[(&'static str, Value)]) { + let fields = fields + .iter() + .map(|(key, value)| ((*key).to_owned(), value.clone())) + .collect(); + FACTS + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .push((event.to_owned(), fields)); + RECORDED.notify_all(); +} + +/// Installs the capturing sink; the first installation in the process wins, +/// so every test may call this before its first connection. +fn install() { + lithe_remote::failure_log::install_failure_sink(sink); +} + +fn belongs_to(fact: &Fact, log: &ConnectionLog) -> bool { + fact.1.get("connection").and_then(Value::as_str) == Some(log.id()) +} + +/// Facts of one attempt in recording order, each checked against the catalog. +fn facts_of(log: &ConnectionLog) -> Vec { + let facts: Vec = FACTS + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .iter() + .filter(|fact| belongs_to(fact, log)) + .cloned() + .collect(); + for (event, fields) in &facts { + if let Err(error) = core_events::prepare(event, fields.clone(), None) { + panic!("{event} {fields:?} does not match the catalog: {error:?}"); + } + } + facts +} + +fn names(facts: &[Fact]) -> Vec<&str> { + facts.iter().map(|(event, _)| event.as_str()).collect() +} + +fn only<'a>(facts: &'a [Fact], event: &str) -> &'a BTreeMap { + let mut matching = facts.iter().filter(|(name, _)| name == event); + let fact = matching.next().unwrap_or_else(|| panic!("no {event}")); + assert!(matching.next().is_none(), "two {event} facts"); + &fact.1 +} + +/// Waits until `log` recorded `event`. The fact is recorded on the session's +/// reader thread, so the test waits on the sink instead of sleeping. +fn wait_for(log: &ConnectionLog, event: &str) -> bool { + let facts = FACTS + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let (_facts, waited) = RECORDED + .wait_timeout_while(facts, STEP_TIMEOUT, |facts| { + !facts + .iter() + .any(|fact| fact.0 == event && belongs_to(fact, log)) + }) + .unwrap_or_else(|poisoned| poisoned.into_inner()); + !waited.timed_out() +} + +/// Asserts that no value names a path or any of `secrets`. The only strings +/// in these facts are controlled tokens, versions and the random id. +fn assert_nothing_identifying(facts: &[Fact], secrets: &[&str]) { + let mut secrets: Vec = secrets.iter().map(|secret| (*secret).to_owned()).collect(); + secrets.extend(std::env::var("HOME").ok()); + for (event, fields) in facts { + for (key, value) in fields { + let Some(text) = value.as_str() else { continue }; + assert!(!text.contains('/'), "{event}.{key} holds a path: {text}"); + for secret in secrets.iter().filter(|secret| !secret.is_empty()) { + assert!( + !text.contains(secret.as_str()), + "{event}.{key} leaks {secret}" + ); + } + } + } + if let Ok(user) = std::env::var("USER") { + let values = facts.iter().flat_map(|(_, fields)| fields.values()); + assert!( + values.filter_map(Value::as_str).all(|text| text != user), + "a fact names the user" + ); + } +} + +/// Runs the launch script in a local shell against `root`, as one SSH +/// connection would. `sha256` replaces the artifact's real digest. +fn run_launch( + root: &str, + log: &ConnectionLog, + sha256: Option<&str>, +) -> ( + Result, + Child, + ChildStdout, + ChildStdin, +) { + let mut child = Command::new("sh") + .args(&launch_command(Some(root), &["--stdio"])[1..]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + let mut input = child.stdin.take().unwrap(); + let mut output = child.stdout.take().unwrap(); + let result = launch( + &mut output, + &mut input, + |report| { + let target = report.target()?; + let mut artifact = + ServerArtifact::from_file(target, SERVER.into(), env!("CARGO_PKG_VERSION")) + .unwrap(); + if let Some(sha256) = sha256 { + artifact.sha256 = sha256.into(); + } + Some(artifact) + }, + log, + ); + (result, child, output, input) +} + +#[test] +fn an_upload_and_a_reuse_record_every_step_of_the_connection() { + install(); + let root = TempDir::new("log-install"); + for action in ["uploaded", "reused"] { + let log = ConnectionLog::begin(ConnectionKind::Ssh); + let (launched, mut child, output, input) = run_launch(root.str(), &log, None); + assert_eq!(launched.unwrap().uploaded, action == "uploaded"); + let options = ConnectOptions { + log: Some(log.clone()), + ..options() + }; + let (session, _events) = RemoteSession::from_streams(output, input, &options).unwrap(); + session.stat("/").unwrap(); + drop(session); + child.wait().unwrap(); + + let facts = facts_of(&log); + assert_eq!(names(&facts), [STARTED, SHELL, DEPLOYED, FINISHED, CLEANED]); + assert_eq!(only(&facts, STARTED)["transport"], "ssh"); + let deployed = only(&facts, DEPLOYED); + assert_eq!(deployed["action"], action); + assert_eq!(deployed["target"], only(&facts, SHELL)["target"]); + assert_eq!(deployed["server_version"], env!("CARGO_PKG_VERSION")); + assert_eq!(deployed.contains_key("bytes"), action == "uploaded"); + let finished = only(&facts, FINISHED); + assert_eq!(finished["outcome"], "connected"); + assert_eq!(finished["persistent"], false); + assert_eq!(finished["resumed"], false); + assert_eq!(only(&facts, CLEANED)["ended"], "closed"); + assert_nothing_identifying(&facts, &[root.str()]); + } +} + +#[test] +fn a_binary_that_fails_verification_records_the_failed_step() { + install(); + let root = TempDir::new("log-verify"); + let log = ConnectionLog::begin(ConnectionKind::Ssh); + let (launched, mut child, output, input) = run_launch(root.str(), &log, Some(&"0".repeat(64))); + assert!( + matches!( + launched, + Err(LaunchError::InstallFailed(InstallStep::Verify)) + ), + "{launched:?}" + ); + drop((output, input)); + child.wait().unwrap(); + + let facts = facts_of(&log); + assert_eq!(names(&facts), [STARTED, SHELL, FAILED]); + let failed = only(&facts, FAILED); + assert_eq!(failed["stage"], "deploy"); + assert_eq!(failed["error_code"], "install-verify"); + assert_eq!(failed["error_domain"], "remote"); + assert_nothing_identifying(&facts, &[root.str()]); +} + +#[test] +fn a_persistent_session_records_detaching_resuming_and_shutdown() { + install(); + let daemon = Daemon::new("log-daemon"); + let (session, _events) = daemon.connect(None); + let first = session.connection_log().clone(); + drop(session); + let token = serde_json::to_value(daemon.token().unwrap()).unwrap(); + let token = token.as_str().unwrap().to_owned(); + + let (session, _events) = daemon.connect(None); + let second = session.connection_log().clone(); + session.shutdown(STEP_TIMEOUT); + assert!(daemon.wait_until_stopped(), "{}", daemon.log()); + + for (log, resumed, ended) in [(&first, false, "detached"), (&second, true, "shutdown")] { + let facts = facts_of(log); + assert_eq!(names(&facts), [STARTED, FINISHED, CLEANED]); + assert_eq!(only(&facts, STARTED)["transport"], "command"); + let finished = only(&facts, FINISHED); + assert_eq!(finished["persistent"], true); + assert_eq!(finished["resumed"], resumed); + assert_eq!(only(&facts, CLEANED)["ended"], ended); + assert_nothing_identifying(&facts, &[&token, &daemon.key, daemon.state.str()]); + } + assert_ne!(first.id(), second.id()); +} + +#[test] +fn a_lost_server_is_recorded_as_an_interruption() { + install(); + let daemon = Daemon::new("log-lost"); + let (session, _events) = daemon.connect(None); + let log = session.connection_log().clone(); + let pid = daemon.pid().expect("the daemon runs"); + // SAFETY: sending a signal has no memory-safety preconditions. + unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) }; + assert!(wait_for(&log, INTERRUPTED), "no interruption recorded"); + drop(session); + + let facts = facts_of(&log); + assert_eq!(names(&facts), [STARTED, FINISHED, INTERRUPTED, CLEANED]); + assert_eq!(only(&facts, INTERRUPTED)["cause"], "eof"); + assert_eq!(only(&facts, CLEANED)["ended"], "lost"); + assert_nothing_identifying(&facts, &[&daemon.key, daemon.state.str()]); +} + +/// A one-connection echo server that uppercases what it reads. +fn spawn_tcp_echo() -> (u16, thread::JoinHandle<()>) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + stream.set_read_timeout(Some(STEP_TIMEOUT)).unwrap(); + let mut buffer = [0_u8; 64]; + loop { + match stream.read(&mut buffer) { + Ok(0) | Err(_) => return, + Ok(read) => { + if stream + .write_all(&buffer[..read].to_ascii_uppercase()) + .is_err() + { + return; + } + } + } + } + }); + (port, server) +} + +#[test] +fn a_port_forward_records_its_ports_and_connections_but_not_the_host() { + install(); + let (remote_port, echo) = spawn_tcp_echo(); + let (session, _events) = support::connect(); + let session = Arc::new(session); + let forward = PortForward::start( + Arc::clone(&session), + "127.0.0.1:0".parse().unwrap(), + TunnelTarget::Tcp { + host: "127.0.0.1".into(), + port: remote_port, + }, + ) + .unwrap(); + let local_port = forward.local_address().port(); + let mut client = TcpStream::connect(forward.local_address()).unwrap(); + client.set_read_timeout(Some(STEP_TIMEOUT)).unwrap(); + client.write_all(b"ping").unwrap(); + let mut reply = [0_u8; 4]; + client.read_exact(&mut reply).unwrap(); + assert_eq!(&reply, b"PING"); + drop(client); + drop(forward); + echo.join().unwrap(); + + let facts = facts_of(session.connection_log()); + let forwarding: Vec = facts + .iter() + .filter(|(event, _)| event.starts_with("remote.forward.")) + .cloned() + .collect(); + assert_eq!(names(&forwarding), [FORWARD_STARTED, FORWARD_REMOVED]); + let started = only(&forwarding, FORWARD_STARTED); + assert_eq!(started["local_port"], local_port); + assert_eq!(started["bind_scope"], "loopback"); + assert_eq!(started["target_kind"], "tcp"); + assert_eq!(started["remote_port"], remote_port); + assert_eq!(started["target_scope"], "loopback"); + let removed = only(&forwarding, FORWARD_REMOVED); + assert_eq!(removed["local_port"], local_port); + assert_eq!(removed["connections"], 1); + assert_nothing_identifying(&facts, &["127.0.0.1"]); +} + +#[test] +fn a_failed_handshake_records_its_category_without_remote_output() { + install(); + let leaked = "secret-diagnostic-from-the-host"; + let log = ConnectionLog::begin(ConnectionKind::Command); + let options = ConnectOptions { + log: Some(log.clone()), + ..options() + }; + let command = [ + "sh".to_owned(), + "-c".into(), + format!("echo {leaked} >&2; exit 3"), + ]; + let result = RemoteSession::connect(&TransportChain::local(), &command, &options); + assert!(result.is_err(), "connected to a shell that exited"); + + let facts = facts_of(&log); + assert_eq!(names(&facts), [STARTED, FAILED]); + let failed = only(&facts, FAILED); + assert_eq!(failed["stage"], "handshake"); + assert_eq!(failed["error_domain"], "remote"); + assert_nothing_identifying(&facts, &[leaked]); +} + +#[test] +fn cancelling_before_the_session_opens_is_not_a_failure() { + install(); + let log = ConnectionLog::begin(ConnectionKind::Ssh); + log.connect_cancelled(); + // A later failure of the abandoned attempt is not a second outcome. + log.connect_failed("connect", "failed", "remote"); + + let facts = facts_of(&log); + assert_eq!(names(&facts), [STARTED, FINISHED]); + assert_eq!(only(&facts, FINISHED)["outcome"], "cancelled"); +} diff --git a/rust/crates/remote/tests/server.rs b/rust/crates/remote/tests/server.rs index 3d4aebb2..5bc15812 100644 --- a/rust/crates/remote/tests/server.rs +++ b/rust/crates/remote/tests/server.rs @@ -5,7 +5,9 @@ mod support; use lithe_remote::client::launch::{launch, launch_command, LaunchError, Launched, UnsafeReason}; use lithe_remote::client::session::ClientError; -use lithe_remote::client::{RemoteSession, ServerArtifact, TransportChain, WriteOptions}; +use lithe_remote::client::{ + ConnectionKind, ConnectionLog, RemoteSession, ServerArtifact, TransportChain, WriteOptions, +}; use lithe_remote::protocol::frame::{read_frame, skip_preamble, write_frame}; use lithe_remote::protocol::methods::{ self, encode_bytes, FileKind, FileVersion, OperatingSystem, OrphanProtection, WatchBackend, @@ -824,10 +826,18 @@ fn run_launch( .unwrap(); let mut input = child.stdin.take().unwrap(); let mut output = child.stdout.take().unwrap(); - let result = launch(&mut output, &mut input, |report| { - let target = report.target()?; - Some(ServerArtifact::from_file(target, SERVER.into(), env!("CARGO_PKG_VERSION")).unwrap()) - }); + let result = launch( + &mut output, + &mut input, + |report| { + let target = report.target()?; + Some( + ServerArtifact::from_file(target, SERVER.into(), env!("CARGO_PKG_VERSION")) + .unwrap(), + ) + }, + &ConnectionLog::begin(ConnectionKind::Ssh), + ); (result, child, output, input) } diff --git a/rust/crates/workspace/src/probe/tests.rs b/rust/crates/workspace/src/probe/tests.rs index 2e377f9a..1e2b920e 100644 --- a/rust/crates/workspace/src/probe/tests.rs +++ b/rust/crates/workspace/src/probe/tests.rs @@ -344,6 +344,30 @@ fn connecting_without_a_matching_server_reports_the_platform() { assert_eq!(value["host"]["system"], local_uname("-s")); } +// The connection log keeps one category per failed status, so a log line +// tells authentication, host key and network failures apart. +#[test] +fn every_failed_status_has_its_own_log_category() { + use crate::sessions::failure_of; + let failed = [ + ProbeStatus::UnsupportedPlatform, + ProbeStatus::AuthenticationFailed, + ProbeStatus::HostKeyRejected, + ProbeStatus::Unreachable, + ProbeStatus::Failed, + ]; + assert_eq!(failure_of(ProbeStatus::Connected), None); + let codes: std::collections::BTreeSet<_> = failed + .iter() + .map(|status| failure_of(*status).unwrap().1) + .collect(); + assert_eq!(codes.len(), failed.len()); + assert_eq!( + failure_of(ProbeStatus::AuthenticationFailed), + Some(("authentication", "authentication-failed")) + ); +} + #[cfg(unix)] #[test] fn unknown_server_targets_are_rejected() { diff --git a/rust/crates/workspace/src/sessions.rs b/rust/crates/workspace/src/sessions.rs index 493a6751..bf01b321 100644 --- a/rust/crates/workspace/src/sessions.rs +++ b/rust/crates/workspace/src/sessions.rs @@ -12,7 +12,9 @@ use lithe_git_host::ProcessTree; use lithe_protocol::{CoreError, ErrorCode}; use lithe_remote::client::launch::{launch, launch_command, LaunchError, Launched}; use lithe_remote::client::session::{ClientError, ConnectOptions}; -use lithe_remote::client::{Hop, RemoteSession, ServerArtifact, ServerTarget, TransportChain}; +use lithe_remote::client::{ + ConnectionKind, ConnectionLog, Hop, RemoteSession, ServerArtifact, ServerTarget, TransportChain, +}; use lithe_remote::protocol::methods; use lithe_request_context::events as execution_events; use serde::{Deserialize, Serialize}; @@ -226,9 +228,49 @@ pub fn connect(request: ConnectRequest) -> Result { } /// `ssh_program` replaces the `ssh` found on `PATH`; tests use a stand-in. +/// +/// The attempt is recorded in a [`ConnectionLog`]. The launch and the +/// handshake record the failures they see themselves; this records what only +/// the SSH process shows (authentication, host key, network), cancellation +/// and local errors, as stable categories without diagnostics or host names. pub(crate) fn connect_with( request: ConnectRequest, ssh_program: Option<&str>, +) -> Result { + let log = ConnectionLog::begin(ConnectionKind::Ssh); + let result = connect_logged(request, ssh_program, &log); + match &result { + Ok(result) => { + if let Some((stage, code)) = failure_of(result.status) { + log.connect_failed(stage, code, "remote"); + } + } + Err(error) if matches!(error.code, ErrorCode::Cancelled) => log.connect_cancelled(), + Err(error) => { + let code = serde_json::to_value(&error.code).unwrap_or_default(); + log.connect_failed("connect", code.as_str().unwrap_or("unknown"), "core"); + } + } + result +} + +/// Log stage and category of an attempt that ended with `status`, or `None` +/// when it connected. Each status has its own category. +pub(crate) fn failure_of(status: ProbeStatus) -> Option<(&'static str, &'static str)> { + match status { + ProbeStatus::Connected => None, + ProbeStatus::UnsupportedPlatform => Some(("probe", "unsupported-platform")), + ProbeStatus::AuthenticationFailed => Some(("authentication", "authentication-failed")), + ProbeStatus::HostKeyRejected => Some(("authentication", "host-key-rejected")), + ProbeStatus::Unreachable => Some(("network", "unreachable")), + ProbeStatus::Failed => Some(("connect", "failed")), + } +} + +fn connect_logged( + request: ConnectRequest, + ssh_program: Option<&str>, + log: &ConnectionLog, ) -> Result { // Only the build for the host's platform is read and hashed, once the // probe reports it; here the target names are just validated. @@ -310,8 +352,9 @@ pub(crate) fn connect_with( // this thread keeps relaying prompts and observing cancellation. Killing // the tree ends the helper's reads. let (finished, launched) = mpsc::channel(); + let launch_log = log.clone(); std::thread::spawn(move || { - let result = launch(&mut output, &mut input, |report| { + let artifact_for = |report: &lithe_remote::client::bootstrap::ProbeReport| { let target = report.target()?; let (_, path) = servers.iter().find(|(known, _)| *known == target)?; match ServerArtifact::from_file(target, path.clone().into(), server_version.clone()) { @@ -323,7 +366,8 @@ pub(crate) fn connect_with( None } } - }); + }; + let result = launch(&mut output, &mut input, artifact_for, &launch_log); // log-exempt: User cancellation: abandon drops the launch receiver before killing the SSH tree. let _ = finished.send((result, output, input)); }); @@ -478,6 +522,7 @@ pub(crate) fn connect_with( }; let options = ConnectOptions { handshake_timeout: HANDSHAKE_TIMEOUT, + log: Some(log.clone()), ..ConnectOptions::default() }; let (session, events) = match RemoteSession::from_streams(output, input, &options) { diff --git a/rust/logging/events/remote.json b/rust/logging/events/remote.json index 4f5ca0b8..ec426efb 100644 --- a/rust/logging/events/remote.json +++ b/rust/logging/events/remote.json @@ -98,6 +98,11 @@ "level": "warn", "message": "Port forward accept failed", "fields": { + "connection": { + "type": "id", + "required": false, + "description": "Random per-connection log identifier of the forward's session; never a host, user name or session token" + }, "stage": { "type": "token", "required": true, @@ -118,6 +123,11 @@ "level": "warn", "message": "Forwarded connection failed", "fields": { + "connection": { + "type": "id", + "required": false, + "description": "Random per-connection log identifier of the forward's session; never a host, user name or session token" + }, "stage": { "type": "token", "required": true, @@ -151,6 +161,232 @@ }, "rate": 60, "owner": "lithe-core" + }, + { + "id": "remote.connection.connect", + "channel": "remote", + "level": "info", + "message": "Remote connection", + "fields": { + "connection": { + "type": "id", + "required": true, + "description": "Random per-connection log identifier that correlates this connection's lines; never a host, user name or session token" + }, + "transport": { + "type": "token", + "required": true, + "description": "How the client reached the server: ssh, command (any spawned transport chain) or streams (caller-supplied pipes)" + }, + "outcome": { + "type": "token", + "required": false, + "description": "How the attempt ended without a failure: connected, or cancelled by the user before the session opened" + }, + "stage": { + "type": "token", + "required": false, + "description": "Connection step that failed: probe, artifact, deploy, handshake, authentication, network or connect" + }, + "server_version": { + "type": "version", + "required": false, + "description": "Version the remote server reported in server.hello once the handshake succeeded" + }, + "persistent": { + "type": "bool", + "required": false, + "description": "Whether the server is a persistent daemon session that survives this client disconnecting" + }, + "resumed": { + "type": "bool", + "required": false, + "description": "Whether this connection reattached to an existing persistent session, i.e. a reconnect" + } + }, + "owner": "lithe-core", + "span": { + "failureLevel": "warn" + } + }, + { + "id": "remote.connection.shell_started", + "channel": "remote", + "level": "info", + "message": "Remote shell answered the probe for {target}", + "fields": { + "connection": { + "type": "id", + "required": true, + "description": "Random per-connection log identifier that correlates this connection's lines; never a host, user name or session token" + }, + "target": { + "type": "token", + "required": true, + "description": "Server build target matching the probed system, e.g. x86_64-unknown-linux-musl, or unsupported; authentication has succeeded" + } + }, + "owner": "lithe-core" + }, + { + "id": "remote.server.deploy_finished", + "channel": "remote", + "level": "info", + "message": "Remote server {action} after {verification} verification", + "fields": { + "connection": { + "type": "id", + "required": true, + "description": "Random per-connection log identifier that correlates this connection's lines; never a host, user name or session token" + }, + "target": { + "type": "token", + "required": true, + "description": "Server build target that was installed or reused, e.g. aarch64-unknown-linux-musl" + }, + "server_version": { + "type": "version", + "required": true, + "description": "Version of the bundled server artifact the client offered for this deployment" + }, + "action": { + "type": "token", + "required": true, + "description": "Deployment result: reused when the private installed binary already matched, uploaded otherwise" + }, + "verification": { + "type": "token", + "required": true, + "description": "How the remote checked the binary: sha256 computed by the host's own tool, or identity (matching size and self-reported identity) when the host has no hash tool" + }, + "bytes": { + "type": "bytes", + "required": false, + "description": "Size of the server binary sent over the connection; present only when it was uploaded" + }, + "duration": { + "type": "duration", + "required": true, + "description": "Time from sending the install request until the remote confirmed the installed binary" + } + }, + "owner": "lithe-core" + }, + { + "id": "remote.connection.interrupted", + "channel": "remote", + "level": "warn", + "message": "Remote connection interrupted: {cause}", + "fields": { + "connection": { + "type": "id", + "required": true, + "description": "Random per-connection log identifier that correlates this connection's lines; never a host, user name or session token" + }, + "cause": { + "type": "token", + "required": true, + "description": "Why the server stream ended without a shutdown request: eof, protocol, overflow, or an I/O error kind" + }, + "duration": { + "type": "duration", + "required": true, + "description": "Time the connection had been established before the stream ended unexpectedly" + } + }, + "owner": "lithe-core" + }, + { + "id": "remote.connection.cleaned", + "channel": "remote", + "level": "info", + "message": "Remote connection {ended}", + "fields": { + "connection": { + "type": "id", + "required": true, + "description": "Random per-connection log identifier that correlates this connection's lines; never a host, user name or session token" + }, + "ended": { + "type": "token", + "required": true, + "description": "How the session was released: shutdown, closed (stdio server ended with the client), detached (daemon kept running) or lost" + }, + "duration": { + "type": "duration", + "required": true, + "description": "Lifetime of the established connection from the completed handshake until release" + } + }, + "owner": "lithe-core" + }, + { + "id": "remote.forward.started", + "channel": "remote", + "level": "info", + "message": "Port forward started on local port {local_port}", + "fields": { + "connection": { + "type": "id", + "required": true, + "description": "Random per-connection log identifier that correlates this connection's lines; never a host, user name or session token" + }, + "local_port": { + "type": "int", + "required": true, + "description": "Local TCP port the forward listens on, after the system chose one for port 0" + }, + "bind_scope": { + "type": "token", + "required": true, + "description": "Whether the local listener is bound to loopback only or to a network-reachable address" + }, + "target_kind": { + "type": "token", + "required": true, + "description": "Remote endpoint family the forward opens: tcp for host and port, unix for a socket path" + }, + "remote_port": { + "type": "int", + "required": false, + "description": "Remote TCP port the forward reaches; absent for unix sockets, and the remote host is never logged" + }, + "target_scope": { + "type": "token", + "required": false, + "description": "Whether the remote TCP host is a loopback name or address, or another network host" + } + }, + "owner": "lithe-core" + }, + { + "id": "remote.forward.removed", + "channel": "remote", + "level": "info", + "message": "Port forward on local port {local_port} removed", + "fields": { + "connection": { + "type": "id", + "required": true, + "description": "Random per-connection log identifier that correlates this connection's lines; never a host, user name or session token" + }, + "local_port": { + "type": "int", + "required": true, + "description": "Local TCP port the forward stopped listening on" + }, + "connections": { + "type": "int", + "required": true, + "description": "Number of local connections the forward accepted during its lifetime" + }, + "duration": { + "type": "duration", + "required": true, + "description": "Time from starting the forward until its acceptor stopped" + } + }, + "owner": "lithe-core" } ] }