Skip to content

Commit 72036de

Browse files
authored
feat(plugins): 命令安装器支持固定 URL 归档下载(commandInstallers 1) (#133)
API-23 的 commandInstallers 升到能力版本 1,新增 download 安装方式: 插件按平台声明固定 HTTPS URL、可选镜像、完整 SHA-256、zip/tar.gz 格式和 stripPrefix,宿主下载、校验、解压后在 managed 目标的 commandDirectory 下查找命令。 - 新增 archives.rs,managedRuntimes 与 commandInstallers 共用归档声明校验。 - requirements/plan 接受宿主平台;下载计划给出所选归档、cacheKey 和命令目录。 - 更新 manifest schema、契约 README、fixture、能力版本表与协议更新记录。
1 parent 4ef9d9e commit 72036de

16 files changed

Lines changed: 1230 additions & 236 deletions

File tree

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

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4875,29 +4875,43 @@ inside an app bundle or installation directory.
48754875
The `plugins.commandInstallers.*` commands implement
48764876
[Command installers](../../shared/plugins/contract/v1/README.md#command-installers).
48774877
They revalidate the manifest, read nothing and start nothing.
4878-
`plugins.commandInstallers.requirements` accepts `{ manifest }` and returns
4879-
`requirements: { consumers: [{ kind, id, commands: [{ command, installer }] }],
4880-
installers: [{ id, commands, tool, minimumVersion, mayUseNetwork, targets }] }`.
4878+
`plugins.commandInstallers.requirements` accepts `{ manifest, platform?: { os,
4879+
arch } }` and returns `requirements: { consumers: [{ kind, id, commands: [{
4880+
command, installer }] }], installers: [{ id, commands, tool, minimumVersion,
4881+
download: null | { version }, mayUseNetwork, targets }] }`.
48814882
`kind` is `languageServer`, `buildProvider`, `vcsProvider`, `debugAdapter` or
48824883
`backend`; `id` is the language, build system, VCS or adapter ID, `null` for
4883-
the backend; `installer` is `null` for a command no installer provides.
4884+
the backend; `installer` is `null` for a command no installer provides. With
4885+
`platform`, a download installer without an archive for it is left out of
4886+
`installers` and its commands have a `null` installer.
48844887
`plugins.commandInstallers.plan` accepts `{ manifest, installerID, target:
4885-
"managed" | "toolDefault", installDirectory? }` and returns `plan: { installer,
4886-
target, commands, tool, minimumVersion, mayUseNetwork, timeoutMilliseconds,
4887-
arguments, environment, commandDirectory, directoryProbes: [{ arguments }] }`.
4888-
A `managed` plan needs the absolute directory the host made and expands
4888+
"managed" | "toolDefault", installDirectory?, platform? }` and returns `plan: {
4889+
installer, target, commands, tool, minimumVersion, mayUseNetwork,
4890+
timeoutMilliseconds, arguments, environment, commandDirectory, directoryProbes:
4891+
[{ arguments }], download }`. For a tool installer `download` is `null`. A
4892+
`managed` plan needs the absolute directory the host made and expands
48894893
`${installDirectory}` in it; `commandDirectory` is that directory or the
48904894
declared path below it, and `directoryProbes` is empty. A `toolDefault` plan
48914895
takes no `installDirectory`, has a `null` `commandDirectory` and lists the
4892-
probes. `plugins.commandInstallers.defaultDirectory` accepts `{ manifest,
4896+
probes. A download installer's plan needs `platform`, takes no
4897+
`installDirectory`, has empty `arguments`, `environment` and
4898+
`directoryProbes`, a `null` `commandDirectory`, and `download: { installer,
4899+
version, os, arch, url, sha256, archive, stripPrefix, cacheKey,
4900+
commandDirectory, mirrors? }` for the platform's archive. `cacheKey` is the
4901+
lowercase SHA-256 of the compact JSON `{installer, version, os, arch, url,
4902+
sha256, archive, stripPrefix}`, mirrors left out; `commandDirectory` is
4903+
relative to the extracted root. `plugins.commandInstallers.defaultDirectory` accepts `{ manifest,
48934904
installerID, outputs }`, one standard output per probe in plan order (`null`
48944905
for a probe that failed), and returns `directory`: the first probe output that
48954906
names an absolute directory, its first path-list entry for a `pathList` probe,
48964907
with `append` joined; `null` when none does. Paths follow the platform Core
48974908
runs on. Refusals are `plugin.commandInstaller.unknown`,
48984909
`plugin.commandInstaller.targetUndeclared`,
4899-
`plugin.commandInstaller.directoryInvalid` and
4900-
`plugin.commandInstaller.probeOutputsInvalid`; the golden cases are
4910+
`plugin.commandInstaller.directoryInvalid`,
4911+
`plugin.commandInstaller.probeOutputsInvalid`,
4912+
`plugin.commandInstaller.platformInvalid` (an unsupported `platform`, or none
4913+
for a download plan) and `plugin.commandInstaller.unavailable` (no archive for
4914+
the platform); the golden cases are
49014915
`shared/plugins/contract/v1/fixtures/command-installers/command-installer-plans.json`.
49024916

49034917
The `plugins.managedRuntimes.*` commands implement

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

Lines changed: 92 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,8 @@ const PROJECT_GENERATOR_TOOL_FIXTURE: &str =
6767
contract_file!("fixtures/project-generators/project-generator-tool-field.plugin.json");
6868
const COMMAND_INSTALLER_FIXTURE: &str =
6969
contract_file!("fixtures/command-installers/command-installer.plugin.json");
70+
const COMMAND_INSTALLER_DOWNLOAD_FIXTURE: &str =
71+
contract_file!("fixtures/command-installers/command-installer-download.plugin.json");
7072
const COMMAND_INSTALLER_PLANS: &str =
7173
contract_file!("fixtures/command-installers/command-installer-plans.json");
7274
const RUN_CONFIGURATION_TYPES_FIXTURE: &str =
@@ -106,6 +108,7 @@ fn fixture(name: &str) -> Value {
106108
"project-generator.plugin.json" => PROJECT_GENERATOR_FIXTURE,
107109
"project-generator-tool-field.plugin.json" => PROJECT_GENERATOR_TOOL_FIXTURE,
108110
"command-installer.plugin.json" => COMMAND_INSTALLER_FIXTURE,
111+
"command-installer-download.plugin.json" => COMMAND_INSTALLER_DOWNLOAD_FIXTURE,
109112
"run-configuration-types.plugin.json" => RUN_CONFIGURATION_TYPES_FIXTURE,
110113
"before-launch-tasks.plugin.json" => BEFORE_LAUNCH_TASKS_FIXTURE,
111114
other => panic!("unknown fixture {other}"),
@@ -140,6 +143,7 @@ fn contract_fixtures_and_official_plugins_validate() {
140143
EDITOR_PROVIDERS_FIXTURE,
141144
PROJECT_GENERATOR_TOOL_FIXTURE,
142145
COMMAND_INSTALLER_FIXTURE,
146+
COMMAND_INSTALLER_DOWNLOAD_FIXTURE,
143147
RUN_CONFIGURATION_TYPES_FIXTURE,
144148
BEFORE_LAUNCH_TASKS_FIXTURE,
145149
] {
@@ -279,7 +283,8 @@ fn command_installer_fixtures_match_on_this_host() {
279283
for case in plans["cases"].as_array().unwrap() {
280284
let name = case["name"].as_str().unwrap();
281285
let specific = &case["platforms"][platform];
282-
let mut payload = json!({ "manifest": fixture("command-installer.plugin.json") });
286+
let plugin = case.get("plugin").unwrap_or(&plans["plugin"]);
287+
let mut payload = json!({ "manifest": fixture(plugin.as_str().unwrap()) });
283288
for source in [&case["payload"], &specific["payload"]] {
284289
for (field, value) in source.as_object().into_iter().flatten() {
285290
payload[field] = value.clone();
@@ -342,6 +347,78 @@ fn command_installers_are_reviewed_programs() {
342347
assert_ne!(programs(changed), before);
343348
}
344349

350+
/// A download installer's review entry shows every archive it may fetch, so
351+
/// a new URL or digest is a new program the user approves again; it runs no
352+
/// tool, so the entry has no tool or arguments.
353+
#[test]
354+
fn download_installers_are_reviewed_programs() {
355+
let programs = |manifest: Value| {
356+
let outcome = lithe_plugin_marketplace::install_review_command(json!({
357+
"manifest": manifest,
358+
}))
359+
.expect("payload is well formed");
360+
outcome["review"]["programs"]
361+
.as_array()
362+
.unwrap()
363+
.iter()
364+
.filter(|program| program["kind"] == "commandInstaller")
365+
.cloned()
366+
.collect::<Vec<_>>()
367+
};
368+
let manifest = fixture("command-installer-download.plugin.json");
369+
let before = programs(manifest.clone());
370+
assert_eq!(before.len(), 1);
371+
let program = &before[0];
372+
assert_eq!(program["installer"], "sample-lldb");
373+
assert_eq!(program["timeoutSeconds"], 900);
374+
assert!(program.get("tool").is_none() && program.get("arguments").is_none());
375+
let artifacts = program["download"]["artifacts"].as_array().unwrap();
376+
assert_eq!(artifacts.len(), 3);
377+
// The review lists the digest Core checks, in lowercase.
378+
let macos = artifacts
379+
.iter()
380+
.find(|artifact| artifact["os"] == "macos")
381+
.unwrap();
382+
assert_eq!(
383+
macos["sha256"],
384+
"2f114a990e1b368dd1dbd33c80c0e719767af2d228391ec0df0571c957f9ac91"
385+
);
386+
for (pointer, value) in [
387+
(
388+
"/commandInstallers/0/download/artifacts/0/url",
389+
json!("https://downloads.example.org/other.zip"),
390+
),
391+
(
392+
"/commandInstallers/0/download/artifacts/1/sha256",
393+
json!("0".repeat(64)),
394+
),
395+
("/commandInstallers/0/download/version", json!("1.2.4")),
396+
] {
397+
let mut changed = manifest.clone();
398+
*changed.pointer_mut(pointer).unwrap() = value;
399+
assert_ne!(programs(changed), before, "{pointer}");
400+
}
401+
}
402+
403+
/// A host that declares `commandInstallers` 0 does not know download
404+
/// installers, so it refuses a plugin that needs them before installing it.
405+
#[test]
406+
fn download_installers_need_a_host_with_version_1() {
407+
let manifest = fixture("command-installer-download.plugin.json");
408+
let host = json!({ "commandInstallers": [0], "debugAdapters": [0], "languages": [0] });
409+
let refused = validate_command(json!({ "manifest": manifest, "hostCapabilities": host }))
410+
.expect("payload is well formed");
411+
assert_eq!(
412+
refused["error"]["code"], "plugin.api.unsupported",
413+
"{refused}"
414+
);
415+
assert_eq!(refused["error"]["field"], "requires.commandInstallers");
416+
let host = json!({ "commandInstallers": [0, 1], "debugAdapters": [0], "languages": [0] });
417+
let accepted = validate_command(json!({ "manifest": manifest, "hostCapabilities": host }))
418+
.expect("payload is well formed");
419+
assert_eq!(accepted["status"], "ok", "{accepted}");
420+
}
421+
345422
/// A malformed request is a Core failure, not a rejection.
346423
#[test]
347424
fn command_installer_requests_decode_strictly() {
@@ -354,6 +431,20 @@ fn command_installer_requests_decode_strictly() {
354431
json!({ "manifest": manifest, "installerID": "sample-ls" })
355432
)
356433
.is_err());
434+
// A platform names a supported pair by its two fields and nothing else.
435+
let manifest = fixture("command-installer-download.plugin.json");
436+
assert!(command_installer_plan_command(json!({
437+
"manifest": manifest,
438+
"installerID": "sample-lldb",
439+
"target": "managed",
440+
"platform": { "os": "macos" }
441+
}))
442+
.is_err());
443+
assert!(command_installer_requirements_command(json!({
444+
"manifest": manifest,
445+
"platform": { "os": "macos", "arch": "arm64", "libc": "musl" }
446+
}))
447+
.is_err());
357448
}
358449

359450
#[test]
Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
//! Pinned download archives: the platform target, source URLs, digest,
2+
//! format and layout paths that `managedRuntimes` dependencies and
3+
//! `commandInstallers` downloads share. Core validates the declaration and
4+
//! selects the archive for the host's platform; the host downloads, checks the
5+
//! digest and extracts.
6+
7+
use super::*;
8+
use lithe_platform::Platform;
9+
use url::Url;
10+
11+
/// Most platform archives one dependency or download declares: one per
12+
/// supported operating system and architecture.
13+
pub(crate) const MAX_ARTIFACTS: usize = 6;
14+
15+
/// Most fallback URLs one archive declares.
16+
pub(crate) const MAX_MIRRORS: usize = 8;
17+
18+
/// Operating systems an archive may target.
19+
pub(crate) const ARCHIVE_OPERATING_SYSTEMS: &[&str] = &["macos", "windows", "linux"];
20+
21+
/// Longest archive URL, in bytes.
22+
const MAX_URL_BYTES: usize = 4096;
23+
24+
/// Longest layout path inside an archive, in bytes.
25+
const MAX_LAYOUT_PATH_BYTES: usize = 512;
26+
27+
/// Text that is not empty, at most `maximum` bytes, without surrounding
28+
/// whitespace or control characters.
29+
pub(crate) fn bounded_text(value: &str, maximum: usize) -> bool {
30+
!value.is_empty()
31+
&& value.len() <= maximum
32+
&& value.trim() == value
33+
&& !value.chars().any(char::is_control)
34+
}
35+
36+
/// A layout path inside an archive: empty, or `/`-separated parts without an
37+
/// empty, `.` or `..` part, backslash or colon, so it means the same on every
38+
/// host. Native extraction also checks filesystem aliases and link targets.
39+
pub(crate) fn is_archive_layout_path(value: &str) -> bool {
40+
value.is_empty()
41+
|| (bounded_text(value, MAX_LAYOUT_PATH_BYTES)
42+
&& !value.contains(['\\', ':'])
43+
&& value
44+
.split('/')
45+
.all(|part| !part.is_empty() && part != "." && part != ".."))
46+
}
47+
48+
/// Whether `os` and `arch` name a platform an archive may target.
49+
pub(crate) fn is_archive_platform(os: &str, arch: &str) -> bool {
50+
ARCHIVE_OPERATING_SYSTEMS.contains(&os) && KNOWN_ARCHITECTURES.contains(&arch)
51+
}
52+
53+
/// The host platform a request selects an archive for.
54+
#[derive(Debug, Clone, Deserialize, Serialize)]
55+
#[serde(rename_all = "camelCase", deny_unknown_fields)]
56+
pub(crate) struct ArchivePlatform {
57+
/// macos, windows or linux.
58+
pub(crate) os: String,
59+
/// arm64 or x86_64.
60+
pub(crate) arch: String,
61+
}
62+
63+
impl ArchivePlatform {
64+
/// Whether an archive may target this platform.
65+
pub(crate) fn is_supported(&self) -> bool {
66+
is_archive_platform(&self.os, &self.arch)
67+
}
68+
69+
/// Whether an archive declared for `os` and `arch` is this platform's.
70+
pub(crate) fn matches(&self, os: &str, arch: &str) -> bool {
71+
self.os == os && self.arch == arch
72+
}
73+
74+
/// The path rules of this platform's filesystem.
75+
pub(crate) fn native_paths(&self) -> Platform {
76+
if self.os == "windows" {
77+
Platform::Windows
78+
} else {
79+
Platform::Unix
80+
}
81+
}
82+
}
83+
84+
/// Where one archive comes from and how to read it.
85+
pub(crate) struct ArchiveSource<'a> {
86+
pub(crate) url: &'a str,
87+
pub(crate) mirrors: &'a [String],
88+
pub(crate) sha256: &'a mut String,
89+
pub(crate) archive: &'a str,
90+
}
91+
92+
/// Checks one archive's URL, mirrors, digest and format, and lowercases the
93+
/// digest. `mirrors_allowed` runs only when the archive declares mirrors and
94+
/// rejects them when the manifest's capability version does not have them.
95+
pub(crate) fn validate_archive_source(
96+
field: &str,
97+
source: ArchiveSource<'_>,
98+
mirrors_allowed: impl FnOnce() -> Validation<()>,
99+
) -> Validation<()> {
100+
if !is_https_source(source.url) {
101+
return Err(invalid(
102+
format!("{field}.url"),
103+
"An archive URL uses HTTPS without credentials or fragments.",
104+
));
105+
}
106+
if !source.mirrors.is_empty() {
107+
mirrors_allowed()?;
108+
if source.mirrors.len() > MAX_MIRRORS {
109+
return Err(invalid(
110+
format!("{field}.mirrors"),
111+
format!("An archive declares at most {MAX_MIRRORS} mirror URLs."),
112+
));
113+
}
114+
let mut seen = BTreeSet::new();
115+
seen.insert(source.url);
116+
for (index, mirror) in source.mirrors.iter().enumerate() {
117+
let entry = format!("{field}.mirrors[{index}]");
118+
if !is_https_source(mirror) {
119+
return Err(invalid(
120+
entry,
121+
"A mirror URL uses HTTPS without credentials or fragments.",
122+
));
123+
}
124+
if !seen.insert(mirror.as_str()) {
125+
return Err(invalid(
126+
entry,
127+
"Mirror URLs are unique and differ from the primary URL.",
128+
));
129+
}
130+
}
131+
}
132+
if source.sha256.len() != 64 || !source.sha256.bytes().all(|byte| byte.is_ascii_hexdigit()) {
133+
return Err(invalid(
134+
format!("{field}.sha256"),
135+
"An archive pins its complete SHA-256 digest.",
136+
));
137+
}
138+
source.sha256.make_ascii_lowercase();
139+
if !["zip", "tar.gz"].contains(&source.archive) {
140+
return Err(invalid(
141+
format!("{field}.archive"),
142+
"An archive format is zip or tar.gz.",
143+
));
144+
}
145+
Ok(())
146+
}
147+
148+
/// An HTTPS URL with a host, without credentials or a fragment.
149+
fn is_https_source(value: &str) -> bool {
150+
let Ok(url) = Url::parse(value) else {
151+
return false;
152+
};
153+
bounded_text(value, MAX_URL_BYTES)
154+
&& url.scheme() == "https"
155+
&& url.host_str().is_some()
156+
&& url.username().is_empty()
157+
&& url.password().is_none()
158+
&& url.fragment().is_none()
159+
}

0 commit comments

Comments
 (0)