diff --git a/rust/crates/core/src/tests/toolchain_definitions.rs b/rust/crates/core/src/tests/toolchain_definitions.rs index 3ac583a9..959352a1 100644 --- a/rust/crates/core/src/tests/toolchain_definitions.rs +++ b/rust/crates/core/src/tests/toolchain_definitions.rs @@ -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() { diff --git a/rust/crates/core/src/tests/toolchain_resolution.rs b/rust/crates/core/src/tests/toolchain_resolution.rs index 9d70873f..7959ced0 100644 --- a/rust/crates/core/src/tests/toolchain_resolution.rs +++ b/rust/crates/core/src/tests/toolchain_resolution.rs @@ -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(); diff --git a/rust/crates/toolchain/src/definitions.rs b/rust/crates/toolchain/src/definitions.rs index 69ae70ef..befa615c 100644 --- a/rust/crates/toolchain/src/definitions.rs +++ b/rust/crates/toolchain/src/definitions.rs @@ -426,6 +426,7 @@ fn definition(plugin_id: &str, value: &Value) -> Validation<()> { "launch", "category", "audience", + "executableLinksOutsideHome", ], &[ "id", @@ -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."))?; diff --git a/rust/crates/toolchain/src/query.rs b/rust/crates/toolchain/src/query.rs index 378f3291..ae0c40da 100644 --- a/rust/crates/toolchain/src/query.rs +++ b/rust/crates/toolchain/src/query.rs @@ -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( @@ -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 @@ -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, diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index d681c166..9a7342ed 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -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, diff --git a/shared/plugins/contract/v1/toolchains/README.md b/shared/plugins/contract/v1/toolchains/README.md index 529a6696..250ae1d2 100644 --- a/shared/plugins/contract/v1/toolchains/README.md +++ b/shared/plugins/contract/v1/toolchains/README.md @@ -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 @@ -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 @@ -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. diff --git a/shared/plugins/reference/domains/toolchains.md b/shared/plugins/reference/domains/toolchains.md index 7166c0ba..38e5425a 100644 --- a/shared/plugins/reference/domains/toolchains.md +++ b/shared/plugins/reference/domains/toolchains.md @@ -33,6 +33,8 @@ 外部安装报告的可执行文件是解析掉链接后的规范路径。例外是 `executableLayouts` 里的文件链接到另一个文件名:这时报告规范主目录下的布局路径。rustup 把 `cargo`、`rust-analyzer` 链接到自身,按启动时的名字决定运行哪个工具,从链接目标启动只会运行 rustup;版本探针和启动都用布局路径。 +外部安装的程序解析后默认必须在主目录内。虚拟环境的 `bin/python3` 链接到环境外的基础解释器,Homebrew 的 `libexec/bin/python3` 链接到 `libexec` 外的 framework,这类工具的定义写 `executableLinksOutsideHome: true`(`toolDefinitions` 0 内的补充,不升版本)。写了以后,程序可以经过一次或多次链接指向主目录外的普通可执行文件,但主目录到程序之间的各级目录(例如 `bin`)解析后必须仍在主目录内,主目录和链接目标都不能在工作区内。这类程序的版本探针和启动都用规范主目录下的布局路径,不用链接目标,所以 Python 仍能按启动路径找到环境的 `pyvenv.cfg` 和包。固定、`homeVariable`、发现规则和提供者报告都按这条规则检查;项目里的候选按 `projectKind` 的规则,不受这个字段影响。Core 早于这个字段的宿主会拒绝写了它的清单,所以用它的插件要求包含它的宿主版本。 + ### 选择顺序 | 层 | 规则 | @@ -223,6 +225,8 @@ The first argument of the version probe `version.arguments` is a flag (`-version An external installation reports its canonical executable, with links resolved. The exception is a file in `executableLayouts` that links to a file with another name: Core then reports the layout path beneath the canonical home. rustup links `cargo` and `rust-analyzer` to itself and picks the tool from the name it starts with; started by the link target's name it runs rustup. Version probes and launches use the layout path. +By default an external installation's program must resolve inside its home. A virtual environment's `bin/python3` links to its base interpreter outside the environment, and Homebrew's `libexec/bin/python3` links to the framework outside `libexec`; a definition for such a tool sets `executableLinksOutsideHome: true` (an addition within `toolDefinitions` 0, with no version bump). The program may then be a single-hop or multi-hop link to a regular executable file outside the home, but every directory between the home and the program (such as `bin`) must still resolve inside the home, and neither the home nor the link target may lie in a workspace. Version probes and launches use the layout path beneath the canonical home, not the link target, so Python still finds the environment's `pyvenv.cfg` and packages from the path it starts with. Pins, `homeVariable`, discovery and provider reports all go through this check; project candidates follow their `projectKind` rules and ignore the field. A host whose Core predates the field rejects manifests that set it, so a plugin that uses it requires a host release that has it. + ### Selection order | Layer | Rule |