From d1b86b55f344af572fd472edaf60d91240cf1149 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Thu, 26 Nov 2026 14:32:33 +0800 Subject: [PATCH] feat(remote): discover container runtimes and prepare devcontainer configurations Discover local Docker contexts, Podman and Windows WSL runtimes with bounded probes. Generate standard devcontainer configuration from basic form inputs and preserve the selected context and distribution through build, connection and trust. --- rust/contracts/application-boundary.md | 18 + rust/contracts/rust-core-api.md | 121 ++++-- rust/crates/core/src/protocol/command.rs | 6 + .../core/src/runtime/dispatcher/remote.rs | 12 + rust/crates/remote/src/client/container.rs | 78 ++++ rust/crates/remote/src/client/transport.rs | 25 +- rust/crates/remote/src/client/trust.rs | 7 + .../workspace/src/container_runtimes.rs | 390 ++++++++++++++++++ rust/crates/workspace/src/containers.rs | 21 + rust/crates/workspace/src/devcontainers.rs | 357 +++++++++++++++- .../workspace/src/devcontainers/tests.rs | 39 ++ rust/crates/workspace/src/lib.rs | 1 + .../remote/devcontainer-configuration-v1.json | 34 ++ 13 files changed, 1059 insertions(+), 50 deletions(-) create mode 100644 rust/crates/workspace/src/container_runtimes.rs create mode 100644 rust/crates/workspace/src/devcontainers/tests.rs create mode 100644 rust/fixtures/remote/devcontainer-configuration-v1.json diff --git a/rust/contracts/application-boundary.md b/rust/contracts/application-boundary.md index 69f06b82..701f06cf 100644 --- a/rust/contracts/application-boundary.md +++ b/rust/contracts/application-boundary.md @@ -63,6 +63,7 @@ this lifecycle protection; actual symbol computation remains upstream-owned. | Feature | Shared input/output | Platform-owned implementation | | --- | --- | --- | | Workspace | visible snapshot, relative paths, file metadata, deterministic ordering | workspace root selection, native dialogs, and watchers | +| Dev Containers | read-only local/WSL runtime discovery, explicit engine/context/distribution targets, basic-form validation and standard configuration, trusted official-CLI lifecycle, context-aware connection and trust | folder picker, draft UI, confirmed atomic configuration publication outside installed resources, upstream CLI availability and platform filesystem access | | Documents | relative-path validation, decoded text, selected encoding, dirty/save state, and conflict outcome | native byte conversion, atomic write, and external-change notifications | | Search | query matching, deterministic result ordering, symbols, and replacement preview | workspace lifecycle and optional index persistence | | Git | workspace commit plans with optional immutable ChangeList path scopes, dependency ordering, guarded steps and partial-success retry, changes, commits, branches, diffs, reviewed history actions and recovery, worktree listing and safe management, worktree-aware PR publication context, validation, and mutation results | Git executable discovery, credentials, process environment, opening checkout paths, local ChangeList selection and preference persistence | @@ -86,6 +87,23 @@ that its editor snapshots still match those versions before touching files or buffers, and stops pending work when Core revokes a delivered request. The [Core commands reference](rust-core-api.md#commands) specifies the event and reply shapes. +### Dev Container configuration and execution environment + +The same explicit runtime target follows discovery, configuration lookup, build, +inspection and connection. Docker contexts remain child-local and trust keys +include the context and WSL distribution, so identically named containers in +different daemons cannot share authority. Discovery is bounded and never switches +the user's global context. A missing or stopped daemon remains visible to the UI. + +The basic form renders a standard workspace-owned `devcontainer.json` through +`remote.devcontainerPrepare`; it does not execute code or write files. Only the +native client's confirmed Create action publishes it, refusing existing content +and installation roots. Building still requires the workspace's trust decision, +and the reference CLI remains responsible for the specification's lifecycle, +mounts, features and compose behavior. Windows WSL targets use that distribution's +CLI and path translation. See the [command contract](rust-core-api.md#dev-containers) +and [shared form examples](../fixtures/remote/devcontainer-configuration-v1.json). + ### Application update channels A missing saved channel selects `stable` for Stable and legacy shared-identity builds; diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 372fa950..ca1a1ed1 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -851,8 +851,10 @@ or removing a command fails until the table changes in the same commit. | `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.containerRuntimes` | Discover local Docker contexts and Windows WSL engines without switching the active context | +| `remote.devcontainerPrepare` | Validate a basic form and render standard workspace-owned `devcontainer.json` without I/O | +| `remote.devcontainerConfigs` | List the `devcontainer.json` files of a local or WSL folder | +| `remote.devcontainerUp` | Build or reuse and start a trusted local or WSL 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 | @@ -5995,15 +5997,17 @@ 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 +`remote.listContainers` takes `{ engine, sessionId?, runtime? }`, 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 +`DOCKER_HOST`) when both `sessionId` and `runtime` are absent, and otherwise on that +connection's host in the server's environment when `sessionId` is present. +`runtime` selects the exact local or WSL environment described below; it is +mutually exclusive with `sessionId` and its engine must match `engine`, or the +request is `invalid_request`. Only running containers are listed; this command +does not start or change them. `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 @@ -6019,14 +6023,73 @@ container listing request"), so a request cannot pick the program; an unknown #### Dev Containers -A local folder's dev container is built and started by the reference Dev +A local or WSL 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 +on Windows) on the selected environment's `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 +and adds no mounts or options to the CLI invocation. The basic form produces +standard configuration before the CLI runs, and agents may edit the same file. + +`remote.containerRuntimes` takes no payload and returns `{ runtimes, +selectedRuntime, diagnostics }`. Each runtime is `{ id, engine, context?, wsl?, +label, current, available, diagnostics }`; `id` is opaque. `label` is the +engine's context description or name, so OrbStack and Docker Desktop are shown +using their real contexts rather than application-installation heuristics. +`available` means a read-only `info` probe answered successfully. An installed +context whose daemon is stopped remains listed with its redacted diagnostics. +Labels omit control characters and keep at most 128 characters from the upstream description. +Missing optional CLIs produce no runtime. `diagnostics` on the result contains +redacted failures or limits not associated with a particular runtime. Diagnostics +are for display; callers record failure categories without upstream text. + +Discovery reads native `docker context ls --format '{{json .}}'` and Podman's +CLI, then on Windows up to eight user WSL distributions from +`remote.listWslDistributions`, looking for those same engines. Context listing +is bounded to five seconds and each daemon probe to three seconds. At most 24 +targets are probed within a 60-second budget; WSL enumeration has its independent +15-second bound. A partial discovery returns the usable results and a diagnostic. +Only `unix://` and `npipe://` Docker endpoints are offered: a remote daemon cannot +bind-mount this workspace. No daemon is explicitly started and the global Docker +context is never changed. `selectedRuntime` prefers a usable current native +context, then the first usable runtime, then the first listed runtime, and is +`null` for an empty list. Cancellation is `cancelled`. + +A runtime target is `{ engine: "docker"|"podman", context?, wsl? }`. +`context` is Docker-only, one to 128 ASCII letters, digits, `_`, `-` or `.`, +and cannot start with `-`; `wsl` is a valid distribution name. Invalid targets +are `invalid_request`. Explicit contexts set `DOCKER_CONTEXT` only on the child +and remove inherited `DOCKER_HOST`, `DOCKER_TLS_VERIFY` and `DOCKER_CERT_PATH`. +WSL commands use `wsl.exe --distribution --exec …`, with the context applied +by `env`; paths are arguments, never interpolated into shell source. Omitted +targets preserve the original native behavior and environment. + +`remote.devcontainerPrepare` accepts `{ name?, image?, dockerfile?, buildContext?, +remoteUser?, workspaceFolder?, ports?, postCreateCommand? }`, with empty defaults, +and returns `{ path: ".devcontainer/devcontainer.json", content }`. It performs +no I/O and runs nothing. Exactly one of `image` and `dockerfile` must be nonempty. +Dockerfile and build-context paths are workspace-relative, without absolute +paths, backslashes or `..` components; an empty context means `.`. Core writes +the standard `build` paths relative to the destination configuration. Optional +fields use standard Dev Container properties; blank values are omitted. `ports` +accepts comma or whitespace separated ports from 1 to 65535, deduplicated to at +most 64, published as `appPort` loopback bindings such as +`127.0.0.1:3000:3000`. A container user follows the `remote.connect` user syntax +and a nonempty workspace folder is an absolute POSIX path. String limits in +bytes are image 512, each build path 1024, name 128, user 64, workspace folder +4096 and post-create command 8192. Refused values are `invalid_request` with +JSON `details: { field }` identifying the form field. Unknown fields are refused. + +Native clients publish this document only after the explicit Create action, +atomically and without overwriting an existing file or following a path outside +the workspace. The configuration belongs to the user's workspace, never the app +bundle or installation directory; drafts and cancellation publish nothing. + +`remote.devcontainerConfigs` takes `{ folder, runtime? }`, an absolute folder on this +machine or the selected WSL distribution, and returns `{ nativeFolder, configs }`: +`nativeFolder` is the native path used by the desktop for trust and confirmed +publication. For WSL, absolute Windows paths are translated using that distribution's +`wslpath -a -u`; absolute Linux paths are accepted directly, and `wslpath -w` +returns their native Windows path. `{ path, name? }` lists 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 @@ -6036,11 +6099,13 @@ 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. +exist is `workspace_not_found`. WSL enumeration uses a fixed read-only script +with NUL-delimited paths and returns paths without reading optional names; +paths containing control characters are omitted. Reading starts no project code. -`remote.devcontainerUp` takes `{ folder, config?, engine, +`remote.devcontainerUp` takes `{ folder, config?, engine, runtime?, projectCodeAllowed }` and returns `{ container?, diagnostics }`. Building runs -the folder's code on this machine (`initializeCommand`, Dockerfiles, feature +the folder's code in the selected environment (`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 @@ -6048,7 +6113,9 @@ folder's trust decision, as for Git. `config` must be one of the `path`s `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 +machine or selected WSL distribution, for at most one hour. `runtime.engine` +must match `engine`. Build, name inspection and subsequent connection must use +the same target; WSL requires the Linux CLI inside that distribution. 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 @@ -6057,11 +6124,12 @@ 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?, +- `success`: `container` is `{ engine, runtime?, 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 + configuration's `remoteUser`, `runtime` the unchanged explicit target (absent + for legacy requests), 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. @@ -6072,7 +6140,8 @@ The result is the last line of standard output that is a JSON object with an 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. +`timed_out`. The up command saves no Lithe connection record; the upstream CLI +owns its container and project lifecycle effects. #### Remote workspace preferences @@ -6232,11 +6301,11 @@ 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 +context?, 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. +becomes ` [--context ] 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 @@ -6252,8 +6321,12 @@ over SSH; and other failures are `failed` with the engine's message in 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. +context?, container, user? } }`, so a decision never carries over to another container, +Docker context or account. A context follows the runtime target's Docker-only +validation. Explicit-context identities use `docker[context]:[user@]container`; +omitting it preserves the original `engine:[user@]container` identity and behavior. +For a runtime with `wsl`, clients also pass `wsl: { distribution }` on connect, +so inspection, connection and trust name the same distribution and context. A request that names both `connection` and `wsl` is `invalid_request` with `details` `{ field: "wsl", reason: "invalid" }`, and one that names none of diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 3d1bbc87..86a248cd 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -1096,6 +1096,10 @@ pub enum RemoteCommand { /// Lists the `devcontainer.json` files of a local folder /// (`remote.devcontainerConfigs`). DevcontainerConfigs, + /// Discovers local and WSL container runtimes (remote.containerRuntimes). + ContainerRuntimes, + /// Renders a standard devcontainer.json from a basic form without I/O. + DevcontainerPrepare, /// Builds or reuses and starts a local folder's dev container with the /// Dev Container CLI (`remote.devcontainerUp`). DevcontainerUp, @@ -1717,6 +1721,8 @@ impl CoreCommand { Some(Self::Remote(RemoteCommand::ListWslDistributions)) } "remote.listContainers" => Some(Self::Remote(RemoteCommand::ListContainers)), + "remote.containerRuntimes" => Some(Self::Remote(RemoteCommand::ContainerRuntimes)), + "remote.devcontainerPrepare" => Some(Self::Remote(RemoteCommand::DevcontainerPrepare)), "remote.devcontainerConfigs" => Some(Self::Remote(RemoteCommand::DevcontainerConfigs)), "remote.devcontainerUp" => Some(Self::Remote(RemoteCommand::DevcontainerUp)), "remote.preferences" => Some(Self::Remote(RemoteCommand::Preferences)), diff --git a/rust/crates/core/src/runtime/dispatcher/remote.rs b/rust/crates/core/src/runtime/dispatcher/remote.rs index 503bd625..72b49bb2 100644 --- a/rust/crates/core/src/runtime/dispatcher/remote.rs +++ b/rust/crates/core/src/runtime/dispatcher/remote.rs @@ -383,6 +383,18 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option, payload: Valu }) }, ), + RemoteCommand::ContainerRuntimes => match lithe_workspace::container_runtimes::discover() { + Ok(result) => { + CoreResponse::success(id, serde_json::to_value(result).expect("runtimes encode")) + } + Err(error) => CoreResponse::failure(id, error), + }, + RemoteCommand::DevcontainerPrepare => { + answer(id, payload, "Invalid dev container form", |request| { + lithe_workspace::devcontainers::prepare(request) + .map(|result| serde_json::to_value(result).expect("form encodes")) + }) + } RemoteCommand::DevcontainerConfigs => answer( id, payload, diff --git a/rust/crates/remote/src/client/container.rs b/rust/crates/remote/src/client/container.rs index 60b6ed9c..4139c8c1 100644 --- a/rust/crates/remote/src/client/container.rs +++ b/rust/crates/remote/src/client/container.rs @@ -40,6 +40,9 @@ const MAX_TEXT_BYTES: usize = 256; pub struct ContainerConnection { /// Engine whose CLI runs `exec`. pub engine: ContainerEngine, + /// Explicit Docker context; omitted preserves the engine environment. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub context: Option, /// Container name or id, as `ps` lists it. pub container: String, /// `user`, `uid` or `user:group` passed as `--user`; the image's default @@ -81,11 +84,29 @@ impl ContainerConnection { } } let mut hop = ContainerHop::new(self.engine, container); + if self + .context + .as_deref() + .is_some_and(|name| !is_context_name(name) || self.engine != ContainerEngine::Docker) + { + return Err(ConnectionError::at("context", Reason::Invalid)); + } + hop.context = self.context.clone(); hop.user = user.map(Into::into); Ok(hop) } } +/// A bounded Docker context name that cannot be interpreted as a CLI option. +pub fn is_context_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= 128 + && !name.starts_with('-') + && name + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.')) +} + /// One running container in a listing. #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] @@ -176,6 +197,7 @@ mod tests { fn connection(container: &str, user: Option<&str>) -> ContainerConnection { ContainerConnection { engine: ContainerEngine::Docker, + context: None, container: container.into(), user: user.map(Into::into), } @@ -219,6 +241,62 @@ mod tests { } } + #[test] + fn docker_context_is_kept_for_exec_identity_and_trust() { + let connection = ContainerConnection { + context: Some("orbstack".into()), + ..connection("api", None) + }; + let hop = connection.hop().unwrap(); + let chain = crate::client::transport::TransportChain::new(vec![ + crate::client::transport::Hop::Container(hop), + ]); + assert_eq!( + chain.command(&["true".into()]).unwrap(), + vec![ + "docker", + "--context", + "orbstack", + "exec", + "-i", + "api", + "true" + ] + ); + assert_eq!(chain.identity(), "docker[orbstack]:api"); + let trusted = crate::client::trust::Target::new(&chain, None); + assert!(trusted.validate().is_ok()); + let mut invalid = trusted.clone(); + if let crate::client::trust::TargetHop::Container(hop) = &mut invalid.hops[0] { + hop.engine = "podman".into(); + } + assert!(invalid.validate().is_err()); + assert_ne!( + crate::client::trust::Target::new(&chain, None), + crate::client::trust::Target::new( + &crate::client::transport::TransportChain::new(vec![ + crate::client::transport::Hop::Container(ContainerHop::new( + ContainerEngine::Docker, + "api" + )) + ]), + None + ) + ); + assert!(ContainerConnection { + context: Some("--host=evil".into()), + ..connection.clone() + } + .hop() + .is_err()); + assert!(ContainerConnection { + engine: ContainerEngine::Podman, + ..connection + } + .hop() + .is_err()); + } + #[test] fn requests_name_only_the_engine_the_container_and_the_user() { let parsed: ContainerConnection = diff --git a/rust/crates/remote/src/client/transport.rs b/rust/crates/remote/src/client/transport.rs index 9cac039d..d5bb9885 100644 --- a/rust/crates/remote/src/client/transport.rs +++ b/rust/crates/remote/src/client/transport.rs @@ -213,7 +213,7 @@ pub(crate) const MAX_WSL_USER_BYTES: usize = 32; /// A WSL distribution name: ASCII letters, digits, `.`, `_` and `-`, starting /// with a letter or digit, which is what `wsl.exe --import` accepts. -pub(crate) fn is_wsl_distribution(name: &str) -> bool { +pub fn is_wsl_distribution(name: &str) -> bool { name.len() <= MAX_WSL_DISTRIBUTION_BYTES && is_plain_name(name) } @@ -282,6 +282,8 @@ pub struct ContainerHop { pub engine: ContainerEngine, /// Engine CLI executable. Defaults to the engine name. pub program: String, + /// Explicit Docker context, applied before exec without changing global configuration. + pub context: Option, /// Container name or id. pub container: String, /// `user`, `uid` or `user:group`; the image default when absent. @@ -299,6 +301,7 @@ impl ContainerHop { Self { engine, program: engine.name().into(), + context: None, container: container.into(), user: None, working_directory: None, @@ -323,8 +326,8 @@ pub(crate) fn is_container_name(name: &str) -> bool { /// 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 { +/// most 64 bytes long. +pub fn is_container_user(user: &str) -> bool { !user.is_empty() && user.len() <= MAX_CONTAINER_USER_BYTES && !user.starts_with('-') @@ -454,7 +457,10 @@ impl TransportChain { Some(port) => format!("ssh:{}:{port}", hop.destination), None => format!("ssh:{}", hop.destination), }, - Hop::Container(hop) => format!("{}:{}", hop.engine.name(), hop.container), + Hop::Container(hop) => match &hop.context { + Some(context) => format!("{}[{context}]:{}", hop.engine.name(), hop.container), + None => format!("{}:{}", hop.engine.name(), hop.container), + }, Hop::Wsl(hop) => match &hop.user { Some(user) => format!("wsl:{user}@{}", hop.distribution), None => format!("wsl:{}", hop.distribution), @@ -583,7 +589,16 @@ fn container_command(hop: &ContainerHop, inner: Vec) -> Result, reason: format!("invalid container name {:?}", hop.container), }); } - let mut command = vec![hop.program.clone(), "exec".into(), "-i".into()]; + let mut command = vec![hop.program.clone()]; + if let Some(context) = &hop.context { + if hop.engine != ContainerEngine::Docker || !super::container::is_context_name(context) { + return Err(TransportError::InvalidHop { + reason: "invalid Docker context".into(), + }); + } + command.extend(["--context".into(), context.clone()]); + } + command.extend(["exec".into(), "-i".into()]); if let Some(user) = &hop.user { if !is_container_user(user) { return Err(TransportError::InvalidHop { diff --git a/rust/crates/remote/src/client/trust.rs b/rust/crates/remote/src/client/trust.rs index 0819ddfd..04ce5d85 100644 --- a/rust/crates/remote/src/client/trust.rs +++ b/rust/crates/remote/src/client/trust.rs @@ -112,6 +112,9 @@ pub struct ContainerTarget { pub engine: String, /// Engine CLI executable. Docker-compatible CLIs reach different daemons. pub program: String, + /// Docker context choosing the daemon; absent in legacy targets. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub context: Option, /// Container name or id. pub container: String, /// `user`, `uid` or `user:group` given to `exec`. @@ -158,6 +161,7 @@ impl Target { Hop::Container(hop) => TargetHop::Container(ContainerTarget { engine: hop.engine.name().into(), program: hop.program.clone(), + context: hop.context.clone(), container: hop.container.clone(), user: hop.user.clone(), }), @@ -202,6 +206,9 @@ impl Target { TargetHop::Container(hop) => { matches!(hop.engine.as_str(), "docker" | "podman") && field(&hop.program) + && hop.context.as_deref().is_none_or(|name| { + hop.engine == "docker" && super::container::is_context_name(name) + }) && field(&hop.container) && optional(&hop.user) } diff --git a/rust/crates/workspace/src/container_runtimes.rs b/rust/crates/workspace/src/container_runtimes.rs new file mode 100644 index 00000000..c2d2f902 --- /dev/null +++ b/rust/crates/workspace/src/container_runtimes.rs @@ -0,0 +1,390 @@ +//! Discovers Docker contexts and WSL engines without changing the user's active context. +//! Targets are carried unchanged through build, inspection and connection; no daemon is started. + +use lithe_protocol::{CoreError, ErrorCode}; +use lithe_remote::client::{ + transport::{is_wsl_distribution, wsl_program}, + ContainerEngine, +}; +use serde::{Deserialize, Serialize}; +use std::io::ErrorKind; +use std::process::Command; +use std::time::{Duration, Instant}; + +/// Maximum contexts and WSL distributions probed in one discovery. +const MAX_TARGETS: usize = 24; + +/// A CLI target. WSL paths and commands are resolved in the named distribution. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RuntimeTarget { + /// Docker or Podman executable syntax. + pub engine: ContainerEngine, + /// Explicit Docker context; omitted preserves the upstream environment. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub context: Option, + /// WSL distribution owning the engine and Dev Container CLI. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wsl: Option, +} + +impl RuntimeTarget { + /// Rejects option-like names and unsupported context/engine combinations before I/O. + pub fn validate(&self) -> Result<(), CoreError> { + if self.context.as_deref().is_some_and(|name| { + !lithe_remote::client::container::is_context_name(name) + || self.engine != ContainerEngine::Docker + }) || self + .wsl + .as_deref() + .is_some_and(|name| !is_wsl_distribution(name)) + { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Invalid container runtime target", + )); + } + Ok(()) + } + + /// Wraps a command in WSL and applies context only to this child process. + pub(crate) fn command(&self, argv: &[String]) -> Result { + self.validate()?; + let mut words = argv.to_vec(); + if let Some(context) = &self.context { + words.splice( + 0..0, + [ + "env".into(), + "-u".into(), + "DOCKER_HOST".into(), + "-u".into(), + "DOCKER_TLS_VERIFY".into(), + "-u".into(), + "DOCKER_CERT_PATH".into(), + format!("DOCKER_CONTEXT={context}"), + ], + ); + } + let mut process = if let Some(distribution) = &self.wsl { + let mut process = Command::new(wsl_program()); + process + .args(["--distribution", distribution, "--exec"]) + .args(words); + process.env("WSL_UTF8", "1"); + process + } else { + let mut process = Command::new(&argv[0]); + process.args(&argv[1..]); + if let Some(context) = &self.context { + process + .env_remove("DOCKER_HOST") + .env_remove("DOCKER_TLS_VERIFY") + .env_remove("DOCKER_CERT_PATH") + .env("DOCKER_CONTEXT", context); + } + process + }; + process.stdin(std::process::Stdio::null()); + Ok(process) + } +} + +/// A discovered target, using upstream names rather than an application-name heuristic. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ContainerRuntime { + /// Stable opaque picker key, also used for namespacing container rows. + pub id: String, + /// Exact engine/context/distribution used by subsequent operations. + #[serde(flatten)] + pub target: RuntimeTarget, + /// Context description, such as OrbStack or Docker Desktop, from the engine CLI. + pub label: String, + /// Whether upstream selected this context at discovery time. + pub current: bool, + /// Whether the daemon answered a bounded read-only `info` request. + pub available: bool, + /// Upstream failure, redacted for display and never logged as free text. + pub diagnostics: String, +} + +/// Discovery result; an empty list means no engine CLI was found. +#[derive(Debug, Default, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Runtimes { + /// Local contexts first, followed by each WSL distribution's contexts. + pub runtimes: Vec, + /// Preferred usable native context, falling back to the first usable WSL engine. + pub selected_runtime: Option, + /// Discovery failures not associated with a listed runtime, redacted for display. + pub diagnostics: Vec, +} + +/// Reads installed CLI contexts and, on Windows, engines in user WSL distributions. +pub fn discover() -> Result { + let mut result = Runtimes::default(); + let deadline = Instant::now() + Duration::from_secs(60); + discover_on(None, &mut result, deadline)?; + let distributions = match crate::wsl::list() { + Ok(distributions) => distributions, + Err(error) if matches!(error.code, ErrorCode::Cancelled) => return Err(error), + Err(error) => { + result.diagnostics.push(error.message); + crate::wsl::Distributions::default() + } + }; + if !distributions.diagnostics.is_empty() { + result.diagnostics.push(distributions.diagnostics); + } + let distributions_truncated = distributions.distributions.len() > 8; + for distribution in distributions.distributions.into_iter().take(8) { + discover_on(Some(distribution), &mut result, deadline)?; + } + if distributions_truncated || result.runtimes.len() >= MAX_TARGETS || Instant::now() >= deadline + { + result.diagnostics.push( + "Container runtime discovery reached its limit; some environments were not probed" + .into(), + ); + } + result.selected_runtime = result + .runtimes + .iter() + .find(|r| r.available && r.current && r.target.wsl.is_none()) + .or_else(|| result.runtimes.iter().find(|r| r.available)) + .or_else(|| result.runtimes.first()) + .map(|r| r.id.clone()); + Ok(result) +} + +#[derive(Deserialize)] +#[serde(rename_all = "PascalCase")] +struct ContextRow { + name: String, + #[serde(default)] + description: String, + #[serde(default)] + current: bool, + #[serde(default)] + docker_endpoint: String, +} + +fn discover_on( + distribution: Option, + result: &mut Runtimes, + deadline: Instant, +) -> Result<(), CoreError> { + for engine in [ContainerEngine::Docker, ContainerEngine::Podman] { + if result.runtimes.len() >= MAX_TARGETS || Instant::now() >= deadline { + break; + } + let base = RuntimeTarget { + engine, + context: None, + wsl: distribution.clone(), + }; + let argv = match engine { + ContainerEngine::Docker => vec![ + "docker".into(), + "context".into(), + "ls".into(), + "--format".into(), + "{{json .}}".into(), + ], + ContainerEngine::Podman => vec!["podman".into(), "--version".into()], + }; + let outcome = match capture( + &base, + &argv, + Duration::from_secs(5).min(deadline.saturating_duration_since(Instant::now())), + ) { + Ok(Some(outcome)) => outcome, + Ok(None) => continue, + Err(error) if matches!(error.code, ErrorCode::Cancelled) => return Err(error), + Err(error) => { + result.diagnostics.push(error.message); + continue; + } + }; + if !outcome.status.is_some_and(|s| s.success()) { + // WSL's env/exec reports a missing optional CLI with 127. + if outcome + .status + .and_then(|s| s.code()) + .is_some_and(|code| code == 127) + { + continue; + } + result + .diagnostics + .push(crate::probe::diagnostics(&String::from_utf8_lossy( + &outcome.stderr, + ))); + continue; + } + let mut targets = Vec::new(); + if engine == ContainerEngine::Docker { + for line in String::from_utf8_lossy(&outcome.stdout) + .lines() + .take(MAX_TARGETS) + { + let row: ContextRow = match serde_json::from_str(line) { + Ok(row) => row, + Err(_) => { + result + .diagnostics + .push("Invalid Docker context listing".into()); + continue; + } + }; + // Dev Container's bind mount requires a daemon on this computer or in this WSL. + if !row.docker_endpoint.starts_with("unix://") + && !row.docker_endpoint.starts_with("npipe://") + { + continue; + } + let label = if row.description.is_empty() { + row.name.clone() + } else { + row.description + .chars() + .filter(|character| !character.is_control()) + .take(128) + .collect() + }; + targets.push(( + RuntimeTarget { + context: Some(row.name), + ..base.clone() + }, + label, + row.current, + )); + } + } else { + targets.push((base, "Podman".into(), true)); + } + for (target, label, current) in targets { + if result.runtimes.len() >= MAX_TARGETS || Instant::now() >= deadline { + break; + } + if target.validate().is_err() { + result + .diagnostics + .push("Invalid container runtime target".into()); + continue; + } + let info = vec![ + engine.name().into(), + "info".into(), + "--format".into(), + "{{.ServerVersion}}".into(), + ]; + let status = capture( + &target, + &info, + Duration::from_secs(3).min(deadline.saturating_duration_since(Instant::now())), + ); + let (available, diagnostics) = match status { + Ok(Some(outcome)) => ( + outcome.status.is_some_and(|s| s.success()), + crate::probe::diagnostics(&String::from_utf8_lossy(&outcome.stderr)), + ), + Ok(None) => (false, String::new()), + Err(error) if matches!(error.code, ErrorCode::Cancelled) => return Err(error), + Err(error) => (false, error.message), + }; + let id = serde_json::to_string(&target).expect("runtime target encodes"); + result.runtimes.push(ContainerRuntime { + id, + target, + label, + current, + available, + diagnostics, + }); + } + } + Ok(()) +} + +/// Runs one read-only probe with cancellation, a local deadline and process-tree cleanup. +pub(crate) fn capture( + target: &RuntimeTarget, + argv: &[String], + timeout: Duration, +) -> Result, CoreError> { + let mut command = target.command(argv)?; + let deadline = Instant::now() + timeout; + let mut stopped = None; + let outcome = lithe_git_host::run( + &mut command, + None, + || { + if let Err(error) = lithe_protocol::cancellation::check() { + stopped = Some(error); + } else if Instant::now() >= deadline { + stopped = Some(CoreError::new( + ErrorCode::TimedOut, + "Container runtime detection timed out", + )); + } + stopped.is_some() + }, + || {}, + |_, _| {}, + ); + if let Some(error) = stopped { + return Err(error); + } + match &outcome.failure { + None => Ok(Some(outcome)), + // log-exempt: Expected absence: an optional container engine is not installed. + Some(lithe_git_host::Failure::Start(error)) if error.kind() == ErrorKind::NotFound => { + Ok(None) + } + Some(failure) => Err(CoreError::new( + ErrorCode::ProcessFailed, + "Container runtime probe failed", + ) + .with_details(format!("{failure:?}"))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn context_environment_is_child_local_and_wsl_arguments_are_not_shell_source() { + let target = RuntimeTarget { + engine: ContainerEngine::Docker, + context: Some("orbstack".into()), + wsl: None, + }; + let command = target.command(&["docker".into(), "info".into()]).unwrap(); + assert_eq!(command.get_program(), "docker"); + assert!(command + .get_envs() + .any(|(key, value)| key == "DOCKER_CONTEXT" + && value == Some(std::ffi::OsStr::new("orbstack")))); + let wsl = RuntimeTarget { + wsl: Some("Ubuntu-24.04".into()), + ..target + }; + let command = wsl + .command(&["devcontainer".into(), "up".into(), "/a path/$x".into()]) + .unwrap(); + let arguments: Vec<_> = command + .get_args() + .map(|arg| arg.to_string_lossy().into_owned()) + .collect(); + assert_eq!( + &arguments[..3], + &["--distribution", "Ubuntu-24.04", "--exec"] + ); + assert_eq!(arguments.last().unwrap(), "/a path/$x"); + assert!(arguments.iter().any(|a| a == "DOCKER_CONTEXT=orbstack")); + } +} diff --git a/rust/crates/workspace/src/containers.rs b/rust/crates/workspace/src/containers.rs index d8f1d493..36d450ce 100644 --- a/rust/crates/workspace/src/containers.rs +++ b/rust/crates/workspace/src/containers.rs @@ -26,6 +26,9 @@ const LIST_TIMEOUT: Duration = Duration::from_secs(15); pub struct ListRequest { /// Engine whose CLI lists the containers. pub engine: ContainerEngine, + /// Explicit local or WSL runtime; sessionId remains mutually exclusive. + #[serde(default)] + pub runtime: Option, /// Connected session whose host runs the engine; this machine when /// absent. #[serde(default)] @@ -62,6 +65,23 @@ pub(crate) fn list_with( if let Some(program) = program { argv[0] = program.into(); } + if let Some(runtime) = request.runtime { + if request.session_id.is_some() || runtime.engine != request.engine { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Conflicting container runtime", + )); + } + let Some(outcome) = crate::container_runtimes::capture(&runtime, &argv, LIST_TIMEOUT)? + else { + return Ok(Containers::default()); + }; + return Ok(answer( + outcome.status.is_some_and(|s| s.success()), + &outcome.stdout, + &outcome.stderr, + )); + } match request.session_id { None => list_here(&argv), Some(session_id) => list_on_host(&session_id, argv), @@ -225,6 +245,7 @@ mod tests { ListRequest { engine, session_id: None, + runtime: None, } } diff --git a/rust/crates/workspace/src/devcontainers.rs b/rust/crates/workspace/src/devcontainers.rs index d0c51400..dec27f1d 100644 --- a/rust/crates/workspace/src/devcontainers.rs +++ b/rust/crates/workspace/src/devcontainers.rs @@ -1,6 +1,5 @@ -//! `remote.devcontainerConfigs` and `remote.devcontainerUp`: a local -//! folder's Dev Container, built and started by the reference Dev Container -//! CLI, for the connection window. +//! A local or WSL folder's Dev Container, configured through a basic form +//! and built and started by the reference Dev Container CLI. //! //! 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 @@ -8,13 +7,15 @@ //! 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. +//! with `remote.connect`'s `container` and opens. Only the host's explicit +//! Create action publishes the standard document rendered by [`prepare`]. //! //! 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 crate::container_runtimes::RuntimeTarget; use lithe_protocol::{CoreError, ErrorCode}; use lithe_remote::client::devcontainer::{ discover, name_command, parse_name, parse_up_result, up_command, UpFailure, @@ -24,7 +25,6 @@ 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 @@ -47,12 +47,17 @@ const MAX_LINE_BYTES: usize = 4096; pub struct ConfigsRequest { /// Absolute folder on this machine. pub folder: String, + /// Environment owning the folder; omitted is this machine. + #[serde(default)] + pub runtime: Option, } /// `remote.devcontainerConfigs` result. #[derive(Debug, Default, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct Configs { + /// Native path the desktop uses for trust and confirmed configuration publication. + pub native_folder: String, /// The folder's configurations in the order the specification searches /// them; empty when it has none. pub configs: Vec, @@ -70,6 +75,9 @@ pub struct UpRequest { pub config: Option, /// Engine the CLI builds and runs the container with. pub engine: ContainerEngine, + /// Explicit environment selected from discovery; omitted preserves legacy behavior. + #[serde(default)] + pub runtime: Option, /// Whether the user trusts the folder, so its code may run here. pub project_code_allowed: bool, } @@ -93,6 +101,9 @@ pub struct Up { pub struct Devcontainer { /// Engine that runs the container. pub engine: ContainerEngine, + /// Exact environment used to build and inspect this container. + #[serde(skip_serializing_if = "Option::is_none")] + pub runtime: Option, /// The container's name, or its id when the engine did not name it. pub container: String, /// Full container id. @@ -106,9 +117,31 @@ pub struct Devcontainer { /// The configurations of the folder `request` names. pub fn configs(request: ConfigsRequest) -> Result { - let folder = local_folder(&request.folder)?; + let target = request.runtime.unwrap_or(RuntimeTarget { + engine: ContainerEngine::Docker, + context: None, + wsl: None, + }); + target.validate()?; + let resolved = resolve_folder(&request.folder, &target)?; + let native_folder = match target.wsl.as_deref() { + Some(_) => { + let argv = vec!["wslpath".into(), "-w".into(), resolved.clone()]; + let outcome = crate::container_runtimes::capture(&target, &argv, NAME_TIMEOUT)? + .filter(|outcome| outcome.status.is_some_and(|status| status.success())) + .ok_or_else(|| { + CoreError::new( + ErrorCode::InvalidRequest, + "Cannot resolve the native WSL workspace folder", + ) + })?; + String::from_utf8_lossy(&outcome.stdout).trim().to_owned() + } + None => resolved.clone(), + }; Ok(Configs { - configs: discover(&folder), + native_folder, + configs: configs_for_resolved(&resolved, &target)?, }) } @@ -126,25 +159,46 @@ pub(crate) fn up_with(request: UpRequest, program: Option<&str>) -> Result None, Some(config) => { - if !discover(&folder).iter().any(|listed| listed.path == config) { + if !listed.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()) + Some(if target.wsl.is_some() { + format!("{}/{}", resolved_folder.trim_end_matches('/'), config) + } else { + 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(); } + if target.wsl.is_some() { + argv[0] = "devcontainer".into(); + } let mut log = Log::default(); - let outcome = run_here(&argv, UP_TIMEOUT, |stream, bytes| { + let outcome = run_target(&target, &argv, UP_TIMEOUT, |stream, bytes| { if matches!(stream, lithe_git_host::Stream::Stderr) { log.push(bytes); } @@ -159,11 +213,12 @@ pub(crate) fn up_with(request: UpRequest, program: Option<&str>) -> Result { - let container = container_name(request.engine, &started.container_id, program) + let container = container_name(&target, &started.container_id, program) .unwrap_or_else(|| started.container_id.clone()); Ok(Up { container: Some(Devcontainer { engine: request.engine, + runtime: request.runtime, container, container_id: started.container_id, user: started.remote_user, @@ -180,6 +235,15 @@ pub(crate) fn up_with(request: UpRequest, program: Option<&str>) -> Result + { + Err(CoreError::new( + ErrorCode::RuntimeMissing, + "The Dev Container CLI is not installed in the selected WSL distribution", + )) + } 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'); @@ -219,19 +283,19 @@ fn local_folder(folder: &str) -> Result { } /// 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); +fn container_name(target: &RuntimeTarget, id: &str, program: Option<&str>) -> Option { + let mut argv = name_command(target.engine, id); if let Some(program) = program { argv[0] = program.into(); } - let outcome = run_here(&argv, NAME_TIMEOUT, |_, _| {}).ok()?; + let outcome = run_target(target, &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. +/// Why [`run_target`] has no outcome. enum Ran { /// Cancelled, out of time or failed while running. Stopped(CoreError), @@ -242,14 +306,13 @@ enum Ran { /// 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( +fn run_target( + target: &RuntimeTarget, 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 mut process = target.command(argv).map_err(Ran::Stopped)?; let deadline = Instant::now() + timeout; let mut stop = None; let outcome = lithe_git_host::run( @@ -274,7 +337,11 @@ fn run_here( } match outcome.failure { None => Ok(outcome), - Some(lithe_git_host::Failure::Start(_)) => Err(Ran::Missing), + Some(lithe_git_host::Failure::Start(error)) + if error.kind() == std::io::ErrorKind::NotFound => + { + Err(Ran::Missing) + } Some(failure) => Err(Ran::Stopped( CoreError::new(ErrorCode::ProcessFailed, "The Dev Container CLI failed") .with_details(format!("{failure:?}")), @@ -380,6 +447,7 @@ mod tests { folder: self.folder.to_string_lossy().into_owned(), config: config.map(Into::into), engine: ContainerEngine::Podman, + runtime: None, project_code_allowed: trusted, } } @@ -408,6 +476,7 @@ printf '{"outcome":"success","containerId":"abc123","remoteUser":"vscode","remot Up { container: Some(Devcontainer { engine: ContainerEngine::Podman, + runtime: None, container: "eager_turing".into(), container_id: "abc123".into(), user: Some("vscode".into()), @@ -491,6 +560,7 @@ exit 1"#, fn configurations_are_listed_for_absolute_existing_folders() { let fixture = Fixture::new("configs", STARTED, "exit 0"); let listed = configs(ConfigsRequest { + runtime: None, folder: fixture.folder.to_string_lossy().into_owned(), }) .unwrap(); @@ -502,6 +572,7 @@ exit 1"#, }] ); let relative = configs(ConfigsRequest { + runtime: None, folder: "app".into(), }); assert!(matches!( @@ -509,6 +580,7 @@ exit 1"#, ErrorCode::InvalidRequest )); let absent = configs(ConfigsRequest { + runtime: None, folder: fixture.root.join("absent").to_string_lossy().into_owned(), }); assert!(matches!( @@ -593,3 +665,246 @@ exit 1"#, assert!(events[sent].get("text").is_none()); } } + +#[cfg(test)] +#[path = "devcontainers/tests.rs"] +mod form_tests; + +/// Basic form fields. The resulting document remains the official CLI's input. +#[derive(Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields, default)] +pub struct PrepareRequest { + /// Optional human-readable configuration name. + pub name: String, + /// Image reference, mutually exclusive with dockerfile. + pub image: String, + /// Workspace-relative Dockerfile path. + pub dockerfile: String, + /// Workspace-relative build context; defaults to the workspace root. + pub build_context: String, + /// Container account, empty to preserve the image default. + pub remote_user: String, + /// Absolute workspace path in the container, empty to preserve the CLI default. + pub workspace_folder: String, + /// Comma or whitespace separated TCP port numbers published with loopback appPort bindings. + pub ports: String, + /// Explicit user-authored command executed after creation by the official CLI. + pub post_create_command: String, +} + +/// A validated, standard configuration to publish only after explicit user confirmation. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Prepared { + /// Workspace-relative write destination; never inside the application installation. + pub path: String, + /// Pretty-printed JSON consumed by agents and the reference CLI alike. + pub content: String, +} + +/// Validates form input and renders standard devcontainer.json without performing I/O. +pub fn prepare(request: PrepareRequest) -> Result { + let invalid = |field| { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid dev container configuration field", + ) + .with_details(json!({"field":field}).to_string()) + }; + let image = request.image.trim(); + let dockerfile = request.dockerfile.trim(); + if image.is_empty() == dockerfile.is_empty() { + return Err(invalid("image")); + } + let mut value = serde_json::Map::new(); + if !image.is_empty() { + if image.len() > 512 + || image.starts_with('-') + || image.chars().any(char::is_whitespace) + || image.chars().any(char::is_control) + { + return Err(invalid("image")); + } + value.insert("image".into(), json!(image)); + } else { + let relative = |text: &str| { + !text.is_empty() + && text.len() <= 1024 + && !text.starts_with('/') + && !text.contains('\\') + && !text.contains(':') + && !text.chars().any(char::is_control) + && text.split('/').all(|part| part != "..") + }; + if !relative(dockerfile) { + return Err(invalid("dockerfile")); + } + let context = if request.build_context.trim().is_empty() { + "." + } else { + request.build_context.trim() + }; + if !relative(context) { + return Err(invalid("buildContext")); + } + // Both paths are relative to .devcontainer/devcontainer.json, not the workspace. + value.insert( + "build".into(), + json!({"dockerfile":format!("../{dockerfile}"),"context":format!("../{context}")}), + ); + } + for (key, text, maximum) in [ + ("name", request.name.trim(), 128), + ("remoteUser", request.remote_user.trim(), 64), + ("workspaceFolder", request.workspace_folder.trim(), 4096), + ( + "postCreateCommand", + request.post_create_command.trim(), + 8192, + ), + ] { + if text.len() > maximum || text.contains('\0') { + return Err(invalid(key)); + } + if key == "remoteUser" + && !text.is_empty() + && !lithe_remote::client::transport::is_container_user(text) + { + return Err(invalid(key)); + } + if key == "workspaceFolder" + && !text.is_empty() + && (!text.starts_with('/') || text.chars().any(char::is_control)) + { + return Err(invalid(key)); + } + if !text.is_empty() { + value.insert(key.into(), json!(text)); + } + } + let mut ports = Vec::::new(); + for port in request + .ports + .split(|c: char| c == ',' || c.is_whitespace()) + .filter(|p| !p.is_empty()) + { + let port = port + .parse::() + .ok() + .filter(|p| *p != 0) + .ok_or_else(|| invalid("ports"))?; + if !ports.contains(&port) { + ports.push(port); + } + if ports.len() > 64 { + return Err(invalid("ports")); + } + } + if !ports.is_empty() { + value.insert( + "appPort".into(), + json!(ports + .into_iter() + .map(|port| format!("127.0.0.1:{port}:{port}")) + .collect::>()), + ); + } + Ok(Prepared { + path: ".devcontainer/devcontainer.json".into(), + content: format!( + "{}\n", + serde_json::to_string_pretty(&value).expect("configuration encodes") + ), + }) +} + +/// Resolves a Windows folder in WSL without assuming its automount prefix. +fn resolve_folder(folder: &str, target: &RuntimeTarget) -> Result { + if target.wsl.is_none() { + return Ok(local_folder(folder)?.to_string_lossy().into_owned()); + } + if folder.is_empty() || folder.len() > 4096 || folder.chars().any(char::is_control) { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Invalid WSL workspace folder", + )); + } + if folder.starts_with('/') { + return Ok(folder.into()); + } + if !lithe_platform::paths::is_absolute_path(folder, lithe_platform::Platform::Windows) { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "The WSL workspace folder must be an absolute Linux or Windows path", + )); + } + let argv = vec!["wslpath".into(), "-a".into(), "-u".into(), folder.into()]; + let result = crate::container_runtimes::capture(target, &argv, NAME_TIMEOUT)? + .filter(|o| o.status.is_some_and(|s| s.success())) + .ok_or_else(|| { + CoreError::new( + ErrorCode::InvalidRequest, + "Cannot resolve the folder in WSL", + ) + })?; + let resolved = String::from_utf8_lossy(&result.stdout).trim().to_string(); + if !resolved.starts_with('/') { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Invalid WSL workspace folder", + )); + } + Ok(resolved) +} + +fn configs_for(folder: &str, target: &RuntimeTarget) -> Result, CoreError> { + target.validate()?; + let folder = resolve_folder(folder, target)?; + configs_for_resolved(&folder, target) +} + +fn configs_for_resolved( + folder: &str, + target: &RuntimeTarget, +) -> Result, CoreError> { + if target.wsl.is_none() { + return Ok(discover(Path::new(folder))); + } + // Positional arguments keep workspace paths out of shell source. Enumeration is read-only. + let script = r#"cd -- "$1" || exit 3 +for file in .devcontainer/devcontainer.json .devcontainer.json .devcontainer/*/devcontainer.json; do + [ ! -f "$file" ] || printf '%s\0' "$file" +done"#; + let argv = vec![ + "sh".into(), + "-c".into(), + script.into(), + "lithe-configs".into(), + folder.into(), + ]; + let outcome = crate::container_runtimes::capture(target, &argv, NAME_TIMEOUT)? + .ok_or_else(|| CoreError::new(ErrorCode::RuntimeMissing, "WSL is unavailable"))?; + if !outcome.status.is_some_and(|s| s.success()) { + return Err(CoreError::new( + ErrorCode::WorkspaceNotFound, + "The folder does not exist in WSL", + )); + } + let mut found = Vec::new(); + for path in String::from_utf8_lossy(&outcome.stdout) + .split('\0') + .filter(|path| !path.is_empty() && !path.chars().any(char::is_control)) + .take(66) + { + if !found + .iter() + .any(|config: &DevcontainerConfig| config.path == path) + { + found.push(DevcontainerConfig { + path: path.into(), + name: None, + }); + } + } + Ok(found) +} diff --git a/rust/crates/workspace/src/devcontainers/tests.rs b/rust/crates/workspace/src/devcontainers/tests.rs new file mode 100644 index 00000000..f18c4359 --- /dev/null +++ b/rust/crates/workspace/src/devcontainers/tests.rs @@ -0,0 +1,39 @@ +//! Shared examples for the form's standard configuration and rejected fields. + +use super::*; + +#[test] +fn basic_forms_follow_the_shared_configuration_fixture() { + let fixture: serde_json::Value = serde_json::from_str(include_str!( + "../../../../fixtures/remote/devcontainer-configuration-v1.json" + )) + .unwrap(); + for case in fixture["cases"].as_array().unwrap() { + let request: PrepareRequest = serde_json::from_value(case["form"].clone()).unwrap(); + let result = prepare(request); + if let Some(field) = case["invalidField"].as_str() { + let error = result.unwrap_err(); + assert!(matches!(error.code, ErrorCode::InvalidRequest)); + let details: serde_json::Value = + serde_json::from_str(error.details.as_deref().unwrap()).unwrap(); + assert_eq!(details["field"], field, "{}", case["id"]); + } else { + let prepared = result.unwrap(); + assert_eq!(prepared.path, case["path"], "{}", case["id"]); + let configuration: serde_json::Value = serde_json::from_str(&prepared.content).unwrap(); + assert_eq!(configuration, case["configuration"], "{}", case["id"]); + } + } + let rejected = configs(ConfigsRequest { + folder: ".".into(), + runtime: Some(RuntimeTarget { + engine: ContainerEngine::Podman, + context: Some("docker-only".into()), + wsl: None, + }), + }); + assert!(matches!( + rejected.unwrap_err().code, + ErrorCode::InvalidRequest + )); +} diff --git a/rust/crates/workspace/src/lib.rs b/rust/crates/workspace/src/lib.rs index f155736d..ae795e9f 100644 --- a/rust/crates/workspace/src/lib.rs +++ b/rust/crates/workspace/src/lib.rs @@ -29,6 +29,7 @@ //! this crate only supplies the IO boundary. pub mod connections; +pub mod container_runtimes; pub mod containers; pub mod devcontainers; pub mod forwards; diff --git a/rust/fixtures/remote/devcontainer-configuration-v1.json b/rust/fixtures/remote/devcontainer-configuration-v1.json new file mode 100644 index 00000000..d75ed78e --- /dev/null +++ b/rust/fixtures/remote/devcontainer-configuration-v1.json @@ -0,0 +1,34 @@ +{ + "cases": [ + { + "id": "image-and-loopback-ports", + "form": { + "name": "API", + "image": "debian:bookworm-slim", + "remoteUser": "dev", + "ports": "3000, 8080 3000", + "postCreateCommand": "echo ready" + }, + "path": ".devcontainer/devcontainer.json", + "configuration": { + "image": "debian:bookworm-slim", + "name": "API", + "remoteUser": "dev", + "postCreateCommand": "echo ready", + "appPort": ["127.0.0.1:3000:3000", "127.0.0.1:8080:8080"] + } + }, + { + "id": "workspace-relative-dockerfile", + "form": {"dockerfile": "docker/Dockerfile", "buildContext": "."}, + "path": ".devcontainer/devcontainer.json", + "configuration": {"build": {"dockerfile": "../docker/Dockerfile", "context": "../."}} + }, + {"id": "no-source", "form": {}, "invalidField": "image"}, + {"id": "two-sources", "form": {"image": "debian", "dockerfile": "Dockerfile"}, "invalidField": "image"}, + {"id": "outside-workspace", "form": {"dockerfile": "../../Dockerfile"}, "invalidField": "dockerfile"}, + {"id": "invalid-port", "form": {"image": "debian", "ports": "70000"}, "invalidField": "ports"} + ], + "connection": {"engine": "docker", "context": "orbstack", "container": "api", "user": "dev"}, + "identity": "docker[orbstack]:dev@api" +}