Skip to content

Commit 2e9740d

Browse files
authored
feat(remote): 进入 Docker/Podman 容器、列出运行中的容器,并用 Dev Container CLI 从 devcontainer.json 启动 (#2231) (#162)
* feat(remote): 进入 Docker/Podman 容器与列出运行中的容器 (#2231) remote.connect 新增 container:单独出现时由本机的 docker/podman exec 进入, 跟在 connection 或 wsl 后面时在那台主机登录后再 exec 进入。只进入正在运行的容器, 不启动、不创建、不改动容器,不挂载目录,不提升权限(S32)。信任目标包含容器, 日志 transport 只记 container / ssh-container / wsl-container,不记容器名。 新增 remote.listContainers:在本机或已连接会话的主机上运行 <engine> ps, 最多 15 秒、256 个容器、256 KiB 输出;没有引擎时 available=false, 引擎报错时返回脱敏后的提示,只显示、不写日志。 * feat(remote): 用官方 Dev Container CLI 构建并启动本机文件夹的 dev container (#2231) - 新增 remote.devcontainerConfigs:按规范位置列出本机文件夹的 devcontainer.json(.devcontainer/devcontainer.json、.devcontainer.json、 .devcontainer/<子目录>/devcontainer.json),按 JSONC 读取 name; 只读文件夹内、不超过 1 MiB 的普通文件,不启动任何程序。 - 新增 remote.devcontainerUp:运行 devcontainer up --workspace-folder [--config],Podman 在 up 之后加 --docker-path podman;最长一小时,可取消。 文件夹不受信任(projectCodeAllowed=false)时什么都不运行,返回新错误码 devcontainer_untrusted_folder;config 只能是列出的路径;没有 CLI 为 runtime_missing。 - stderr 日志按行以 devcontainerOutput 事件发给窗口,脱敏,单行 4 KiB、 总共 2 MiB,之后发一次 truncated;只显示,不写日志。 - 结果读 stdout 最后一行 outcome JSON:成功时返回 engine、容器名(inspect 得到,没有时用 id)、containerId、remoteUser 与 remoteWorkspaceFolder, 供 remote.connect 的 container 进入;CLI 报错时返回脱敏的日志尾部和 message/description。Lithe 不解释配置,不额外挂载或加参数(S32)。 - 契约文档与错误码列表同步更新。 * test(remote): devcontainerUp 的构建日志按行脱敏、超长行分段、超出上限只发一次截断 (#2231) - 补 Log 的单元测试:跨两次读取的凭据作为同一行脱敏,CRLF 不进入文本; 超过 4096 字节的行分段发送,剩余部分在 CLI 退出时发出。 - 超过 2 MiB 后只发一次 truncated 事件,之后的行都不再发送。
1 parent dc4a648 commit 2e9740d

21 files changed

Lines changed: 2395 additions & 63 deletions

File tree

‎rust/contracts/application-boundary.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,8 @@ meaning; `lithe_protocol::ErrorCode` documents when it is reported:
416416
- `reverse_forward_disabled`: the remote workspace settings do not allow reverse forwards
417417
- `remote_server_invalid`: the server build `remote.connect` would send cannot
418418
be read or is not the build its SHA-256 names
419+
- `devcontainer_untrusted_folder`: the folder is not trusted, so its dev
420+
container was not built or started
419421
- `unknown`
420422

421423
GitHub authorization is independent of a Lithe account. Device Flow is the

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

Lines changed: 118 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -833,6 +833,9 @@ or removing a command fails until the table changes in the same commit.
833833
| `remote.sshConfigHosts` | List the Host aliases of the user's SSH configuration for an import |
834834
| `remote.mottyHosts` | List the SSH hosts saved in Motty for an import |
835835
| `remote.listWslDistributions` | List the WSL distributions installed on this Windows machine |
836+
| `remote.listContainers` | List the running Docker or Podman containers on this machine or a connected host |
837+
| `remote.devcontainerConfigs` | List the `devcontainer.json` files of a local folder |
838+
| `remote.devcontainerUp` | Build or reuse and start a trusted local folder's dev container with the Dev Container CLI |
836839
| `remote.preferences` | Read the remote workspace settings and what each automatic value resolves to |
837840
| `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 |
838841
| `remote.runningPrograms` | List the processes and terminals a connection's host session still runs |
@@ -5941,6 +5944,85 @@ its redacted message for display; it is never logged. Cancellation and the
59415944
bound are `cancelled` and `timed_out`. Nothing is saved: the window lists
59425945
the distributions each time it opens.
59435946

5947+
`remote.listContainers` takes `{ engine, sessionId? }`, where `engine` is
5948+
`docker` or `podman`, and returns `{ available, containers, diagnostics }`.
5949+
Core runs `<engine> ps --no-trunc --format '{{.ID}}\t{{.Names}}\t{{.Image}}\t{{.Status}}'`,
5950+
at most 15 seconds: on this machine in Core's own environment (the login
5951+
shell's `PATH` the application put in front, and variables such as
5952+
`DOCKER_HOST`) when `sessionId` is absent, and otherwise on that
5953+
connection's host in the server's environment, the same one the connection
5954+
later enters the container from. Only running containers are listed, since
5955+
Lithe never starts, creates or changes a container. `containers` are
5956+
`{ id, name, image, status }` in the engine's order, at most 256 and from at
5957+
most 256 KiB of output: `id` is the full id, `name` the first of the
5958+
container's names, and `image` and `status` the engine's text without
5959+
control characters, at most 256 bytes each. Lines that are not four fields,
5960+
or whose id or name is not a container name, are skipped, and so are
5961+
repeated ids. `available` is `false` when the engine CLI cannot start there;
5962+
when it runs and fails, for example because its service is not running,
5963+
`containers` is empty and `diagnostics` holds its redacted message for
5964+
display; it is never logged. Any other field is `invalid_request` ("Invalid
5965+
container listing request"), so a request cannot pick the program; an unknown
5966+
`sessionId` is `connection_closed`, and cancellation and the bound are
5967+
`cancelled` and `timed_out`. Nothing is saved.
5968+
5969+
#### Dev Containers
5970+
5971+
A local folder's dev container is built and started by the reference Dev
5972+
Container CLI (`devcontainer`, from `@devcontainers/cli`; `devcontainer.cmd`
5973+
on Windows) on `PATH`, then entered like any running container with
5974+
`remote.connect`'s `container`. Lithe does not interpret the configuration
5975+
and adds no mounts or options to it.
5976+
5977+
`remote.devcontainerConfigs` takes `{ folder }`, an absolute folder on this
5978+
machine, and returns `{ configs }`: `{ path, name? }` for each regular file in
5979+
the places the specification searches, in this order:
5980+
`.devcontainer/devcontainer.json`, `.devcontainer.json`, then
5981+
`.devcontainer/<subfolder>/devcontainer.json` for at most 64 subfolders in
5982+
name order, skipping names that start with `.`. `path` is relative to the
5983+
folder with `/` separators. `name` is the configuration's `name`, read as
5984+
JSON with comments and trailing commas, without control characters and at
5985+
most 128 bytes; it is absent when the file is larger than 1 MiB, resolves
5986+
outside the folder, cannot be read or has no non-empty string `name`. A
5987+
relative or empty `folder` is `invalid_request`; a folder that does not
5988+
exist is `workspace_not_found`. Reading starts nothing.
5989+
5990+
`remote.devcontainerUp` takes `{ folder, config?, engine,
5991+
projectCodeAllowed }` and returns `{ container?, diagnostics }`. Building runs
5992+
the folder's code on this machine (`initializeCommand`, Dockerfiles, feature
5993+
scripts), so when `projectCodeAllowed` is `false` nothing starts and the
5994+
request fails with `devcontainer_untrusted_folder`; native clients pass the
5995+
folder's trust decision, as for Git. `config` must be one of the `path`s
5996+
`remote.devcontainerConfigs` lists for the folder, otherwise
5997+
`invalid_request`; without it the CLI searches the folder itself. Core runs
5998+
`devcontainer up --workspace-folder <folder> [--config <folder>/<config>]`,
5999+
adding `--docker-path podman` after `up` for `engine: "podman"`, on this
6000+
machine in Core's own environment, for at most one hour. Each line the CLI
6001+
logs to standard error is sent as a `{ type: "devcontainerOutput", text }`
6002+
event, redacted, at most 4096 bytes per event and 2 MiB in all; after that
6003+
one `{ type: "devcontainerOutput", truncated: true }` event follows and later
6004+
lines are dropped. The log is shown, never logged.
6005+
6006+
The result is the last line of standard output that is a JSON object with an
6007+
`outcome`:
6008+
6009+
- `success`: `container` is `{ engine, container, containerId, user?,
6010+
workspaceFolder }`. `containerId` is the CLI's container id, `container` the
6011+
name `<engine> inspect --format '{{.Name}}'` gives within 15 seconds
6012+
(without Docker's leading `/`), or the id when it gives none, `user` the
6013+
configuration's `remoteUser`, and `workspaceFolder` the absolute
6014+
`remoteWorkspaceFolder` to open. A container id that is not a container
6015+
name, a user `exec` cannot take, or a folder that is not absolute is
6016+
`parse_failed`, and so is a successful exit without a result line.
6017+
- `error`, or no result line with a failed exit: `container` is absent and
6018+
`diagnostics` holds the end of the CLI's log followed by its `message` and
6019+
`description`, redacted, for display.
6020+
6021+
A missing CLI is `runtime_missing`; any other field is `invalid_request`
6022+
("Invalid dev container start request"), so a request cannot add mounts or
6023+
pick the program; cancellation and the bound are `cancelled` and
6024+
`timed_out`. Nothing is saved.
6025+
59446026
#### Remote workspace preferences
59456027

59466028
The settings page "Tools › Remote Workspace" edits three values that apply to
@@ -6075,14 +6157,43 @@ because `wsl.exe` asks no questions. An unknown distribution is
60756157
the distribution and the account (`{ wsl: { distribution, user } }` as the
60766158
first and only hop).
60776159

6160+
The request may also name a running container as `container: { engine,
6161+
container, user? }`, where `engine` is `docker` or `podman`, `container` a
6162+
name or id such as `remote.listContainers` returned, and `user` a user, uid or
6163+
`user:group` inside it (the image's default user when absent or empty). Next
6164+
to `connection` or `wsl` the container is on that host: the remote command
6165+
becomes `<engine> exec -i [-u <user>] <container> …` there, after the login.
6166+
On its own the container is on this machine, and Core starts that command
6167+
itself in place of OpenSSH, with its own environment so the engine finds its
6168+
service. Core only enters the running container: it never starts, creates or
6169+
reconfigures it, mounts directories into it or asks for more rights than the
6170+
engine CLI has. The probe, the checked upload into the container's `$HOME`
6171+
and the stages are the same, and nothing is relayed through
6172+
`remote.authRespond` for the engine. When the engine gives up before the
6173+
server starts, a container that does not exist, is not running or is paused,
6174+
and an engine whose service does not answer, are `unreachable`; a service
6175+
socket the user may not open is `failed`, not `authenticationFailed`, even
6176+
over SSH; and other failures are `failed` with the engine's message in
6177+
`diagnostics` (or `<engine> exited with status <code>` when it printed
6178+
nothing). The connection log's `transport` is `container`, `ssh-container` or
6179+
`wsl-container`, without the container's name. Trust decisions name the
6180+
container after the other hops, as `{ container: { engine, program,
6181+
container, user? } }`, so a decision never carries over to another container
6182+
or account.
6183+
60786184
A request that names both `connection` and `wsl` is `invalid_request` with
6079-
`details` `{ field: "wsl", reason: "invalid" }`, and one that names neither
6080-
`{ field: "connection", reason: "required" }`. A malformed connection, a
6081-
distribution that is empty, longer than 64 bytes or not a WSL distribution
6082-
name, a user that is longer than 32 bytes or not a Linux login name, an
6083-
unknown `target` or a `sha256` that is not 64 hexadecimal digits is
6084-
`invalid_request`, before OpenSSH or `wsl.exe` starts. A missing `ssh` or
6085-
`wsl.exe` is `runtime_missing`. When the build for the host's platform cannot be
6185+
`details` `{ field: "wsl", reason: "invalid" }`, and one that names none of
6186+
`connection`, `wsl` and `container` `{ field: "connection", reason:
6187+
"required" }`. A malformed connection, a distribution that is empty, longer
6188+
than 64 bytes or not a WSL distribution name, a user that is longer than 32
6189+
bytes or not a Linux login name, a container that is empty (`{ field:
6190+
"container", reason: "required" }`), longer than 128 bytes or not a container
6191+
name, a container user that is longer than 64 bytes, starts with `-` or holds
6192+
other characters than letters, digits and `_.:-` (`{ field: "user" }`), an
6193+
unknown `engine` or field, an unknown `target` or a `sha256` that is not 64
6194+
hexadecimal digits is `invalid_request`, before OpenSSH, `wsl.exe` or the
6195+
engine starts. A missing `ssh`, `wsl.exe` or local engine CLI is
6196+
`runtime_missing`. When the build for the host's platform cannot be
60866197
read or its SHA-256 differs, the attempt ends as `remote_server_invalid`
60876198
without sending anything; `details` says which of the two happened and, for a
60886199
mismatch, the SHA-256 Core computed, but never the path. Cancellation and the

‎rust/crates/core/src/protocol/command.rs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1055,6 +1055,15 @@ pub enum RemoteCommand {
10551055
/// Lists the WSL distributions installed on this Windows machine
10561056
/// (`remote.listWslDistributions`).
10571057
ListWslDistributions,
1058+
/// Lists the running containers of a container engine on this machine
1059+
/// or on a connected host (`remote.listContainers`).
1060+
ListContainers,
1061+
/// Lists the `devcontainer.json` files of a local folder
1062+
/// (`remote.devcontainerConfigs`).
1063+
DevcontainerConfigs,
1064+
/// Builds or reuses and starts a local folder's dev container with the
1065+
/// Dev Container CLI (`remote.devcontainerUp`).
1066+
DevcontainerUp,
10581067
/// Reads the remote workspace preferences and what each automatic value
10591068
/// resolves to (`remote.preferences`).
10601069
Preferences,
@@ -1651,6 +1660,9 @@ impl CoreCommand {
16511660
"remote.listWslDistributions" => {
16521661
Some(Self::Remote(RemoteCommand::ListWslDistributions))
16531662
}
1663+
"remote.listContainers" => Some(Self::Remote(RemoteCommand::ListContainers)),
1664+
"remote.devcontainerConfigs" => Some(Self::Remote(RemoteCommand::DevcontainerConfigs)),
1665+
"remote.devcontainerUp" => Some(Self::Remote(RemoteCommand::DevcontainerUp)),
16541666
"remote.preferences" => Some(Self::Remote(RemoteCommand::Preferences)),
16551667
"remote.editPreferences" => Some(Self::Remote(RemoteCommand::EditPreferences)),
16561668
"remote.runningPrograms" => Some(Self::Remote(RemoteCommand::RunningPrograms)),

‎rust/crates/core/src/runtime/dispatcher/remote.rs‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,37 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option<String>, payload: Valu
361361
),
362362
Err(error) => CoreResponse::failure(id, error),
363363
},
364+
RemoteCommand::ListContainers => answer(
365+
id,
366+
payload,
367+
"Invalid container listing request",
368+
|request| {
369+
lithe_workspace::containers::list(request).map(|listed| {
370+
serde_json::to_value(listed).expect("container listings should encode")
371+
})
372+
},
373+
),
374+
RemoteCommand::DevcontainerConfigs => answer(
375+
id,
376+
payload,
377+
"Invalid dev container configuration request",
378+
|request| {
379+
lithe_workspace::devcontainers::configs(request).map(|listed| {
380+
serde_json::to_value(listed)
381+
.expect("dev container configurations should encode")
382+
})
383+
},
384+
),
385+
RemoteCommand::DevcontainerUp => answer(
386+
id,
387+
payload,
388+
"Invalid dev container start request",
389+
|request| {
390+
lithe_workspace::devcontainers::up(request).map(|started| {
391+
serde_json::to_value(started).expect("dev container starts should encode")
392+
})
393+
},
394+
),
364395
RemoteCommand::AuthRespond => {
365396
#[derive(serde::Deserialize)]
366397
#[serde(rename_all = "camelCase", deny_unknown_fields)]

‎rust/crates/core/src/tests/remote_sessions.rs‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1638,6 +1638,37 @@ fn connection_window_helpers_answer_through_the_dispatcher() {
16381638
assert_eq!(both["error"]["code"], "invalid_request", "{both}");
16391639
let details: Value = serde_json::from_str(both["error"]["details"].as_str().unwrap()).unwrap();
16401640
assert_eq!(details, json!({"field": "wsl", "reason": "invalid"}));
1641+
// A container listing names a known engine and nothing that could pick
1642+
// the program.
1643+
for payload in [
1644+
json!({"engine": "nerdctl"}),
1645+
json!({"engine": "docker", "program": "/bin/sh"}),
1646+
] {
1647+
let refused = call("remote.listContainers", payload);
1648+
assert_eq!(refused["error"]["code"], "invalid_request", "{refused}");
1649+
assert_eq!(
1650+
refused["error"]["message"], "Invalid container listing request",
1651+
"{refused}"
1652+
);
1653+
}
1654+
// A dev container starts only for a trusted folder, from a configuration
1655+
// the folder lists; nothing runs otherwise.
1656+
let untrusted = call(
1657+
"remote.devcontainerUp",
1658+
json!({"folder": "/nonexistent", "engine": "docker", "projectCodeAllowed": false}),
1659+
);
1660+
assert_eq!(
1661+
untrusted["error"]["code"], "devcontainer_untrusted_folder",
1662+
"{untrusted}"
1663+
);
1664+
let unknown = call(
1665+
"remote.devcontainerUp",
1666+
json!({"folder": "/nonexistent", "engine": "docker", "projectCodeAllowed": true,
1667+
"mounts": ["/"]}),
1668+
);
1669+
assert_eq!(unknown["error"]["code"], "invalid_request", "{unknown}");
1670+
let relative = call("remote.devcontainerConfigs", json!({"folder": "app"}));
1671+
assert_eq!(relative["error"]["code"], "invalid_request", "{relative}");
16411672

16421673
// The settings page reads automatic values and stores an edit; a damaged
16431674
// document stops the SSH commands before OpenSSH starts.
@@ -1993,6 +2024,48 @@ fn remote_host_and_reverse_forwards_follow_their_own_rules() {
19932024
);
19942025
}
19952026

2027+
// The connection window lists a connected host's containers through the
2028+
// host's own engine CLI; a host without one says so instead of failing.
2029+
#[test]
2030+
fn container_listings_run_on_the_host_and_say_when_it_has_no_engine() {
2031+
use std::os::unix::fs::PermissionsExt;
2032+
let host = HostFixture::new();
2033+
let engine = host.root.join("host/docker");
2034+
std::fs::write(
2035+
&engine,
2036+
"#!/bin/sh\nprintf 'c0ffee\\tdev\\tubuntu:24.04\\tUp 1 minute\\n'\n",
2037+
)
2038+
.unwrap();
2039+
std::fs::set_permissions(&engine, std::fs::Permissions::from_mode(0o755)).unwrap();
2040+
let request = |engine: &str| {
2041+
serde_json::from_value(json!({"engine": engine, "sessionId": host.id})).unwrap()
2042+
};
2043+
let listed =
2044+
test_support::list_containers_with(request("docker"), engine.to_str().unwrap()).unwrap();
2045+
assert_eq!(
2046+
serde_json::to_value(listed).unwrap(),
2047+
json!({"available": true, "diagnostics": "", "containers": [
2048+
{"id": "c0ffee", "name": "dev", "image": "ubuntu:24.04", "status": "Up 1 minute"}
2049+
]})
2050+
);
2051+
let absent = host.root.join("host/absent");
2052+
let missing =
2053+
test_support::list_containers_with(request("podman"), absent.to_str().unwrap()).unwrap();
2054+
assert_eq!(
2055+
serde_json::to_value(missing).unwrap(),
2056+
json!({"available": false, "containers": [], "diagnostics": ""})
2057+
);
2058+
let unknown = test_support::list_containers_with(
2059+
serde_json::from_value(json!({"engine": "docker", "sessionId": "absent"})).unwrap(),
2060+
engine.to_str().unwrap(),
2061+
)
2062+
.unwrap_err();
2063+
assert!(
2064+
matches!(unknown.code, ErrorCode::ConnectionClosed),
2065+
"{unknown:?}"
2066+
);
2067+
}
2068+
19962069
#[test]
19972070
fn remote_programs_are_listed_ended_and_kept_only_by_a_persistent_session() {
19982071
use lithe_remote::client::api::{SpawnSpec, TerminalEvent, TerminalSpec};

0 commit comments

Comments
 (0)