Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 25 additions & 11 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -4875,29 +4875,43 @@ inside an app bundle or installation directory.
The `plugins.commandInstallers.*` commands implement
[Command installers](../../shared/plugins/contract/v1/README.md#command-installers).
They revalidate the manifest, read nothing and start nothing.
`plugins.commandInstallers.requirements` accepts `{ manifest }` and returns
`requirements: { consumers: [{ kind, id, commands: [{ command, installer }] }],
installers: [{ id, commands, tool, minimumVersion, mayUseNetwork, targets }] }`.
`plugins.commandInstallers.requirements` accepts `{ manifest, platform?: { os,
arch } }` and returns `requirements: { consumers: [{ kind, id, commands: [{
command, installer }] }], installers: [{ id, commands, tool, minimumVersion,
download: null | { version }, mayUseNetwork, targets }] }`.
`kind` is `languageServer`, `buildProvider`, `vcsProvider`, `debugAdapter` or
`backend`; `id` is the language, build system, VCS or adapter ID, `null` for
the backend; `installer` is `null` for a command no installer provides.
the backend; `installer` is `null` for a command no installer provides. With
`platform`, a download installer without an archive for it is left out of
`installers` and its commands have a `null` installer.
`plugins.commandInstallers.plan` accepts `{ manifest, installerID, target:
"managed" | "toolDefault", installDirectory? }` and returns `plan: { installer,
target, commands, tool, minimumVersion, mayUseNetwork, timeoutMilliseconds,
arguments, environment, commandDirectory, directoryProbes: [{ arguments }] }`.
A `managed` plan needs the absolute directory the host made and expands
"managed" | "toolDefault", installDirectory?, platform? }` and returns `plan: {
installer, target, commands, tool, minimumVersion, mayUseNetwork,
timeoutMilliseconds, arguments, environment, commandDirectory, directoryProbes:
[{ arguments }], download }`. For a tool installer `download` is `null`. A
`managed` plan needs the absolute directory the host made and expands
`${installDirectory}` in it; `commandDirectory` is that directory or the
declared path below it, and `directoryProbes` is empty. A `toolDefault` plan
takes no `installDirectory`, has a `null` `commandDirectory` and lists the
probes. `plugins.commandInstallers.defaultDirectory` accepts `{ manifest,
probes. A download installer's plan needs `platform`, takes no
`installDirectory`, has empty `arguments`, `environment` and
`directoryProbes`, a `null` `commandDirectory`, and `download: { installer,
version, os, arch, url, sha256, archive, stripPrefix, cacheKey,
commandDirectory, mirrors? }` for the platform's archive. `cacheKey` is the
lowercase SHA-256 of the compact JSON `{installer, version, os, arch, url,
sha256, archive, stripPrefix}`, mirrors left out; `commandDirectory` is
relative to the extracted root. `plugins.commandInstallers.defaultDirectory` accepts `{ manifest,
installerID, outputs }`, one standard output per probe in plan order (`null`
for a probe that failed), and returns `directory`: the first probe output that
names an absolute directory, its first path-list entry for a `pathList` probe,
with `append` joined; `null` when none does. Paths follow the platform Core
runs on. Refusals are `plugin.commandInstaller.unknown`,
`plugin.commandInstaller.targetUndeclared`,
`plugin.commandInstaller.directoryInvalid` and
`plugin.commandInstaller.probeOutputsInvalid`; the golden cases are
`plugin.commandInstaller.directoryInvalid`,
`plugin.commandInstaller.probeOutputsInvalid`,
`plugin.commandInstaller.platformInvalid` (an unsupported `platform`, or none
for a download plan) and `plugin.commandInstaller.unavailable` (no archive for
the platform); the golden cases are
`shared/plugins/contract/v1/fixtures/command-installers/command-installer-plans.json`.

The `plugins.managedRuntimes.*` commands implement
Expand Down
93 changes: 92 additions & 1 deletion rust/crates/core/src/tests/declarative_plugins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ const PROJECT_GENERATOR_TOOL_FIXTURE: &str =
contract_file!("fixtures/project-generators/project-generator-tool-field.plugin.json");
const COMMAND_INSTALLER_FIXTURE: &str =
contract_file!("fixtures/command-installers/command-installer.plugin.json");
const COMMAND_INSTALLER_DOWNLOAD_FIXTURE: &str =
contract_file!("fixtures/command-installers/command-installer-download.plugin.json");
const COMMAND_INSTALLER_PLANS: &str =
contract_file!("fixtures/command-installers/command-installer-plans.json");
const RUN_CONFIGURATION_TYPES_FIXTURE: &str =
Expand Down Expand Up @@ -106,6 +108,7 @@ fn fixture(name: &str) -> Value {
"project-generator.plugin.json" => PROJECT_GENERATOR_FIXTURE,
"project-generator-tool-field.plugin.json" => PROJECT_GENERATOR_TOOL_FIXTURE,
"command-installer.plugin.json" => COMMAND_INSTALLER_FIXTURE,
"command-installer-download.plugin.json" => COMMAND_INSTALLER_DOWNLOAD_FIXTURE,
"run-configuration-types.plugin.json" => RUN_CONFIGURATION_TYPES_FIXTURE,
"before-launch-tasks.plugin.json" => BEFORE_LAUNCH_TASKS_FIXTURE,
other => panic!("unknown fixture {other}"),
Expand Down Expand Up @@ -140,6 +143,7 @@ fn contract_fixtures_and_official_plugins_validate() {
EDITOR_PROVIDERS_FIXTURE,
PROJECT_GENERATOR_TOOL_FIXTURE,
COMMAND_INSTALLER_FIXTURE,
COMMAND_INSTALLER_DOWNLOAD_FIXTURE,
RUN_CONFIGURATION_TYPES_FIXTURE,
BEFORE_LAUNCH_TASKS_FIXTURE,
] {
Expand Down Expand Up @@ -279,7 +283,8 @@ fn command_installer_fixtures_match_on_this_host() {
for case in plans["cases"].as_array().unwrap() {
let name = case["name"].as_str().unwrap();
let specific = &case["platforms"][platform];
let mut payload = json!({ "manifest": fixture("command-installer.plugin.json") });
let plugin = case.get("plugin").unwrap_or(&plans["plugin"]);
let mut payload = json!({ "manifest": fixture(plugin.as_str().unwrap()) });
for source in [&case["payload"], &specific["payload"]] {
for (field, value) in source.as_object().into_iter().flatten() {
payload[field] = value.clone();
Expand Down Expand Up @@ -342,6 +347,78 @@ fn command_installers_are_reviewed_programs() {
assert_ne!(programs(changed), before);
}

/// A download installer's review entry shows every archive it may fetch, so
/// a new URL or digest is a new program the user approves again; it runs no
/// tool, so the entry has no tool or arguments.
#[test]
fn download_installers_are_reviewed_programs() {
let programs = |manifest: Value| {
let outcome = lithe_plugin_marketplace::install_review_command(json!({
"manifest": manifest,
}))
.expect("payload is well formed");
outcome["review"]["programs"]
.as_array()
.unwrap()
.iter()
.filter(|program| program["kind"] == "commandInstaller")
.cloned()
.collect::<Vec<_>>()
};
let manifest = fixture("command-installer-download.plugin.json");
let before = programs(manifest.clone());
assert_eq!(before.len(), 1);
let program = &before[0];
assert_eq!(program["installer"], "sample-lldb");
assert_eq!(program["timeoutSeconds"], 900);
assert!(program.get("tool").is_none() && program.get("arguments").is_none());
let artifacts = program["download"]["artifacts"].as_array().unwrap();
assert_eq!(artifacts.len(), 3);
// The review lists the digest Core checks, in lowercase.
let macos = artifacts
.iter()
.find(|artifact| artifact["os"] == "macos")
.unwrap();
assert_eq!(
macos["sha256"],
"2f114a990e1b368dd1dbd33c80c0e719767af2d228391ec0df0571c957f9ac91"
);
for (pointer, value) in [
(
"/commandInstallers/0/download/artifacts/0/url",
json!("https://downloads.example.org/other.zip"),
),
(
"/commandInstallers/0/download/artifacts/1/sha256",
json!("0".repeat(64)),
),
("/commandInstallers/0/download/version", json!("1.2.4")),
] {
let mut changed = manifest.clone();
*changed.pointer_mut(pointer).unwrap() = value;
assert_ne!(programs(changed), before, "{pointer}");
}
}

/// A host that declares `commandInstallers` 0 does not know download
/// installers, so it refuses a plugin that needs them before installing it.
#[test]
fn download_installers_need_a_host_with_version_1() {
let manifest = fixture("command-installer-download.plugin.json");
let host = json!({ "commandInstallers": [0], "debugAdapters": [0], "languages": [0] });
let refused = validate_command(json!({ "manifest": manifest, "hostCapabilities": host }))
.expect("payload is well formed");
assert_eq!(
refused["error"]["code"], "plugin.api.unsupported",
"{refused}"
);
assert_eq!(refused["error"]["field"], "requires.commandInstallers");
let host = json!({ "commandInstallers": [0, 1], "debugAdapters": [0], "languages": [0] });
let accepted = validate_command(json!({ "manifest": manifest, "hostCapabilities": host }))
.expect("payload is well formed");
assert_eq!(accepted["status"], "ok", "{accepted}");
}

/// A malformed request is a Core failure, not a rejection.
#[test]
fn command_installer_requests_decode_strictly() {
Expand All @@ -354,6 +431,20 @@ fn command_installer_requests_decode_strictly() {
json!({ "manifest": manifest, "installerID": "sample-ls" })
)
.is_err());
// A platform names a supported pair by its two fields and nothing else.
let manifest = fixture("command-installer-download.plugin.json");
assert!(command_installer_plan_command(json!({
"manifest": manifest,
"installerID": "sample-lldb",
"target": "managed",
"platform": { "os": "macos" }
}))
.is_err());
assert!(command_installer_requirements_command(json!({
"manifest": manifest,
"platform": { "os": "macos", "arch": "arm64", "libc": "musl" }
}))
.is_err());
}

#[test]
Expand Down
159 changes: 159 additions & 0 deletions rust/crates/plugin-manifest/src/archives.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
//! Pinned download archives: the platform target, source URLs, digest,
//! format and layout paths that `managedRuntimes` dependencies and
//! `commandInstallers` downloads share. Core validates the declaration and
//! selects the archive for the host's platform; the host downloads, checks the
//! digest and extracts.

use super::*;
use lithe_platform::Platform;
use url::Url;

/// Most platform archives one dependency or download declares: one per
/// supported operating system and architecture.
pub(crate) const MAX_ARTIFACTS: usize = 6;

/// Most fallback URLs one archive declares.
pub(crate) const MAX_MIRRORS: usize = 8;

/// Operating systems an archive may target.
pub(crate) const ARCHIVE_OPERATING_SYSTEMS: &[&str] = &["macos", "windows", "linux"];

/// Longest archive URL, in bytes.
const MAX_URL_BYTES: usize = 4096;

/// Longest layout path inside an archive, in bytes.
const MAX_LAYOUT_PATH_BYTES: usize = 512;

/// Text that is not empty, at most `maximum` bytes, without surrounding
/// whitespace or control characters.
pub(crate) fn bounded_text(value: &str, maximum: usize) -> bool {
!value.is_empty()
&& value.len() <= maximum
&& value.trim() == value
&& !value.chars().any(char::is_control)
}

/// A layout path inside an archive: empty, or `/`-separated parts without an
/// empty, `.` or `..` part, backslash or colon, so it means the same on every
/// host. Native extraction also checks filesystem aliases and link targets.
pub(crate) fn is_archive_layout_path(value: &str) -> bool {
value.is_empty()
|| (bounded_text(value, MAX_LAYOUT_PATH_BYTES)
&& !value.contains(['\\', ':'])
&& value
.split('/')
.all(|part| !part.is_empty() && part != "." && part != ".."))
}

/// Whether `os` and `arch` name a platform an archive may target.
pub(crate) fn is_archive_platform(os: &str, arch: &str) -> bool {
ARCHIVE_OPERATING_SYSTEMS.contains(&os) && KNOWN_ARCHITECTURES.contains(&arch)
}

/// The host platform a request selects an archive for.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub(crate) struct ArchivePlatform {
/// macos, windows or linux.
pub(crate) os: String,
/// arm64 or x86_64.
pub(crate) arch: String,
}

impl ArchivePlatform {
/// Whether an archive may target this platform.
pub(crate) fn is_supported(&self) -> bool {
is_archive_platform(&self.os, &self.arch)
}

/// Whether an archive declared for `os` and `arch` is this platform's.
pub(crate) fn matches(&self, os: &str, arch: &str) -> bool {
self.os == os && self.arch == arch
}

/// The path rules of this platform's filesystem.
pub(crate) fn native_paths(&self) -> Platform {
if self.os == "windows" {
Platform::Windows
} else {
Platform::Unix
}
}
}

/// Where one archive comes from and how to read it.
pub(crate) struct ArchiveSource<'a> {
pub(crate) url: &'a str,
pub(crate) mirrors: &'a [String],
pub(crate) sha256: &'a mut String,
pub(crate) archive: &'a str,
}

/// Checks one archive's URL, mirrors, digest and format, and lowercases the
/// digest. `mirrors_allowed` runs only when the archive declares mirrors and
/// rejects them when the manifest's capability version does not have them.
pub(crate) fn validate_archive_source(
field: &str,
source: ArchiveSource<'_>,
mirrors_allowed: impl FnOnce() -> Validation<()>,
) -> Validation<()> {
if !is_https_source(source.url) {
return Err(invalid(
format!("{field}.url"),
"An archive URL uses HTTPS without credentials or fragments.",
));
}
if !source.mirrors.is_empty() {
mirrors_allowed()?;
if source.mirrors.len() > MAX_MIRRORS {
return Err(invalid(
format!("{field}.mirrors"),
format!("An archive declares at most {MAX_MIRRORS} mirror URLs."),
));
}
let mut seen = BTreeSet::new();
seen.insert(source.url);
for (index, mirror) in source.mirrors.iter().enumerate() {
let entry = format!("{field}.mirrors[{index}]");
if !is_https_source(mirror) {
return Err(invalid(
entry,
"A mirror URL uses HTTPS without credentials or fragments.",
));
}
if !seen.insert(mirror.as_str()) {
return Err(invalid(
entry,
"Mirror URLs are unique and differ from the primary URL.",
));
}
}
}
if source.sha256.len() != 64 || !source.sha256.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Err(invalid(
format!("{field}.sha256"),
"An archive pins its complete SHA-256 digest.",
));
}
source.sha256.make_ascii_lowercase();
if !["zip", "tar.gz"].contains(&source.archive) {
return Err(invalid(
format!("{field}.archive"),
"An archive format is zip or tar.gz.",
));
}
Ok(())
}

/// An HTTPS URL with a host, without credentials or a fragment.
fn is_https_source(value: &str) -> bool {
let Ok(url) = Url::parse(value) else {
return false;
};
bounded_text(value, MAX_URL_BYTES)
&& url.scheme() == "https"
&& url.host_str().is_some()
&& url.username().is_empty()
&& url.password().is_none()
&& url.fragment().is_none()
}
Loading
Loading