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
63 changes: 60 additions & 3 deletions rust/crates/core/src/tests/toolchain_definitions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,11 +150,13 @@ fn registry_accepts_short_ids_from_any_enabled_plugin() {
.is_err());
}

/// Install order and plugin ID must not pick an owner, so a contested ID has none.
/// Install order and plugin ID must not pick an owner, so differing claims stay unowned.
#[test]
fn registry_leaves_a_contested_tool_id_unowned_and_registers_the_rest() {
let first = manifest("dev.lithe.fixture.first", definition("compiler"));
let second = manifest("dev.lithe.fixture.second", definition("compiler"));
let mut different = definition("compiler");
different["executableLayouts"] = json!([{"path":"bin/other-compiler"}]);
let second = manifest("dev.lithe.fixture.second", different);
let mut third = manifest("dev.lithe.fixture.third", definition("renderer"));
third["toolDefinitions"]
.as_array_mut()
Expand Down Expand Up @@ -184,11 +186,66 @@ fn registry_leaves_a_contested_tool_id_unowned_and_registers_the_rest() {
.is_err());
}

/// Identical normalized short-ID definitions across plugins aggregate into one shared entry.
#[test]
fn registry_aggregates_identical_short_tool_definitions_across_plugins() {
let first = manifest("dev.lithe.fixture.first", definition("compiler"));
let second = manifest("dev.lithe.fixture.second", definition("compiler"));
for plugins in [
json!([{"manifest":first},{"manifest":second}]),
json!([{"manifest":second},{"manifest":first}]),
] {
let result = registry(&json!({"plugins":plugins}), validated_manifest_json).unwrap();
assert_eq!(result["conflicts"], json!([]));
assert_eq!(result["definitions"].as_array().map(Vec::len), Some(1));
let entry = &result["definitions"][0];
assert_eq!(entry["definition"]["id"], "compiler");
assert_eq!(entry["pluginID"], "dev.lithe.fixture.first");
assert_eq!(
entry["pluginIDs"],
json!(["dev.lithe.fixture.first", "dev.lithe.fixture.second"])
);
let plan = crate::execute_json(
&json!({
"id": "shared-plan",
"command": "toolchains.discoveryPlan",
"payload": {
"registry": {"plugins": plugins},
"platform": "macos"
}
})
.to_string(),
);
let plan: Value = serde_json::from_str(&plan).unwrap();
assert_eq!(plan["ok"], true, "{plan}");
assert_eq!(
plan["data"]["plan"]["tools"][0]["pluginIDs"],
json!(["dev.lithe.fixture.first", "dev.lithe.fixture.second"])
);
}
// Any semantic difference still triggers a conflict instead of silently picking one.
let mut changed = definition("compiler");
changed["version"]["arguments"] = json!(["-v"]);
let differing = manifest("dev.lithe.fixture.second", changed);
let conflict = registry(
&json!({"plugins":[{"manifest":first},{"manifest":differing}]}),
validated_manifest_json,
)
.unwrap();
assert_eq!(conflict["definitions"], json!([]));
assert_eq!(
conflict["conflicts"],
json!([{"tool":"compiler","pluginIDs":["dev.lithe.fixture.first","dev.lithe.fixture.second"]}])
);
}

/// A provider that lists a contested tool still registers; only the definition is withheld.
#[test]
fn registry_keeps_providers_that_name_a_contested_tool() {
let first = manifest("dev.lithe.fixture.first", definition("compiler"));
let second = manifest("dev.lithe.fixture.second", definition("compiler"));
let mut different = definition("compiler");
different["displayName"] = json!("Different compiler");
let second = manifest("dev.lithe.fixture.second", different);
let provider = json!({"schemaVersion":0,"id":"dev.lithe.fixture.provider","displayName":"Provider","version":"1.0.0",
"pluginAPIVersion":0,"requires":{"toolchainProviders":0,"backend":0},
"vendor":{"id":"org.example","displayName":"Fixture","signatureRequirement":"publisherPackage"},
Expand Down
37 changes: 36 additions & 1 deletion rust/crates/core/src/tests/toolchain_resolution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1208,9 +1208,10 @@ fn toolchain_resolution_contested_tool_id_is_unowned_for_every_consumer() {
installation(&mut value, HOME, "21.0.4");
value["local"] = local_pins();
value["commandHomes"][tool.as_str()] = json!(HOME);
// The rival is a copy of the defining plugin under another ID.
// The rival claims the same short ID with a differing definition.
let mut rival = value["registry"]["plugins"][0]["manifest"].clone();
rival["id"] = json!("io.example.rival");
rival["toolDefinitions"][0]["displayName"] = json!("Rival Java");
value["registry"]["plugins"]
.as_array_mut()
.unwrap()
Expand Down Expand Up @@ -2093,3 +2094,37 @@ fn toolchain_candidates_and_multi_hop_environment_links_use_synthetic_tool_defin
assert_eq!(selection["pathPrepend"], json!([dir]), "{platform}");
}
}

/// An existing external scan root (such as `~/.local`) whose declared layouts are all observed
/// as missing must resolve to `notFound` rather than `unsafePath`, and must not taint valid runs.
#[test]
fn empty_observed_system_scan_directory_does_not_report_unsafe_path() {
let mut value = input();
let empty_home = "/opt/lithe-fixtures/empty-local";
value["filesystem"].as_array_mut().unwrap().extend([
fact(empty_home, "directory", false),
fact(&format!("{empty_home}/bin/java"), "missing", false),
]);
value["systemInstallations"] = json!([{"tool":"java","home":empty_home}]);
value["probes"] = json!([]);

let unresolved = resolve(&value);
assert_eq!(unresolved["outcome"]["kind"], "skip");
assert_eq!(unresolved["outcome"]["reason"]["code"], "notFound");
let listed_empty = candidates(&value);
assert_eq!(listed_empty["skipped"], json!([]));

// With another valid candidate, the empty scan directory does not leave any skipped error.
installation(&mut value, HOME, "21.0.4");
value["systemInstallations"] =
json!([{"tool":"java","home":empty_home},{"tool":"java","home":HOME}]);
let resolved = resolve(&value);
assert_eq!(resolved["outcome"]["kind"], "resolved");
assert_eq!(resolved["outcome"]["selection"]["home"], HOME);
assert_eq!(candidates(&value)["skipped"], json!([]));

// Unobserved directories and escaping links still fail closed as unsafePath.
let unobserved_home = "/opt/lithe-fixtures/unobserved";
value["systemInstallations"] = json!([{"tool":"java","home":unobserved_home}]);
assert_eq!(fixed_home_failure(&value, unobserved_home), "unsafePath");
}
72 changes: 42 additions & 30 deletions rust/crates/toolchain/src/definitions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -762,20 +762,21 @@ pub fn validate_declarations(
}

/// Revalidates the complete manifests of enabled plugins and builds the tool registry.
/// A tool ID declared by several plugins belongs to none of them: install order and plugin
/// ID must not decide ownership, or a hostile plugin could claim an ID before its rightful
/// owner. Those definitions are left out and reported in `conflicts`; every other definition
/// still registers. Duplicate plugin IDs make the enabled set ambiguous, so they reject the
/// whole batch.
/// When several plugins declare the same short tool ID with identical normalized definitions,
/// they aggregate into one shared registry entry carrying `pluginIDs`. When their definitions
/// differ, ownership belongs to none of them: install order and plugin ID must not decide
/// ownership, or a hostile plugin could claim an ID before its rightful owner. Those differing
/// definitions are left out and reported in `conflicts`; every other definition still registers.
/// Duplicate plugin IDs make the enabled set ambiguous, so they reject the whole batch.
///
/// `validate_manifest` revalidates each complete manifest. The plugin host supplies it:
/// only the host assembles the sections every domain contributes to a manifest.
pub fn registry(input: &Value, validate_manifest: ManifestValidator) -> Validation<Value> {
object(input, &["plugins"], &["plugins"], "registry")?;
let plugins = list(&input["plugins"], 0, 128, "plugins")?;
let mut definitions = Vec::new();
let mut grouped: BTreeMap<String, BTreeMap<String, Value>> = BTreeMap::new();
let mut providers = Vec::new();
let mut owners: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
let mut definition_count = 0usize;
let mut plugin_ids = BTreeSet::new();
for entry in plugins {
object(entry, &["manifest"], &["manifest"], "plugins")?;
Expand All @@ -789,47 +790,58 @@ pub fn registry(input: &Value, validate_manifest: ManifestValidator) -> Validati
}
for definition in optional_list(&manifest, "toolDefinitions", 32)? {
let id = text(&definition["id"], 192, "toolDefinitions.id")?;
owners
.entry(id.to_owned())
.or_default()
.insert(plugin_id.to_owned());
let mut normalized = definition.clone();
let indices = candidates(definition)?;
normalized["executables"] = json!(indices
.iter()
.map(|index| definition["executables"][*index].clone())
.collect::<Vec<_>>());
definitions.push(json!({"pluginID":plugin_id,"definition":normalized}));
grouped
.entry(id.to_owned())
.or_default()
.insert(plugin_id.to_owned(), normalized);
definition_count += 1;
}
for provider in optional_list(&manifest, "toolchainProviders", 8)? {
providers.push(json!({"pluginID":plugin_id,
"version":manifest["requires"]["toolchainProviders"],"provider":provider}));
}
if definitions.len() > 512 || providers.len() > 256 {
if definition_count > 512 || providers.len() > 256 {
return Err(invalid(
"plugins",
"The registry exceeds aggregate contribution limits.",
));
}
}
// A qualified ID starts with its unique plugin ID, so only short IDs can be claimed twice.
let conflicts: Vec<Value> = owners
.iter()
.filter(|(_, claimants)| claimants.len() > 1)
.map(|(tool, claimants)| json!({"tool":tool,"pluginIDs":claimants}))
.collect();
definitions.retain(|entry| {
entry["definition"]["id"]
.as_str()
.and_then(|id| owners.get(id))
.is_some_and(|claimants| claimants.len() == 1)
});
definitions.sort_by_key(|entry| {
(
entry["definition"]["id"].as_str().unwrap_or("").to_owned(),
entry["pluginID"].as_str().unwrap_or("").to_owned(),
)
});
// Identical normalized declarations share one entry; differing ones stay unowned conflicts.
let mut definitions = Vec::new();
let mut conflicts = Vec::new();
for (tool, claimants) in grouped {
let mut entries = claimants.into_iter();
let Some((first_plugin, first_definition)) = entries.next() else {
continue;
};
let mut all_plugin_ids = vec![first_plugin.clone()];
let mut all_identical = true;
for (plugin_id, definition) in entries {
if definition != first_definition {
all_identical = false;
}
all_plugin_ids.push(plugin_id);
}
if all_plugin_ids.len() == 1 {
definitions.push(json!({"pluginID": first_plugin, "definition": first_definition}));
} else if all_identical {
definitions.push(json!({
"pluginID": first_plugin,
"pluginIDs": all_plugin_ids,
"definition": first_definition,
}));
} else {
conflicts.push(json!({"tool": tool, "pluginIDs": all_plugin_ids}));
}
}
providers.sort_by_key(|entry| {
(
entry["pluginID"].as_str().unwrap_or("").to_owned(),
Expand Down
79 changes: 73 additions & 6 deletions rust/crates/toolchain/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -507,23 +507,38 @@ fn same_target(known: &FileFact, target: &FileFact, facts: &Facts) -> bool {
&& known.executable == target.executable
}

/// Distinguishes an observed external directory that simply lacks any matching
/// executable from an unobserved, escaping, or non-executable path.
pub(crate) enum InstallationCheckError {
MissingExecutable,
Unsafe(PluginRejection),
}

impl From<PluginRejection> for InstallationCheckError {
fn from(error: PluginRejection) -> Self {
Self::Unsafe(error)
}
}

/// `layout_path` limits the search to one declared executable layout, as an environment
/// candidate names; otherwise the first present platform layout is selected.
fn checked_installation(
fn checked_installation_detail(
home: &str,
definition: &Value,
facts: &Facts,
roots: &[String],
layout_path: Option<&str>,
) -> Validation<Value> {
) -> Result<Value, InstallationCheckError> {
let canonical_home = facts.canonical(home, Some("directory"))?;
if roots.iter().any(|root| facts.within(&canonical_home, root)) {
return Err(reject(
UNSAFE,
"installation.home",
"A provider installation cannot be workspace code.",
));
)
.into());
}
let mut saw_unobserved_layout = false;
for layout in definition["executableLayouts"]
.as_array()
.into_iter()
Expand All @@ -540,6 +555,7 @@ fn checked_installation(
let path = paths::join(home, layout["path"].as_str().unwrap_or(""), &facts.platform)
.ok_or_else(|| reject(UNSAFE, "executableLayouts", "Invalid executable layout."))?;
let Some(fact) = facts.values.get(&facts.key(&path)?) else {
saw_unobserved_layout = true;
continue;
};
if fact.kind == "missing" {
Expand All @@ -554,7 +570,7 @@ fn checked_installation(
)
};
if roots.iter().any(|root| facts.within(&executable, root)) {
return Err(escapes());
return Err(escapes().into());
}
if facts.within(&executable, &canonical_home) {
let executable = invoked_executable(&executable, &canonical_home, layout, facts)?;
Expand All @@ -564,19 +580,42 @@ fn checked_installation(
// starts from the layout path so the program still finds the environment it was
// started from; the canonical target would run the base installation instead.
if definition["executableLinksOutsideHome"] != true {
return Err(escapes());
return Err(escapes().into());
}
let relative = layout["path"].as_str().unwrap_or("");
contained_parents(home, relative, &canonical_home, facts, roots)?;
let executable = paths::join(&canonical_home, relative, &facts.platform)
.ok_or_else(|| reject(UNSAFE, "executableLayouts", "Invalid executable layout."))?;
return Ok(json!({"home":canonical_home,"executable":executable}));
}
if !saw_unobserved_layout {
return Err(InstallationCheckError::MissingExecutable);
}
Err(reject(
UNSAFE,
"installation.executable",
"No validated executable matches the tool definition.",
))
)
.into())
}

fn checked_installation(
home: &str,
definition: &Value,
facts: &Facts,
roots: &[String],
layout_path: Option<&str>,
) -> Validation<Value> {
checked_installation_detail(home, definition, facts, roots, layout_path).map_err(
|err| match err {
InstallationCheckError::MissingExecutable => reject(
UNSAFE,
"installation.executable",
"No validated executable matches the tool definition.",
),
InstallationCheckError::Unsafe(error) => error,
},
)
}

/// Checks the directories between a home and its layout's program (such as `bin` in
Expand Down Expand Up @@ -667,6 +706,34 @@ pub fn validate_installation(
checked_installation(home, definition, &facts, &roots, layout_path)
}

/// Validates an installation for host resolution, returning `"notFound"` instead of
/// `"unsafePath"` when an observed external directory simply lacks all declared layouts.
pub(crate) fn validate_installation_reason(
home: &str,
definition: &Value,
filesystem: &[Value],
workspace_roots: &[String],
platform: &str,
case_sensitive: bool,
layout_path: Option<&str>,
) -> Result<Value, &'static str> {
if !matches!(platform, "macos" | "windows" | "linux") {
return Err("unsafePath");
}
let facts = read_facts(filesystem, platform, case_sensitive).map_err(|_| "unsafePath")?;
let roots = workspace_roots
.iter()
.map(|root| facts.canonical(root, Some("directory")))
.collect::<Validation<Vec<_>>>()
.map_err(|_| "unsafePath")?;
checked_installation_detail(home, definition, &facts, &roots, layout_path).map_err(|err| {
match err {
InstallationCheckError::MissingExecutable => "notFound",
InstallationCheckError::Unsafe(_) => "unsafePath",
}
})
}

/// Decodes one provider reply using only the revalidated registry and native facts.
/// No filesystem, process, environment or JSON-RPC transport is accessed here.
pub fn decode(input: &Value, validate_manifest: ManifestValidator) -> Validation<Value> {
Expand Down
5 changes: 5 additions & 0 deletions rust/crates/toolchain/src/resolution/automatic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ pub(crate) fn automatic_set(
}
}
Err(code) => {
// An existing shared scan root (such as `~/.local` or `/usr/local`) without
// this tool's executable is simply empty for this tool, not a broken candidate.
if code == "notFound" && provider == SYSTEM_PROVIDER {
continue;
}
set.failure = Some(code);
let checked = snapshot.checked(home, None).ok();
let canonical = checked
Expand Down
Loading
Loading