From 959367a0802b9fdbd57a418e3ae281543c9b5ae4 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Thu, 19 Nov 2026 03:20:21 -0800 Subject: [PATCH 1/3] feat(build): record workspace trust and refuse plans that run project code in untrusted workspaces The toolchain catalog records a decision on each workspace as IntelliJ IDEA does: trusted, distrusted (kept in safe mode) or unknown, plus trusted locations whose every workspace is trusted. catalogState reports the state, the location that trusts the workspace and the parent folder a prompt may offer; editCatalog records trust, safe mode, or trust with the parent folder. Plan requests take projectCodeAllowed. Without it Core refuses with plugin.build.untrustedWorkspace every task, test, run configuration, before-launch task, run and debug preparation, a model or dependency command declaring executesProjectCode, and a request to a provider declaring it. Run entries from a decoded model and test discovery decoding need no trust. The contract replaces "Lithe has no workspace trust state" with a Workspace trust section and documents the new code. Co-Authored-By: Claude Opus 5.5 --- rust/contracts/rust-core-api.md | 44 ++- rust/crates/build/src/configuration.rs | 8 +- rust/crates/build/src/plans.rs | 73 +++- rust/crates/build/src/run_entrypoints.rs | 4 +- rust/crates/build/src/run_preparation.rs | 4 +- rust/crates/build/src/run_types.rs | 10 + rust/crates/build/src/test_discovery.rs | 6 +- .../core/src/tests/before_launch_tasks.rs | 2 +- .../core/src/tests/build_configuration.rs | 6 +- rust/crates/core/src/tests/build_systems.rs | 142 +++++-- .../crates/core/src/tests/plugin_run_types.rs | 2 +- .../core/src/tests/published_build_plugins.rs | 2 +- rust/crates/core/src/tests/support.rs | 20 + rust/crates/toolchain/src/catalog.rs | 359 +++++++++++++++--- rust/fixtures/toolchain-global-catalog.json | 64 +++- shared/plugins/contract/v1/README.md | 43 ++- .../fixtures/build-systems/build-plans.json | 140 +++++-- .../guides/plugin-backend-workspace.md | 4 +- shared/plugins/reference/domains/backend.md | 4 +- 19 files changed, 752 insertions(+), 185 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index af6bd508..5bcabdf3 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -5269,9 +5269,19 @@ Paths in requests are workspace-relative with `/` unless named absolute. `root` is the instance root from detection. Selected entities are `{ name, path?, tags?, execution?, properties? }` as the decoded model returned them. Plan requests share `{ root, options?, pluginDirectory?, -workspaceStateDirectory?, modelInputs? }`; `options` are the stored values by option ID, +workspaceStateDirectory?, modelInputs?, projectCodeAllowed? }`; `options` are the stored values by option ID, and the directories are absolute host paths used only as substitution text. +`projectCodeAllowed` is the workspace's trust from `toolchains.catalogState`; absent means +`false`. A plan that would run project code in an untrusted workspace is refused with +`plugin.build.untrustedWorkspace`: every task, test, run configuration, before-launch task, run +preparation and debug preparation, since they run the project; a model or dependency command +that declares `executesProjectCode: true`; and a provider request to a provider that declares +it. A model or dependency command declaring `executesProjectCode: false` plans without trust. +Run entries listed from a decoded model and `build.decodeTestDiscovery` need no trust, since +they return no plan. The host leaves an automatic load undone on this refusal and asks the +user to trust the workspace before an action the user started. + | Command | Request | Result | | --- | --- | --- | | `build.detect` | `{ workspaceRoot, plugins: [{ manifest }], options?: { : { : value } }, instanceOptions?: { : { : { : value } } }, instanceDefaults?: { : { : value } }, emptySelections?: { : { : [optionID] } }, ignoredPaths?: [pattern] }` | `detection`: `{ instances, rejected: [{ index, error }], shadowed: [{ pluginID, buildSystemID, by }] }`; each instance is `{ id, pluginID, buildSystemID, displayName, root, markers, modelSource, optionFingerprint, options, droppedOptions }` plus `model` or `modelError` for `static` and `hostIntegration` sources; a `provider` source has neither. `options` contains accepted stored values after Core scope/root merging, including explicit empty selections; `droppedOptions` names rejected stored values without rewriting the source document. The scan does not enter a directory `ignoredPaths` names; omitted (or `null`), it is Core's default `[".*"]`, every directory whose name starts with a dot, and `[]` ignores nothing beyond the shared scan policy. Hosts pass `storage.ignoredPaths.patterns` from `build.resolveStoredOptions`. An unusable list rejects with `plugin.build.invalidIgnoredPath` (see `build.editIgnoredPaths`). | @@ -5289,8 +5299,8 @@ and the directories are absolute host paths used only as substitution text. | `build.decodeConfigurationEdit` | `{ snapshot, edits, result }` | `edit: { sourceID, revision, changed }`; validates bounded receipt and exact draft/source identity; native adapter verifies staged hash and publishes atomically | | `build.modelPlan`, `build.dependencyPlan` | plan fields plus `project?` (dependencies), `outputFile?`, and for provider sources `refresh?` (boolean) and `tool?: { executable }` (absolute path) | `plan`: `{ buildSystemID, root, arguments, environment, workingDirectory, execution, optionFingerprint, output, decoder, executesProjectCode, mayUseNetwork }`; for a `provider` source `{ buildSystemID, root, provider: { method, params }, decoder, executesProjectCode, mayUseNetwork, optionFingerprint }`, where `method` is `lithe/build/model` or `lithe/build/dependencies` and `params` is `{ buildSystemID, root, options, optionArguments, environment, project?, refresh?, tool? }`; `refresh` appears only when `true` and `tool` only when the host sent it | | `build.taskPlan` | plan fields plus `task`, `project?`, `target?`, `modelTask?`, `userArguments?` | command `plan` with `arguments`, `environment`, `workingDirectory`, `execution`, and `optionFingerprint`; a provider task instead returns `provider: {method: "lithe/build/execute", params}` with effective options, selected task/entities, user arguments and effect metadata | -| `build.runConfigurationPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {configurationId, localDocument?, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?}` | `plan` as `build.taskPlan` returns it plus `runType: {pluginID, buildSystemID, type}`: the global arguments, then the type's `arguments` with the saved field values, the instance's options and the configuration's program arguments, at the configuration's working directory, with its environment over the options'. The instance is the deepest one whose root holds the working directory, or the only one; `plugin.build.invalidSelection` when several exist and none holds it or the configuration belongs to another plugin or build system, `plugin.build.unavailable` when the type is no longer declared, `plugin.build.invalidRunConfiguration` with `field: values.` when a saved value no longer fits. A configuration that is missing, disabled, unavailable or of another provider fails the call | -| `build.beforeLaunchTaskPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {task, workingDirectory, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?}`, with `task` and `workingDirectory` as `runConfig.beforeLaunch` returned the step | `plan` as `build.taskPlan` returns it plus `beforeLaunchTask: {pluginID, buildSystemID, type}`: the global arguments, then the task's `arguments` with the saved field values and the instance's options, at the step's working directory with the options' environment, as a `task` execution. The instance is chosen as for `build.runConfigurationPlan`; `plugin.build.invalidSelection` when several exist and none holds the working directory or the task belongs to another plugin or build system, `plugin.build.unavailable` when the task is no longer declared, `plugin.build.invalidBeforeLaunchTask` with `field: values.` when a saved value no longer fits. A working directory outside the workspace fails the call | +| `build.runConfigurationPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {configurationId, localDocument?, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?, projectCodeAllowed?}` | `plan` as `build.taskPlan` returns it plus `runType: {pluginID, buildSystemID, type}`: the global arguments, then the type's `arguments` with the saved field values, the instance's options and the configuration's program arguments, at the configuration's working directory, with its environment over the options'. The instance is the deepest one whose root holds the working directory, or the only one; `plugin.build.invalidSelection` when several exist and none holds it or the configuration belongs to another plugin or build system, `plugin.build.unavailable` when the type is no longer declared, `plugin.build.invalidRunConfiguration` with `field: values.` when a saved value no longer fits. A configuration that is missing, disabled, unavailable or of another provider fails the call | +| `build.beforeLaunchTaskPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {task, workingDirectory, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?, projectCodeAllowed?}`, with `task` and `workingDirectory` as `runConfig.beforeLaunch` returned the step | `plan` as `build.taskPlan` returns it plus `beforeLaunchTask: {pluginID, buildSystemID, type}`: the global arguments, then the task's `arguments` with the saved field values and the instance's options, at the step's working directory with the options' environment, as a `task` execution. The instance is chosen as for `build.runConfigurationPlan`; `plugin.build.invalidSelection` when several exist and none holds the working directory or the task belongs to another plugin or build system, `plugin.build.unavailable` when the task is no longer declared, `plugin.build.invalidBeforeLaunchTask` with `field: values.` when a saved value no longer fits. A working directory outside the workspace fails the call | | `build.testPlan` | plan fields plus `project?`, `target?`, `suite?`, `case?`, `userArguments?`, `projects?` (the model's project directories) | command plan or `provider: {method: "lithe/build/test", params}`, plus `results`: `null`, `{ decoder, reports }` with workspace-relative globs (for the selected project, or for the root and every listed project when none is selected), or command-only `{ decoder: "hostIntegration" }`. Command filters that templates cannot place, such as a case without its suite when the tool only addresses `Suite#case`, are `plugin.build.invalidSelection`; Provider filters remain separate typed values and must be declared supported | | `build.testDiscoveryPlan` | Common plan fields, plus a fresh absolute `outputFile` for `test.discoveryCommand`, or optional `refresh` and `tool` for `test.discovery: true`. No project selection. | Command plan with argv, environment, instance working directory, `output: "outputFile"`, `decoder: "litheTestDiscovery"` and effect metadata, or `plan.provider` for `lithe/build/discoverTests` with the effective options. | | `build.decodeTestDiscovery` | Original common plan fields plus the same `outputFile` for a completed command or canonical inline `result` for a Provider. | `discovery.tests` with validated `{id, suite, case, project?, target?}` selectors. Bounded at 10,000 items and 32 MiB, deterministic and exactly runnable. Malformed results reject in full with `plugin.build.invalidOutput`. | @@ -7432,21 +7442,31 @@ must not infer executable names from opaque runtime IDs. ### Global SDK registrations without an open project `toolchains.catalogState` accepts `{document:string|null,platform,filesystemCaseSensitive?,workspaceRoot?}` -and returns `{status:"ok",state:{document,storage:{relativePath:"toolchains/global.json",maximumBytes:262144},projectCodeAllowed?}}`. -When `workspaceRoot` is supplied, `projectCodeAllowed` reports whether that normalized workspace -root is in the machine-local `trustedWorkspaces` list (`false` when `workspaceRoot` is `""`); -when `workspaceRoot` is omitted, `projectCodeAllowed` is omitted. +and returns `{status:"ok",state:{document,storage:{relativePath:"toolchains/global.json",maximumBytes:262144},projectCodeAllowed?,workspaceTrust?}}`. +When a nonempty `workspaceRoot` is supplied, `workspaceTrust` is `{state, location, offeredLocation}` +and `projectCodeAllowed` is `state == "trusted"`; both are omitted otherwise. The machine-local +document keeps three lists of normalized absolute paths, at most 256 each: `trustedWorkspaces`, +`distrustedWorkspaces` (workspaces kept in safe mode) and `trustedLocations` (folders whose every +workspace at any depth is trusted). As in IntelliJ IDEA, an explicit decision on the workspace +applies first, then a trusted location containing it: `state` is `trusted`, `distrusted`, or +`unknown` when the user has not been asked. `location` is the trusted location that trusts the +workspace, else `null`. `offeredLocation` is the parent folder a trust prompt may offer to trust +with the workspace, or `null` when that parent is a filesystem root (`/`, a drive, a UNC share). +The two newer lists are written only once used, so a document without them stays readable by +hosts that predate them. Native clients resolve the relative path below their platform user-preference directory, never below a workspace, SDK, installed package or application bundle. Reading an absent source returns `{version:1,tools:{}}` and must not create a directory or file. `toolchains.editCatalog` accepts `{document:string|null,platform,filesystemCaseSensitive?,edits?,workspaceTrust?}`, where at least one of a nonempty `edits` array of `{tool,homes:[absoluteHome],defaultHome:string|null}` -or `workspaceTrust:{workspace,trusted}` is required. Each tool edit replaces only that tool's -registrations and default; other tools, dormant plugins and `trustedWorkspaces` remain intact. -`workspaceTrust` grants or revokes machine-local `projectCodeAllowed` trust for one normalized -workspace root (at most 256 distinct workspaces), preserving `tools`; revoking trust on an absent -document returns `changed:false,document:null` and creates no file. At most +or `workspaceTrust:{workspace,trusted,location?}` is required. Each tool edit replaces only that tool's +registrations and default; other tools, dormant plugins and the trust lists remain intact. +`workspaceTrust` records one decision on one normalized workspace root, preserving `tools` and +other decisions: `trusted: true` moves it to `trustedWorkspaces`, `trusted: false` to +`distrustedWorkspaces` (safe mode), and `location: true` also adds its `offeredLocation` to +`trustedLocations`; `location` with `trusted: false`, or without an offered location, rejects at +`workspaceTrust.location`. At most 64 tools and 32 distinct homes per tool are accepted. Native platform path normalization and case identity apply before deduplication. A selected default is registered if needed; null clears only the default. Empty registrations plus null remove the tool entry. diff --git a/rust/crates/build/src/configuration.rs b/rust/crates/build/src/configuration.rs index f09b4746..477b2178 100644 --- a/rust/crates/build/src/configuration.rs +++ b/rust/crates/build/src/configuration.rs @@ -126,12 +126,12 @@ pub(crate) fn plan( .provider .as_ref() .ok_or_else(|| plans::unavailable(declaration, "a provider"))?; - Ok(context.provider_plan( + context.provider_plan( provider, "lithe/build/configuration", "litheBuildConfiguration", plans::provider_hints(request)?, - )) + ) } /// Validates all fields before they become a settings form or write binding. @@ -367,12 +367,12 @@ pub(crate) fn edit_plan( params.insert("snapshot".into(), json!(request.snapshot)); params.insert("edits".into(), json!({"sourceID":request.edits.source_id,"revision":request.edits.revision,"values":request.edits.values})); params.insert("outputFile".into(), json!(output)); - Ok(context.provider_plan( + context.provider_plan( provider, "lithe/build/editConfiguration", "litheConfigurationEdit", params, - )) + ) } /// Bounded receipt only; private native document bytes stay in staging storage. diff --git a/rust/crates/build/src/plans.rs b/rust/crates/build/src/plans.rs index 8626cea2..05bffe7e 100644 --- a/rust/crates/build/src/plans.rs +++ b/rust/crates/build/src/plans.rs @@ -81,6 +81,26 @@ pub(crate) struct PlanBase { /// Absolute writable directory of this plugin for this workspace. #[serde(default)] pub(crate) workspace_state_directory: Option, + /// Whether the user trusts the workspace, from `toolchains.catalogState`. + /// Absent means untrusted: a plan that runs project code is then refused + /// with [`UNTRUSTED_WORKSPACE`]. + #[serde(default)] + pub(crate) project_code_allowed: bool, +} + +/// Refusal of a plan that would run project code in a workspace the user has +/// not trusted. The host asks for trust before a user action and leaves an +/// automatic load undone. +pub(crate) const UNTRUSTED_WORKSPACE: &str = "plugin.build.untrustedWorkspace"; + +fn untrusted(build_system: &BuildSystemDeclaration) -> PluginRejection { + PluginRejection::new( + UNTRUSTED_WORKSPACE, + format!( + "{} would run project code; the workspace is not trusted.", + build_system.display_name + ), + ) } #[derive(Debug, Deserialize)] @@ -292,6 +312,7 @@ pub(crate) struct PlanContext<'a> { model_inputs: Option, plugin_directory: Option, workspace_state_directory: Option, + project_code_allowed: bool, } fn host_directory(value: &Option, name: &str) -> Validation> { @@ -347,9 +368,17 @@ impl<'a> PlanContext<'a> { &base.workspace_state_directory, "workspaceStateDirectory", )?, + project_code_allowed: base.project_code_allowed, }) } + /// This context for plans that are only checked and never returned to the + /// host, which therefore run nothing and need no trusted workspace. + pub(crate) fn validating(mut self) -> Self { + self.project_code_allowed = true; + self + } + pub(crate) fn values<'v>(&'v self, user_arguments: &'v [String]) -> Values<'v> { Values { root: &self.root, @@ -380,6 +409,15 @@ impl<'a> PlanContext<'a> { execution: BuildExecution, extra: Map, ) -> Validation { + // A model or dependency command states whether it runs project code; any + // other command runs the build tool on the project, so it does. + let executes = extra + .get("executesProjectCode") + .and_then(Value::as_bool) + .unwrap_or(true); + if executes && !self.project_code_allowed { + return Err(untrusted(self.build_system)); + } let mut plan = json!({ "buildSystemID": self.build_system.id, "root": self.root, @@ -401,13 +439,21 @@ impl<'a> PlanContext<'a> { /// would contribute to a command line, so the provider can hand either /// to the tool. `params` already holds the source's own fields and the /// host's `refresh` and `tool` hints. + /// + /// An execution (`execution`) or a run preparation runs the project, so it + /// needs a trusted workspace whatever the provider declares; a request that + /// only reads the project needs it when the provider runs project code. pub(crate) fn provider_plan( &self, provider: &ProviderDeclaration, method: &str, decoder: &str, mut params: Map, - ) -> Value { + ) -> Validation { + let runs = matches!(decoder, "execution" | "litheRunPreparation"); + if (runs || provider.executes_project_code()) && !self.project_code_allowed { + return Err(untrusted(self.build_system)); + } let option_arguments: Vec<&String> = self .contribution .arguments @@ -432,7 +478,7 @@ impl<'a> PlanContext<'a> { if let Some(inputs) = &self.model_inputs { params.insert("modelInputs".into(), inputs.clone()); } - json!({ + Ok(json!({ "buildSystemID": self.build_system.id, "root": self.root, "provider": { "method": method, "params": params }, @@ -440,7 +486,7 @@ impl<'a> PlanContext<'a> { "executesProjectCode": provider.executes_project_code(), "mayUseNetwork": provider.may_use_network(), "optionFingerprint": self.fingerprint, - }) + })) } } @@ -623,12 +669,12 @@ pub(crate) fn task_plan( ); } } - return Ok(context.provider_plan( + return context.provider_plan( declared_provider(build_system)?, "lithe/build/execute", "execution", params, - )); + ); } context.plan(&declaration.arguments, &values, execution, Map::new()) } @@ -678,12 +724,12 @@ pub(crate) fn test_discovery_plan( "A provider returns test discovery directly.", )); } - Ok(context.provider_plan( + context.provider_plan( declared_provider(build_system)?, "lithe/build/discoverTests", "litheTestDiscovery", provider_hints(request)?, - )) + ) } /// Whether a selected target carries one of the declared tags; no tags @@ -874,7 +920,7 @@ pub(crate) fn test_plan_with_selection( "lithe/build/test", "execution", params, - ); + )?; plan.as_object_mut() .expect("provider plan is an object") .extend(extra); @@ -915,12 +961,12 @@ pub(crate) fn model_plan( )); } let context = PlanContext::new(build_system, &request.base)?; - return Ok(context.provider_plan( + return context.provider_plan( declared_provider(build_system)?, PROVIDER_MODEL_METHOD, "litheBuildModel", provider_hints(request)?, - )); + ); } let Some(ModelSource::Command { arguments, @@ -1024,12 +1070,12 @@ pub(crate) fn dependency_plan( |project| json!({ "name": project.name, "path": project.path }), ), ); - Ok(context.provider_plan( + context.provider_plan( declared_provider(build_system)?, PROVIDER_DEPENDENCIES_METHOD, "litheDependencies", params, - )) + ) } } } @@ -1088,6 +1134,9 @@ pub(crate) fn run_entries( options: stored_options.clone(), plugin_directory: None, workspace_state_directory: None, + // Entries only expand templates for the run list; starting one asks for + // a plan of its own, which checks trust. + project_code_allowed: false, }; let context = PlanContext::with_model_options( build_system, diff --git a/rust/crates/build/src/run_entrypoints.rs b/rust/crates/build/src/run_entrypoints.rs index 0c982dda..87866cbc 100644 --- a/rust/crates/build/src/run_entrypoints.rs +++ b/rust/crates/build/src/run_entrypoints.rs @@ -86,12 +86,12 @@ pub(crate) fn plan( .provider .as_ref() .ok_or_else(|| plans::unavailable(build_system, "a provider"))?; - Ok(context.provider_plan( + context.provider_plan( provider, "lithe/build/runEntrypoints", "litheRunEntrypoints", params, - )) + ) } /// `build.decodeRunEntrypoints`: the entrypoints the host may save and start, in diff --git a/rust/crates/build/src/run_preparation.rs b/rust/crates/build/src/run_preparation.rs index a56f1e3a..30efc2e6 100644 --- a/rust/crates/build/src/run_preparation.rs +++ b/rust/crates/build/src/run_preparation.rs @@ -276,12 +276,12 @@ pub(crate) fn plan( .provider .as_ref() .ok_or_else(|| plans::unavailable(build_system, "a provider"))?; - Ok(context.provider_plan( + context.provider_plan( provider, "lithe/build/prepareRun", "litheRunPreparation", params, - )) + ) } /// The platform supplies its writable workspace root, never an installation path. diff --git a/rust/crates/build/src/run_types.rs b/rust/crates/build/src/run_types.rs index 6c932cbc..ef0bc940 100644 --- a/rust/crates/build/src/run_types.rs +++ b/rust/crates/build/src/run_types.rs @@ -452,6 +452,9 @@ pub(crate) struct RunConfigurationPlanRequest { /// Absolute writable directory of this plugin for this workspace. #[serde(default)] pub(crate) workspace_state_directory: Option, + /// Whether the user trusts the workspace, as in a task plan. + #[serde(default)] + pub(crate) project_code_allowed: bool, } /// One detected instance of the build system. @@ -486,6 +489,9 @@ pub(crate) struct BeforeLaunchTaskPlanRequest { /// Absolute writable directory of this plugin for this workspace. #[serde(default)] pub(crate) workspace_state_directory: Option, + /// Whether the user trusts the workspace, as in a task plan. + #[serde(default)] + pub(crate) project_code_allowed: bool, } /// What a plan takes from its request besides the launch. @@ -493,6 +499,7 @@ struct PlanSources<'a> { instances: &'a [RunTypeInstance], plugin_directory: Option, workspace_state_directory: Option, + project_code_allowed: bool, } /// The wording and identity of one role in a plan. @@ -549,6 +556,7 @@ pub(crate) fn run_configuration_plan( instances: &request.instances, plugin_directory: request.plugin_directory.clone(), workspace_state_directory: request.workspace_state_directory.clone(), + project_code_allowed: request.project_code_allowed, }, workspace_root, ) @@ -575,6 +583,7 @@ pub(crate) fn before_launch_task_plan( instances: &request.instances, plugin_directory: request.plugin_directory.clone(), workspace_state_directory: request.workspace_state_directory.clone(), + project_code_allowed: request.project_code_allowed, }, workspace_root, ) @@ -622,6 +631,7 @@ fn declared_plan( options: instance.options.clone(), plugin_directory: sources.plugin_directory, workspace_state_directory: sources.workspace_state_directory, + project_code_allowed: sources.project_code_allowed, }; let context = PlanContext::new(system, &base)?; let mut values = context.values(&launch.arguments); diff --git a/rust/crates/build/src/test_discovery.rs b/rust/crates/build/src/test_discovery.rs index a3d5b1d0..003a5e2b 100644 --- a/rust/crates/build/src/test_discovery.rs +++ b/rust/crates/build/src/test_discovery.rs @@ -49,8 +49,10 @@ pub(crate) fn decode( .as_ref() .filter(|test| test.discovers_tests()) .ok_or_else(|| plans::unavailable(build_system, "test discovery"))?; - // Validate host context even for a valid empty discovery result. - let context = plans::PlanContext::new(build_system, &request.base)?; + // Validate host context even for a valid empty discovery result. The test + // plans below only check that each selector could run and are never + // returned, so they do not need a trusted workspace. + let context = plans::PlanContext::new(build_system, &request.base)?.validating(); let command_result; let result = if test.discovery_command.is_some() { if request.result.is_some() { diff --git a/rust/crates/core/src/tests/before_launch_tasks.rs b/rust/crates/core/src/tests/before_launch_tasks.rs index 26f8186e..1d773c4f 100644 --- a/rust/crates/core/src/tests/before_launch_tasks.rs +++ b/rust/crates/core/src/tests/before_launch_tasks.rs @@ -91,7 +91,7 @@ fn plan(root: &std::path::Path, request: Value) -> Value { "manifest": manifest(), "buildSystemID": "go", "workspaceRoot": root, - "request": request, + "request": super::support::trusted(request), }), ) } diff --git a/rust/crates/core/src/tests/build_configuration.rs b/rust/crates/core/src/tests/build_configuration.rs index 633237ec..bc625deb 100644 --- a/rust/crates/core/src/tests/build_configuration.rs +++ b/rust/crates/core/src/tests/build_configuration.rs @@ -37,7 +37,7 @@ fn call(command: fn(Value) -> Result, request command(json!({"manifest":manifest,"buildSystemID":id,"request":request})).unwrap() } fn edit_request() -> Value { - json!({"root":".", "workspaceStateDirectory":native_fixture_path("/fixture/state"), "outputFile":native_fixture_path("/fixture/state/outputs/edit.json"), + json!({"root":".", "projectCodeAllowed":true, "workspaceStateDirectory":native_fixture_path("/fixture/state"), "outputFile":native_fixture_path("/fixture/state/outputs/edit.json"), "snapshot":snapshot(), "edits":{"sourceID":"user", "revision":snapshot()["sources"][0]["revision"], "values":{"localRepository":"/new"}}}) } @@ -51,7 +51,7 @@ fn native_configuration_needs_a_provider_host_and_preserves_option_arguments() { }; let plan = call( build_configuration_plan_command::, - json!({"root":".","options":{"offline":true},"tool":{"executable":executable}}), + json!({"root":".","projectCodeAllowed":true,"options":{"offline":true},"tool":{"executable":executable}}), ); assert_eq!(plan["status"], "ok", "{plan}"); assert_eq!( @@ -65,7 +65,7 @@ fn native_configuration_needs_a_provider_host_and_preserves_option_arguments() { assert_eq!( call( build_configuration_plan_command::, - json!({"root":".","tool":{"executable":"relative/mvn"}}) + json!({"root":".","projectCodeAllowed":true,"tool":{"executable":"relative/mvn"}}) )["status"], "rejected" ); diff --git a/rust/crates/core/src/tests/build_systems.rs b/rust/crates/core/src/tests/build_systems.rs index ead95ab0..a76b6cfa 100644 --- a/rust/crates/core/src/tests/build_systems.rs +++ b/rust/crates/core/src/tests/build_systems.rs @@ -116,7 +116,13 @@ fn call(name: &str, manifest: Value, build_system: &str, request: Value) -> Valu operation(name)(json!({ "manifest": manifest, "buildSystemID": build_system, - "request": request, + // Only the plans that run something read workspace trust. + "request": match name { + "modelPlan" | "taskPlan" | "testPlan" | "dependencyPlan" => { + super::support::trusted(request) + } + _ => request, + }, })) .expect("payload is well formed") } @@ -2053,22 +2059,22 @@ fn provider_execution_tasks_are_typed_and_need_a_provider_host() { .remove("scopes"); run["buildSystems"][0]["run"] = json!([{"id":"run", "fromTasks":{"templates":["build"]}}]); assert_eq!(validate(run)["status"], "rejected"); - let escape = build_task_plan_command::(json!({ + let escape = build_task_plan_command::(super::support::trusted_payload(json!({ "manifest":manifest, "buildSystemID":"gradle", "request":{"root":"app","task":"build","project":{"name":"escape","path":"../escape"}} - })) + }))) .unwrap(); assert_eq!(escape["status"], "rejected"); - let oversized = build_task_plan_command::(json!({ + let oversized = build_task_plan_command::(super::support::trusted_payload(json!({ "manifest":manifest, "buildSystemID":"gradle", "request":{"root":".","task":"custom","userArguments":vec!["arg";65]} - })) + }))) .unwrap(); assert_eq!(oversized["status"], "rejected"); - let result = build_task_plan_command::(json!({ + let result = build_task_plan_command::(super::support::trusted_payload(json!({ "manifest": manifest, "buildSystemID":"gradle", "request": {"root":".", "task":"build", "project": {"name":"app","path":"app"}, "options":{"offline":true}} - })) + }))) .unwrap(); assert_eq!(result["status"], "ok", "{result}"); assert!(result["plan"].get("arguments").is_none(), "{result}"); @@ -2083,6 +2089,52 @@ fn provider_execution_tasks_are_typed_and_need_a_provider_host() { ); } +// A provider that only reads the project may answer in an untrusted workspace +// when it declares it runs no project code, but an execution runs the project +// whatever the provider declares; a provider that runs project code needs trust +// even to read the model. +#[test] +fn provider_requests_that_run_project_code_need_a_trusted_workspace() { + let mut manifest: Value = serde_json::from_str(contract_file!( + "fixtures/build-providers/build-provider-execution.plugin.json" + )) + .unwrap(); + let request = |manifest: &Value, command: Command, request: Value| { + command(json!({"manifest": manifest, "buildSystemID": "gradle", "request": request})) + .unwrap() + }; + let untrusted = json!({"root": ".", "projectCodeAllowed": false}); + let task = json!({"root": ".", "task": "build", "project": {"name": "app", "path": "app"}}); + + let model = request(&manifest, operation("modelPlan"), untrusted.clone()); + assert_eq!( + model["error"]["code"], "plugin.build.untrustedWorkspace", + "{model}" + ); + let dependencies = request(&manifest, operation("dependencyPlan"), untrusted.clone()); + assert_eq!( + dependencies["error"]["code"], "plugin.build.untrustedWorkspace", + "{dependencies}" + ); + + manifest["buildSystems"][0]["provider"]["executesProjectCode"] = json!(false); + let model = request(&manifest, operation("modelPlan"), untrusted); + assert_eq!(model["status"], "ok", "{model}"); + assert_eq!(model["plan"]["executesProjectCode"], false, "{model}"); + let execution = request(&manifest, operation("taskPlan"), task.clone()); + assert_eq!( + execution["error"]["code"], "plugin.build.untrustedWorkspace", + "{execution}" + ); + let mut trusted = task; + trusted["projectCodeAllowed"] = json!(true); + let execution = request(&manifest, operation("taskPlan"), trusted); + assert_eq!( + execution["plan"]["provider"]["method"], "lithe/build/execute", + "{execution}" + ); +} + #[test] fn preparation_tasks_are_declared_and_unambiguous() { let manifest: Value = serde_json::from_str(contract_file!( @@ -2164,9 +2216,9 @@ fn provider_tests_preserve_filters_and_report_ownership() { )) .unwrap(); assert_eq!(validate(manifest.clone())["status"], "ok"); - let plan = build_test_plan_command::( + let plan = build_test_plan_command::(super::support::trusted_payload( json!({"manifest": manifest, "buildSystemID":"gradle", "request":fixture["request"]}), - ) + )) .unwrap(); assert_eq!(plan["status"], "ok", "{plan}"); assert_eq!(plan["plan"]["provider"], fixture["provider"]); @@ -2185,10 +2237,11 @@ fn provider_tests_preserve_filters_and_report_ownership() { ); // A case-only filter is a typed value, not a CLI expression needing a suite. - let case_only = - build_test_plan_command::(json!({"manifest":manifest,"buildSystemID":"gradle", - "request":{"root":".","case":"exact"}})) - .unwrap(); + let case_only = build_test_plan_command::(super::support::trusted_payload( + json!({"manifest":manifest,"buildSystemID":"gradle", + "request":{"root":".","case":"exact"}}), + )) + .unwrap(); assert_eq!(case_only["status"], "ok", "{case_only}"); for request in [ json!({"root":"app","project":{"name":"escape","path":"../escape"}}), @@ -2196,19 +2249,19 @@ fn provider_tests_preserve_filters_and_report_ownership() { json!({"root":".","suite":"bad\u{0}filter"}), json!({"root":".","userArguments":vec!["arg";65]}), ] { - let rejected = build_test_plan_command::( + let rejected = build_test_plan_command::(super::support::trusted_payload( json!({"manifest":manifest,"buildSystemID":"gradle","request":request}), - ) + )) .unwrap(); assert_eq!(rejected["status"], "rejected", "{rejected}"); } let mut unsupported = manifest.clone(); unsupported["buildSystems"][0]["test"]["filters"] = json!([]); assert_eq!( - build_test_plan_command::( + build_test_plan_command::(super::support::trusted_payload( json!({"manifest":unsupported,"buildSystemID":"gradle", "request":fixture["request"]}) - ) + )) .unwrap()["status"], "rejected" ); @@ -2264,10 +2317,10 @@ fn provider_test_discovery_is_bounded_deterministic_and_runnable() { "fixtures/build-providers/build-test-discovery.json" )) .unwrap(); - let plan = build_test_discovery_plan_command::( + let plan = build_test_discovery_plan_command::(super::support::trusted_payload( json!({"manifest":manifest,"buildSystemID":"gradle", "request":{"root":".","refresh":true}}), - ) + )) .unwrap(); assert_eq!(plan["status"], "ok", "{plan}"); assert_eq!( @@ -2296,9 +2349,9 @@ fn provider_test_discovery_is_bounded_deterministic_and_runnable() { let mut request = test.clone(); request.as_object_mut().unwrap().remove("id"); request["root"] = json!("."); - let runnable = build_test_plan_command::( + let runnable = build_test_plan_command::(super::support::trusted_payload( json!({"manifest":manifest,"buildSystemID":"gradle","request":request}), - ) + )) .unwrap(); assert_eq!(runnable["status"], "ok", "{runnable}"); } @@ -2390,7 +2443,10 @@ fn command_test_discovery_plans_a_file_and_round_trips_exact_selectors() { let payload = |request: &Value| json!({"manifest":manifest, "buildSystemID":"sample", "request":request}); - let plan = build_test_discovery_plan_command::(payload(&request)).unwrap(); + let plan = build_test_discovery_plan_command::(super::support::trusted_payload( + payload(&request), + )) + .unwrap(); assert_eq!(plan["status"], "ok", "{plan}"); assert_eq!(plan["plan"]["output"], "outputFile"); assert_eq!(plan["plan"]["decoder"], "litheTestDiscovery"); @@ -2416,8 +2472,10 @@ fn command_test_discovery_plans_a_file_and_round_trips_exact_selectors() { ] { let mut unsafe_request = request.clone(); unsafe_request[field] = value; - let rejected = - build_test_discovery_plan_command::(payload(&unsafe_request)).unwrap(); + let rejected = build_test_discovery_plan_command::( + super::support::trusted_payload(payload(&unsafe_request)), + ) + .unwrap(); assert_eq!(rejected["error"]["code"], "plugin.build.invalidSelection"); } @@ -2435,7 +2493,9 @@ fn command_test_discovery_plans_a_file_and_round_trips_exact_selectors() { for test in tests { let mut run = test.clone(); run["root"] = json!("."); - let plan = build_test_plan_command::(payload(&run)).unwrap(); + let plan = + build_test_plan_command::(super::support::trusted_payload(payload(&run))) + .unwrap(); assert_eq!(plan["status"], "ok", "{plan}"); let argv = plan["plan"]["arguments"].as_array().unwrap(); assert!(argv.contains(&json!("--suite=ExampleSuite")), "{argv:?}"); @@ -2536,9 +2596,9 @@ fn provider_run_entrypoints_are_found_by_file_and_start_without_a_target() { } let plan = |request: Value| { - build_run_entrypoints_plan_command::( + build_run_entrypoints_plan_command::(super::support::trusted_payload( json!({"manifest":manifest,"buildSystemID":"gradle","request":request}), - ) + )) .unwrap() }; let planned = plan(fixture["plan"].clone()); @@ -2594,9 +2654,9 @@ fn provider_run_entrypoints_are_found_by_file_and_start_without_a_target() { } let prepare = |request: Value| { - build_prepare_run_plan_command::( + build_prepare_run_plan_command::(super::support::trusted_payload( json!({"manifest":manifest,"buildSystemID":"gradle","request":request}), - ) + )) .unwrap() }; let prepared = prepare(fixture["prepareRun"].clone()); @@ -2633,9 +2693,9 @@ fn provider_run_preparation_selects_targets_and_validates_launch_data() { .unwrap(); assert_eq!(validate(manifest.clone())["status"], "ok"); let plan = |request: Value| { - build_prepare_run_plan_command::( + build_prepare_run_plan_command::(super::support::trusted_payload( json!({"manifest":manifest,"buildSystemID":"gradle","request":request}), - ) + )) .unwrap() }; let prepared = plan(fixture["request"].clone()); @@ -2755,9 +2815,9 @@ fn provider_debug_preparation_validates_native_target_and_same_plugin_adapter() )) .unwrap(); assert_eq!(validate(manifest.clone())["status"], "ok"); - let planned = build_prepare_debug_plan_command::( + let planned = build_prepare_debug_plan_command::(super::support::trusted_payload( json!({"manifest":manifest,"buildSystemID":"gradle","request":run["request"]}), - ) + )) .unwrap(); assert_eq!( planned["plan"]["provider"]["method"], "lithe/build/prepareDebug", @@ -2908,7 +2968,7 @@ fn model_inputs_project_public_facts_and_preserve_configuration_identity() { instance["model"]["targets"][0]["tags"], json!(["application"]) ); - let plan = build_task_plan_command::(json!({"manifest":consumer,"buildSystemID":"gradle","request":{"root":"app","task":"build","modelInputs":snapshot}})).unwrap(); + let plan = build_task_plan_command::(super::support::trusted_payload(json!({"manifest":consumer,"buildSystemID":"gradle","request":{"root":"app","task":"build","modelInputs":snapshot}}))).unwrap(); assert_eq!(plan["status"], "ok", "{plan}"); assert_eq!(plan["plan"]["provider"]["params"]["modelInputs"], *snapshot); let mut no_sharing = request.clone(); @@ -3031,7 +3091,7 @@ fn model_inputs_reject_invalid_manifests_models_and_snapshot_smuggling() { "unavailablePayload" => snapshot["inputs"][0]["state"] = json!("unavailable"), _ => snapshot["revision"] = json!(9007199254740992_u64), } - let plan = build_task_plan_command::(json!({"manifest":consumer,"buildSystemID":"gradle","request":{"root":"app","task":"build","modelInputs":snapshot}})).unwrap(); + let plan = build_task_plan_command::(super::support::trusted_payload(json!({"manifest":consumer,"buildSystemID":"gradle","request":{"root":"app","task":"build","modelInputs":snapshot}}))).unwrap(); assert_eq!(plan["status"], "rejected", "{change}: {plan}"); } } @@ -3060,9 +3120,9 @@ fn provider_run_options_preserve_argv_and_validate_declared_execution_and_cwd() request["workspaceRoot"] = json!(workspace.root()); request["launchOptions"] = fixture["launchOptions"].clone(); let plan = |manifest: Value, request: Value| { - build_prepare_run_plan_command::( + build_prepare_run_plan_command::(super::support::trusted_payload( json!({"manifest":manifest,"buildSystemID":"gradle","request":request}), - ) + )) }; let result = plan(manifest.clone(), request.clone()).unwrap(); assert_eq!(result["status"], "ok", "{result}"); @@ -3150,9 +3210,9 @@ fn provider_connection_debug_options_require_a_declared_registry_type() { request["workspaceRoot"] = json!(workspace.root()); request["launchOptions"] = fixture["launchOptions"].clone(); let plan = |manifest: &Value, request: &Value| { - build_prepare_run_plan_command::( + build_prepare_run_plan_command::(super::support::trusted_payload( json!({"manifest":manifest,"buildSystemID":"gradle","request":request}), - ) + )) }; assert_eq!(plan(&manifest, &request).unwrap()["status"], "rejected"); let runs = manifest["buildSystems"][0]["run"].as_array_mut().unwrap(); @@ -3309,14 +3369,14 @@ fn model_option_defaults_and_exclusions_round_trip_through_storage_and_plans() { assert_eq!(after_uncheck["value"], json!(["-dev"])); assert_eq!(after_uncheck["selectedChoices"], json!([])); - let plan = build_model_plan_command::(json!({ + let plan = build_model_plan_command::(super::support::trusted_payload(json!({ "manifest": manifest, "buildSystemID": "fixture", "request": { "root": ".", "options": {"profiles": ["-dev"]} } - })) + }))) .unwrap(); let args: Vec<&str> = plan["plan"]["arguments"] .as_array() diff --git a/rust/crates/core/src/tests/plugin_run_types.rs b/rust/crates/core/src/tests/plugin_run_types.rs index e20de4a2..b374d4a6 100644 --- a/rust/crates/core/src/tests/plugin_run_types.rs +++ b/rust/crates/core/src/tests/plugin_run_types.rs @@ -60,7 +60,7 @@ fn plan(root: &std::path::Path, manifest: Value, request: Value) -> Value { "manifest": manifest, "buildSystemID": "go", "workspaceRoot": root, - "request": request, + "request": super::support::trusted(request), }), ) } diff --git a/rust/crates/core/src/tests/published_build_plugins.rs b/rust/crates/core/src/tests/published_build_plugins.rs index ccdd6a5f..ffa0d679 100644 --- a/rust/crates/core/src/tests/published_build_plugins.rs +++ b/rust/crates/core/src/tests/published_build_plugins.rs @@ -142,7 +142,7 @@ fn ok(command: Command, manifest: Value, build_system: &str, request: Value) -> let outcome = command(json!({ "manifest": manifest, "buildSystemID": build_system, - "request": request, + "request": super::support::trusted(request), })) .expect("payload is well formed"); assert_eq!(outcome["status"], "ok", "{outcome}"); diff --git a/rust/crates/core/src/tests/support.rs b/rust/crates/core/src/tests/support.rs index efd632a1..14617816 100644 --- a/rust/crates/core/src/tests/support.rs +++ b/rust/crates/core/src/tests/support.rs @@ -7,6 +7,26 @@ use std::sync::{ }; use std::time::{SystemTime, UNIX_EPOCH}; +/// `request` in a workspace the user trusts: build plans that run project code +/// need `projectCodeAllowed`, so tests of other behaviour state it unless they +/// set it themselves. +pub(crate) fn trusted(mut request: Value) -> Value { + if let Value::Object(object) = &mut request { + object + .entry("projectCodeAllowed") + .or_insert(Value::Bool(true)); + } + request +} + +/// A command payload whose `request` is [`trusted`]. +pub(crate) fn trusted_payload(mut payload: Value) -> Value { + if let Some(request) = payload.get_mut("request") { + *request = trusted(request.take()); + } + payload +} + pub(super) fn fixture() -> Value { let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/search/basic.json"); diff --git a/rust/crates/toolchain/src/catalog.rs b/rust/crates/toolchain/src/catalog.rs index 3c9c767b..4c992d47 100644 --- a/rust/crates/toolchain/src/catalog.rs +++ b/rust/crates/toolchain/src/catalog.rs @@ -1,7 +1,9 @@ -//! Machine-wide SDK registrations and defaults, independent of project pins. +//! Machine-wide SDK registrations and defaults, independent of project pins, +//! and the machine-local workspace trust decisions. //! //! Native adapters validate installations, preserve source identity and publish -//! edits atomically. This module owns bounds, path identity and document merges. +//! edits atomically. This module owns bounds, path identity, document merges and +//! the order in which trust decisions apply to a workspace. use super::paths; use lithe_plugin_model::{is_tool_id, PluginRejection, Validation}; @@ -11,7 +13,8 @@ use serde_json::{json, Value}; use std::collections::{BTreeMap, BTreeSet}; const MAX_BYTES: usize = 256 * 1024; -const MAX_TRUSTED_WORKSPACES: usize = 256; +/// Bound of each trust list: trusted and distrusted workspaces, and trusted locations. +const MAX_TRUST_ENTRIES: usize = 256; #[derive(Clone, Default, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -28,6 +31,25 @@ struct Catalog { tools: BTreeMap, #[serde(default, skip_serializing_if = "Vec::is_empty")] trusted_workspaces: Vec, + /// Workspaces the user chose to keep in safe mode. An explicit decision on a + /// workspace wins over a trusted location that contains it. Written only once + /// used, so a catalog without decisions stays readable by older hosts. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + distrusted_workspaces: Vec, + /// Folders whose every workspace, at any depth, is trusted unless distrusted + /// itself. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + trusted_locations: Vec, +} + +/// A workspace's trust: `trusted` allows project code to run, `distrusted` is a +/// recorded choice of safe mode, and `unknown` means the user was not asked yet. +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +enum TrustState { + Trusted, + Distrusted, + Unknown, } #[derive(Deserialize)] @@ -49,12 +71,17 @@ struct Edit { default_home: Option, } -/// Explicit machine-local trust mutation for executing tool environments inside one workspace. +/// Explicit machine-local trust decision on one workspace: `trusted: true` lets +/// its project code run, `trusted: false` records safe mode. `location` also +/// trusts the workspace's parent folder, and is refused with `trusted: false` or +/// when the workspace has no parent to offer. #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct WorkspaceTrustEdit { workspace: String, trusted: bool, + #[serde(default)] + location: bool, } #[derive(Deserialize)] @@ -127,22 +154,29 @@ impl Request { }) } - fn trusted_workspaces(&self, workspaces: &[String]) -> Validation> { + /// Normalizes one trust list, refusing duplicates under the platform's case rules. + fn trust_list(&self, entries: &[String], field: &str) -> Validation> { + Ok(self.trust_keys(entries, field)?.into_values().collect()) + } + + /// One trust list by identity key, so an edit adds or removes a path whatever + /// its spelling. + fn trust_keys(&self, entries: &[String], field: &str) -> Validation> { let case_sensitive = self.case_sensitive()?; - if workspaces.len() > MAX_TRUSTED_WORKSPACES { - return Err(invalid("trustedWorkspaces")); + if entries.len() > MAX_TRUST_ENTRIES { + return Err(invalid(field)); } let mut by_key = BTreeMap::new(); - for workspace in workspaces { - let path = paths::normalize(workspace, &self.platform, true) - .ok_or_else(|| invalid("trustedWorkspaces"))?; + for entry in entries { + let path = + paths::normalize(entry, &self.platform, true).ok_or_else(|| invalid(field))?; let key = paths::normalize(&path, &self.platform, case_sensitive) - .ok_or_else(|| invalid("trustedWorkspaces"))?; + .ok_or_else(|| invalid(field))?; if by_key.insert(key, path).is_some() { - return Err(invalid("trustedWorkspaces")); + return Err(invalid(field)); } } - Ok(by_key.into_values().collect()) + Ok(by_key) } fn read(&self) -> Validation { @@ -158,6 +192,8 @@ impl Request { version: 1, tools: BTreeMap::new(), trusted_workspaces: Vec::new(), + distrusted_workspaces: Vec::new(), + trusted_locations: Vec::new(), } }; if catalog.version != 1 || catalog.tools.len() > 64 { @@ -169,20 +205,61 @@ impl Request { } *entry = self.entry(&entry.homes, &entry.default_home)?; } - catalog.trusted_workspaces = self.trusted_workspaces(&catalog.trusted_workspaces)?; + catalog.trusted_workspaces = + self.trust_list(&catalog.trusted_workspaces, "trustedWorkspaces")?; + catalog.distrusted_workspaces = + self.trust_list(&catalog.distrusted_workspaces, "distrustedWorkspaces")?; + catalog.trusted_locations = + self.trust_list(&catalog.trusted_locations, "trustedLocations")?; Ok(catalog) } - fn workspace_trusted(&self, catalog: &Catalog, workspace: &str) -> Validation { - if workspace.is_empty() { - return Ok(false); - } + /// The trust of `workspace`, as IntelliJ IDEA orders it: an explicit decision on + /// the workspace first, then a trusted location containing it. The matching + /// location is returned with a location-derived trust. + fn workspace_trust( + &self, + catalog: &Catalog, + workspace: &str, + ) -> Validation<(TrustState, Option)> { let case_sensitive = self.case_sensitive()?; let key = paths::normalize(workspace, &self.platform, case_sensitive) .ok_or_else(|| invalid("workspaceRoot"))?; - Ok(catalog.trusted_workspaces.iter().any(|entry| { - paths::normalize(entry, &self.platform, case_sensitive).as_ref() == Some(&key) - })) + let names = |entries: &[String]| { + entries.iter().any(|entry| { + paths::normalize(entry, &self.platform, case_sensitive).as_ref() == Some(&key) + }) + }; + if names(&catalog.trusted_workspaces) { + return Ok((TrustState::Trusted, None)); + } + if names(&catalog.distrusted_workspaces) { + return Ok((TrustState::Distrusted, None)); + } + let location = catalog + .trusted_locations + .iter() + .find(|location| paths::within(workspace, location, &self.platform, case_sensitive)); + Ok(match location { + Some(location) => (TrustState::Trusted, Some(location.clone())), + None => (TrustState::Unknown, None), + }) + } + + /// The folder a trust prompt may offer to trust with `workspace`: its parent, + /// unless the parent is a filesystem root (`/`, a drive or a UNC share), which + /// would trust every project on the volume. + fn offered_location(&self, workspace: &str) -> Option { + let path = paths::normalize(workspace, &self.platform, true)?; + let (parent, _) = path.rsplit_once('/')?; + let root = parent.is_empty() + || (self.platform == "windows" + && (parent.len() == 2 && parent.ends_with(':') + || parent.starts_with("//") && parent[2..].split('/').count() <= 2)); + if root { + return None; + } + paths::normalize(parent, &self.platform, true) } } @@ -190,11 +267,6 @@ impl Request { pub(crate) fn state(input: &Value) -> Validation { let request: Request = serde_json::from_value(input.clone()).map_err(|_| invalid("input"))?; let catalog = request.read()?; - let project_code_allowed = request - .workspace_root - .as_deref() - .map(|root| request.workspace_trusted(&catalog, root)) - .transpose()?; let mut response = json!({ "document": catalog, "storage": { @@ -202,13 +274,25 @@ pub(crate) fn state(input: &Value) -> Validation { "maximumBytes": MAX_BYTES } }); - if let Some(allowed) = project_code_allowed { - response["projectCodeAllowed"] = json!(allowed); + // An absent or empty root asks for the catalog only. + if let Some(root) = request + .workspace_root + .as_deref() + .filter(|root| !root.is_empty()) + { + let (trust, location) = request.workspace_trust(&catalog, root)?; + response["projectCodeAllowed"] = json!(trust == TrustState::Trusted); + response["workspaceTrust"] = json!({ + "state": trust, + "location": location, + "offeredLocation": request.offered_location(root), + }); } Ok(response) } -/// Merges confirmed tool edits and explicit machine-local workspace trust, preserving dormant registrations. +/// Merges confirmed tool edits and one explicit machine-local workspace trust decision, +/// preserving dormant registrations and the other trust decisions. pub(crate) fn edit(input: &Value) -> Validation { let request: EditRequest = serde_json::from_value(input.clone()).map_err(|_| invalid("input"))?; @@ -240,29 +324,49 @@ pub(crate) fn edit(input: &Value) -> Validation { return Err(invalid("tools")); } if let Some(trust) = request.workspace_trust { - let normalized = paths::normalize(&trust.workspace, &source.platform, true) - .ok_or_else(|| invalid("workspaceTrust.workspace"))?; - let key = paths::normalize(&normalized, &source.platform, case_sensitive) + let workspace = [trust.workspace.clone()]; + let (key, normalized) = source + .trust_keys(&workspace, "workspaceTrust.workspace")? + .into_iter() + .next() .ok_or_else(|| invalid("workspaceTrust.workspace"))?; - let mut by_key: BTreeMap = catalog - .trusted_workspaces - .iter() - .filter_map(|entry| { - Some(( - paths::normalize(entry, &source.platform, case_sensitive)?, - entry.clone(), - )) - }) - .collect(); + let mut trusted = source.trust_keys(&catalog.trusted_workspaces, "trustedWorkspaces")?; + let mut distrusted = + source.trust_keys(&catalog.distrusted_workspaces, "distrustedWorkspaces")?; + // A decision replaces the other one, so the two lists never name one workspace. if trust.trusted { - by_key.entry(key).or_insert(normalized); - if by_key.len() > MAX_TRUSTED_WORKSPACES { - return Err(invalid("trustedWorkspaces")); - } + distrusted.remove(&key); + trusted.insert(key, normalized); } else { - by_key.remove(&key); + if trust.location { + return Err(invalid("workspaceTrust.location")); + } + trusted.remove(&key); + distrusted.insert(key, normalized); } - catalog.trusted_workspaces = by_key.into_values().collect(); + if trust.location { + let location = source + .offered_location(&trust.workspace) + .ok_or_else(|| invalid("workspaceTrust.location"))?; + let mut locations = + source.trust_keys(&catalog.trusted_locations, "trustedLocations")?; + let key = paths::normalize(&location, &source.platform, case_sensitive) + .ok_or_else(|| invalid("workspaceTrust.location"))?; + locations.entry(key).or_insert(location); + catalog.trusted_locations = locations.into_values().collect(); + } + if [ + trusted.len(), + distrusted.len(), + catalog.trusted_locations.len(), + ] + .iter() + .any(|len| *len > MAX_TRUST_ENTRIES) + { + return Err(invalid("workspaceTrust")); + } + catalog.trusted_workspaces = trusted.into_values().collect(); + catalog.distrusted_workspaces = distrusted.into_values().collect(); } let changed = catalog != original; let document = if changed { @@ -345,16 +449,6 @@ mod tests { r"C:\Projects\Other", ), ] { - // Revoking trust on an absent document is a no-op and creates no file. - let noop = edit(&json!({ - "document": null, - "platform": platform, - "workspaceTrust": {"workspace": workspace, "trusted": false} - })) - .unwrap(); - assert_eq!(noop["changed"], false, "{platform}"); - assert_eq!(noop["document"], Value::Null, "{platform}"); - // Granting trust normalizes the path and reports projectCodeAllowed only for that root. let trusted = edit(&json!({ "document": null, @@ -417,4 +511,153 @@ mod tests { ); } } + + /// The trust a `state` request reports for `workspace`. + fn trust(document: &Value, platform: &str, workspace: &str) -> Value { + let state = + state(&json!({"document": document, "platform": platform, "workspaceRoot": workspace})) + .unwrap(); + let mut trust = state["workspaceTrust"].clone(); + trust["projectCodeAllowed"] = state["projectCodeAllowed"].clone(); + trust + } + + // A workspace starts undecided, a choice of safe mode is recorded rather than + // forgotten, and trusting it afterwards replaces that choice: the trust prompt asks + // only while the state is unknown. + #[test] + fn a_workspace_moves_between_unknown_distrusted_and_trusted() { + for (platform, workspace, spelling) in [ + ("macos", "/Users/dev/code/app", "/Users/dev/code/app/"), + ("windows", r"C:\Code\App", "c:/code/app"), + ] { + let unknown = trust(&Value::Null, platform, workspace); + assert_eq!(unknown["state"], "unknown", "{platform}"); + assert_eq!(unknown["projectCodeAllowed"], false, "{platform}"); + + let distrusted = edit(&json!({ + "document": null, + "platform": platform, + "workspaceTrust": {"workspace": workspace, "trusted": false} + })) + .unwrap(); + assert_eq!(distrusted["changed"], true, "{platform}"); + let document = distrusted["document"].clone(); + let after = trust(&document, platform, spelling); + assert_eq!(after["state"], "distrusted", "{platform}"); + assert_eq!(after["projectCodeAllowed"], false, "{platform}"); + + let trusted = edit(&json!({ + "document": document, + "platform": platform, + "workspaceTrust": {"workspace": spelling, "trusted": true} + })) + .unwrap(); + assert_eq!( + trusted["catalog"]["distrustedWorkspaces"], + Value::Null, + "{platform}" + ); + assert_eq!( + trusted["catalog"]["trustedWorkspaces"] + .as_array() + .unwrap() + .len(), + 1 + ); + let after = trust(&trusted["document"], platform, workspace); + assert_eq!(after["state"], "trusted", "{platform}"); + assert_eq!(after["location"], Value::Null, "{platform}"); + assert_eq!(after["projectCodeAllowed"], true, "{platform}"); + } + } + + // Trusting a location trusts every workspace beneath it, but not a sibling whose + // name only starts the same, and a workspace distrusted explicitly stays in safe + // mode inside a trusted location, as in IntelliJ IDEA. + #[test] + fn a_trusted_location_covers_its_workspaces_unless_one_is_distrusted() { + for (platform, workspace, nested, sibling, parent) in [ + ( + "macos", + "/Users/dev/code/app", + "/Users/dev/code/libs/util", + "/Users/dev/code-old/app", + "/Users/dev/code", + ), + ( + "windows", + r"C:\Code\App", + r"C:\code\Libs\Util", + r"C:\Code-old\App", + "C:/Code", + ), + ] { + let offered = trust(&Value::Null, platform, workspace); + assert_eq!(offered["offeredLocation"], parent, "{platform}"); + + let trusted = edit(&json!({ + "document": null, + "platform": platform, + "workspaceTrust": {"workspace": workspace, "trusted": true, "location": true} + })) + .unwrap(); + assert_eq!( + trusted["catalog"]["trustedLocations"], + json!([parent]), + "{platform}" + ); + let document = trusted["document"].clone(); + let covered = trust(&document, platform, nested); + assert_eq!(covered["state"], "trusted", "{platform}"); + assert_eq!(covered["location"], parent, "{platform}"); + assert_eq!( + trust(&document, platform, sibling)["state"], + "unknown", + "{platform}" + ); + + let distrusted = edit(&json!({ + "document": document, + "platform": platform, + "workspaceTrust": {"workspace": nested, "trusted": false} + })) + .unwrap(); + let after = trust(&distrusted["document"], platform, nested); + assert_eq!(after["state"], "distrusted", "{platform}"); + assert_eq!(after["projectCodeAllowed"], false, "{platform}"); + } + } + + // Trusting the parent of a workspace at the top of a volume would trust every + // project on it, so no location is offered and an edit asking for one is refused. + #[test] + fn a_filesystem_root_is_never_offered_as_a_location() { + for (platform, workspace) in [ + ("macos", "/app"), + ("windows", r"D:\App"), + ("windows", r"\\server\share\App"), + ] { + assert_eq!( + trust(&Value::Null, platform, workspace)["offeredLocation"], + Value::Null, + "{workspace}" + ); + assert!( + edit(&json!({ + "document": null, + "platform": platform, + "workspaceTrust": {"workspace": workspace, "trusted": true, "location": true} + })) + .is_err(), + "{workspace}" + ); + } + assert!(edit(&json!({ + "document": null, + "platform": "macos", + "workspaceTrust": {"workspace": "/Users/dev/app", "trusted": false, "location": true} + })) + .is_err()); + } } diff --git a/rust/fixtures/toolchain-global-catalog.json b/rust/fixtures/toolchain-global-catalog.json index dce1c746..cd903307 100644 --- a/rust/fixtures/toolchain-global-catalog.json +++ b/rust/fixtures/toolchain-global-catalog.json @@ -111,7 +111,69 @@ "relativePath": "toolchains/global.json", "maximumBytes": 262144 }, - "projectCodeAllowed": true + "projectCodeAllowed": true, + "workspaceTrust": { + "state": "trusted", + "location": null, + "offeredLocation": "c:/projects" + } + } + } + }, + { + "name": "workspace-safe-mode-choice-is-recorded", + "command": "toolchains.editCatalog", + "input": { + "document": "{\"version\":1,\"tools\":{},\"trustedWorkspaces\":[\"/Users/dev/app\"]}", + "platform": "macos", + "workspaceTrust": { + "workspace": "/Users/dev/app", + "trusted": false + } + }, + "expected": { + "status": "ok", + "edit": { + "changed": true, + "document": "{\n \"version\": 1,\n \"tools\": {},\n \"distrustedWorkspaces\": [\n \"/Users/dev/app\"\n ]\n}\n", + "catalog": { + "version": 1, + "tools": {}, + "distrustedWorkspaces": [ + "/Users/dev/app" + ] + } + } + } + }, + { + "name": "workspace-trusted-location-covers-nested-workspaces", + "command": "toolchains.catalogState", + "input": { + "document": "{\"version\":1,\"tools\":{},\"trustedLocations\":[\"/Users/dev/code\"]}", + "platform": "macos", + "workspaceRoot": "/Users/dev/code/libs/util" + }, + "expected": { + "status": "ok", + "state": { + "document": { + "version": 1, + "tools": {}, + "trustedLocations": [ + "/Users/dev/code" + ] + }, + "storage": { + "relativePath": "toolchains/global.json", + "maximumBytes": 262144 + }, + "projectCodeAllowed": true, + "workspaceTrust": { + "state": "trusted", + "location": "/Users/dev/code", + "offeredLocation": "/Users/dev/code/libs" + } } } } diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 492fc644..c62ef542 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -1339,9 +1339,9 @@ dependencies. Own build providers adapt command/runtime launches through their process protocol is unchanged. Language servers, execution providers, and other launch forms name a [tool definition](#tool-references) instead of declaring a candidate list. Any launch form adapted to this resolver must -preserve the package-realpath/executable checks, per-operation consent (there -is no workspace trust state yet), auto-start restrictions, runtime ownership -and cancellation. +preserve the package-realpath/executable checks, the +[workspace trust](#workspace-trust) of the operation, auto-start restrictions, +runtime ownership and cancellation. See [`build-tool-path.plugin.json`](fixtures/build-systems/build-tool-path.plugin.json). @@ -2043,6 +2043,31 @@ list, except under opposite conditions. An option that no list references contributes nothing. Unknown, misplaced, unguarded, or repeated variables are `plugin.template.invalid`. +### Workspace trust + +Loading, building, testing or running a project can run code from it: build +scripts, build-tool extensions and plugins, and the program itself. The user +decides once per workspace, as in IntelliJ IDEA: the host asks when a workspace +opens whose trust is unknown, and the user trusts it (optionally with every +project in its parent folder) or keeps it in safe mode. Core stores the +decision in the machine-local toolchain catalog and reports it as +`projectCodeAllowed`; the host passes that value with every build plan request. + +In a workspace the user has not trusted, Core refuses with +`plugin.build.untrustedWorkspace` every plan that would run project code: + +- every task, test, run configuration, before-launch task, run preparation and + debug preparation, since they run the project; +- a `command` model or dependency source that declares + `executesProjectCode: true`; +- a request to a build provider that declares `executesProjectCode: true`. + +A `command` model or dependency source that declares +`executesProjectCode: false` loads in safe mode, so declare `false` only for a +command that never runs build scripts or other project code. A `static` model +needs no process. In safe mode the host leaves automatic loads undone and asks +the user to trust the workspace before an action the user starts. + ### Model and outputs A model or dependency command prints to `stdout` (default) or to the @@ -3280,9 +3305,10 @@ contexts. `fixtures/backend/backend-workspace.plugin.json` is the example. authority, and the plugin's per-workspace state directory; it reads no file content. - Activation is gated only by the plugin being installed, enabled, and - reviewed. Lithe has no workspace trust state at the moment: an operation - that runs or changes something asks the user per operation, as the host's - own controls do. + reviewed. A build operation that runs project code also needs a trusted + workspace (see [Workspace trust](#workspace-trust)); any other operation that + runs or changes something asks the user per operation, as the host's own + controls do. ## Project generators @@ -4830,6 +4856,7 @@ command payload is a Core `invalid_request` failure instead. | `plugin.build.unavailable` | Core | The plugin declares no such build system, or the build system does not declare the requested operation | | `plugin.build.invalidSelection` | Core | A build request selects a scope, target, filter, or argument the declaration does not allow, or misses a required path | | `plugin.build.invalidOutput` | Core | Build-tool output or a report does not fit its decoder | +| `plugin.build.untrustedWorkspace` | Core | The plan would run project code and the user has not trusted the workspace; see [Workspace trust](#workspace-trust) | | `plugin.build.invalidRunConfiguration` | Core | A saved configuration of a [run configuration type](#run-configuration-types) holds a value the type no longer accepts; `field` is `values.` | | `plugin.build.invalidBeforeLaunchTask` | Core | A step of a [before-launch task](#before-launch-tasks) holds a value the task no longer accepts; `field` is `values.` | | `plugin.build.invalidLocalization` | Core | The `runConfigurationTypes` or `beforeLaunchTasks` part of a [translation file](#translations) does not fit the declarations; the host shows the next candidate or the manifest text | @@ -4988,8 +5015,8 @@ Before the page's scripts run, the host defines `window.lithe`: result or rejects with `{ code, message }`, and `lithe.on(event, listener)`, which returns an unsubscribe function. A page reaches only its own plugin's build systems and the open workspace. Requests that run anything ask for the -same per-operation consent as the host's own controls (Lithe has no workspace -trust state at the moment), and +same consent as the host's own controls, including +[workspace trust](#workspace-trust), and their output appears in the host's Build output window. | Method | Parameters | Result | diff --git a/shared/plugins/contract/v1/fixtures/build-systems/build-plans.json b/shared/plugins/contract/v1/fixtures/build-systems/build-plans.json index e18835c9..59bc2c78 100644 --- a/shared/plugins/contract/v1/fixtures/build-systems/build-plans.json +++ b/shared/plugins/contract/v1/fixtures/build-systems/build-plans.json @@ -84,7 +84,8 @@ "cli", "serde" ] - } + }, + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -122,7 +123,8 @@ "tags": [ "example" ] - } + }, + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -158,7 +160,8 @@ "tags": [ "application" ] - } + }, + "projectCodeAllowed": true }, "expected": { "status": "rejected", @@ -179,7 +182,8 @@ "project": { "path": ".", "name": "app" - } + }, + "projectCodeAllowed": true }, "expected": { "status": "rejected", @@ -200,7 +204,8 @@ "path": ".", "name": "app" }, - "case": "parser::parses_empty" + "case": "parser::parses_empty", + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -238,7 +243,8 @@ "test" ] }, - "case": "runs" + "case": "runs", + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -277,7 +283,8 @@ "tags": [ "application" ] - } + }, + "projectCodeAllowed": true }, "expected": { "status": "rejected", @@ -298,7 +305,8 @@ "path": ".", "name": "app" }, - "suite": "parser" + "suite": "parser", + "projectCodeAllowed": true }, "expected": { "status": "rejected", @@ -526,7 +534,8 @@ "buildSystemID": "go", "operation": "modelPlan", "request": { - "root": "." + "root": ".", + "projectCodeAllowed": false }, "expected": { "status": "ok", @@ -549,6 +558,28 @@ } } }, + { + "name": "a task is refused in an untrusted workspace", + "plugin": "build-command-stdout.plugin.json", + "buildSystemID": "go", + "operation": "taskPlan", + "request": { + "root": "shop", + "task": "build", + "project": { + "path": "shop", + "name": "example.com/shop" + }, + "projectCodeAllowed": false + }, + "expected": { + "status": "rejected", + "error": { + "code": "plugin.build.untrustedWorkspace", + "message": "Go Modules would run project code; the workspace is not trusted." + } + } + }, { "name": "go list output becomes projects, targets, and run entries", "plugin": "build-command-stdout.plugin.json", @@ -673,7 +704,8 @@ "project": { "path": "shop", "name": "example.com/shop" - } + }, + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -748,7 +780,8 @@ "test" ] }, - "case": "TestOrder/refund.full" + "case": "TestOrder/refund.full", + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -947,7 +980,8 @@ "outputFile": "${workspace}/state/model.json", "options": { "offline": true - } + }, + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -981,7 +1015,8 @@ "operation": "modelPlan", "request": { "root": ".", - "pluginDirectory": "${workspace}/plugins/gradle" + "pluginDirectory": "${workspace}/plugins/gradle", + "projectCodeAllowed": true }, "expected": { "status": "rejected", @@ -1009,7 +1044,8 @@ "options": { "offline": true, "buildCache": false - } + }, + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -1035,7 +1071,8 @@ "operation": "taskPlan", "request": { "root": ".", - "task": "build" + "task": "build", + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -1074,7 +1111,8 @@ }, "userArguments": [ "--args=--debug" - ] + ], + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -1105,7 +1143,8 @@ "dependencies", "--configuration", "runtimeClasspath" - ] + ], + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -1135,7 +1174,8 @@ "task": "build", "userArguments": [ "--scan" - ] + ], + "projectCodeAllowed": true }, "expected": { "status": "rejected", @@ -1160,7 +1200,8 @@ } }, "suite": "com.example.OrderTest", - "case": "refunds" + "case": "refunds", + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -1200,7 +1241,8 @@ "taskPrefix": ":app:" } }, - "case": "refunds" + "case": "refunds", + "projectCodeAllowed": true }, "expected": { "status": "rejected", @@ -1220,7 +1262,8 @@ "projects": [ "app", "lib" - ] + ], + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -1254,7 +1297,8 @@ "request": { "root": ".", "pluginDirectory": "${workspace}/plugins/gradle", - "outputFile": "${workspace}/state/deps.json" + "outputFile": "${workspace}/state/deps.json", + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -1324,7 +1368,8 @@ "root": ".", "options": { "offline": true - } + }, + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -1362,7 +1407,8 @@ "project": { "path": "app", "name": "app" - } + }, + "projectCodeAllowed": true }, "expected": { "status": "rejected", @@ -1385,7 +1431,8 @@ "properties": { "taskPrefix": ":app:" } - } + }, + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -1426,7 +1473,8 @@ "refresh": true, "tool": { "executable": "${workspace}/tools/gradle/bin/gradle" - } + }, + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -1468,7 +1516,8 @@ "options": { "offline": true }, - "refresh": false + "refresh": false, + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -1513,7 +1562,8 @@ "refresh": true, "tool": { "executable": "${workspace}/tools/gradle/bin/gradle" - } + }, + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -1557,7 +1607,8 @@ }, "tool": { "executable": "tools/gradle/bin/gradle" - } + }, + "projectCodeAllowed": true }, "expected": { "status": "rejected", @@ -1582,7 +1633,8 @@ "refresh": true, "tool": { "executable": "${workspace}/tools/gradle/bin/gradle" - } + }, + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -1887,7 +1939,8 @@ "buildSystemID": "mix", "operation": "modelPlan", "request": { - "root": "." + "root": ".", + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -1921,7 +1974,8 @@ "project": { "path": "apps/web", "name": "web" - } + }, + "projectCodeAllowed": true }, "expected": { "status": "rejected", @@ -1937,7 +1991,8 @@ "buildSystemID": "mix", "operation": "dependencyPlan", "request": { - "root": "." + "root": ".", + "projectCodeAllowed": true }, "expected": { "status": "ok", @@ -1961,6 +2016,25 @@ "optionFingerprint": "76fb003af18a13133b3836c6d0870963ebe7baab6b4cd6bbd4ec61e30334492f" } } + }, + { + "name": "a model command that runs project code is refused in an untrusted workspace", + "plugin": "build-command-output-file.plugin.json", + "buildSystemID": "gradle", + "operation": "modelPlan", + "request": { + "root": ".", + "pluginDirectory": "${workspace}/plugins/gradle", + "outputFile": "${workspace}/state/model.json", + "projectCodeAllowed": false + }, + "expected": { + "status": "rejected", + "error": { + "code": "plugin.build.untrustedWorkspace", + "message": "Gradle would run project code; the workspace is not trusted." + } + } } ] } diff --git a/shared/plugins/guides/plugin-backend-workspace.md b/shared/plugins/guides/plugin-backend-workspace.md index 20e3181f..d24961a4 100644 --- a/shared/plugins/guides/plugin-backend-workspace.md +++ b/shared/plugins/guides/plugin-backend-workspace.md @@ -64,7 +64,7 @@ - `onWorkspaceOpen` 不会拖慢打开工作区。宿主在窗口显示之后逐个启动这些后端;`initialize` 超时的后端会被停止, 并像其他启动失败一样报告,不会挡住工作区。后端失败或被禁用也不会阻塞工作区。 - 后端在插件被禁用、更新、卸载和宿主退出时结束。 -- 激活只看插件是否已安装、启用、通过审查。Lithe 目前没有工作区信任状态;会运行或修改东西的操作,由宿主逐次询问用户。 +- 激活只看插件是否已安装、启用、通过审查。会运行项目代码的构建操作还要求用户信任这个工作区(见契约的 [Workspace trust](../contract/v1/README.md#workspace-trust));其他会运行或修改东西的操作,由宿主逐次询问用户。 - 后端只服务插件自己:它不回答 `lithe/build/*` 或 VCS 请求。只回答构建请求的后端(不回答 `litheFunctions`)收不到函数请求,函数请求得到 `-32601`。 ### 4. 协商协议 @@ -387,7 +387,7 @@ The manifest only declares. The host reads it to decide whether to install and w - `onWorkspaceOpen` does not slow down opening a workspace. The host starts these backends one by one after the window appears; a backend whose `initialize` times out is stopped and reported like any other start failure, without blocking the workspace. A failed or disabled backend never blocks the workspace either. - The backend ends when the plugin is disabled, updated, or uninstalled, and when the host quits. -- Activation only checks that the plugin is installed, enabled, and approved in review. Lithe has no workspace trust state yet; the host asks the user each time before an operation runs or changes something. +- Activation only checks that the plugin is installed, enabled, and approved in review. A build operation that runs project code also needs the user to trust the workspace (see [Workspace trust](../contract/v1/README.md#workspace-trust) in the contract); the host asks the user each time before any other operation runs or changes something. - A backend serves only its own plugin: it never answers `lithe/build/*` or VCS requests. A build-only backend (one that does not answer `litheFunctions`) receives no function requests, and those get `-32601`. ### 4. Negotiating the protocol diff --git a/shared/plugins/reference/domains/backend.md b/shared/plugins/reference/domains/backend.md index db7c52ae..e8ba8191 100644 --- a/shared/plugins/reference/domains/backend.md +++ b/shared/plugins/reference/domains/backend.md @@ -28,7 +28,7 @@ - 宿主在上面“激活事件”一行的第一个触发点启动后端;插件被停用、更新、卸载,或宿主退出时结束它。同意来自安装审查,不需要按工作区弹确认;审查里它显示为 `packagedBackend`、`systemCommandBackend` 或 `runtimeBackend`。 - `onWorkspaceOpen` 不会拖慢打开工作区。宿主在窗口显示后一次启动一个这样的后端;在初始化时限内没有完成 `initialize` 的后端被停止,按普通的服务器启动失败处理。失败或被停用的后端从不阻塞工作区。 - `workspace.metadata` 权限授予 `workspace` 宿主服务:开放工作区的名称、根目录和 ID、authority 以及插件在该工作区的状态目录;它不读任何文件内容。 -- 激活只取决于插件已安装、已启用且已审查。Lithe 目前没有工作区信任状态:会运行或修改内容的操作,像宿主自己的控件一样按操作询问用户。 +- 激活只取决于插件已安装、已启用且已审查。会运行项目代码的构建操作还要求用户信任这个工作区(见契约的 [Workspace trust](../../contract/v1/README.md#workspace-trust));其他会运行或修改内容的操作,像宿主自己的控件一样按操作询问用户。 - 插件按平台发布一个包,所以包内路径不随 `${arch}` 变化;macOS 的包可以带通用二进制。 ### 协议要点 @@ -248,7 +248,7 @@ A plugin backend is the plugin's own long-lived process. It runs what a web page - The host starts the backend on the first trigger in the "Activation" row above, and ends it when the plugin is disabled, updated, or uninstalled, and when the host quits. Consent is the install review, which lists it as `packagedBackend`, `systemCommandBackend`, or `runtimeBackend`; no per-workspace prompt is needed. - Starting on `onWorkspaceOpen` never delays opening the workspace. The host starts such backends after the window is shown, one at a time; a backend that does not finish `initialize` within its initialize timeout is stopped and reported like any failed server start. A failed or disabled backend never blocks the workspace. - The `workspace.metadata` permission grants the `workspace` host service: the open workspaces' names, root folders and IDs, their authority, and the plugin's per-workspace state directory; it reads no file content. -- Activation is gated only by the plugin being installed, enabled, and reviewed. Lithe has no workspace trust state at the moment: an operation that runs or changes something asks the user per operation, as the host's own controls do. +- Activation is gated only by the plugin being installed, enabled, and reviewed. A build operation that runs project code also needs a trusted workspace (see [Workspace trust](../../contract/v1/README.md#workspace-trust) in the contract); any other operation that runs or changes something asks the user per operation, as the host's own controls do. - A plugin publishes one archive per platform, so its packaged path does not vary by `${arch}`; a macOS archive may carry a universal binary. ### Protocol essentials From 150c857efc3c286798e224a9d04b78d062eba9ce Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Thu, 19 Nov 2026 03:20:59 -0800 Subject: [PATCH 2/3] docs(plugins): record workspace trust in the protocol changelog Co-Authored-By: Claude Opus 5.5 --- shared/plugins/reference/protocol-changelog.md | 1 + 1 file changed, 1 insertion(+) diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 6a39c823..d5addf83 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,6 +14,7 @@ ## 待合入 +- [#118](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/118),[@1lck](https://github.com/1lck),`buildSystems` 0 内的行为补充(—):契约新增 [Workspace trust](../contract/v1/README.md#workspace-trust) 一节,取代“Lithe 没有工作区信任状态”的说法。构建计划请求新增 `projectCodeAllowed`;工作区未受信任时,Core 以新错误码 `plugin.build.untrustedWorkspace` 拒绝所有任务、测试、运行、调试准备,以及声明了 `executesProjectCode: true` 的模型、依赖命令和构建提供者请求。声明 `false` 的模型和依赖命令在安全模式下照常加载。插件清单和后端协议都不变;宿主必须在计划请求里传入信任,否则会运行项目代码的计划都会被拒绝。没有新增版本号、宿主方法、通知或 SDK 版本。见 [1lck/Lithe-IDEA#2201](https://github.com/1lck/Lithe-IDEA/issues/2201)。 - [#112](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/112),[@Mucheen](https://github.com/Mucheen),**`buildSystems` 1**(API-29):清单新增 `buildSystems[].test.discoveryCommand`,已有测试运行可以独立采用命令或 provider。命令使用现有构建工具,把 `litheTestDiscovery` v0 写到宿主提供的 `${outputFile}`。Core 的 `build.testDiscoveryPlan`、`build.decodeTestDiscovery` 和测试树兼容两种发现来源,检查每条选择器可原样运行,命令尝试沿用 `lithe/build/discoverTests` 的结构化终态。没有新增宿主方法、通知或 SDK 版本。见 [1lck/Lithe-IDEA#2122](https://github.com/1lck/Lithe-IDEA/issues/2122)。 ## 按协议查首次出现 From 91ba789d5b431902f7675828c3fbc2dab7612ca6 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Thu, 19 Nov 2026 03:49:03 -0800 Subject: [PATCH 3/3] test(plugins): trust the SDK end-to-end fixture workspaces in plan requests The SDK scenarios plan builds of their own fixture workspaces, which they trust: models, tasks, tests and run preparations of the sample providers run the workspace's code, so Core now refuses them without projectCodeAllowed. Co-Authored-By: Claude Opus 5.5 --- shared/plugins/sdk/e2e/plugin_sdk/mod.rs | 8 ++++++-- shared/plugins/sdk/e2e/plugin_sdk/native_build.rs | 11 ++++++++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/shared/plugins/sdk/e2e/plugin_sdk/mod.rs b/shared/plugins/sdk/e2e/plugin_sdk/mod.rs index 7576a749..d076e246 100644 --- a/shared/plugins/sdk/e2e/plugin_sdk/mod.rs +++ b/shared/plugins/sdk/e2e/plugin_sdk/mod.rs @@ -457,8 +457,12 @@ pub fn run_sample_scenario(sample: &Sample) { let mut session = Session::start(&plugin_id, runtime, &arguments, &workspace); assert_eq!(session.functions(), ["snapshot.read", "workspace.build"]); - // Typed build requests: Core plans them and decodes the answers. - let build = |operation: &str, request: Value| { + // Typed build requests: Core plans them and decodes the answers. The fixture workspace is + // the test's own, so it is trusted: a plan that runs the workspace's code needs that. + let build = |operation: &str, mut request: Value| { + if operation.ends_with("Plan") { + request["projectCodeAllowed"] = json!(true); + } core( operation, json!({ "manifest": manifest, "buildSystemID": BUILD_SYSTEM, "request": request }), diff --git a/shared/plugins/sdk/e2e/plugin_sdk/native_build.rs b/shared/plugins/sdk/e2e/plugin_sdk/native_build.rs index 010bbdb7..143ec600 100644 --- a/shared/plugins/sdk/e2e/plugin_sdk/native_build.rs +++ b/shared/plugins/sdk/e2e/plugin_sdk/native_build.rs @@ -55,7 +55,12 @@ pub fn run(sample: &Sample) { session.functions().is_empty(), "native workflows must not need private functions" ); - let build = |command: &str, request: Value| { + // The fixture workspace is the test's own, so it is trusted: a plan that runs the + // workspace's code is refused without that. + let build = |command: &str, mut request: Value| { + if command.ends_with("Plan") { + request["projectCodeAllowed"] = json!(true); + } core( command, json!({"manifest":manifest,"buildSystemID":BUILD_SYSTEM,"request":request}), @@ -89,7 +94,7 @@ pub fn run(sample: &Sample) { ); let source_plan = core( "build.modelPlan", - json!({"manifest":producer,"buildSystemID":"shared-source","request":{"root":root}}), + json!({"manifest":producer,"buildSystemID":"shared-source","request":{"root":root,"projectCodeAllowed":true}}), ); assert_eq!(source_plan["status"], "ok", "{source_plan}"); let source_reply = source_session.build_request("source-model", &source_plan["plan"]); @@ -120,7 +125,7 @@ pub fn run(sample: &Sample) { let input_plan = core( "build.modelPlan", json!({"manifest":consumer,"buildSystemID":BUILD_SYSTEM, - "request":{"root":root,"modelInputs":snapshot}}), + "request":{"root":root,"modelInputs":snapshot,"projectCodeAllowed":true}}), ); assert_eq!(input_plan["status"], "ok", "{input_plan}"); let input_reply = session.build_request("consumer-model", &input_plan["plan"]);