diff --git a/rust/contracts/application-boundary.md b/rust/contracts/application-boundary.md index ce6d1fc1..df79b32e 100644 --- a/rust/contracts/application-boundary.md +++ b/rust/contracts/application-boundary.md @@ -416,6 +416,8 @@ meaning; `lithe_protocol::ErrorCode` documents when it is reported: - `reverse_forward_disabled`: the remote workspace settings do not allow reverse forwards - `remote_server_invalid`: the server build `remote.connect` would send cannot be read or is not the build its SHA-256 names +- `devcontainer_untrusted_folder`: the folder is not trusted, so its dev + container was not built or started - `unknown` GitHub authorization is independent of a Lithe account. Device Flow is the diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 6efe44d8..1d65afc8 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -830,6 +830,9 @@ or removing a command fails until the table changes in the same commit. | `remote.sshConfigHosts` | List the Host aliases of the user's SSH configuration for an import | | `remote.mottyHosts` | List the SSH hosts saved in Motty for an import | | `remote.listWslDistributions` | List the WSL distributions installed on this Windows machine | +| `remote.listContainers` | List the running Docker or Podman containers on this machine or a connected host | +| `remote.devcontainerConfigs` | List the `devcontainer.json` files of a local folder | +| `remote.devcontainerUp` | Build or reuse and start a trusted local folder's dev container with the Dev Container CLI | | `remote.preferences` | Read the remote workspace settings and what each automatic value resolves to | | `remote.editPreferences` | Set the SSH program, the reconnect limit, whether reverse forwards are allowed or what closing a connection does to its programs, or make one automatic again | | `remote.runningPrograms` | List the processes and terminals a connection's host session still runs | @@ -5938,6 +5941,85 @@ its redacted message for display; it is never logged. Cancellation and the bound are `cancelled` and `timed_out`. Nothing is saved: the window lists the distributions each time it opens. +`remote.listContainers` takes `{ engine, sessionId? }`, where `engine` is +`docker` or `podman`, and returns `{ available, containers, diagnostics }`. +Core runs ` ps --no-trunc --format '{{.ID}}\t{{.Names}}\t{{.Image}}\t{{.Status}}'`, +at most 15 seconds: on this machine in Core's own environment (the login +shell's `PATH` the application put in front, and variables such as +`DOCKER_HOST`) when `sessionId` is absent, and otherwise on that +connection's host in the server's environment, the same one the connection +later enters the container from. Only running containers are listed, since +Lithe never starts, creates or changes a container. `containers` are +`{ id, name, image, status }` in the engine's order, at most 256 and from at +most 256 KiB of output: `id` is the full id, `name` the first of the +container's names, and `image` and `status` the engine's text without +control characters, at most 256 bytes each. Lines that are not four fields, +or whose id or name is not a container name, are skipped, and so are +repeated ids. `available` is `false` when the engine CLI cannot start there; +when it runs and fails, for example because its service is not running, +`containers` is empty and `diagnostics` holds its redacted message for +display; it is never logged. Any other field is `invalid_request` ("Invalid +container listing request"), so a request cannot pick the program; an unknown +`sessionId` is `connection_closed`, and cancellation and the bound are +`cancelled` and `timed_out`. Nothing is saved. + +#### Dev Containers + +A local folder's dev container is built and started by the reference Dev +Container CLI (`devcontainer`, from `@devcontainers/cli`; `devcontainer.cmd` +on Windows) on `PATH`, then entered like any running container with +`remote.connect`'s `container`. Lithe does not interpret the configuration +and adds no mounts or options to it. + +`remote.devcontainerConfigs` takes `{ folder }`, an absolute folder on this +machine, and returns `{ configs }`: `{ path, name? }` for each regular file in +the places the specification searches, in this order: +`.devcontainer/devcontainer.json`, `.devcontainer.json`, then +`.devcontainer//devcontainer.json` for at most 64 subfolders in +name order, skipping names that start with `.`. `path` is relative to the +folder with `/` separators. `name` is the configuration's `name`, read as +JSON with comments and trailing commas, without control characters and at +most 128 bytes; it is absent when the file is larger than 1 MiB, resolves +outside the folder, cannot be read or has no non-empty string `name`. A +relative or empty `folder` is `invalid_request`; a folder that does not +exist is `workspace_not_found`. Reading starts nothing. + +`remote.devcontainerUp` takes `{ folder, config?, engine, +projectCodeAllowed }` and returns `{ container?, diagnostics }`. Building runs +the folder's code on this machine (`initializeCommand`, Dockerfiles, feature +scripts), so when `projectCodeAllowed` is `false` nothing starts and the +request fails with `devcontainer_untrusted_folder`; native clients pass the +folder's trust decision, as for Git. `config` must be one of the `path`s +`remote.devcontainerConfigs` lists for the folder, otherwise +`invalid_request`; without it the CLI searches the folder itself. Core runs +`devcontainer up --workspace-folder [--config /]`, +adding `--docker-path podman` after `up` for `engine: "podman"`, on this +machine in Core's own environment, for at most one hour. Each line the CLI +logs to standard error is sent as a `{ type: "devcontainerOutput", text }` +event, redacted, at most 4096 bytes per event and 2 MiB in all; after that +one `{ type: "devcontainerOutput", truncated: true }` event follows and later +lines are dropped. The log is shown, never logged. + +The result is the last line of standard output that is a JSON object with an +`outcome`: + +- `success`: `container` is `{ engine, container, containerId, user?, + workspaceFolder }`. `containerId` is the CLI's container id, `container` the + name ` inspect --format '{{.Name}}'` gives within 15 seconds + (without Docker's leading `/`), or the id when it gives none, `user` the + configuration's `remoteUser`, and `workspaceFolder` the absolute + `remoteWorkspaceFolder` to open. A container id that is not a container + name, a user `exec` cannot take, or a folder that is not absolute is + `parse_failed`, and so is a successful exit without a result line. +- `error`, or no result line with a failed exit: `container` is absent and + `diagnostics` holds the end of the CLI's log followed by its `message` and + `description`, redacted, for display. + +A missing CLI is `runtime_missing`; any other field is `invalid_request` +("Invalid dev container start request"), so a request cannot add mounts or +pick the program; cancellation and the bound are `cancelled` and +`timed_out`. Nothing is saved. + #### Remote workspace preferences The settings page "Tools › Remote Workspace" edits three values that apply to @@ -6072,14 +6154,43 @@ because `wsl.exe` asks no questions. An unknown distribution is the distribution and the account (`{ wsl: { distribution, user } }` as the first and only hop). +The request may also name a running container as `container: { engine, +container, user? }`, where `engine` is `docker` or `podman`, `container` a +name or id such as `remote.listContainers` returned, and `user` a user, uid or +`user:group` inside it (the image's default user when absent or empty). Next +to `connection` or `wsl` the container is on that host: the remote command +becomes ` exec -i [-u ] …` there, after the login. +On its own the container is on this machine, and Core starts that command +itself in place of OpenSSH, with its own environment so the engine finds its +service. Core only enters the running container: it never starts, creates or +reconfigures it, mounts directories into it or asks for more rights than the +engine CLI has. The probe, the checked upload into the container's `$HOME` +and the stages are the same, and nothing is relayed through +`remote.authRespond` for the engine. When the engine gives up before the +server starts, a container that does not exist, is not running or is paused, +and an engine whose service does not answer, are `unreachable`; a service +socket the user may not open is `failed`, not `authenticationFailed`, even +over SSH; and other failures are `failed` with the engine's message in +`diagnostics` (or ` exited with status ` when it printed +nothing). The connection log's `transport` is `container`, `ssh-container` or +`wsl-container`, without the container's name. Trust decisions name the +container after the other hops, as `{ container: { engine, program, +container, user? } }`, so a decision never carries over to another container +or account. + A request that names both `connection` and `wsl` is `invalid_request` with -`details` `{ field: "wsl", reason: "invalid" }`, and one that names neither -`{ field: "connection", reason: "required" }`. A malformed connection, a -distribution that is empty, longer than 64 bytes or not a WSL distribution -name, a user that is longer than 32 bytes or not a Linux login name, an -unknown `target` or a `sha256` that is not 64 hexadecimal digits is -`invalid_request`, before OpenSSH or `wsl.exe` starts. A missing `ssh` or -`wsl.exe` is `runtime_missing`. When the build for the host's platform cannot be +`details` `{ field: "wsl", reason: "invalid" }`, and one that names none of +`connection`, `wsl` and `container` `{ field: "connection", reason: +"required" }`. A malformed connection, a distribution that is empty, longer +than 64 bytes or not a WSL distribution name, a user that is longer than 32 +bytes or not a Linux login name, a container that is empty (`{ field: +"container", reason: "required" }`), longer than 128 bytes or not a container +name, a container user that is longer than 64 bytes, starts with `-` or holds +other characters than letters, digits and `_.:-` (`{ field: "user" }`), an +unknown `engine` or field, an unknown `target` or a `sha256` that is not 64 +hexadecimal digits is `invalid_request`, before OpenSSH, `wsl.exe` or the +engine starts. A missing `ssh`, `wsl.exe` or local engine CLI is +`runtime_missing`. When the build for the host's platform cannot be read or its SHA-256 differs, the attempt ends as `remote_server_invalid` without sending anything; `details` says which of the two happened and, for a mismatch, the SHA-256 Core computed, but never the path. Cancellation and the diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 2c1c5149..ad199155 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -1046,6 +1046,15 @@ pub enum RemoteCommand { /// Lists the WSL distributions installed on this Windows machine /// (`remote.listWslDistributions`). ListWslDistributions, + /// Lists the running containers of a container engine on this machine + /// or on a connected host (`remote.listContainers`). + ListContainers, + /// Lists the `devcontainer.json` files of a local folder + /// (`remote.devcontainerConfigs`). + DevcontainerConfigs, + /// Builds or reuses and starts a local folder's dev container with the + /// Dev Container CLI (`remote.devcontainerUp`). + DevcontainerUp, /// Reads the remote workspace preferences and what each automatic value /// resolves to (`remote.preferences`). Preferences, @@ -1639,6 +1648,9 @@ impl CoreCommand { "remote.listWslDistributions" => { Some(Self::Remote(RemoteCommand::ListWslDistributions)) } + "remote.listContainers" => Some(Self::Remote(RemoteCommand::ListContainers)), + "remote.devcontainerConfigs" => Some(Self::Remote(RemoteCommand::DevcontainerConfigs)), + "remote.devcontainerUp" => Some(Self::Remote(RemoteCommand::DevcontainerUp)), "remote.preferences" => Some(Self::Remote(RemoteCommand::Preferences)), "remote.editPreferences" => Some(Self::Remote(RemoteCommand::EditPreferences)), "remote.runningPrograms" => Some(Self::Remote(RemoteCommand::RunningPrograms)), diff --git a/rust/crates/core/src/runtime/dispatcher/remote.rs b/rust/crates/core/src/runtime/dispatcher/remote.rs index e304d066..91683da8 100644 --- a/rust/crates/core/src/runtime/dispatcher/remote.rs +++ b/rust/crates/core/src/runtime/dispatcher/remote.rs @@ -343,6 +343,37 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option, payload: Valu ), Err(error) => CoreResponse::failure(id, error), }, + RemoteCommand::ListContainers => answer( + id, + payload, + "Invalid container listing request", + |request| { + lithe_workspace::containers::list(request).map(|listed| { + serde_json::to_value(listed).expect("container listings should encode") + }) + }, + ), + RemoteCommand::DevcontainerConfigs => answer( + id, + payload, + "Invalid dev container configuration request", + |request| { + lithe_workspace::devcontainers::configs(request).map(|listed| { + serde_json::to_value(listed) + .expect("dev container configurations should encode") + }) + }, + ), + RemoteCommand::DevcontainerUp => answer( + id, + payload, + "Invalid dev container start request", + |request| { + lithe_workspace::devcontainers::up(request).map(|started| { + serde_json::to_value(started).expect("dev container starts should encode") + }) + }, + ), RemoteCommand::AuthRespond => { #[derive(serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] diff --git a/rust/crates/core/src/tests/remote_sessions.rs b/rust/crates/core/src/tests/remote_sessions.rs index 24dfcc9f..740ff196 100644 --- a/rust/crates/core/src/tests/remote_sessions.rs +++ b/rust/crates/core/src/tests/remote_sessions.rs @@ -1434,6 +1434,37 @@ fn connection_window_helpers_answer_through_the_dispatcher() { assert_eq!(both["error"]["code"], "invalid_request", "{both}"); let details: Value = serde_json::from_str(both["error"]["details"].as_str().unwrap()).unwrap(); assert_eq!(details, json!({"field": "wsl", "reason": "invalid"})); + // A container listing names a known engine and nothing that could pick + // the program. + for payload in [ + json!({"engine": "nerdctl"}), + json!({"engine": "docker", "program": "/bin/sh"}), + ] { + let refused = call("remote.listContainers", payload); + assert_eq!(refused["error"]["code"], "invalid_request", "{refused}"); + assert_eq!( + refused["error"]["message"], "Invalid container listing request", + "{refused}" + ); + } + // A dev container starts only for a trusted folder, from a configuration + // the folder lists; nothing runs otherwise. + let untrusted = call( + "remote.devcontainerUp", + json!({"folder": "/nonexistent", "engine": "docker", "projectCodeAllowed": false}), + ); + assert_eq!( + untrusted["error"]["code"], "devcontainer_untrusted_folder", + "{untrusted}" + ); + let unknown = call( + "remote.devcontainerUp", + json!({"folder": "/nonexistent", "engine": "docker", "projectCodeAllowed": true, + "mounts": ["/"]}), + ); + assert_eq!(unknown["error"]["code"], "invalid_request", "{unknown}"); + let relative = call("remote.devcontainerConfigs", json!({"folder": "app"})); + assert_eq!(relative["error"]["code"], "invalid_request", "{relative}"); // The settings page reads automatic values and stores an edit; a damaged // document stops the SSH commands before OpenSSH starts. @@ -1789,6 +1820,48 @@ fn remote_host_and_reverse_forwards_follow_their_own_rules() { ); } +// The connection window lists a connected host's containers through the +// host's own engine CLI; a host without one says so instead of failing. +#[test] +fn container_listings_run_on_the_host_and_say_when_it_has_no_engine() { + use std::os::unix::fs::PermissionsExt; + let host = HostFixture::new(); + let engine = host.root.join("host/docker"); + std::fs::write( + &engine, + "#!/bin/sh\nprintf 'c0ffee\\tdev\\tubuntu:24.04\\tUp 1 minute\\n'\n", + ) + .unwrap(); + std::fs::set_permissions(&engine, std::fs::Permissions::from_mode(0o755)).unwrap(); + let request = |engine: &str| { + serde_json::from_value(json!({"engine": engine, "sessionId": host.id})).unwrap() + }; + let listed = + test_support::list_containers_with(request("docker"), engine.to_str().unwrap()).unwrap(); + assert_eq!( + serde_json::to_value(listed).unwrap(), + json!({"available": true, "diagnostics": "", "containers": [ + {"id": "c0ffee", "name": "dev", "image": "ubuntu:24.04", "status": "Up 1 minute"} + ]}) + ); + let absent = host.root.join("host/absent"); + let missing = + test_support::list_containers_with(request("podman"), absent.to_str().unwrap()).unwrap(); + assert_eq!( + serde_json::to_value(missing).unwrap(), + json!({"available": false, "containers": [], "diagnostics": ""}) + ); + let unknown = test_support::list_containers_with( + serde_json::from_value(json!({"engine": "docker", "sessionId": "absent"})).unwrap(), + engine.to_str().unwrap(), + ) + .unwrap_err(); + assert!( + matches!(unknown.code, ErrorCode::ConnectionClosed), + "{unknown:?}" + ); +} + #[test] fn remote_programs_are_listed_ended_and_kept_only_by_a_persistent_session() { use lithe_remote::client::api::{SpawnSpec, TerminalEvent, TerminalSpec}; diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index 844812fb..22b84afd 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -1309,7 +1309,7 @@ pub static EVENTS: &[EventMetadata] = &[ 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, wsl (a local WSL distribution through wsl.exe), command (any spawned transport chain) or streams (caller-supplied pipes)", reason: None }, + FieldMetadata { name: "transport", field_type: FieldType::Token, required: true, description: "How the client reached the server: ssh, wsl (a local WSL distribution through wsl.exe), container (a local container through its engine's exec), ssh-container or wsl-container (a container on that host), command (any spawned transport chain) or streams (caller-supplied pipes)", reason: None }, ], span: Some(SpanPhase::Failed), rate: 60, @@ -1328,7 +1328,7 @@ pub static EVENTS: &[EventMetadata] = &[ 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, wsl (a local WSL distribution through wsl.exe), command (any spawned transport chain) or streams (caller-supplied pipes)", reason: None }, + FieldMetadata { name: "transport", field_type: FieldType::Token, required: true, description: "How the client reached the server: ssh, wsl (a local WSL distribution through wsl.exe), container (a local container through its engine's exec), ssh-container or wsl-container (a container on that host), command (any spawned transport chain) or streams (caller-supplied pipes)", reason: None }, ], span: Some(SpanPhase::Finished), rate: 60, @@ -1346,7 +1346,7 @@ pub static EVENTS: &[EventMetadata] = &[ 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, wsl (a local WSL distribution through wsl.exe), command (any spawned transport chain) or streams (caller-supplied pipes)", reason: None }, + FieldMetadata { name: "transport", field_type: FieldType::Token, required: true, description: "How the client reached the server: ssh, wsl (a local WSL distribution through wsl.exe), container (a local container through its engine's exec), ssh-container or wsl-container (a container on that host), command (any spawned transport chain) or streams (caller-supplied pipes)", reason: None }, ], span: Some(SpanPhase::Started), rate: 60, diff --git a/rust/crates/protocol/src/error.rs b/rust/crates/protocol/src/error.rs index 38acf3d3..05cf8f1d 100644 --- a/rust/crates/protocol/src/error.rs +++ b/rust/crates/protocol/src/error.rs @@ -99,6 +99,11 @@ pub enum ErrorCode { /// request gives for it. Nothing was installed on the host; the /// application's copy of the build is damaged or was replaced. RemoteServerInvalid, + /// `remote.devcontainerUp` names a folder the user does not trust + /// (`projectCodeAllowed: false`), so the Dev Container CLI was not + /// started: building runs the folder's code on this machine. Trusting the + /// folder and repeating the request builds it. + DevcontainerUntrustedFolder, /// A failure does not fit a more stable cross-platform category. Unknown, } diff --git a/rust/crates/remote/src/client/connection_log.rs b/rust/crates/remote/src/client/connection_log.rs index a2825971..453f7cd0 100644 --- a/rust/crates/remote/src/client/connection_log.rs +++ b/rust/crates/remote/src/client/connection_log.rs @@ -74,6 +74,13 @@ pub enum ConnectionKind { Ssh, /// A WSL distribution started through `wsl.exe`, owned by the caller. Wsl, + /// A container on this machine, entered through its engine's `exec`, + /// owned by the caller. + Container, + /// A container on an SSH host, owned by the caller. + SshContainer, + /// A container inside a WSL distribution, owned by the caller. + WslContainer, /// A transport chain [`crate::client::RemoteSession::connect`] spawns. Command, /// Streams the caller supplies to @@ -86,6 +93,9 @@ impl ConnectionKind { match self { Self::Ssh => "ssh", Self::Wsl => "wsl", + Self::Container => "container", + Self::SshContainer => "ssh-container", + Self::WslContainer => "wsl-container", Self::Command => "command", Self::Streams => "streams", } diff --git a/rust/crates/remote/src/client/container.rs b/rust/crates/remote/src/client/container.rs new file mode 100644 index 00000000..60b6ed9c --- /dev/null +++ b/rust/crates/remote/src/client/container.rs @@ -0,0 +1,306 @@ +//! Running containers as remote workspaces. +//! +//! A container on this machine, on an SSH host or inside a WSL distribution +//! is reached through its engine's `exec -i`. [`ContainerConnection`] names +//! the engine, the container and, optionally, the user, and becomes the last +//! hop of a transport chain; the server is then probed, installed and +//! started inside the container exactly as on an SSH host. Nothing is saved: +//! the connection window lists the running containers each time it asks, +//! with [`list_command`] and [`parse_containers`]. +//! +//! Lithe only runs `exec` in a container that already runs. It does not +//! start, create or reconfigure containers, mount directories or ask for +//! elevated rights: whoever may use the engine may already do all of that, +//! so the engine is not a security boundary (S32). +//! +//! Note: .agents/notes/proposed/architecture/2026-10-24-remote-development-workspace-host.md + +use crate::client::connections::{ConnectionError, Reason}; +use crate::client::transport::{ + is_container_name, is_container_user, ContainerEngine, ContainerHop, MAX_CONTAINER_NAME_BYTES, + MAX_CONTAINER_USER_BYTES, +}; +use serde::{Deserialize, Serialize}; + +/// Containers one listing returns at most; later ones are dropped. +pub const MAX_CONTAINERS: usize = 256; + +/// Bytes of `ps` output read at most; the rest is ignored. +pub const MAX_LIST_BYTES: usize = 256 * 1024; + +/// Longest image or status text a listing keeps, in bytes; longer text is +/// cut at a character boundary. +const MAX_TEXT_BYTES: usize = 256; + +/// `remote.connect`'s `container` field: the engine, the running container +/// and the user. On its own it names a container on this machine; next to +/// `connection` or `wsl` a container on that host. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ContainerConnection { + /// Engine whose CLI runs `exec`. + pub engine: ContainerEngine, + /// Container name or id, as `ps` lists it. + pub container: String, + /// `user`, `uid` or `user:group` passed as `--user`; the image's default + /// user when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub user: Option, +} + +impl ContainerConnection { + /// The hop into the container through the engine CLI on `PATH`. Both + /// fields are trimmed and an empty `user` means the image's default user. + /// + /// Refused, with the field and the reason, when the container is empty, + /// longer than 128 bytes or not a name or id the engine CLI cannot read + /// as an option, or the user is longer than 64 bytes or not a name, uid + /// or `user:group`. + pub fn hop(&self) -> Result { + let container = self.container.trim(); + if container.is_empty() { + return Err(ConnectionError::at("container", Reason::Required)); + } + if container.len() > MAX_CONTAINER_NAME_BYTES { + return Err(ConnectionError::at("container", Reason::TooLong)); + } + if !is_container_name(container) { + return Err(ConnectionError::at("container", Reason::Invalid)); + } + let user = self + .user + .as_deref() + .map(str::trim) + .filter(|user| !user.is_empty()); + if let Some(user) = user { + if user.len() > MAX_CONTAINER_USER_BYTES { + return Err(ConnectionError::at("user", Reason::TooLong)); + } + if !is_container_user(user) { + return Err(ConnectionError::at("user", Reason::Invalid)); + } + } + let mut hop = ContainerHop::new(self.engine, container); + hop.user = user.map(Into::into); + Ok(hop) + } +} + +/// One running container in a listing. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ListedContainer { + /// Full container id. + pub id: String, + /// The container's name; its first one when the engine lists several. + pub name: String, + /// Image the container runs, as the engine prints it. + pub image: String, + /// The engine's own status text, for example `Up 2 hours`. + pub status: String, +} + +/// Command line, starting with the engine CLI's name, that prints the +/// running containers one per line: full id, names, image and status, +/// separated by tabs. Docker and Podman both read this template; their JSON +/// output differs. +pub fn list_command(engine: ContainerEngine) -> Vec { + vec![ + engine.name().into(), + "ps".into(), + "--no-trunc".into(), + "--format".into(), + "{{.ID}}\t{{.Names}}\t{{.Image}}\t{{.Status}}".into(), + ] +} + +/// The containers in the output of [`list_command`], in the order the +/// engine printed them. +/// +/// Leaves out lines without four fields, ids or names `exec` cannot be given, +/// and repeated ids. Image and status are kept as display text without +/// control characters, at most 256 bytes each. At most [`MAX_LIST_BYTES`] of +/// output and [`MAX_CONTAINERS`] containers are read. +pub fn parse_containers(output: &[u8]) -> Vec { + let output = &output[..output.len().min(MAX_LIST_BYTES)]; + let text = String::from_utf8_lossy(output); + let mut containers: Vec = Vec::new(); + for line in text.lines() { + let fields: Vec<&str> = line.split('\t').collect(); + let [id, names, image, status] = fields.as_slice() else { + continue; + }; + let id = id.trim(); + // Docker lists links as extra comma-separated names. + let name = names.split(',').next().unwrap_or_default().trim(); + if !is_container_name(id) + || !is_container_name(name) + || containers.iter().any(|seen| seen.id == id) + { + continue; + } + containers.push(ListedContainer { + id: id.into(), + name: name.into(), + image: display_text(image), + status: display_text(status), + }); + if containers.len() == MAX_CONTAINERS { + break; + } + } + containers +} + +/// `text` trimmed, without control characters and cut to [`MAX_TEXT_BYTES`] +/// at a character boundary. +fn display_text(text: &str) -> String { + let mut kept = String::new(); + for character in text + .trim() + .chars() + .filter(|character| !character.is_control()) + { + if kept.len() + character.len_utf8() > MAX_TEXT_BYTES { + break; + } + kept.push(character); + } + kept +} + +#[cfg(test)] +mod tests { + use super::*; + + fn connection(container: &str, user: Option<&str>) -> ContainerConnection { + ContainerConnection { + engine: ContainerEngine::Docker, + container: container.into(), + user: user.map(Into::into), + } + } + + #[test] + fn connections_become_a_hop_after_trimming_and_refuse_malformed_fields() { + let hop = connection(" api-1 ", Some(" 1000:1000 ")).hop().unwrap(); + assert_eq!(hop.container, "api-1"); + assert_eq!(hop.user.as_deref(), Some("1000:1000")); + assert_eq!(hop.program, "docker"); + assert!(hop.working_directory.is_none() && hop.environment.is_empty()); + assert_eq!(connection("api", Some(" ")).hop().unwrap().user, None); + let podman = ContainerConnection { + engine: ContainerEngine::Podman, + ..connection("api", None) + }; + assert_eq!(podman.hop().unwrap().program, "podman"); + + let long_container = "c".repeat(MAX_CONTAINER_NAME_BYTES + 1); + let long_user = "u".repeat(MAX_CONTAINER_USER_BYTES + 1); + for (refused, field, reason) in [ + (connection(" ", None), "container", Reason::Required), + ( + connection(&long_container, None), + "container", + Reason::TooLong, + ), + (connection("-it", None), "container", Reason::Invalid), + (connection("api web", None), "container", Reason::Invalid), + (connection("api;id", None), "container", Reason::Invalid), + (connection("api", Some(&long_user)), "user", Reason::TooLong), + (connection("api", Some("-u")), "user", Reason::Invalid), + (connection("api", Some("a b")), "user", Reason::Invalid), + ] { + assert_eq!( + refused.hop(), + Err(ConnectionError::at(field, reason)), + "{refused:?}" + ); + } + } + + #[test] + fn requests_name_only_the_engine_the_container_and_the_user() { + let parsed: ContainerConnection = + serde_json::from_value(serde_json::json!({"engine": "podman", "container": "api"})) + .unwrap(); + assert_eq!(parsed.engine, ContainerEngine::Podman); + assert_eq!(parsed.user, None); + for refused in [ + serde_json::json!({"engine": "docker", "container": "api", "program": "/tmp/evil"}), + serde_json::json!({"engine": "nerdctl", "container": "api"}), + serde_json::json!({"container": "api"}), + ] { + assert!( + serde_json::from_value::(refused).is_err(), + "a request with unknown or missing fields is refused" + ); + } + } + + #[test] + fn the_listing_asks_the_engine_for_running_containers_with_full_ids() { + assert_eq!( + list_command(ContainerEngine::Podman), + vec![ + "podman", + "ps", + "--no-trunc", + "--format", + "{{.ID}}\t{{.Names}}\t{{.Image}}\t{{.Status}}", + ] + ); + assert_eq!(list_command(ContainerEngine::Docker)[0], "docker"); + } + + #[test] + fn listings_keep_valid_containers_in_order_and_once() { + let id = "a".repeat(64); + let other = "b".repeat(64); + let listing = format!( + "{id}\tapi,web/db\tghcr.io/acme/api:1\tUp 2 hours\r\n\ + malformed line\n\ + {other}\t-it\timage\tUp\n\ + {other}\tworker\tbusybox\tUp 3 seconds (healthy)\n\ + {id}\tagain\timage\tUp\n\ + -x\tname\timage\tUp\n" + ); + assert_eq!( + parse_containers(listing.as_bytes()), + vec![ + ListedContainer { + id: id.clone(), + name: "api".into(), + image: "ghcr.io/acme/api:1".into(), + status: "Up 2 hours".into(), + }, + ListedContainer { + id: other, + name: "worker".into(), + image: "busybox".into(), + status: "Up 3 seconds (healthy)".into(), + }, + ] + ); + assert!(parse_containers(b"").is_empty()); + } + + #[test] + fn listings_bound_their_input_their_length_and_their_text() { + let many: String = (0..MAX_CONTAINERS + 5) + .map(|index| format!("id{index}\tname{index}\timage\tUp\n")) + .collect(); + let listed = parse_containers(many.as_bytes()); + assert_eq!(listed.len(), MAX_CONTAINERS); + assert_eq!(listed[0].name, "name0"); + + let mut long = "a".repeat(MAX_LIST_BYTES).into_bytes(); + long.extend(b"\nid\tlate\timage\tUp\n"); + assert!(parse_containers(&long).is_empty()); + + let image = format!("{}é", "i".repeat(MAX_TEXT_BYTES - 1)); + let listed = parse_containers(format!("id\tname\t{image}\tUp\u{1b}[31m\n").as_bytes()); + assert_eq!(listed[0].image, "i".repeat(MAX_TEXT_BYTES - 1)); + assert_eq!(listed[0].status, "Up[31m"); + } +} diff --git a/rust/crates/remote/src/client/devcontainer.rs b/rust/crates/remote/src/client/devcontainer.rs new file mode 100644 index 00000000..413676e5 --- /dev/null +++ b/rust/crates/remote/src/client/devcontainer.rs @@ -0,0 +1,540 @@ +//! Dev Containers: a local folder's `devcontainer.json` built and started +//! by the reference Dev Container CLI, then entered as a running container. +//! +//! Lithe does not interpret the configuration. [`discover`] finds the +//! configuration files the specification places in a folder and reads only +//! their `name` for the picker; [`up_command`] asks the `devcontainer` CLI +//! (`@devcontainers/cli`) to build or reuse the container exactly as the +//! configuration says, including its mounts, features and lifecycle +//! commands; [`parse_up_result`] reads the container, user and workspace +//! folder the CLI reports. The connection then enters that container through +//! [`ContainerConnection`](crate::client::ContainerConnection), like any +//! running container (S32), and opens the reported workspace folder. +//! +//! Building runs the folder's code on this machine (`initializeCommand`, +//! Dockerfiles, feature scripts), so the caller starts it only for a folder +//! the user trusts. +//! +//! Note: .agents/notes/proposed/architecture/2026-10-24-remote-development-workspace-host.md + +use crate::client::transport::{is_container_name, is_container_user, ContainerEngine}; +use serde::{Deserialize, Serialize}; +use std::path::Path; + +/// The Dev Container CLI's executable, which `PATH` resolves. npm installs a +/// command script on Windows. +#[cfg(not(windows))] +pub const CLI: &str = "devcontainer"; +/// The Dev Container CLI's executable, which `PATH` resolves. npm installs a +/// command script on Windows. +#[cfg(windows)] +pub const CLI: &str = "devcontainer.cmd"; + +/// Bytes of one `devcontainer.json` read for its name; larger files are +/// listed without one. +pub const MAX_CONFIG_BYTES: u64 = 1024 * 1024; + +/// Subfolders of `.devcontainer` searched for configurations, in name order. +const MAX_SUBFOLDERS: usize = 64; + +/// Longest configuration name kept, in bytes. +const MAX_NAME_BYTES: usize = 128; + +/// Longest workspace folder accepted from the CLI, in bytes. +const MAX_FOLDER_BYTES: usize = 4096; + +/// Longest error text kept from the CLI's result, in bytes. +const MAX_MESSAGE_BYTES: usize = 2048; + +/// One configuration in a folder. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DevcontainerConfig { + /// Path relative to the folder, with `/` separators, for example + /// `.devcontainer/devcontainer.json`. + pub path: String, + /// The configuration's `name`, when it has a readable one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, +} + +/// The configurations of `folder` in the places the Dev Container +/// specification looks: `.devcontainer/devcontainer.json`, +/// `.devcontainer.json`, then `.devcontainer//devcontainer.json` for +/// each subfolder in name order. Only regular files are listed; a name is +/// read only from a file inside `folder` that is at most +/// [`MAX_CONFIG_BYTES`] long. +pub fn discover(folder: &Path) -> Vec { + let mut candidates = vec![ + ".devcontainer/devcontainer.json".to_string(), + ".devcontainer.json".to_string(), + ]; + if let Ok(entries) = std::fs::read_dir(folder.join(".devcontainer")) { + let mut subfolders: Vec = entries + .filter_map(Result::ok) + .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_dir())) + .filter_map(|entry| entry.file_name().into_string().ok()) + .filter(|name| !name.starts_with('.')) + .collect(); + subfolders.sort(); + subfolders.truncate(MAX_SUBFOLDERS); + candidates.extend( + subfolders + .into_iter() + .map(|name| format!(".devcontainer/{name}/devcontainer.json")), + ); + } + let root = std::fs::canonicalize(folder).ok(); + candidates + .into_iter() + .filter_map(|path| { + let file = folder.join(&path); + if !std::fs::metadata(&file).is_ok_and(|metadata| metadata.is_file()) { + return None; + } + let name = read_name(&file, root.as_deref()); + Some(DevcontainerConfig { path, name }) + }) + .collect() +} + +/// The `name` of the configuration at `file` when it resolves inside `root`. +fn read_name(file: &Path, root: Option<&Path>) -> Option { + let resolved = std::fs::canonicalize(file).ok()?; + if !root.is_some_and(|root| resolved.starts_with(root)) { + return None; + } + if std::fs::metadata(&resolved).ok()?.len() > MAX_CONFIG_BYTES { + return None; + } + config_name(&std::fs::read_to_string(&resolved).ok()?) +} + +/// The `name` of a `devcontainer.json` text, which is JSON with comments and +/// trailing commas. Control characters are removed and the name is cut to +/// 128 bytes; an empty or missing name is `None`. +pub fn config_name(text: &str) -> Option { + let value: serde_json::Value = serde_json::from_str(&strip_jsonc(text)).ok()?; + let name = value.get("name")?.as_str()?; + let cleaned: String = name.chars().filter(|c| !c.is_control()).collect(); + let cleaned = cut(cleaned.trim(), MAX_NAME_BYTES); + (!cleaned.is_empty()).then(|| cleaned.to_string()) +} + +/// `text` without `//` and `/* */` comments and without commas that only +/// precede a closing `}` or `]`, outside strings. +fn strip_jsonc(text: &str) -> String { + strip_trailing_commas(&strip_comments(text)) +} + +/// Calls `outside` for each character outside a JSON string and copies the +/// characters of strings, escapes included, unchanged. +fn rewrite_outside_strings( + text: &str, + mut outside: impl FnMut(char, &mut std::iter::Peekable, &mut String), +) -> String { + let mut out = String::with_capacity(text.len()); + let mut chars = text.chars().peekable(); + let mut in_string = false; + while let Some(c) = chars.next() { + if in_string { + out.push(c); + if c == '\\' { + if let Some(next) = chars.next() { + out.push(next); + } + } else if c == '"' { + in_string = false; + } + } else if c == '"' { + in_string = true; + out.push(c); + } else { + outside(c, &mut chars, &mut out); + } + } + out +} + +fn strip_comments(text: &str) -> String { + rewrite_outside_strings(text, |c, chars, out| match c { + '/' if chars.peek() == Some(&'/') => { + for next in chars.by_ref() { + if next == '\n' { + out.push('\n'); + break; + } + } + } + '/' if chars.peek() == Some(&'*') => { + chars.next(); + let mut previous = '\0'; + for next in chars.by_ref() { + if previous == '*' && next == '/' { + break; + } + previous = next; + } + out.push(' '); + } + _ => out.push(c), + }) +} + +fn strip_trailing_commas(text: &str) -> String { + rewrite_outside_strings(text, |c, chars, out| { + let trailing = c == ',' + && matches!( + chars.clone().find(|next| !next.is_whitespace()), + Some('}') | Some(']') + ); + if !trailing { + out.push(c); + } + }) +} + +/// Command line, starting with [`CLI`], that builds or reuses the dev +/// container of `folder` and starts it. `config` is the configuration file's +/// absolute path; the CLI's default search when absent. Podman is passed as +/// the CLI's Docker program, after `up`, which is where the CLI reads it. +pub fn up_command(engine: ContainerEngine, folder: &str, config: Option<&str>) -> Vec { + let mut argv = vec![ + CLI.to_string(), + "up".into(), + "--workspace-folder".into(), + folder.into(), + ]; + if let Some(config) = config { + argv.push("--config".into()); + argv.push(config.into()); + } + if engine == ContainerEngine::Podman { + argv.push("--docker-path".into()); + argv.push(engine.name().into()); + } + argv +} + +/// The container `devcontainer up` started. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct StartedDevcontainer { + /// Full container id. + pub container_id: String, + /// User the configuration connects as (`remoteUser`), which the + /// connection passes to `exec`; the image's default user when absent. + pub remote_user: Option, + /// Absolute folder inside the container that holds the workspace. + pub remote_workspace_folder: String, +} + +/// Why [`parse_up_result`] found no started container. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum UpFailure { + /// The CLI reported an error: its message and description, joined. + Reported(String), + /// The CLI printed no result line. + Missing, + /// The CLI reported success with a container id, user or folder Lithe + /// cannot use. + Unusable, +} + +/// The result `devcontainer up` printed: the last line of `stdout` that is a +/// JSON object with an `outcome`. +pub fn parse_up_result(stdout: &[u8]) -> Result { + let text = String::from_utf8_lossy(stdout); + let result = text + .lines() + .rev() + .map(str::trim) + .filter(|line| line.starts_with('{')) + .filter_map(|line| serde_json::from_str::(line).ok()) + .find(|value| { + value + .get("outcome") + .is_some_and(|outcome| outcome.is_string()) + }) + .ok_or(UpFailure::Missing)?; + let field = |name: &str| result.get(name).and_then(|value| value.as_str()); + if field("outcome") != Some("success") { + let reported: Vec<&str> = [field("message"), field("description")] + .into_iter() + .flatten() + .map(str::trim) + .filter(|text| !text.is_empty()) + .collect(); + return Err(UpFailure::Reported( + cut(&reported.join("\n"), MAX_MESSAGE_BYTES).to_string(), + )); + } + let container_id = field("containerId") + .map(str::trim) + .filter(|id| is_container_name(id)) + .ok_or(UpFailure::Unusable)?; + let remote_user = match field("remoteUser").map(str::trim) { + None | Some("") => None, + Some(user) if is_container_user(user) => Some(user.to_string()), + Some(_) => return Err(UpFailure::Unusable), + }; + let folder = field("remoteWorkspaceFolder").ok_or(UpFailure::Unusable)?; + if !folder.starts_with('/') + || folder.len() > MAX_FOLDER_BYTES + || folder.chars().any(char::is_control) + { + return Err(UpFailure::Unusable); + } + Ok(StartedDevcontainer { + container_id: container_id.to_string(), + remote_user, + remote_workspace_folder: folder.to_string(), + }) +} + +/// Command line, starting with the engine CLI's name, that prints the name +/// of container `id`. +pub fn name_command(engine: ContainerEngine, id: &str) -> Vec { + vec![ + engine.name().into(), + "inspect".into(), + "--format".into(), + "{{.Name}}".into(), + id.into(), + ] +} + +/// The container name [`name_command`] printed, without Docker's leading +/// `/`; `None` when it is not a name `exec` can be given. +pub fn parse_name(stdout: &[u8]) -> Option { + let text = String::from_utf8_lossy(stdout); + let name = text.lines().next()?.trim(); + let name = name.strip_prefix('/').unwrap_or(name); + is_container_name(name).then(|| name.to_string()) +} + +/// `text` cut to at most `limit` bytes at a character boundary. +fn cut(text: &str, limit: usize) -> &str { + if text.len() <= limit { + return text; + } + let mut end = limit; + while !text.is_char_boundary(end) { + end -= 1; + } + &text[..end] +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::PathBuf; + use std::sync::atomic::{AtomicU64, Ordering}; + + struct Folder(PathBuf); + + impl Folder { + fn new(label: &str) -> Self { + static SEQUENCE: AtomicU64 = AtomicU64::new(0); + let root = std::env::temp_dir().join(format!( + "lithe-devcontainer-{label}-{}-{}", + std::process::id(), + SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + Self(root) + } + + fn write(&self, path: &str, text: &str) { + let file = self.0.join(path); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(file, text).unwrap(); + } + } + + impl Drop for Folder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn config(path: &str, name: Option<&str>) -> DevcontainerConfig { + DevcontainerConfig { + path: path.into(), + name: name.map(Into::into), + } + } + + #[test] + fn discovery_lists_the_specification_places_in_order() { + let folder = Folder::new("places"); + folder.write(".devcontainer.json", r#"{"name": "Root"}"#); + folder.write(".devcontainer/devcontainer.json", r#"{"name": "Main"}"#); + folder.write(".devcontainer/zeta/devcontainer.json", "{}"); + folder.write( + ".devcontainer/alpha/devcontainer.json", + r#"{"name": " Alpha "}"#, + ); + folder.write(".devcontainer/empty/other.json", "{}"); + folder.write(".devcontainer/.hidden/devcontainer.json", "{}"); + folder.write(".devcontainer/deep/one/devcontainer.json", "{}"); + assert_eq!( + discover(&folder.0), + vec![ + config(".devcontainer/devcontainer.json", Some("Main")), + config(".devcontainer.json", Some("Root")), + config(".devcontainer/alpha/devcontainer.json", Some("Alpha")), + config(".devcontainer/zeta/devcontainer.json", None), + ] + ); + assert!(discover(&folder.0.join("absent")).is_empty()); + } + + #[test] + fn discovery_skips_folders_named_like_configurations() { + let folder = Folder::new("folders"); + std::fs::create_dir_all(folder.0.join(".devcontainer.json")).unwrap(); + assert!(discover(&folder.0).is_empty()); + } + + #[cfg(unix)] + #[test] + fn names_are_read_only_inside_the_folder() { + let folder = Folder::new("inside"); + let outside = Folder::new("outside"); + outside.write("devcontainer.json", r#"{"name": "Outside"}"#); + std::fs::create_dir_all(folder.0.join(".devcontainer")).unwrap(); + std::os::unix::fs::symlink( + outside.0.join("devcontainer.json"), + folder.0.join(".devcontainer/devcontainer.json"), + ) + .unwrap(); + assert_eq!( + discover(&folder.0), + vec![config(".devcontainer/devcontainer.json", None)] + ); + } + + #[test] + fn names_are_read_from_json_with_comments_and_trailing_commas() { + let text = r#"// Dev container for "the app" +{ + /* the picker shows this */ + "name": "App // not a comment", // trailing + "image": "mcr.microsoft.com/devcontainers/base:ubuntu", + "forwardPorts": [3000, 5432,], + "features": { + "ghcr.io/devcontainers/features/node:1": {}, + }, +}"#; + assert_eq!(config_name(text).as_deref(), Some("App // not a comment")); + assert_eq!( + config_name(r#"{"name": "a\"b, }"}"#).as_deref(), + Some("a\"b, }") + ); + assert_eq!( + config_name("{\"name\": \"n\", // last\n}").as_deref(), + Some("n") + ); + assert_eq!( + config_name("{\"name\": \"n\", /* x */ }").as_deref(), + Some("n") + ); + assert_eq!(config_name(r#"{"name": " "}"#), None); + assert_eq!(config_name(r#"{"name": 3}"#), None); + assert_eq!(config_name("{"), None); + assert_eq!( + config_name(r#"{"name": "x\u0007y"}"#).as_deref(), + Some("xy") + ); + let long = format!(r#"{{"name": "{}"}}"#, "é".repeat(100)); + assert_eq!(config_name(&long).unwrap().len(), 128); + } + + #[test] + fn up_passes_the_folder_the_configuration_and_podman_after_up() { + assert_eq!( + up_command(ContainerEngine::Docker, "/work/app", None), + [CLI, "up", "--workspace-folder", "/work/app"] + ); + assert_eq!( + up_command( + ContainerEngine::Podman, + "/work/app", + Some("/work/app/.devcontainer/python/devcontainer.json") + ), + [ + CLI, + "up", + "--workspace-folder", + "/work/app", + "--config", + "/work/app/.devcontainer/python/devcontainer.json", + "--docker-path", + "podman", + ] + ); + } + + #[test] + fn results_name_the_container_user_and_folder() { + let stdout = b"[2 ms] Start: Run\n{\"outcome\":\"success\",\"containerId\":\"0123abcd\",\"remoteUser\":\"vscode\",\"remoteWorkspaceFolder\":\"/workspaces/app\"}\n"; + assert_eq!( + parse_up_result(stdout), + Ok(StartedDevcontainer { + container_id: "0123abcd".into(), + remote_user: Some("vscode".into()), + remote_workspace_folder: "/workspaces/app".into(), + }) + ); + let without_user = + br#"{"outcome":"success","containerId":"c1","remoteWorkspaceFolder":"/w"}"#; + assert_eq!(parse_up_result(without_user).unwrap().remote_user, None); + } + + #[test] + fn failed_or_unusable_results_say_why() { + let reported = br#"{"outcome":"error","message":"Command failed: docker build","description":"An error occurred building the image."}"#; + assert_eq!( + parse_up_result(reported), + Err(UpFailure::Reported( + "Command failed: docker build\nAn error occurred building the image.".into() + )) + ); + assert_eq!( + parse_up_result(b"npm ERR! not found\n"), + Err(UpFailure::Missing) + ); + assert_eq!(parse_up_result(b"{\"other\":1}\n"), Err(UpFailure::Missing)); + for unusable in [ + r#"{"outcome":"success","containerId":"--privileged","remoteWorkspaceFolder":"/w"}"#, + r#"{"outcome":"success","containerId":"c","remoteUser":"a b","remoteWorkspaceFolder":"/w"}"#, + r#"{"outcome":"success","containerId":"c","remoteWorkspaceFolder":"w"}"#, + r#"{"outcome":"success","containerId":"c"}"#, + r#"{"outcome":"success","remoteWorkspaceFolder":"/w"}"#, + ] { + assert_eq!( + parse_up_result(unusable.as_bytes()), + Err(UpFailure::Unusable) + ); + } + } + + #[test] + fn names_come_from_inspect_without_the_leading_slash() { + assert_eq!( + name_command(ContainerEngine::Podman, "c1"), + ["podman", "inspect", "--format", "{{.Name}}", "c1"] + ); + assert_eq!( + parse_name(b"/vigilant_bassi\n").as_deref(), + Some("vigilant_bassi") + ); + assert_eq!( + parse_name(b"app_devcontainer-app-1\n").as_deref(), + Some("app_devcontainer-app-1") + ); + assert_eq!(parse_name(b"\n"), None); + assert_eq!(parse_name(b"-x\n"), None); + } +} diff --git a/rust/crates/remote/src/client/mod.rs b/rust/crates/remote/src/client/mod.rs index 3ddb5b03..12a76daa 100644 --- a/rust/crates/remote/src/client/mod.rs +++ b/rust/crates/remote/src/client/mod.rs @@ -6,6 +6,11 @@ //! local command line that runs a program at the end of the chain. //! - [`wsl`] turns a WSL distribution into the first hop and lists the //! installed distributions. +//! - [`container`] turns a running container into the last hop and lists +//! the running containers. +//! - [`devcontainer`] finds a folder's `devcontainer.json` files and reads +//! what the Dev Container CLI's `up` reports about the container it +//! started. //! - [`bootstrap`] probes the platform at the end of the chain and describes //! the local server builds that can run there. //! - [`launch`] probes, installs and starts the server over one connection, @@ -45,6 +50,8 @@ pub mod bootstrap; mod command; pub mod connection_log; pub mod connections; +pub mod container; +pub mod devcontainer; pub mod forward; pub mod forward_address; pub mod forward_set; @@ -63,6 +70,8 @@ pub mod wsl; pub use api::{SpawnSpec, TerminalSpec, WriteOptions}; pub use bootstrap::{ArtifactError, ServerArtifact, ServerTarget}; pub use connection_log::{ConnectionKind, ConnectionLog}; +pub use container::{ContainerConnection, ListedContainer}; +pub use devcontainer::{DevcontainerConfig, StartedDevcontainer, UpFailure}; pub use forward::PortForward; pub use forward_address::{AddressError, ForwardAddress}; pub use forward_set::{ diff --git a/rust/crates/remote/src/client/transport.rs b/rust/crates/remote/src/client/transport.rs index f39b8355..d6f656d3 100644 --- a/rust/crates/remote/src/client/transport.rs +++ b/rust/crates/remote/src/client/transport.rs @@ -253,8 +253,10 @@ impl SshHop { } } -/// Container engine whose CLI runs the `exec`. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] +/// Container engine whose CLI runs the `exec`; `docker` or `podman` in +/// requests. +#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "lowercase")] pub enum ContainerEngine { /// Docker, or a Docker-compatible CLI. Docker, @@ -263,7 +265,8 @@ pub enum ContainerEngine { } impl ContainerEngine { - pub(crate) fn name(self) -> &'static str { + /// The engine CLI's executable name, which `PATH` resolves. + pub fn name(self) -> &'static str { match self { Self::Docker => "docker", Self::Podman => "podman", @@ -304,6 +307,32 @@ impl ContainerHop { } } +/// Longest container name or id, in bytes. Ids are 64 hexadecimal digits; +/// the bound only refuses garbage. +pub(crate) const MAX_CONTAINER_NAME_BYTES: usize = 128; + +/// Longest container user, in bytes: a name or uid, optionally with a group. +pub(crate) const MAX_CONTAINER_USER_BYTES: usize = 64; + +/// A container name or id the engine CLI cannot read as an option: ASCII +/// letters, digits, `.`, `_` and `-`, starting with a letter or digit, at +/// most [`MAX_CONTAINER_NAME_BYTES`] long. +pub(crate) fn is_container_name(name: &str) -> bool { + name.len() <= MAX_CONTAINER_NAME_BYTES && is_plain_name(name) +} + +/// A `--user` value for `exec`: a name or uid, optionally `:group`, from +/// ASCII letters, digits, `_`, `.`, `:` and `-`, not starting with `-`, at +/// most [`MAX_CONTAINER_USER_BYTES`] long. +pub(crate) fn is_container_user(user: &str) -> bool { + !user.is_empty() + && user.len() <= MAX_CONTAINER_USER_BYTES + && !user.starts_with('-') + && user + .chars() + .all(|character| character.is_ascii_alphanumeric() || "_.:-".contains(character)) +} + /// Why a transport chain could not build a command line. #[derive(Clone, Debug, Eq, PartialEq)] pub enum TransportError { @@ -549,19 +578,14 @@ fn ssh_options(hop: &SshHop) -> Result, TransportError> { } fn container_command(hop: &ContainerHop, inner: Vec) -> Result, TransportError> { - if !is_plain_name(&hop.container) { + if !is_container_name(&hop.container) { return Err(TransportError::InvalidHop { reason: format!("invalid container name {:?}", hop.container), }); } let mut command = vec![hop.program.clone(), "exec".into(), "-i".into()]; if let Some(user) = &hop.user { - if user.is_empty() - || user.starts_with('-') - || !user - .chars() - .all(|character| character.is_ascii_alphanumeric() || "_.:-".contains(character)) - { + if !is_container_user(user) { return Err(TransportError::InvalidHop { reason: format!("invalid container user {user:?}"), }); diff --git a/rust/crates/workspace/src/containers.rs b/rust/crates/workspace/src/containers.rs new file mode 100644 index 00000000..d8f1d493 --- /dev/null +++ b/rust/crates/workspace/src/containers.rs @@ -0,0 +1,294 @@ +//! `remote.listContainers`: the running containers of one container engine, +//! on this machine or on the host of a connected session, for the connection +//! window. +//! +//! The list comes from the engine CLI's `ps` each time the window asks; +//! nothing is saved. Lithe only lists and enters running containers: it never +//! starts, creates or changes one, so stopped containers are not offered +//! (S32). Connecting to a container is `remote.connect` with `container`. + +use lithe_protocol::{CoreError, ErrorCode}; +use lithe_remote::client::container::{list_command, parse_containers, MAX_LIST_BYTES}; +use lithe_remote::client::{ContainerEngine, ListedContainer}; +use lithe_remote::protocol::methods; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::process::Command; +use std::time::{Duration, Instant}; + +/// How long the engine CLI may take. The first call can start the engine's +/// service or virtual machine, which takes a few seconds. +const LIST_TIMEOUT: Duration = Duration::from_secs(15); + +/// `remote.listContainers` request. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ListRequest { + /// Engine whose CLI lists the containers. + pub engine: ContainerEngine, + /// Connected session whose host runs the engine; this machine when + /// absent. + #[serde(default)] + pub session_id: Option, +} + +/// `remote.listContainers` result. +#[derive(Debug, Default, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Containers { + /// The engine CLI ran. `false` when the host has no such CLI. + pub available: bool, + /// Running containers in the engine's order, at most + /// [`lithe_remote::client::container::MAX_CONTAINERS`]. + pub containers: Vec, + /// What the CLI printed when it failed, such as the message that its + /// service is not running, redacted; empty otherwise. Shown, never + /// logged. + pub diagnostics: String, +} + +/// The running containers `request` asks for. +pub fn list(request: ListRequest) -> Result { + list_with(request, None) +} + +/// `program` replaces the engine CLI on this machine or on the host; tests +/// use a stand-in. +pub(crate) fn list_with( + request: ListRequest, + program: Option<&str>, +) -> Result { + let mut argv = list_command(request.engine); + if let Some(program) = program { + argv[0] = program.into(); + } + match request.session_id { + None => list_here(&argv), + Some(session_id) => list_on_host(&session_id, argv), + } +} + +/// Runs the listing on this machine, in Core's own environment, which holds +/// the login shell's `PATH` and the variables, such as `DOCKER_HOST`, that +/// choose the engine. +fn list_here(argv: &[String]) -> Result { + let (program, arguments) = argv.split_first().expect("the listing names the engine"); + let mut process = Command::new(program); + process.args(arguments); + let deadline = Instant::now() + LIST_TIMEOUT; + let mut stop = None; + let outcome = lithe_git_host::run( + &mut process, + None, + || { + if let Err(error) = lithe_protocol::cancellation::check() { + stop = Some(error); + } else if Instant::now() >= deadline { + stop = Some(timed_out()); + } + stop.is_some() + }, + || {}, + |_, _| {}, + ); + if let Some(error) = stop { + return Err(error); + } + match outcome.failure { + None => {} + // No such CLI on this machine. + Some(lithe_git_host::Failure::Start(_)) => return Ok(Containers::default()), + Some(failure) => { + return Err( + CoreError::new(ErrorCode::ProcessFailed, "The container engine failed") + .with_details(format!("{failure:?}")), + ) + } + } + Ok(answer( + outcome.status.is_some_and(|status| status.success()), + &outcome.stdout, + &outcome.stderr, + )) +} + +/// Runs the listing on the host of session `session_id`, in the server's +/// environment there. The connection later enters the container from the +/// same kind of non-login shell that started the server, so the listing finds +/// the CLI, and the engine it talks to, exactly when the connection will. +fn list_on_host(session_id: &str, argv: Vec) -> Result { + let params = methods::SpawnParams { + process_id: 0, + argv, + cwd: None, + environment: methods::EnvironmentSource::Server, + env: BTreeMap::new(), + pipe_stdin: false, + label: None, + }; + let captured = match crate::host::capture(session_id, params, LIST_TIMEOUT, MAX_LIST_BYTES) { + Ok(captured) => captured, + // The host could not start the CLI: it has no such engine. + Err(error) if is_spawn_failure(&error) => return Ok(Containers::default()), + Err(error) if matches!(error.code, ErrorCode::TimedOut) => return Err(timed_out()), + Err(error) => return Err(error), + }; + // A shell wrapper that found no such command. + if captured.exit["exitCode"] == 127 { + return Ok(Containers::default()); + } + Ok(answer( + captured.exit["exitCode"] == 0, + &captured.stdout, + &captured.stderr, + )) +} + +/// A failed `process.spawn`, which the host reports when the program does +/// not exist or may not run. +fn is_spawn_failure(error: &CoreError) -> bool { + matches!(error.code, ErrorCode::ProcessFailed) + && error + .details + .as_deref() + .and_then(|details| serde_json::from_str::(details).ok()) + .is_some_and(|details| details["remoteCode"] == "SPAWN_FAILED") +} + +fn timed_out() -> CoreError { + CoreError::new( + ErrorCode::TimedOut, + "The container engine did not list the containers in time", + ) +} + +/// The listing of a CLI that ran: its containers when it succeeded, or what +/// it printed about the failure. +fn answer(succeeded: bool, stdout: &[u8], stderr: &[u8]) -> Containers { + if succeeded { + return Containers { + available: true, + containers: parse_containers(stdout), + diagnostics: String::new(), + }; + } + let mut printed = String::from_utf8_lossy(stdout).into_owned(); + printed.push('\n'); + printed.push_str(&String::from_utf8_lossy(stderr)); + Containers { + available: true, + containers: Vec::new(), + diagnostics: crate::probe::diagnostics(&printed), + } +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use std::os::unix::fs::PermissionsExt; + use std::path::PathBuf; + use std::sync::atomic::{AtomicU64, Ordering}; + + /// A stand-in engine CLI: a shell script in its own directory. + struct FakeEngine { + root: PathBuf, + program: String, + } + + impl FakeEngine { + fn new(label: &str, body: &str) -> Self { + static SEQUENCE: AtomicU64 = AtomicU64::new(0); + let root = std::env::temp_dir().join(format!( + "lithe-container-list-{label}-{}-{}", + std::process::id(), + SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let program = root.join("docker"); + std::fs::write(&program, format!("#!/bin/sh\n{body}\n")).unwrap(); + std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap(); + Self { + root, + program: program.to_string_lossy().into_owned(), + } + } + } + + impl Drop for FakeEngine { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.root); + } + } + + fn here(engine: ContainerEngine) -> ListRequest { + ListRequest { + engine, + session_id: None, + } + } + + #[test] + fn listings_run_ps_on_this_machine_and_read_its_lines() { + let fake = FakeEngine::new( + "running", + r#"printf '%s\n' "$@" > "$0.arguments" +printf 'abc123\tweb,alias\tnginx:1\tUp 2 hours\n'"#, + ); + let listed = list_with(here(ContainerEngine::Podman), Some(&fake.program)).unwrap(); + assert_eq!( + listed, + Containers { + available: true, + containers: vec![ListedContainer { + id: "abc123".into(), + name: "web".into(), + image: "nginx:1".into(), + status: "Up 2 hours".into(), + }], + diagnostics: String::new(), + } + ); + let arguments = std::fs::read_to_string(format!("{}.arguments", fake.program)).unwrap(); + assert_eq!( + arguments, + "ps\n--no-trunc\n--format\n{{.ID}}\t{{.Names}}\t{{.Image}}\t{{.Status}}\n" + ); + } + + #[test] + fn failed_listings_are_available_with_the_message_and_no_containers() { + let fake = FakeEngine::new( + "stopped", + "printf 'Cannot connect to the Docker daemon. Is the docker daemon running?\\n' >&2\nexit 1", + ); + let listed = list_with(here(ContainerEngine::Docker), Some(&fake.program)).unwrap(); + assert!(listed.available); + assert!(listed.containers.is_empty()); + assert_eq!( + listed.diagnostics, + "Cannot connect to the Docker daemon. Is the docker daemon running?" + ); + } + + #[test] + fn a_missing_engine_is_unavailable() { + let fake = FakeEngine::new("missing", "exit 0"); + let missing = fake.root.join("absent").to_string_lossy().into_owned(); + assert_eq!( + list_with(here(ContainerEngine::Docker), Some(&missing)).unwrap(), + Containers::default() + ); + } + + #[test] + fn requests_name_a_known_engine_and_nothing_else() { + let decode = |value| serde_json::from_value::(value); + let request = decode(serde_json::json!({"engine": "podman", "sessionId": "s"})).unwrap(); + assert_eq!(request.engine, ContainerEngine::Podman); + assert_eq!(request.session_id.as_deref(), Some("s")); + assert!(decode(serde_json::json!({"engine": "nerdctl"})).is_err()); + assert!(decode(serde_json::json!({"engine": "docker", "program": "sh"})).is_err()); + assert!(decode(serde_json::json!({})).is_err()); + } +} diff --git a/rust/crates/workspace/src/devcontainers.rs b/rust/crates/workspace/src/devcontainers.rs new file mode 100644 index 00000000..d0c51400 --- /dev/null +++ b/rust/crates/workspace/src/devcontainers.rs @@ -0,0 +1,595 @@ +//! `remote.devcontainerConfigs` and `remote.devcontainerUp`: a local +//! folder's Dev Container, built and started by the reference Dev Container +//! CLI, for the connection window. +//! +//! The window lists the folder's `devcontainer.json` files, then asks for +//! `up` with the one the user picked. The CLI builds or reuses the container +//! exactly as the configuration says, mounts included, and runs its +//! lifecycle commands; its log streams to the window as `devcontainerOutput` +//! events, redacted and never logged. The result names the container, the +//! user and the workspace folder inside it, which the window then enters +//! with `remote.connect`'s `container` and opens. Nothing is saved. +//! +//! Building runs the folder's code on this machine (`initializeCommand`, +//! Dockerfiles, feature scripts), so `up` runs only when the host says the +//! folder is trusted (`projectCodeAllowed`), the same rule as Git. Lithe +//! itself adds no mounts and no options to the configuration (S32). + +use lithe_protocol::{CoreError, ErrorCode}; +use lithe_remote::client::devcontainer::{ + discover, name_command, parse_name, parse_up_result, up_command, UpFailure, +}; +use lithe_remote::client::{ContainerEngine, DevcontainerConfig}; +use lithe_request_context::events as execution_events; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::{Duration, Instant}; + +/// How long `up` may take: pulling images and building them can take many +/// minutes on a slow connection. +const UP_TIMEOUT: Duration = Duration::from_secs(60 * 60); + +/// How long the engine may take to name the container. +const NAME_TIMEOUT: Duration = Duration::from_secs(15); + +/// Bytes of the CLI's log sent to the window; later lines are dropped and +/// one `truncated` event says so. +const MAX_STREAMED_BYTES: usize = 2 * 1024 * 1024; + +/// Longest log line sent, in bytes; a longer one is sent in parts. +const MAX_LINE_BYTES: usize = 4096; + +/// `remote.devcontainerConfigs` request. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ConfigsRequest { + /// Absolute folder on this machine. + pub folder: String, +} + +/// `remote.devcontainerConfigs` result. +#[derive(Debug, Default, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Configs { + /// The folder's configurations in the order the specification searches + /// them; empty when it has none. + pub configs: Vec, +} + +/// `remote.devcontainerUp` request. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct UpRequest { + /// Absolute folder on this machine. + pub folder: String, + /// One of the `path`s `remote.devcontainerConfigs` listed; the CLI's own + /// search when absent. + #[serde(default)] + pub config: Option, + /// Engine the CLI builds and runs the container with. + pub engine: ContainerEngine, + /// Whether the user trusts the folder, so its code may run here. + pub project_code_allowed: bool, +} + +/// `remote.devcontainerUp` result. +#[derive(Debug, Default, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Up { + /// The running container; absent when the CLI reported a failure. + #[serde(skip_serializing_if = "Option::is_none")] + pub container: Option, + /// What the CLI reported about the failure, redacted; empty otherwise. + /// Shown, never logged. + pub diagnostics: String, +} + +/// The container `up` started, as `remote.connect`'s `container` takes it, +/// and the folder to open in it. +#[derive(Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Devcontainer { + /// Engine that runs the container. + pub engine: ContainerEngine, + /// The container's name, or its id when the engine did not name it. + pub container: String, + /// Full container id. + pub container_id: String, + /// User the configuration connects as; the image's default when absent. + #[serde(skip_serializing_if = "Option::is_none")] + pub user: Option, + /// Absolute folder inside the container that holds the workspace. + pub workspace_folder: String, +} + +/// The configurations of the folder `request` names. +pub fn configs(request: ConfigsRequest) -> Result { + let folder = local_folder(&request.folder)?; + Ok(Configs { + configs: discover(&folder), + }) +} + +/// Builds or reuses and starts the dev container `request` names. +pub fn up(request: UpRequest) -> Result { + up_with(request, None) +} + +/// `program` replaces both the Dev Container CLI and the engine CLI; tests +/// use one stand-in for both. +pub(crate) fn up_with(request: UpRequest, program: Option<&str>) -> Result { + if !request.project_code_allowed { + return Err(CoreError::new( + ErrorCode::DevcontainerUntrustedFolder, + "The folder is not trusted, so its dev container was not built or started", + )); + } + let folder = local_folder(&request.folder)?; + let config = match request.config.as_deref() { + None => None, + Some(config) => { + if !discover(&folder).iter().any(|listed| listed.path == config) { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "The configuration is not one of the folder's devcontainer.json files", + )); + } + Some(folder.join(config).to_string_lossy().into_owned()) + } + }; + let mut argv = up_command(request.engine, &folder.to_string_lossy(), config.as_deref()); + if let Some(program) = program { + argv[0] = program.into(); + } + let mut log = Log::default(); + let outcome = run_here(&argv, UP_TIMEOUT, |stream, bytes| { + if matches!(stream, lithe_git_host::Stream::Stderr) { + log.push(bytes); + } + }) + .map_err(|error| match error { + Ran::Stopped(error) => error, + Ran::Missing => CoreError::new( + ErrorCode::RuntimeMissing, + "The Dev Container CLI (devcontainer) is not installed", + ), + })?; + log.finish(); + match parse_up_result(&outcome.stdout) { + Ok(started) => { + let container = container_name(request.engine, &started.container_id, program) + .unwrap_or_else(|| started.container_id.clone()); + Ok(Up { + container: Some(Devcontainer { + engine: request.engine, + container, + container_id: started.container_id, + user: started.remote_user, + workspace_folder: started.remote_workspace_folder, + }), + diagnostics: String::new(), + }) + } + Err(UpFailure::Reported(message)) => { + let mut printed = String::from_utf8_lossy(&outcome.stderr) + .trim_end() + .to_string(); + printed.push('\n'); + printed.push_str(&message); + Ok(failed(&printed)) + } + Err(UpFailure::Missing) if !outcome.status.is_some_and(|status| status.success()) => { + let mut printed = String::from_utf8_lossy(&outcome.stdout).into_owned(); + printed.push('\n'); + printed.push_str(&String::from_utf8_lossy(&outcome.stderr)); + Ok(failed(&printed)) + } + Err(UpFailure::Missing | UpFailure::Unusable) => Err(CoreError::new( + ErrorCode::ParseFailed, + "The Dev Container CLI did not report a container Lithe can enter", + )), + } +} + +fn failed(printed: &str) -> Up { + Up { + container: None, + diagnostics: crate::probe::diagnostics(printed), + } +} + +/// The existing absolute folder `folder` names on this machine. +fn local_folder(folder: &str) -> Result { + let path = Path::new(folder); + if folder.is_empty() || !path.is_absolute() { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "The dev container folder must be an absolute path", + )); + } + if !path.is_dir() { + return Err(CoreError::new( + ErrorCode::WorkspaceNotFound, + "The dev container folder does not exist", + )); + } + Ok(path.to_path_buf()) +} + +/// The name the engine gives container `id`, when it answers in time. +fn container_name(engine: ContainerEngine, id: &str, program: Option<&str>) -> Option { + let mut argv = name_command(engine, id); + if let Some(program) = program { + argv[0] = program.into(); + } + let outcome = run_here(&argv, NAME_TIMEOUT, |_, _| {}).ok()?; + if !outcome.status.is_some_and(|status| status.success()) { + return None; + } + parse_name(&outcome.stdout) +} + +/// Why [`run_here`] has no outcome. +enum Ran { + /// Cancelled, out of time or failed while running. + Stopped(CoreError), + /// The program does not exist here. + Missing, +} + +/// Runs `argv` on this machine, in Core's own environment, which holds the +/// login shell's `PATH` and the variables, such as `DOCKER_HOST`, that +/// choose the engine. +fn run_here( + argv: &[String], + timeout: Duration, + output: impl FnMut(lithe_git_host::Stream, &[u8]), +) -> Result { + let (program, arguments) = argv.split_first().expect("the command names a program"); + let mut process = Command::new(program); + process.args(arguments); + let deadline = Instant::now() + timeout; + let mut stop = None; + let outcome = lithe_git_host::run( + &mut process, + None, + || { + if let Err(error) = lithe_protocol::cancellation::check() { + stop = Some(error); + } else if Instant::now() >= deadline { + stop = Some(CoreError::new( + ErrorCode::TimedOut, + "The dev container did not start in time", + )); + } + stop.is_some() + }, + || {}, + output, + ); + if let Some(error) = stop { + return Err(Ran::Stopped(error)); + } + match outcome.failure { + None => Ok(outcome), + Some(lithe_git_host::Failure::Start(_)) => Err(Ran::Missing), + Some(failure) => Err(Ran::Stopped( + CoreError::new(ErrorCode::ProcessFailed, "The Dev Container CLI failed") + .with_details(format!("{failure:?}")), + )), + } +} + +/// The CLI's log, sent to the window line by line. +#[derive(Default)] +struct Log { + pending: Vec, + sent: usize, + truncated: bool, +} + +impl Log { + fn push(&mut self, bytes: &[u8]) { + self.pending.extend_from_slice(bytes); + while let Some(end) = self.pending.iter().position(|byte| *byte == b'\n') { + let line: Vec = self.pending.drain(..=end).collect(); + self.send(&line); + } + while self.pending.len() > MAX_LINE_BYTES { + let part: Vec = self.pending.drain(..MAX_LINE_BYTES).collect(); + self.send(&part); + } + } + + fn finish(&mut self) { + if !self.pending.is_empty() { + let rest = std::mem::take(&mut self.pending); + self.send(&rest); + } + } + + fn send(&mut self, line: &[u8]) { + if self.truncated { + return; + } + if self.sent + line.len() > MAX_STREAMED_BYTES { + self.truncated = true; + execution_events::emit(json!({ "type": "devcontainerOutput", "truncated": true })); + return; + } + self.sent += line.len(); + let text = String::from_utf8_lossy(line); + let text = text.trim_end_matches(['\r', '\n']); + execution_events::emit(json!({ + "type": "devcontainerOutput", + "text": execution_events::redact(text), + })); + } +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use std::os::unix::fs::PermissionsExt; + use std::sync::atomic::{AtomicU64, Ordering}; + + /// A folder with a configuration and a stand-in CLI beside it: the + /// script answers `up` with `up_body` and `inspect` with `name_body`. + struct Fixture { + root: PathBuf, + folder: PathBuf, + program: String, + } + + impl Fixture { + fn new(label: &str, up_body: &str, name_body: &str) -> Self { + static SEQUENCE: AtomicU64 = AtomicU64::new(0); + let root = std::env::temp_dir().join(format!( + "lithe-devcontainer-up-{label}-{}-{}", + std::process::id(), + SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + let _ = std::fs::remove_dir_all(&root); + let folder = root.join("app"); + std::fs::create_dir_all(folder.join(".devcontainer/python")).unwrap(); + std::fs::write( + folder.join(".devcontainer/python/devcontainer.json"), + "{ \"name\": \"Python\", }", + ) + .unwrap(); + let program = root.join("devcontainer"); + std::fs::write( + &program, + format!( + "#!/bin/sh\nprintf '%s\\n' \"$@\" >> \"$0.arguments\"\nif [ \"$1\" = up ]; then\n{up_body}\nelse\n{name_body}\nfi\n" + ), + ) + .unwrap(); + std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap(); + Self { + root, + folder, + program: program.to_string_lossy().into_owned(), + } + } + + fn request(&self, config: Option<&str>, trusted: bool) -> UpRequest { + UpRequest { + folder: self.folder.to_string_lossy().into_owned(), + config: config.map(Into::into), + engine: ContainerEngine::Podman, + project_code_allowed: trusted, + } + } + + fn arguments(&self) -> String { + std::fs::read_to_string(format!("{}.arguments", self.program)).unwrap_or_default() + } + } + + impl Drop for Fixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.root); + } + } + + const STARTED: &str = r#"printf '[1 ms] Start: Run\n' >&2 +printf '{"outcome":"success","containerId":"abc123","remoteUser":"vscode","remoteWorkspaceFolder":"/workspaces/app"}\n'"#; + + #[test] + fn up_starts_the_picked_configuration_and_names_the_container() { + let fixture = Fixture::new("started", STARTED, "printf '/eager_turing\\n'"); + let config = ".devcontainer/python/devcontainer.json"; + let up = up_with(fixture.request(Some(config), true), Some(&fixture.program)).unwrap(); + assert_eq!( + up, + Up { + container: Some(Devcontainer { + engine: ContainerEngine::Podman, + container: "eager_turing".into(), + container_id: "abc123".into(), + user: Some("vscode".into()), + workspace_folder: "/workspaces/app".into(), + }), + diagnostics: String::new(), + } + ); + let folder = fixture.folder.to_string_lossy(); + assert_eq!( + fixture.arguments(), + format!( + "up\n--workspace-folder\n{folder}\n--config\n{folder}/{config}\n--docker-path\npodman\ninspect\n--format\n{{{{.Name}}}}\nabc123\n" + ) + ); + } + + #[test] + fn an_unnamed_container_is_entered_by_its_id() { + let fixture = Fixture::new("unnamed", STARTED, "exit 1"); + let up = up_with(fixture.request(None, true), Some(&fixture.program)).unwrap(); + assert_eq!(up.container.unwrap().container, "abc123"); + } + + #[test] + fn untrusted_folders_run_nothing() { + let fixture = Fixture::new("untrusted", STARTED, "exit 0"); + let error = up_with(fixture.request(None, false), Some(&fixture.program)).unwrap_err(); + assert!(matches!(error.code, ErrorCode::DevcontainerUntrustedFolder)); + assert_eq!(fixture.arguments(), ""); + } + + #[test] + fn only_listed_configurations_are_accepted() { + let fixture = Fixture::new("unlisted", STARTED, "exit 0"); + for config in [ + "../outside.json", + "/etc/devcontainer.json", + ".devcontainer/x.json", + ] { + let error = + up_with(fixture.request(Some(config), true), Some(&fixture.program)).unwrap_err(); + assert!(matches!(error.code, ErrorCode::InvalidRequest)); + } + assert_eq!(fixture.arguments(), ""); + } + + #[test] + fn reported_failures_are_shown_with_the_log_tail() { + let fixture = Fixture::new( + "failed", + r#"printf 'Step 3/7 failed\n' >&2 +printf '{"outcome":"error","message":"Command failed: docker build","description":"An error occurred building the image."}\n' +exit 1"#, + "exit 0", + ); + let up = up_with(fixture.request(None, true), Some(&fixture.program)).unwrap(); + assert_eq!(up.container, None); + assert_eq!( + up.diagnostics, + "Step 3/7 failed\nCommand failed: docker build\nAn error occurred building the image." + ); + } + + #[test] + fn a_missing_cli_is_a_missing_runtime() { + let fixture = Fixture::new("missing", STARTED, "exit 0"); + let missing = fixture.root.join("absent").to_string_lossy().into_owned(); + let error = up_with(fixture.request(None, true), Some(&missing)).unwrap_err(); + assert!(matches!(error.code, ErrorCode::RuntimeMissing)); + } + + #[test] + fn a_success_without_a_usable_container_cannot_be_read() { + let fixture = Fixture::new("unusable", "printf 'done\\n'", "exit 0"); + let error = up_with(fixture.request(None, true), Some(&fixture.program)).unwrap_err(); + assert!(matches!(error.code, ErrorCode::ParseFailed)); + } + + #[test] + fn configurations_are_listed_for_absolute_existing_folders() { + let fixture = Fixture::new("configs", STARTED, "exit 0"); + let listed = configs(ConfigsRequest { + folder: fixture.folder.to_string_lossy().into_owned(), + }) + .unwrap(); + assert_eq!( + listed.configs, + vec![DevcontainerConfig { + path: ".devcontainer/python/devcontainer.json".into(), + name: Some("Python".into()), + }] + ); + let relative = configs(ConfigsRequest { + folder: "app".into(), + }); + assert!(matches!( + relative.unwrap_err().code, + ErrorCode::InvalidRequest + )); + let absent = configs(ConfigsRequest { + folder: fixture.root.join("absent").to_string_lossy().into_owned(), + }); + assert!(matches!( + absent.unwrap_err().code, + ErrorCode::WorkspaceNotFound + )); + } + + #[test] + fn requests_name_the_trust_decision_and_nothing_else() { + let decode = |value| serde_json::from_value::(value); + assert!(decode(json!({"folder": "/a", "engine": "docker"})).is_err()); + assert!(decode( + json!({"folder": "/a", "engine": "docker", "projectCodeAllowed": true, "mount": "/"}) + ) + .is_err()); + let request = + decode(json!({"folder": "/a", "engine": "docker", "projectCodeAllowed": true})) + .unwrap(); + assert_eq!(request.config, None); + } + + /// The `devcontainerOutput` events one run of `log` sends. + fn log_events(log: impl FnOnce(&mut Log)) -> Vec { + let observed = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let records = std::sync::Arc::clone(&observed); + let sink: execution_events::EventSink = std::sync::Arc::new(move |raw: &str| { + let event: serde_json::Value = serde_json::from_str(raw).unwrap(); + records.lock().unwrap().push(event); + }); + execution_events::with_sink(sink, || { + let mut state = Log::default(); + log(&mut state); + state.finish(); + }); + let events = observed.lock().unwrap().clone(); + assert!(events + .iter() + .all(|event| event["type"] == "devcontainerOutput")); + events + } + + #[test] + fn the_log_is_sent_line_by_line_and_redacted() { + let events = log_events(|log| { + // A credential split across two reads is redacted as one line, + // and a CRLF ending is not part of the text. + log.push(b"[1 ms] Start: Run: docker build\r\n[2 ms] pull https://ci:hunter2@"); + log.push(b"registry.example/app\n"); + // A line longer than one event is sent in parts; the rest of it + // is sent when the CLI exits. + log.push(&vec![b'x'; MAX_LINE_BYTES + 10]); + }); + let texts: Vec<&str> = events + .iter() + .map(|event| event["text"].as_str().unwrap()) + .collect(); + assert_eq!(texts.len(), 4, "{texts:?}"); + assert_eq!(texts[0], "[1 ms] Start: Run: docker build"); + assert!(!texts[1].contains("hunter2"), "{}", texts[1]); + assert!(texts[1].contains("registry.example/app"), "{}", texts[1]); + assert_eq!(texts[2].len(), MAX_LINE_BYTES); + assert_eq!(texts[3].len(), 10); + assert!(events.iter().all(|event| event.get("truncated").is_none())); + } + + #[test] + fn the_log_stops_once_after_its_bound() { + let line = [vec![b'y'; 4000], vec![b'\n']].concat(); + let sent = MAX_STREAMED_BYTES / line.len(); + let events = log_events(|log| { + for _ in 0..sent + 20 { + log.push(&line); + } + log.push(b"after the bound\n"); + }); + assert_eq!(events.len(), sent + 1); + assert!(events[..sent] + .iter() + .all(|event| event["text"].as_str().map(str::len) == Some(4000))); + assert_eq!(events[sent]["truncated"], true); + assert!(events[sent].get("text").is_none()); + } +} diff --git a/rust/crates/workspace/src/host.rs b/rust/crates/workspace/src/host.rs index 01fb10a9..22e4bb22 100644 --- a/rust/crates/workspace/src/host.rs +++ b/rust/crates/workspace/src/host.rs @@ -147,21 +147,52 @@ pub fn capture_process(request: CaptureRequest) -> Result { "Invalid host capture limits", )); } - let connection = lookup(&request.session_id)?; + let captured = capture( + &request.session_id, + request.params, + Duration::from_millis(request.timeout_milliseconds), + request.max_output_bytes, + )?; + Ok(json!({ + "stdout": methods::encode_bytes(&captured.stdout), + "stderr": methods::encode_bytes(&captured.stderr), + "exitCode": captured.exit["exitCode"], + "signal": captured.exit["signal"], + })) +} + +/// What [`capture`] collected from one host process. +pub(crate) struct Captured { + pub(crate) stdout: Vec, + pub(crate) stderr: Vec, + /// The process's `exit` event: `exitCode` and `signal`. + pub(crate) exit: Value, +} + +/// Runs `params` on the host of session `session_id` and collects both +/// output streams, killing the process when it runs longer than `timeout` or +/// prints more than `max_output_bytes` in all. +pub(crate) fn capture( + session_id: &str, + params: methods::SpawnParams, + timeout: Duration, + max_output_bytes: usize, +) -> Result { + let connection = lookup(session_id)?; let mut stdout = Vec::new(); let mut stderr = Vec::new(); let exit = run_observing( &connection.session, Request { - session_id: request.session_id, + session_id: session_id.into(), method: String::new(), - params: serde_json::to_value(request.params).expect("spawn parameters encode"), + params: serde_json::to_value(params).expect("spawn parameters encode"), timeout_milliseconds: None, }, "process", methods::PROCESS_SPAWN, None, - Some(Instant::now() + Duration::from_millis(request.timeout_milliseconds)), + Some(Instant::now() + timeout), &mut |event| { if event.event == methods::EVENT_PROCESS_OUTPUT { let output: methods::ProcessOutputEvent = event.decode().map_err(|error| { @@ -172,7 +203,7 @@ pub fn capture_process(request: CaptureRequest) -> Result { CoreError::new(ErrorCode::ParseFailed, "Invalid host process bytes") .with_details(error.to_string()) })?; - if stdout.len() + stderr.len() + bytes.len() > request.max_output_bytes { + if stdout.len() + stderr.len() + bytes.len() > max_output_bytes { return Err(CoreError::new( ErrorCode::ProcessFailed, "Host process output exceeded its limit", @@ -186,10 +217,11 @@ pub fn capture_process(request: CaptureRequest) -> Result { Ok(()) }, )?; - Ok( - json!({"stdout": methods::encode_bytes(&stdout), "stderr": methods::encode_bytes(&stderr), - "exitCode": exit["exitCode"], "signal": exit["signal"]}), - ) + Ok(Captured { + stdout, + stderr, + exit, + }) } struct Resource<'a> { diff --git a/rust/crates/workspace/src/lib.rs b/rust/crates/workspace/src/lib.rs index cb5295a5..4c397782 100644 --- a/rust/crates/workspace/src/lib.rs +++ b/rust/crates/workspace/src/lib.rs @@ -11,9 +11,13 @@ //! the SSH connections the user saved, [`ssh_configuration`] tells what //! OpenSSH makes of them and lists the hosts of the user's SSH configuration, //! [`motty`] lists the hosts saved in Motty for an import, [`wsl`] lists the -//! WSL distributions of this Windows machine, [`probe`] checks that a saved -//! SSH connection reaches a usable host, [`sessions`] opens and keeps the -//! connections (over OpenSSH or `wsl.exe`), [`host`] forwards finite requests +//! WSL distributions of this Windows machine, [`containers`] lists the +//! running containers on this machine or a connected host, [`devcontainers`] +//! builds and starts a local folder's dev container with the Dev Container +//! CLI, [`probe`] checks +//! that a saved SSH connection reaches a usable host, [`sessions`] opens and +//! keeps the connections (over OpenSSH, `wsl.exe` or a container engine's +//! `exec`), [`host`] forwards finite requests //! and owned streaming resources (processes, terminals, watches), //! [`forwards`] keeps the port forwards of the ports page, [`upload`] streams //! a verified file to the host, [`trust`] keys remote workspace trust by @@ -23,6 +27,8 @@ //! this crate only supplies the IO boundary. pub mod connections; +pub mod containers; +pub mod devcontainers; pub mod forwards; pub mod fs; pub mod host; diff --git a/rust/crates/workspace/src/probe.rs b/rust/crates/workspace/src/probe.rs index d66d8bda..8e37f1d1 100644 --- a/rust/crates/workspace/src/probe.rs +++ b/rust/crates/workspace/src/probe.rs @@ -287,6 +287,51 @@ pub(crate) fn classify_wsl(exit: Option, stderr: &[u8]) -> ProbeResu } } +/// Interprets a local container engine CLI that exited before the server +/// started, from what it printed (see [`container_status`]). +pub(crate) fn classify_container( + exit: Option, + stderr: &[u8], + engine: lithe_remote::client::ContainerEngine, +) -> ProbeResult { + let text = String::from_utf8_lossy(stderr); + ProbeResult { + status: container_status(&text).unwrap_or(ProbeStatus::Failed), + host: None, + diagnostics: or_exit_status(diagnostics(&text), engine.name(), exit), + } +} + +/// What a container engine's CLI printed when `exec` failed, as a status: +/// a container that does not exist, is not running or is paused, and an +/// engine whose service does not answer, are unreachable, like an unknown +/// host; a service socket the user may not open is a failure the message +/// explains, not a rejected SSH login. `None` when the text holds none of +/// the Docker or Podman messages, so the client that reached the host +/// decides. +pub(crate) fn container_status(text: &str) -> Option { + let lower = text.to_ascii_lowercase(); + let mentions = |needles: &[&str]| needles.iter().any(|needle| lower.contains(needle)); + if mentions(&[ + "permission denied while trying to connect to the docker daemon", + "docker.sock: connect: permission denied", + "podman.sock: connect: permission denied", + ]) { + Some(ProbeStatus::Failed) + } else if mentions(&[ + "no such container", + "is not running", + "is paused", + "container state improper", + "cannot connect to the docker daemon", + "cannot connect to podman", + ]) { + Some(ProbeStatus::Unreachable) + } else { + None + } +} + /// `diagnostics`, or the exit status of `program` when it printed nothing: /// some failures, such as a remote shell that exits early, are silent. fn or_exit_status(diagnostics: String, program: &str, exit: Option) -> String { diff --git a/rust/crates/workspace/src/probe/tests.rs b/rust/crates/workspace/src/probe/tests.rs index 56497b62..e47d1934 100644 --- a/rust/crates/workspace/src/probe/tests.rs +++ b/rust/crates/workspace/src/probe/tests.rs @@ -470,6 +470,164 @@ fn connections_name_exactly_one_client() { assert!(!wsl.program.with_extension("ran").exists()); } +#[cfg(unix)] +fn container_request(fields: serde_json::Value) -> sessions::ConnectRequest { + let mut request = json!({ "servers": [], "serverVersion": "0.1.0" }); + request + .as_object_mut() + .unwrap() + .extend(fields.as_object().unwrap().clone()); + serde_json::from_value(request).unwrap() +} + +/// Stand-in for a container engine CLI: writes its arguments and variables +/// next to itself, then skips `exec -i`, the user and the container name +/// and runs the inner command with the local shell. +#[cfg(unix)] +const FAKE_ENGINE: &str = "printf '%s\\n' \"$@\" > \"$0.arguments\"\n\ + env > \"$0.environment\"\n\ + shift 2\n\ + if [ \"$1\" = -u ]; then shift 2; fi\n\ + shift\n\ + exec \"$@\""; + +// A container on this machine is entered through its engine's `exec`: the +// server is probed inside it like on an SSH host, the engine keeps the +// environment that selects its service, and nothing asks through AskPass. +#[cfg(unix)] +#[test] +fn connecting_to_a_local_container_runs_the_launch_through_the_engine() { + let engine = FakeSsh::new("remote-connect-container", FAKE_ENGINE); + let request = container_request(json!({ + "container": { "engine": "podman", "container": " web ", "user": " dev " } + })); + let result = sessions::connect_with(request, Some(engine.path())).unwrap(); + let value = serde_json::to_value(result).unwrap(); + assert_eq!(value["status"], "unsupportedPlatform"); + assert_eq!(value["host"]["system"], local_uname("-s")); + let arguments = std::fs::read_to_string(engine.program.with_extension("arguments")).unwrap(); + let arguments: Vec<&str> = arguments.lines().collect(); + assert_eq!(arguments[..5], ["exec", "-i", "-u", "dev", "web"]); + let seen = environment_seen_by(&engine); + let names = seen.keys().collect::>(); + assert!(seen.contains_key("CARGO_PKG_NAME"), "{names:?}"); + assert!(!seen.contains_key("SSH_ASKPASS_REQUIRE"), "{names:?}"); +} + +// What Docker and Podman print about a missing or stopped container reads +// like an unknown host; an engine that prints nothing still names itself. +#[cfg(unix)] +#[test] +fn a_missing_container_is_unreachable_with_the_engine_message() { + let engine = FakeSsh::new( + "remote-connect-container-missing", + "echo 'Error response from daemon: No such container: web' >&2\nexit 1", + ); + let request = container_request(json!({ + "container": { "engine": "docker", "container": "web" } + })); + let value = serde_json::to_value(sessions::connect_with(request, Some(engine.path())).unwrap()) + .unwrap(); + assert_eq!(value["status"], "unreachable"); + assert_eq!(value["session"], serde_json::Value::Null); + assert_eq!( + value["diagnostics"], + "Error response from daemon: No such container: web" + ); + let silent = FakeSsh::new("remote-connect-container-silent", "exit 3"); + let request = container_request(json!({ + "container": { "engine": "podman", "container": "web" } + })); + let value = serde_json::to_value(sessions::connect_with(request, Some(silent.path())).unwrap()) + .unwrap(); + assert_eq!(value["status"], "failed"); + assert_eq!(value["diagnostics"], "podman exited with status 3"); +} + +// A container on an SSH host is one more hop inside the remote command, and +// the engine's refusal to open its socket is not a rejected SSH login. +#[cfg(unix)] +#[test] +fn a_container_on_an_ssh_host_is_entered_after_the_login() { + let ssh = FakeSsh::new( + "remote-connect-ssh-container", + "for last; do :; done\nprintf '%s' \"$last\" > \"$0.command\"\n\ + echo 'permission denied while trying to connect to the Docker daemon socket at \ + unix:///var/run/docker.sock: connect: permission denied' >&2\nexit 1", + ); + let request = container_request(json!({ + "connection": { "host": "devbox", "user": "dev" }, + "container": { "engine": "docker", "container": "web" } + })); + let value = + serde_json::to_value(sessions::connect_with(request, Some(ssh.path())).unwrap()).unwrap(); + assert_eq!(value["status"], "failed"); + let command = std::fs::read_to_string(ssh.program.with_extension("command")).unwrap(); + assert!(command.starts_with("docker exec -i web "), "{command}"); +} + +// A container inside a WSL distribution follows `--exec`, and the engine +// message there decides the status as on an SSH host. +#[cfg(unix)] +#[test] +fn a_container_in_a_wsl_distribution_is_entered_inside_it() { + let wsl = FakeSsh::new( + "remote-connect-wsl-container", + "printf '%s\\n' \"$@\" > \"$0.arguments\"\n\ + echo 'Error: no container with name or ID \"web\" found: no such container' >&2\nexit 125", + ); + let request = container_request(json!({ + "wsl": { "distribution": "Ubuntu" }, + "container": { "engine": "podman", "container": "web" } + })); + let value = + serde_json::to_value(sessions::connect_with(request, Some(wsl.path())).unwrap()).unwrap(); + assert_eq!(value["status"], "unreachable"); + let arguments = std::fs::read_to_string(wsl.program.with_extension("arguments")).unwrap(); + let arguments: Vec<&str> = arguments.lines().collect(); + let exec = arguments.iter().position(|word| *word == "--exec").unwrap(); + assert_eq!( + arguments[exec + 1..exec + 5], + ["podman", "exec", "-i", "web"] + ); +} + +// A malformed container is refused before anything runs, naming the field; +// so is a request that names no host and no container. +#[cfg(unix)] +#[test] +fn malformed_containers_are_refused_naming_the_field() { + let engine = FakeSsh::new("remote-connect-container-refused", "touch \"$0.ran\""); + let refused = |fields: serde_json::Value| { + let error = + sessions::connect_with(container_request(fields), Some(engine.path())).unwrap_err(); + assert!(matches!(error.code, ErrorCode::InvalidRequest), "{error:?}"); + serde_json::from_str::(error.details.as_deref().unwrap()).unwrap() + }; + assert_eq!( + refused(json!({ "container": { "engine": "docker", "container": " " } })), + json!({ "field": "container", "reason": "required" }) + ); + assert_eq!( + refused(json!({ "container": { "engine": "docker", "container": "-web" } })), + json!({ "field": "container", "reason": "invalid" }) + ); + assert_eq!( + refused(json!({ + "container": { "engine": "docker", "container": "web", "user": "root;id" } + })), + json!({ "field": "user", "reason": "invalid" }) + ); + assert_eq!( + refused(json!({ + "connection": { "host": "devbox" }, + "container": { "engine": "docker", "container": "web", "user": "-u" } + })), + json!({ "field": "user", "reason": "invalid" }) + ); + assert!(!engine.program.with_extension("ran").exists()); +} + // A session key reaches the remote command line, so one the server would // refuse, or a token it never issues, is refused before anything runs. #[cfg(unix)] diff --git a/rust/crates/workspace/src/sessions.rs b/rust/crates/workspace/src/sessions.rs index 08266f16..7e5308de 100644 --- a/rust/crates/workspace/src/sessions.rs +++ b/rust/crates/workspace/src/sessions.rs @@ -1,7 +1,8 @@ //! Long-lived remote connections. //! -//! `remote.connect` starts one client process, OpenSSH for a host or -//! `wsl.exe` for a WSL distribution on this machine, that probes the host, +//! `remote.connect` starts one client process, OpenSSH for a host, +//! `wsl.exe` for a WSL distribution on this machine or the container +//! engine's CLI for a container on this machine, that probes the host, //! installs the server when needed and starts it (see //! `lithe_remote::client::launch`), so the user authenticates once. The //! connection then stays open in this registry until `remote.disconnect`; @@ -18,7 +19,8 @@ //! programs once the server's idle timeout passes without a client. use crate::probe::{ - classify, classify_wsl, diagnostics, relay_challenge, ssh_hop, ProbeStatus, ProbedHost, + classify, classify_container, classify_wsl, container_status, diagnostics, relay_challenge, + ssh_hop, ProbeStatus, ProbedHost, }; use crate::programs::RunningProgram; use lithe_git_host::ProcessTree; @@ -28,8 +30,8 @@ use lithe_remote::client::launch::{launch, launch_command, LaunchError, Launched use lithe_remote::client::session::{ClientError, ConnectOptions}; use lithe_remote::client::trust::Target; use lithe_remote::client::{ - wsl, ArtifactError, ConnectionKind, ConnectionLog, ForwardSet, Hop, RemoteSession, - ServerArtifact, ServerTarget, TransportChain, WslConnection, + wsl, ArtifactError, ConnectionKind, ConnectionLog, ContainerConnection, ForwardSet, Hop, + RemoteSession, ServerArtifact, ServerTarget, TransportChain, WslConnection, }; use lithe_remote::protocol::message::ErrorCode as RemoteErrorCode; use lithe_remote::protocol::methods::{self, SessionToken}; @@ -78,7 +80,9 @@ struct ServerInput { } /// `remote.connect`: the host, the server builds Core may install, and where -/// to install them. Exactly one of `connection` and `wsl` names the host. +/// to install them. At most one of `connection` and `wsl` names the host; +/// `container` then names a running container on that host, or, on its own, +/// one on this machine. #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ConnectRequest { @@ -88,8 +92,13 @@ pub struct ConnectRequest { /// A WSL distribution on this machine, reached through `wsl.exe`. #[serde(default)] wsl: Option, + /// A running container, reached through its engine's `exec`, on the + /// host the other fields name or on this machine. + #[serde(default)] + container: Option, /// Remote preferences document, whose SSH program starts OpenSSH; - /// `null` or absent is every value automatic. Unused for `wsl`. + /// `null` or absent is every value automatic. Unused without + /// `connection`. #[serde(default)] preferences: Option, servers: Vec, @@ -390,23 +399,31 @@ enum Client { Ssh, /// `wsl.exe`, which starts a local distribution and asks nothing. Wsl, + /// The CLI of a container engine on this machine, which asks nothing. + Container, } impl Client { - /// The client `request` names. A request that names both or neither is - /// refused by [`first_hop`]; it counts as SSH until then. + /// The client `request` names. A request that names neither SSH, WSL + /// nor a container, or both SSH and WSL, is refused by [`first_hop`]; it + /// counts as SSH until then. fn of(request: &ConnectRequest) -> Self { - if request.wsl.is_some() && request.connection.is_none() { - Self::Wsl - } else { - Self::Ssh + match (&request.connection, &request.wsl, &request.container) { + (None, Some(_), _) => Self::Wsl, + (None, None, Some(_)) => Self::Container, + _ => Self::Ssh, } } - fn log_kind(self) -> ConnectionKind { - match self { - Self::Ssh => ConnectionKind::Ssh, - Self::Wsl => ConnectionKind::Wsl, + /// How the log names the attempt: the client, and whether the chain + /// then enters a container. + fn log_kind(self, container: bool) -> ConnectionKind { + match (self, container) { + (Self::Ssh, false) => ConnectionKind::Ssh, + (Self::Ssh, true) => ConnectionKind::SshContainer, + (Self::Wsl, false) => ConnectionKind::Wsl, + (Self::Wsl, true) => ConnectionKind::WslContainer, + (Self::Container, _) => ConnectionKind::Container, } } @@ -414,6 +431,7 @@ impl Client { match self { Self::Ssh => "Invalid SSH connection", Self::Wsl => "Invalid WSL connection", + Self::Container => "Invalid container connection", } } @@ -421,6 +439,7 @@ impl Client { match self { Self::Ssh => "Could not start the SSH client", Self::Wsl => "Could not start wsl.exe", + Self::Container => "Could not start the container engine", } } @@ -428,6 +447,7 @@ impl Client { match self { Self::Ssh => "Could not supervise the SSH client", Self::Wsl => "Could not supervise wsl.exe", + Self::Container => "Could not supervise the container engine", } } @@ -435,21 +455,39 @@ impl Client { match self { Self::Ssh => "The SSH connection did not finish in time", Self::Wsl => "The WSL distribution did not finish starting in time", + Self::Container => "The container did not finish starting the server in time", } } /// The client's standard error as text; `wsl.exe` may print UTF-16. fn text(self, stderr: &[u8]) -> String { match self { - Self::Ssh => String::from_utf8_lossy(stderr).into_owned(), + Self::Ssh | Self::Container => String::from_utf8_lossy(stderr).into_owned(), Self::Wsl => wsl::output_text(stderr), } } } +/// The hops of the chain: [`first_hop`], then the container when the +/// request names one on the host `connection` or `wsl` reaches. +fn chain_hops(request: &ConnectRequest, program: Option<&str>) -> Result, CoreError> { + let mut hops = vec![first_hop(request, program)?]; + if let (false, Some(container)) = ( + matches!(hops[0], Hop::Container(_)), + request.container.as_ref(), + ) { + let hop = container + .hop() + .map_err(crate::connections::invalid_request)?; + hops.push(Hop::Container(hop)); + } + Ok(hops) +} + /// The hop that starts the chain, with `program` in place of the system -/// client when set; OpenSSH is otherwise the preferences' SSH program. -/// Exactly one of `connection` and `wsl` must be set. +/// client when set; OpenSSH is otherwise the preferences' SSH program, and +/// a container engine its CLI on `PATH`. At most one of `connection` and +/// `wsl` may be set; without either, `container` must be. fn first_hop(request: &ConnectRequest, program: Option<&str>) -> Result { let refused = |field, reason| crate::connections::invalid_request(ConnectionError { field, reason }); @@ -468,13 +506,25 @@ fn first_hop(request: &ConnectRequest, program: Option<&str>) -> Result Err(refused("connection", Reason::Required)), + (None, None) => { + let Some(container) = &request.container else { + return Err(refused("connection", Reason::Required)); + }; + let mut hop = container + .hop() + .map_err(crate::connections::invalid_request)?; + if let Some(program) = program { + hop.program = program.into(); + } + Ok(Hop::Container(hop)) + } (Some(_), Some(_)) => Err(refused("wsl", Reason::Invalid)), } } -/// `program` replaces the system client (`ssh` on `PATH`, or `wsl.exe`); -/// tests use a stand-in. +/// `program` replaces the system client (`ssh` on `PATH`, `wsl.exe`, or the +/// container engine's CLI for a container on this machine); 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 @@ -486,7 +536,7 @@ pub(crate) fn connect_with( program: Option<&str>, ) -> Result { let client = Client::of(&request); - let log = ConnectionLog::begin(client.log_kind()); + let log = ConnectionLog::begin(client.log_kind(request.container.is_some())); let mut refused = false; let mut result = connect_logged( &request, @@ -572,7 +622,7 @@ fn connect_logged( let rejected_in_launch = Arc::clone(&rejected); let _connecting = ConnectingGuard::enter(); - let chain = TransportChain::new(vec![first_hop(request, program)?]); + let chain = TransportChain::new(chain_hops(request, program)?); let argv = chain .command(&launch_command( request.install_root.as_deref(), @@ -592,7 +642,8 @@ fn connect_logged( // Before the AskPass variables, which must reach ssh. chain.restrict_environment(&mut process); // OpenSSH asks for passwords, passphrases and host keys through AskPass; - // `wsl.exe` starts a local distribution as a local user and asks nothing. + // `wsl.exe` starts a local distribution as a local user and asks nothing, + // and so does a local container engine. let mut authentication = match client { Client::Ssh => { let authentication = @@ -612,7 +663,7 @@ fn connect_logged( })?; Some(authentication) } - Client::Wsl => None, + Client::Wsl | Client::Container => None, }; ProcessTree::prepare(&mut process); let mut child = process.spawn().map_err(|error| { @@ -767,10 +818,20 @@ fn connect_logged( let status = wait_for_exit(&mut child, EXIT_GRACE); reap(&tree, &mut child); let stderr = tail(&stderr_tail); - let probe = match client { - Client::Ssh => classify(status, &[], &stderr), - Client::Wsl => classify_wsl(status, &stderr), + let mut probe = match (client, request.container.as_ref()) { + (Client::Container, Some(container)) => { + classify_container(status, &stderr, container.engine) + } + (Client::Wsl, _) => classify_wsl(status, &stderr), + _ => classify(status, &[], &stderr), }; + // The engine on the host printed why it gave up, after the SSH + // or WSL client had connected. + if let (Client::Ssh | Client::Wsl, Some(_)) = (client, &request.container) { + if let Some(status) = container_status(&client.text(&stderr)) { + probe.status = status; + } + } return Ok(failed(probe.status, None, probe.diagnostics)); } Err(LaunchError::NoArtifact(report)) => { diff --git a/rust/crates/workspace/src/test_support.rs b/rust/crates/workspace/src/test_support.rs index 45eec91a..dd361a8d 100644 --- a/rust/crates/workspace/src/test_support.rs +++ b/rust/crates/workspace/src/test_support.rs @@ -48,3 +48,21 @@ pub fn unique_id() -> String { pub fn stat_requests() -> usize { crate::fs::stat_requests_for_test() } + +/// `remote.listContainers` with `program` in place of the engine CLI, on +/// this machine or on the host the request names. +pub fn list_containers_with( + request: crate::containers::ListRequest, + program: &str, +) -> Result { + crate::containers::list_with(request, Some(program)) +} + +/// `remote.devcontainerUp` with `program` in place of both the Dev Container +/// CLI and the engine CLI. +pub fn devcontainer_up_with( + request: crate::devcontainers::UpRequest, + program: &str, +) -> Result { + crate::devcontainers::up_with(request, Some(program)) +} diff --git a/rust/logging/events/remote.json b/rust/logging/events/remote.json index f26c6a4d..9f5bdc33 100644 --- a/rust/logging/events/remote.json +++ b/rust/logging/events/remote.json @@ -196,7 +196,7 @@ "transport": { "type": "token", "required": true, - "description": "How the client reached the server: ssh, wsl (a local WSL distribution through wsl.exe), command (any spawned transport chain) or streams (caller-supplied pipes)" + "description": "How the client reached the server: ssh, wsl (a local WSL distribution through wsl.exe), container (a local container through its engine's exec), ssh-container or wsl-container (a container on that host), command (any spawned transport chain) or streams (caller-supplied pipes)" }, "outcome": { "type": "token",