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
30 changes: 30 additions & 0 deletions rust/crates/core/src/tests/toolchain_definitions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,36 @@ fn tool_definitions_declare_settings_category_and_audience() {
}
}

/// `executableLinksOutsideHome` is an addition within version 0: a manifest that sets it
/// still requires `toolDefinitions: 0`, and only a boolean is accepted.
#[test]
fn tool_definitions_may_let_their_program_link_outside_the_home_within_version_0() {
let mut linked = definition("dev.lithe.fixture.compiler:compiler");
linked["executableLinksOutsideHome"] = json!(true);
let plugin = manifest("dev.lithe.fixture.compiler", linked);
assert!(validate_manifest_value(plugin.clone()).is_ok());
let result = registry(
&json!({"plugins":[{"manifest":plugin}]}),
validated_manifest_json,
)
.unwrap();
assert_eq!(
result["definitions"][0]["definition"]["executableLinksOutsideHome"],
true
);
for value in [json!("true"), json!(1), json!(null)] {
let mut changed = definition("dev.lithe.fixture.compiler:compiler");
changed["executableLinksOutsideHome"] = value.clone();
let rejected = validate_declarations("dev.lithe.fixture.compiler", &[changed], &[])
.expect_err("only a boolean is accepted");
assert_eq!(
rejected.field.as_deref(),
Some("toolDefinitions.executableLinksOutsideHome"),
"{value}"
);
}
}

/// No plugin needs a host-attested origin for a short ID.
#[test]
fn registry_accepts_short_ids_from_any_enabled_plugin() {
Expand Down
162 changes: 162 additions & 0 deletions rust/crates/core/src/tests/toolchain_resolution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -886,6 +886,168 @@ fn toolchain_resolution_starts_a_multi_call_link_by_its_layout_name() {
assert_eq!(selected["version"], "21.0.4");
}

/// An environment outside the workspace whose program links to its base installation,
/// as `python -m venv` makes one on macOS and Linux.
const ENVIRONMENT: &str = "/opt/lithe-fixtures/environments/app";

/// Lets the fixture definition's program link outside its home.
fn links_outside_home(value: &mut Value) {
value["registry"]["plugins"][0]["manifest"]["toolDefinitions"][0]
["executableLinksOutsideHome"] = json!(true);
}

/// Records `home`, its `bin` directory resolving to `bin`, and `bin/java` resolving to
/// `target`, the facts a host observes along the layout path, with a probe of the
/// layout path.
fn linked_home(value: &mut Value, home: &str, bin: &str, target: &str) {
value["filesystem"].as_array_mut().unwrap().extend([
fact(home, "directory", false),
json!({"path":format!("{home}/bin"),"canonicalPath":bin,"kind":"directory"}),
json!({"path":format!("{home}/bin/java"),"canonicalPath":target,"kind":"file","executable":true}),
]);
value["probes"].as_array_mut().unwrap().push(
json!({"executable":format!("{home}/bin/java"),"output":"openjdk version \"21.0.4\"","exitCode":0}),
);
}

/// The reason a resolution with only an explicit `{home}` choice fails.
fn fixed_home_failure(value: &Value, home: &str) -> Value {
let mut value = value.clone();
value["fixed"] = json!({ "home": home });
let result = resolve(&value);
assert_eq!(result["outcome"]["kind"], "terminalFailure", "{result}");
result["outcome"]["reason"]["code"].clone()
}

/// The environment's program starts from its layout path, not the base program it links
/// to: Python finds `pyvenv.cfg` from the path it starts with, so the target would drop
/// the environment. Without the field the same link is refused.
#[test]
fn toolchain_resolution_starts_an_environment_linked_outside_its_home_from_its_layout() {
let mut value = input();
installation(&mut value, HOME, "21.0.4");
let program = format!("{ENVIRONMENT}/bin/java");
linked_home(
&mut value,
ENVIRONMENT,
&format!("{ENVIRONMENT}/bin"),
&format!("{HOME}/bin/java"),
);
assert_eq!(fixed_home_failure(&value, ENVIRONMENT), "unsafePath");

links_outside_home(&mut value);
let mut unprobed = value.clone();
unprobed["fixed"] = json!({ "home": ENVIRONMENT });
unprobed["probes"] = json!([]);
let listed =
candidates_command(value_for_candidates(&unprobed), validated_manifest_json).unwrap();
assert!(
listed["candidates"]["skipped"]
.as_array()
.unwrap()
.iter()
.any(|row| row["reason"] == "probeFailed" && row["executable"] == program.as_str()),
"{listed}"
);
for (key, choice) in [
("fixed", json!({ "home": ENVIRONMENT })),
("environment", json!({ "JAVA_HOME": ENVIRONMENT })),
] {
let mut routed = value.clone();
routed[key] = choice;
let result = resolve(&routed);
let selected = &result["outcome"]["selection"];
assert_eq!(selected["home"], ENVIRONMENT, "{key}: {result}");
assert_eq!(selected["executable"], program.as_str(), "{key}");
assert_eq!(
selected["environment"],
json!({"JAVA_HOME":ENVIRONMENT,"LITHE_JAVA_PATH":program}),
"{key}"
);
assert_eq!(
selected["pathPrepend"],
json!([format!("{ENVIRONMENT}/bin")]),
"{key}"
);
}
}

/// Homebrew's `libexec/bin/python3` links to its framework, a sibling of `libexec`.
/// Discovery and a pin through the `opt` alias both select the canonical home and start
/// the program from the layout path beneath it.
#[test]
fn toolchain_resolution_accepts_a_program_linked_to_a_sibling_of_its_home() {
let keg = "/opt/lithe-fixtures/cellar/tool/21.0.4";
let home = format!("{keg}/libexec");
let alias = "/opt/lithe-fixtures/opt/tool/libexec";
let target = format!("{keg}/Frameworks/bin/java21");
let mut value = input();
links_outside_home(&mut value);
linked_home(&mut value, &home, &format!("{home}/bin"), &target);
value["filesystem"].as_array_mut().unwrap().extend([
json!({"path":alias,"canonicalPath":home,"kind":"directory"}),
json!({"path":format!("{alias}/bin"),"canonicalPath":format!("{home}/bin"),"kind":"directory"}),
json!({"path":format!("{alias}/bin/java"),"canonicalPath":target,"kind":"file","executable":true}),
]);
let program = format!("{home}/bin/java");
value["systemInstallations"] = json!([{"tool":"java","home":home}]);
let discovered = resolve(&value);
assert_eq!(
discovered["outcome"]["selection"]["executable"],
program.as_str(),
"{discovered}"
);
value["systemInstallations"] = json!([]);
value["local"] = json!({"version":1,"toolchains":{},"pins":{".":{"java":{"home":alias,"version":"21","provider":"host:manual"}}}});
let pinned = resolve(&value);
let selected = &pinned["outcome"]["selection"];
assert_eq!(selected["home"], home.as_str(), "{pinned}");
assert_eq!(selected["executable"], program.as_str());
}

/// The field lets only the program leave the home: a target in the workspace, a `bin`
/// directory that links elsewhere and a `bin` directory the host did not observe are
/// all refused before any probe.
#[test]
fn toolchain_resolution_refuses_links_outside_the_home_that_reach_the_workspace_or_skip_bin() {
let elsewhere = "/opt/lithe-fixtures/elsewhere/bin";
let cases = [
(
format!("{ENVIRONMENT}/bin"),
format!("{WORKSPACE}/tools/java"),
true,
),
(elsewhere.to_owned(), format!("{elsewhere}/java"), true),
(
format!("{ENVIRONMENT}/bin"),
format!("{HOME}/bin/java"),
false,
),
];
for (bin, target, observed) in cases {
let mut value = input();
links_outside_home(&mut value);
installation(&mut value, HOME, "21.0.4");
linked_home(&mut value, ENVIRONMENT, &bin, &target);
value["filesystem"].as_array_mut().unwrap().extend([
fact(&format!("{WORKSPACE}/tools/java"), "file", true),
fact(elsewhere, "directory", false),
fact(&format!("{elsewhere}/java"), "file", true),
]);
if !observed {
value["filesystem"]
.as_array_mut()
.unwrap()
.retain(|fact| fact["path"] != format!("{ENVIRONMENT}/bin").as_str());
}
assert_eq!(
fixed_home_failure(&value, ENVIRONMENT),
"unsafePath",
"{bin} -> {target}"
);
}
}

#[test]
fn toolchain_resolution_definition_plugin_can_be_its_own_installation_provider() {
let mut value = input();
Expand Down
12 changes: 12 additions & 0 deletions rust/crates/toolchain/src/definitions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,7 @@ fn definition(plugin_id: &str, value: &Value) -> Validation<()> {
"launch",
"category",
"audience",
"executableLinksOutsideHome",
],
&[
"id",
Expand Down Expand Up @@ -473,6 +474,17 @@ fn definition(plugin_id: &str, value: &Value) -> Validation<()> {
));
}
}
// Lets a program in the home link outside it, as a virtual environment's interpreter
// links to its base installation. Directories on the way stay checked.
if value
.get("executableLinksOutsideHome")
.is_some_and(|value| !value.is_boolean())
{
return Err(invalid(
"toolDefinitions.executableLinksOutsideHome",
"The field must be a boolean.",
));
}
if let Some(icon) = value.get("icon") {
let icon: UIIcon = serde_json::from_value(icon.clone())
.map_err(|_| invalid("toolDefinitions.icon", "The icon shape is invalid."))?;
Expand Down
60 changes: 52 additions & 8 deletions rust/crates/toolchain/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -533,16 +533,30 @@ fn checked_installation(
continue;
}
let executable = facts.executable(&path)?;
if !facts.within(&executable, &canonical_home)
|| roots.iter().any(|root| facts.within(&executable, root))
{
return Err(reject(
let escapes = || {
reject(
UNSAFE,
"installation.executable",
"The executable escapes its installation or enters the workspace.",
));
)
};
if roots.iter().any(|root| facts.within(&executable, root)) {
return Err(escapes());
}
if facts.within(&executable, &canonical_home) {
let executable = invoked_executable(&executable, &canonical_home, layout, facts)?;
return Ok(json!({"home":canonical_home,"executable":executable}));
}
let executable = invoked_executable(&executable, &canonical_home, layout, facts)?;
// An environment's program links to its base interpreter outside the home. It
// 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());
}
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}));
}
Err(reject(
Expand All @@ -552,6 +566,36 @@ fn checked_installation(
))
}

/// Checks the directories between a home and its layout's program (such as `bin` in
/// `bin/python3`) when the program links outside the home. Each one must be an observed
/// directory that canonically stays inside the canonical home and outside every
/// workspace, so the layout path beneath the canonical home names the file the facts
/// checked and only the program itself leaves the home.
fn contained_parents(
home: &str,
relative: &str,
canonical_home: &str,
facts: &Facts,
roots: &[String],
) -> Validation<()> {
let segments: Vec<&str> = relative.split('/').collect();
for depth in 1..segments.len() {
let parent = paths::join(home, &segments[..depth].join("/"), &facts.platform)
.ok_or_else(|| reject(UNSAFE, "executableLayouts", "Invalid executable layout."))?;
let canonical = facts.canonical(&parent, Some("directory"))?;
if !facts.within(&canonical, canonical_home)
|| roots.iter().any(|root| facts.within(&canonical, root))
{
return Err(reject(
UNSAFE,
"installation.executable",
"A directory of the executable layout escapes its installation.",
));
}
}
Ok(())
}

/// The path a checked installation's program starts from: its canonical target,
/// unless the layout's file links to a program with another file name. Such a
/// program may pick what to run from the name it was started with (rustup links
Expand Down Expand Up @@ -583,8 +627,8 @@ fn invoked_executable(

/// Validates an external installation against trusted, authority-local native facts.
/// Returns the canonical home and the executable to start (the canonical target, or the
/// layout path when that target has another file name)
/// without touching the native filesystem.
/// layout path when that target has another file name or, for a definition that allows
/// it, lies outside the home) without touching the native filesystem.
/// Project-code candidates require their separate consumer trust policy.
pub fn validate_installation(
home: &str,
Expand Down
4 changes: 4 additions & 0 deletions shared/plugins/contract/v1/plugin-manifest.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -4304,6 +4304,10 @@
"description": "toolDefinitions 1: user (default) for a tool people run; plugin for a runtime the plugin runs for itself, such as a language server's JDK.",
"enum": ["user", "plugin"]
},
"executableLinksOutsideHome": {
"description": "toolDefinitions 0 addition: true lets the layout's program be a link to a regular executable file outside the home, such as a virtual environment's bin/python3 linking to its base interpreter. The directories between the home and the program must stay inside the home, the target must stay outside every workspace, and the program starts from its layout path beneath the home. Absent or false keeps the program inside the home.",
"type": "boolean"
},
"executableLayouts": {
"type": "array",
"minItems": 1,
Expand Down
27 changes: 26 additions & 1 deletion shared/plugins/contract/v1/toolchains/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ does not gain definition-owned candidate fields (see
[Executable resolution](../README.md#executable-resolution)).

Definitions own IDs, labels/icons, optional display `category` and `audience`,
`executableLayouts`, ordered `executables`,
`executableLayouts`, optional `executableLinksOutsideHome`, ordered `executables`,
`version`, `homeLayouts`, `discovery`, `homeVariable`, `commands`, `wrappers`,
`exports`, `pathPrepend` and argv `launch`. Counts, relative paths, bounded globs,
platforms, templates and version expressions are validated recursively; unknown
Expand All @@ -47,6 +47,16 @@ reject the manifest. They are `toolDefinitions` version 1: a manifest that sets
either requires `toolDefinitions: 1`, and a host that supports only version 0
does not install it. Definitions without them keep requiring `0`.

`executableLinksOutsideHome` is a boolean added within `toolDefinitions` version 0.
`true` lets an external installation's layout program link outside its home, as a
virtual environment's `bin/python3` links to its base interpreter and Homebrew's
`libexec/bin/python3` links to its framework. Absent or `false` keeps the program
inside the home; other values reject the manifest. The field does not change project
candidates, which follow their own `projectKind` rules, and it is never needed for a
program that is a file inside its home. A host whose Core predates the field rejects
manifests that set it, so a plugin that sets it requires a host release that has it.
See [Pins and snapshot resolution](#pins-and-snapshot-resolution) for the checks.

`version` is `{arguments, pattern}`. `arguments` lists one to eight distinct
literal words of at most 64 bytes. The first is a flag (`-version`,
`--version`) or a subcommand (`version`, for a tool such as Go that prints its
Expand Down Expand Up @@ -313,6 +323,21 @@ another name, the reported executable is that layout path beneath the canonical
home instead: a multi-call program such as rustup links `cargo` to itself and picks
the tool from the name it starts with, so starting the link target would run the
wrong program. The facts still check the target's kind, mode and containment.

Every external installation (pin, `fixed:{home}`, `homeVariable`, discovery and
provider report) passes one check. The canonical home must lie outside every
workspace, and the layout program must be a regular executable file, or a link to
one, whose canonical target lies outside every workspace. The target must also stay
inside the canonical home, unless the definition sets `executableLinksOutsideHome:
true`. Then a single-hop or multi-hop link to a target outside the home is accepted
when every directory between the home and the program (such as `bin`) is observed as
a directory whose canonical path stays inside the canonical home and outside every
workspace; an unobserved or escaping directory fails with `unsafePath`. Such a
program reports, is probed at and starts from its layout path beneath the canonical
home, never its target, so a virtual environment keeps finding its `pyvenv.cfg` and
packages; `${home}` exports still name the home. A host observes each of those
directories when it records a home's layout programs.

Shell environment home variables and `commandHomes` come from the native login-shell
adapter, not command-name guessing. An environment candidate selects only through
its declared `path` layout.
Expand Down
Loading
Loading