diff --git a/rust/contracts/application-boundary.md b/rust/contracts/application-boundary.md index 6d873566..da6bdbb5 100644 --- a/rust/contracts/application-boundary.md +++ b/rust/contracts/application-boundary.md @@ -385,6 +385,7 @@ Use stable categories rather than platform error strings: - `git_branch_not_merged` - `git_branch_changed` +- `git_untrusted_workspace`: the workspace is not trusted, so Git did not start - `invalid_request` - `workspace_not_found` - `permission_denied` diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 90b5fbc1..cdbc29a2 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -1156,7 +1156,8 @@ is active; it does not wait behind a mutex outside its cancellation deadline. Git requests may include optional envelope metadata `gitExecution`: `{ executable?: string | null, interactive?: boolean, useCredentialHelper?: boolean, fetchDefaults?: GitFetchOptions, detailedFetch?: boolean, source?: "user" | "background" | "unknown", -consoleQueries?: QueryCategory[], queryCategory?: QueryCategory }`. Defaults are PATH, +consoleQueries?: QueryCategory[], queryCategory?: QueryCategory, projectCodeAllowed?: boolean }`. +Defaults are PATH, noninteractive, helper enabled, normal Fetch defaults, legacy Fetch results, and no recorded query category, which leaves every internal query silent as IDEA does. An executable must be an absolute native path to Git 2.31 or newer. Interactive @@ -1164,6 +1165,19 @@ commands require an event receiver. These values are request-scoped, including nested requests, and never implicitly persist. Both current applications opt into detailed Fetch and supply their application settings snapshot. +`projectCodeAllowed` is the workspace trust that `toolchains.catalogState` reports +(issue 2208). Every Git command reads the repository's own configuration, which can +name programs Git runs: a `core.fsmonitor` hook on each status refresh, hooks, +filters, `diff.external`. With `false`, Core starts no Git process for the request, +locally or on a remote host, and the request fails with `git_untrusted_workspace` +before anything is traced or recorded in a console. It applies to every command, +not only `git.*`: a file request such as `workspace.listDirectories` that would ask +`git check-ignore` still answers, using the native ignore rules. A request that +belongs to no workspace, such as a clone, has no trust state, so the field +defaults to `true`; a host that +tracks workspace trust sends `false` with every request of an untrusted workspace +and offers to trust it, after which the same request runs Git. + `git.fetchPlan` accepts `{ options?: GitFetchOptions, root?: string }`. Options are `{ remote?: string | null, prune?: boolean, submodules?: "inherit" | "no" | "onDemand" | "yes", tags?: "inherit" | "all" | "none" | "prune" }`. It returns @@ -4827,7 +4841,7 @@ Success returns `plan` (`executable`, `arguments`, `workingDirectory`, plus `buildSystemID` (a build provider), `vcsProviderID` (a VCS provider), `backend: true` (the plugin backend), or `debugAdapterID` (a debug adapter). Naming none or more than one is an `invalid_request` failure. The request is `{ pluginDirectory, stateDirectory, -workspaceStateDirectory?, logDirectory?, temporaryDirectory?, architecture, settings?, projectSettings? }`. The directories are absolute host paths used only +workspaceStateDirectory?, logDirectory?, temporaryDirectory?, architecture, settings?, projectSettings?, projectCodeAllowed? }`. The directories are absolute host paths used only as substitution text; the command does not read or create them. `settings` maps setting IDs to the values the user stored for every project, and `projectSettings` to the open project's overrides; a project value counts only @@ -4844,7 +4858,13 @@ and the host reuses its session. An unknown architecture or an empty directory is refused with `plugin.launch.invalidRequest`; a language without a server, an undeclared build system, and a build system without a provider with -`plugin.launch.unavailable`. +`plugin.launch.unavailable`. `projectCodeAllowed` is the workspace trust that +`toolchains.catalogState` reports; absent means untrusted. In an untrusted +workspace a language server that does not declare `executesProjectCode: false` +(`languageServers` 1), a build provider with a process of its own that declares +`executesProjectCode: true`, and every VCS provider are refused with +`plugin.launch.untrustedWorkspace`; a build provider on a shared server follows +that server. A backend plan additionally returns `backend.hostServices`. These are the declared grants; the host must provide only services it actually implements and must verify the @@ -4874,7 +4894,9 @@ step's request and `result` is what the backend function returned, and answers `sessionPolicy` with the answer's `gates`) or `{ status: "rejected", error }`. Refusals are `plugin.launch.unavailable` (no such server), `plugin.launch.notBackend` (the server is not launched by a backend), -`plugin.launch.invalidRequest` (a missing directory), and +`plugin.launch.invalidRequest` (a missing directory), +`plugin.launch.untrustedWorkspace` (the workspace is not trusted, checked again +because trust can be revoked between the steps), and `plugin.launch.invalidResult`, `plugin.launch.outsidePackage`, `plugin.launch.undeclaredTool`, and `plugin.launch.unwritablePath` for the answer. The golden cases are diff --git a/rust/crates/core/src/tests/declarative_plugins.rs b/rust/crates/core/src/tests/declarative_plugins.rs index 308d06cc..5895898f 100644 --- a/rust/crates/core/src/tests/declarative_plugins.rs +++ b/rust/crates/core/src/tests/declarative_plugins.rs @@ -21,6 +21,8 @@ const HELLO_FIXTURE: &str = contract_file!("fixtures/manifest/hello-lithe.plugin const WEB_PANEL_FIXTURE: &str = contract_file!("fixtures/ui/web-panel.plugin.json"); const GO_FIXTURE: &str = contract_file!("fixtures/languages/language-system-command.plugin.json"); const NODE_RUNTIME_FIXTURE: &str = contract_file!("fixtures/languages/node-runtime.plugin.json"); +const UNTRUSTED_SERVER_FIXTURE: &str = + contract_file!("fixtures/languages/language-server-untrusted.plugin.json"); const BUILD_TOOLCHAINS_FIXTURE: &str = contract_file!("fixtures/build-systems/build-toolchains.plugin.json"); const PUBLISHER_BUNDLED_FIXTURE: &str = @@ -85,6 +87,7 @@ fn fixture(name: &str) -> Value { "hello-lithe.plugin.json" => HELLO_FIXTURE, "web-panel.plugin.json" => WEB_PANEL_FIXTURE, "node-runtime.plugin.json" => NODE_RUNTIME_FIXTURE, + "language-server-untrusted.plugin.json" => UNTRUSTED_SERVER_FIXTURE, "build-toolchains.plugin.json" => BUILD_TOOLCHAINS_FIXTURE, "publisher-bundled.plugin.json" => PUBLISHER_BUNDLED_FIXTURE, "build-static-file.plugin.json" => CARGO_BUILD_FIXTURE, @@ -128,6 +131,7 @@ fn contract_fixtures_and_official_plugins_validate() { HELLO_FIXTURE, WEB_PANEL_FIXTURE, NODE_RUNTIME_FIXTURE, + UNTRUSTED_SERVER_FIXTURE, PUBLISHER_BUNDLED_FIXTURE, BACKEND_FIXTURE, WORKSPACE_BACKEND_FIXTURE, @@ -502,6 +506,7 @@ fn language_server_arguments_expand_launch_variables() { "pluginDirectory": "/plugins/php", "stateDirectory": "/state/php", "workspaceStateDirectory": "/state/php/workspace", + "projectCodeAllowed": true, "architecture": "arm64" } })) @@ -661,6 +666,7 @@ fn build_providers_require_their_own_host_capability() { "pluginDirectory": "/plugins/provider", "stateDirectory": "/state/provider", "workspaceStateDirectory": "/state/provider/workspace", + "projectCodeAllowed": true, "architecture": "arm64" } })) @@ -1398,6 +1404,7 @@ fn debug_adapter_inside_the_language_server_has_no_process_of_its_own() { "request": { "pluginDirectory": "/plugins/example", "stateDirectory": "/state/example", + "projectCodeAllowed": true, "architecture": "arm64" }, })) @@ -2425,7 +2432,7 @@ fn launch_log_directory_is_explicit_for_servers_and_backends() { declaration["arguments"] = json!(["--log=${logDir}/native.log"]); let mut payload = selection; payload["manifest"] = manifest; - payload["request"] = json!({"pluginDirectory":"/plugins/example", "stateDirectory":"/state/example", "workspaceStateDirectory":"/state/example/workspace", "architecture":"arm64"}); + payload["request"] = json!({"pluginDirectory":"/plugins/example", "stateDirectory":"/state/example", "workspaceStateDirectory":"/state/example/workspace", "projectCodeAllowed":true, "architecture":"arm64"}); let missing = language_server_launch_plan_command(payload.clone()).unwrap(); assert_eq!( missing["error"]["code"], "plugin.launch.invalidRequest", diff --git a/rust/crates/core/src/tests/git_workspace_trust.rs b/rust/crates/core/src/tests/git_workspace_trust.rs new file mode 100644 index 00000000..2e57a2d9 --- /dev/null +++ b/rust/crates/core/src/tests/git_workspace_trust.rs @@ -0,0 +1,94 @@ +//! Issue 2208: in safe mode Core starts no Git, because a repository's own configuration +//! can name a program Git runs, such as a `core.fsmonitor` hook on every status refresh. +use super::support::temporary_root; +use crate::execute_json; +use serde_json::{json, Value}; +use std::fs; +use std::path::PathBuf; + +/// `trusted` is the request's `gitExecution.projectCodeAllowed`. +fn request(command: &str, payload: Value, trusted: bool) -> Value { + serde_json::from_str(&execute_json( + &json!({ + "timeoutMilliseconds": 10000, + "gitExecution": { "projectCodeAllowed": trusted }, + "command": command, + "payload": payload, + }) + .to_string(), + )) + .unwrap() +} + +struct Repository(PathBuf); + +impl Drop for Repository { + fn drop(&mut self) { + if let Err(error) = fs::remove_dir_all(&self.0) { + eprintln!("Could not clean the workspace trust repository: {error}"); + } + } +} + +#[test] +fn untrusted_workspace_requests_start_no_git() { + let repository = Repository(temporary_root("git-untrusted-workspace")); + let root = &repository.0; + fs::create_dir_all(root.join("ignored")).unwrap(); + fs::write(root.join(".gitignore"), "ignored/\n").unwrap(); + let init = request( + "git.command", + json!({ "root": root, "arguments": ["init", "--template=", "-q", "-b", "main"] }), + true, + ); + assert_eq!(init["ok"], true, "{init}"); + assert_eq!(init["data"]["exitCode"], 0, "{init}"); + + // A hook the repository configures: it leaves a marker whenever Git runs it. + let marker = root.join("hook-ran"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let hook = root.join("fsmonitor-hook"); + fs::write( + &hook, + format!("#!/bin/sh\ntouch '{}'\nexit 1\n", marker.display()), + ) + .unwrap(); + fs::set_permissions(&hook, fs::Permissions::from_mode(0o755)).unwrap(); + let config = root.join(".git/config"); + let mut text = fs::read_to_string(&config).unwrap(); + text.push_str(&format!("[core]\n\tfsmonitor = {}\n", hook.display())); + fs::write(config, text).unwrap(); + } + + for (command, payload) in [ + ("git.status", json!({ "root": root })), + ( + "git.command", + json!({ "root": root, "arguments": ["status"] }), + ), + ("git.historyPage", json!({ "root": root, "limit": 10 })), + ] { + let refused = request(command, payload, false); + assert_eq!(refused["ok"], false, "{command}: {refused}"); + assert_eq!( + refused["error"]["code"], "git_untrusted_workspace", + "{command}: {refused}" + ); + } + // A file request still answers, with the native ignore rules instead of Git's. + let listing = request( + "workspace.listDirectories", + json!({ "root": root, "paths": [""] }), + false, + ); + assert_eq!(listing["ok"], true, "{listing}"); + assert!(!marker.exists(), "an untrusted request ran the hook"); + + // The same status in a trusted workspace runs Git, and with it the hook. + let status = request("git.status", json!({ "root": root }), true); + assert_eq!(status["ok"], true, "{status}"); + #[cfg(unix)] + assert!(marker.exists(), "the fixture's hook never ran: {status}"); +} diff --git a/rust/crates/core/src/tests/mod.rs b/rust/crates/core/src/tests/mod.rs index 279e5976..c1e02407 100644 --- a/rust/crates/core/src/tests/mod.rs +++ b/rust/crates/core/src/tests/mod.rs @@ -36,6 +36,7 @@ mod git_update_plan; mod git_workspace_commit; mod git_workspace_repositories; mod git_workspace_status; +mod git_workspace_trust; mod git_worktree_creation_preview; mod github; mod group_layout; diff --git a/rust/crates/core/src/tests/plugin_run_debug.rs b/rust/crates/core/src/tests/plugin_run_debug.rs index ed7405d2..042e57d3 100644 --- a/rust/crates/core/src/tests/plugin_run_debug.rs +++ b/rust/crates/core/src/tests/plugin_run_debug.rs @@ -544,6 +544,7 @@ fn a_tool_reference_launch_plan_hands_the_host_the_parts_of_the_launch() { "request": { "pluginDirectory": "/plugins/script", "stateDirectory": "/state/script", + "projectCodeAllowed": true, "architecture": "arm64", }, })) diff --git a/rust/crates/core/src/tests/vcs.rs b/rust/crates/core/src/tests/vcs.rs index 6d88030e..24413a9a 100644 --- a/rust/crates/core/src/tests/vcs.rs +++ b/rust/crates/core/src/tests/vcs.rs @@ -158,6 +158,7 @@ fn a_launch_plan_names_the_vcs_provider_it_starts() { "pluginDirectory": "/plugins/svn", "stateDirectory": "/state/svn", "workspaceStateDirectory": "/state/svn/workspace", + "projectCodeAllowed": true, "architecture": "arm64" }); let plan = language_server_launch_plan_command(json!({ @@ -192,6 +193,27 @@ fn a_launch_plan_names_the_vcs_provider_it_starts() { assert!(matches!(both.code, ErrorCode::InvalidRequest), "{both:?}"); } +#[test] +fn a_vcs_provider_has_no_launch_plan_in_an_untrusted_workspace() { + // A VCS client reads the repository's own configuration, which can name + // programs to run, so no provider declaration can opt out of trust. + let plan = language_server_launch_plan_command(json!({ + "manifest": svn_provider(), + "vcsProviderID": "svn", + "request": { + "pluginDirectory": "/plugins/svn", + "stateDirectory": "/state/svn", + "workspaceStateDirectory": "/state/svn/workspace", + "architecture": "arm64" + }, + })) + .unwrap(); + assert_eq!( + plan["error"]["code"], "plugin.launch.untrustedWorkspace", + "{plan}" + ); +} + fn under(path: &Value, root: &Path) -> bool { path.as_str() .is_some_and(|path| Path::new(path).starts_with(root)) diff --git a/rust/crates/git/src/execution_policy.rs b/rust/crates/git/src/execution_policy.rs index 3cf6cb01..be3083e0 100644 --- a/rust/crates/git/src/execution_policy.rs +++ b/rust/crates/git/src/execution_policy.rs @@ -34,6 +34,14 @@ pub struct GitExecutionOptions { /// [`GitExecutionOptions::for_command`]; it is never read from the request. #[serde(skip)] pub command_category: Option, + /// Whether the request's workspace is trusted. Any Git command reads the repository's + /// own configuration, which can name programs Git runs (`core.fsmonitor`, hooks, + /// filters, `diff.external`), so `false` refuses to start Git, locally or on a remote + /// host, with [`ErrorCode::GitUntrustedWorkspace`]. A request outside any workspace, + /// such as a clone, has no trust state, so the field defaults to `true`; a host that + /// tracks workspace trust sends `false` with every request of an untrusted workspace, + /// including file requests whose ignore checks ask Git. + pub project_code_allowed: bool, } impl Default for GitExecutionOptions { fn default() -> Self { @@ -47,6 +55,7 @@ impl Default for GitExecutionOptions { console_queries: Vec::new(), query_category: None, command_category: None, + project_code_allowed: true, } } } @@ -91,6 +100,19 @@ pub(super) fn current() -> GitExecutionOptions { OPTIONS.with(|current| current.borrow().clone()) } +/// Refuses to start Git for a request of an untrusted workspace. Every local Git process +/// is built by `process::git_process` and every remote one by `remote_process::parameters`; +/// both call this first, so no path starts Git in safe mode. +pub(super) fn require_project_code() -> Result<(), CoreError> { + if OPTIONS.with(|current| current.borrow().project_code_allowed) { + return Ok(()); + } + Err(CoreError::new( + ErrorCode::GitUntrustedWorkspace, + "Git does not run in safe mode; trust the workspace to use Git", + )) +} + /// The provenance of the running request's Git processes: the Git policy's, or the request /// envelope's when the policy names none. pub(super) fn source() -> super::console::Source { @@ -295,6 +317,29 @@ mod tests { .is_err()); } + /// An untrusted request builds no Git process; without the field, as for a clone that + /// belongs to no workspace, Git runs. + #[test] + fn untrusted_requests_build_no_git_process() { + let options: GitExecutionOptions = serde_json::from_value(serde_json::json!({})).unwrap(); + assert!(options.project_code_allowed); + assert!(crate::process::git_process().is_ok()); + { + let _scope = Scope::begin(Some( + serde_json::from_value(serde_json::json!({ "projectCodeAllowed": false })).unwrap(), + )) + .unwrap(); + let refused = crate::process::git_process().unwrap_err(); + assert!(matches!(refused.code, ErrorCode::GitUntrustedWorkspace)); + assert!( + crate::ignored_paths(std::path::Path::new("."), &["x".into()]) + .unwrap() + .is_none() + ); + } + assert!(crate::process::git_process().is_ok()); + } + /// The shared cases fix each command's category and which queries a console records. #[test] fn console_queries_follow_the_named_or_command_category() { diff --git a/rust/crates/git/src/history.rs b/rust/crates/git/src/history.rs index 02b51df2..8d4e2ba0 100644 --- a/rust/crates/git/src/history.rs +++ b/rust/crates/git/src/history.rs @@ -781,6 +781,8 @@ impl HistorySession { GIT_COMMIT_DATE_ARGUMENT.to_string(), "--pretty=format:%H%x1f%h%x1f%P%x1f%an%x1f%ae%x1f%ad%x1f%s%x1f%D".to_string(), ]); + // Refused before the trace, as no Git starts in safe mode. + super::execution_policy::require_project_code()?; let trace = super::command_trace::Trace::begin(&root, &arguments, false); let remote = match super::remote_history::RemoteHistory::start(&root, &arguments) { Ok(remote) => remote, @@ -1112,7 +1114,7 @@ fn spawn_history_process( root: &str, arguments: &[String], ) -> Result<(Child, ChildStdout, ChildStderr), CoreError> { - let mut child = git_process() + let mut child = git_process()? .args(arguments) .current_dir(root) .env("GIT_OPTIONAL_LOCKS", "0") diff --git a/rust/crates/git/src/process.rs b/rust/crates/git/src/process.rs index 1c28a334..3b983e19 100644 --- a/rust/crates/git/src/process.rs +++ b/rust/crates/git/src/process.rs @@ -286,6 +286,9 @@ pub(crate) fn capture_git_process( ) -> Result { validate_windows_git_path(Path::new(root)).map_err(git_path_error)?; lithe_protocol::cancellation::check()?; + // Refuse before the trace: in safe mode no Git starts, so there is nothing to record. + // The process builders refuse too, for paths that do not pass through here. + execution_policy::require_project_code()?; let mut trace = command_trace::Trace::begin(root, arguments, visible); let result = match remote_process::capture( root, @@ -320,7 +323,7 @@ fn capture_local_git_process( visible: bool, trace: &mut command_trace::Trace, ) -> Result { - let mut process = git_process(); + let mut process = git_process()?; let version = lithe_git_host::configuration::version(process.get_program(), || { lithe_protocol::cancellation::check().is_err() }); @@ -464,7 +467,10 @@ fn capture_local_git_process( }) } -pub(crate) fn git_process() -> Command { +/// The local Git process of the running request. It is the only builder of one, so it +/// refuses with `git_untrusted_workspace` when the request's workspace is untrusted. +pub(crate) fn git_process() -> Result { + execution_policy::require_project_code()?; let options = execution_policy::current(); let executable = lithe_git_host::configuration::executable(options.executable.as_deref()) .unwrap_or_else(|| options.executable.unwrap_or_else(|| "git".into()).into()); @@ -472,7 +478,7 @@ pub(crate) fn git_process() -> Command { // the user's default terminal whenever status or repository data refreshes. let mut process = Command::new(executable); lithe_platform::process::hide_console_window(&mut process); - process + Ok(process) } pub(crate) fn successful_git_result() -> GitCommandResponse { @@ -562,12 +568,14 @@ pub(crate) fn run_git( // which emits `.git/index` events into the native watcher and can trigger // another status refresh. let root = directory.to_string_lossy(); + // A refusal in safe mode is no Git invocation, so it is neither traced nor reported. + let mut process = git_process()?; let mut trace = command_trace::Trace::begin(&root, &arguments, false); let mut invocation = execution_events::Invocation::reported(false); if let Some(invocation) = &invocation { invocation.started(&root, &arguments); } - let result = git_process() + let result = process .env("GIT_OPTIONAL_LOCKS", "0") .args(&arguments) .current_dir(directory) diff --git a/rust/crates/git/src/remote_process.rs b/rust/crates/git/src/remote_process.rs index ceb6c3eb..15460c2a 100644 --- a/rust/crates/git/src/remote_process.rs +++ b/rust/crates/git/src/remote_process.rs @@ -107,6 +107,8 @@ pub(super) fn capture( } /// Builds host-native argv and environment without exporting client executable paths. +/// Every remote Git process starts from these parameters, so they are refused with +/// `git_untrusted_workspace` when the request's workspace is untrusted. pub(super) fn parameters( host: &workspace::Host, root: &str, @@ -115,6 +117,7 @@ pub(super) fn parameters( disable_optional_locks: bool, environment: &[(String, String)], ) -> Result { + execution_policy::require_project_code()?; let result = workspace_host::request_cancellable( &host.connection.session, methods::ENVIRONMENT_RESOLVE, diff --git a/rust/crates/plugin-manifest/src/declarations.rs b/rust/crates/plugin-manifest/src/declarations.rs index 659e6c19..3aa3e568 100644 --- a/rust/crates/plugin-manifest/src/declarations.rs +++ b/rust/crates/plugin-manifest/src/declarations.rs @@ -80,6 +80,12 @@ impl LanguageDeclaration { } impl LanguageServerDeclaration { + /// Whether starting the server needs a trusted workspace. A server + /// that does not say so is assumed to run project code. + pub(crate) fn executes_project_code(&self) -> bool { + self.executes_project_code.unwrap_or(true) + } + pub(crate) fn validate( &self, field: &str, diff --git a/rust/crates/plugin-manifest/src/launch.rs b/rust/crates/plugin-manifest/src/launch.rs index 78c2e30e..5afe8bcf 100644 --- a/rust/crates/plugin-manifest/src/launch.rs +++ b/rust/crates/plugin-manifest/src/launch.rs @@ -34,9 +34,31 @@ pub struct LanguageServerLaunchPlanRequest { /// The current workspace's overrides of project-scoped settings. #[serde(default)] project_settings: BTreeMap, + /// Whether the user trusts the workspace, from `toolchains.catalogState`. + /// Absent means untrusted: a process that would run project code then + /// has no plan and is refused with [`UNTRUSTED_WORKSPACE`]. + #[serde(default)] + project_code_allowed: bool, } +/// Refusal of a launch whose process would run code or configuration the +/// workspace controls while the user has not trusted the workspace. The +/// host leaves the process stopped and asks again once trust is granted. +pub(crate) const UNTRUSTED_WORKSPACE: &str = "plugin.launch.untrustedWorkspace"; + impl LanguageServerLaunchPlanRequest { + /// Refuses the launch of a process that runs project code, `subject` + /// naming it, unless the workspace is trusted. + pub(crate) fn require_trust(&self, runs_project_code: bool, subject: &str) -> Validation<()> { + if runs_project_code && !self.project_code_allowed { + return Err(PluginRejection::new( + UNTRUSTED_WORKSPACE, + format!("{subject} would run project code; the workspace is not trusted."), + )); + } + Ok(()) + } + fn layers(&self) -> SettingLayers<'_> { SettingLayers { global: &self.settings, @@ -106,6 +128,10 @@ pub(crate) fn language_server_launch_plan( format!("The plugin does not provide a language server for {language_id}."), ) })?; + request.require_trust( + server.executes_project_code(), + &format!("The language server for {language_id}"), + )?; let mut plan = match &server.process.launch { LanguageServerLaunch::Backend { function, @@ -219,6 +245,12 @@ pub fn decode_language_server_launch_command(payload: Value) -> Result = manifest .tool_definitions diff --git a/rust/crates/plugin-manifest/src/manifest.rs b/rust/crates/plugin-manifest/src/manifest.rs index 0918fed7..aa906a18 100644 --- a/rust/crates/plugin-manifest/src/manifest.rs +++ b/rust/crates/plugin-manifest/src/manifest.rs @@ -261,6 +261,11 @@ pub(crate) struct LanguageServerDeclaration { pub(crate) language_identifier: Option, #[serde(flatten)] pub(crate) process: ServerProcess, + /// `languageServers` 1: whether the server runs code or configuration + /// the workspace controls, such as build scripts it imports. Absent + /// means it does, so the server starts only in a trusted workspace. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) executes_project_code: Option, /// Reserved. Core implements no host integration: a language server's /// run, test and debug support comes from the plugin's own backend and /// providers, so any value is refused with `plugin.integration.unsupported` diff --git a/rust/crates/plugin-manifest/src/provider_launch.rs b/rust/crates/plugin-manifest/src/provider_launch.rs index 7b1a82fa..25553456 100644 --- a/rust/crates/plugin-manifest/src/provider_launch.rs +++ b/rust/crates/plugin-manifest/src/provider_launch.rs @@ -7,6 +7,11 @@ use super::*; /// language server gets that server's plan; `buildProvider.languageServer` /// then tells the host to send build requests to the session it already /// keeps for the language instead of starting a second process. +/// +/// A provider process of its own that runs project code has no plan in an +/// untrusted workspace, since every request it would answer is refused +/// there too. A shared server follows the language server's own +/// `executesProjectCode`. pub(crate) fn build_provider_launch_plan( manifest: &DeclarativePluginManifest, build_system_id: &str, @@ -38,6 +43,10 @@ pub(crate) fn build_provider_launch_plan( language_server_launch_plan(manifest, language_id, request)? } lithe_build::ProviderProcess::Own(process) => { + request.require_trust( + provider.executes_project_code(), + &format!("The provider of {build_system_id}"), + )?; server_launch_plan(manifest, process, request)? } }; @@ -48,6 +57,10 @@ pub(crate) fn build_provider_launch_plan( /// The launch plan of a VCS provider. `vcsProvider` repeats what the host /// needs to resolve the client tool and to check the provider's answer in /// `initialize`, which must name the same VCS. +/// +/// A VCS client reads the repository's own configuration, which can name +/// programs to run (hooks, extensions, filters), so a provider has no plan +/// in an untrusted workspace. pub(crate) fn vcs_provider_launch_plan( manifest: &DeclarativePluginManifest, vcs_id: &str, @@ -63,6 +76,7 @@ pub(crate) fn vcs_provider_launch_plan( format!("The plugin declares no VCS provider {vcs_id}."), ) })?; + request.require_trust(true, &format!("The VCS provider {vcs_id}"))?; let mut plan = server_launch_plan(manifest, &provider.process, request)?; plan["vcsProvider"] = provider.descriptor(&manifest.id); Ok(plan) diff --git a/rust/crates/plugin-manifest/src/validation.rs b/rust/crates/plugin-manifest/src/validation.rs index 28914d44..5d43a1be 100644 --- a/rust/crates/plugin-manifest/src/validation.rs +++ b/rust/crates/plugin-manifest/src/validation.rs @@ -113,6 +113,20 @@ impl DeclarativePluginManifest { } } capabilities::check_used(&self.requires, &self.used_capabilities())?; + if self + .language_servers + .iter() + .any(|server| server.executes_project_code.is_some()) + && self + .requires + .get(capabilities::LANGUAGE_SERVERS) + .is_none_or(|version| *version < 1) + { + return Err(invalid( + "requires.languageServers", + "executesProjectCode needs languageServers 1.", + )); + } if self .build_systems .iter() diff --git a/rust/crates/plugin-model/src/capabilities.rs b/rust/crates/plugin-model/src/capabilities.rs index 6b7ebb7d..e2f13787 100644 --- a/rust/crates/plugin-model/src/capabilities.rs +++ b/rust/crates/plugin-model/src/capabilities.rs @@ -47,7 +47,8 @@ pub const LANGUAGES: &str = "languages"; /// `languageServers[]`: the launch, `workspaceConfiguration`, and the session /// fields a plugin backend uses to talk to its own server (`requestMethods`, /// `commands`, `serializedCommands`, `forwardNotifications`, `state`, and -/// `remote`). +/// `remote`). Version 1 adds `executesProjectCode`, which lets a server that +/// runs nothing from the project start in an untrusted workspace. pub const LANGUAGE_SERVERS: &str = "languageServers"; /// `vendor.bundledSignatureRequirement`: origin-scoped host-seal trust for a /// package whose independently installed versions require a publisher signature. @@ -137,7 +138,7 @@ pub const SUPPORTED_CAPABILITIES: &[(&str, &[u32])] = &[ (DEBUG_ADAPTERS, &[0]), (EXECUTION_PROVIDERS, &[0]), (KEYMAP_IMPORT_PROVIDERS, &[0]), - (LANGUAGE_SERVERS, &[0]), + (LANGUAGE_SERVERS, &[0, 1]), (LANGUAGES, &[0]), (MANAGED_RUNTIMES, &[0, 1]), (OUTPUT_LINK_MATCHERS, &[0]), diff --git a/rust/crates/protocol/src/error.rs b/rust/crates/protocol/src/error.rs index 6f751e6f..171706bd 100644 --- a/rust/crates/protocol/src/error.rs +++ b/rust/crates/protocol/src/error.rs @@ -56,6 +56,10 @@ pub enum ErrorCode { /// between angle brackets, without line breaks. Git would otherwise treat the value /// as a pattern that picks an earlier author. GitCommitAuthorInvalid, + /// The request's workspace is not trusted (`gitExecution.projectCodeAllowed: false`), + /// so Git was not started: the repository's configuration can name programs Git + /// runs. Trusting the workspace and repeating the request runs it. + GitUntrustedWorkspace, /// Input or tool output could not be decoded into the stable contract. ParseFailed, /// `file.write` text contains characters the requested encoding cannot diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index a7aacd8c..1122a55f 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -345,6 +345,7 @@ The matcher reads text without starting a process. | `initializationOptions` | A JSON object sent as the LSP `initializationOptions`. Every string value inside it is a launch template. | | `indexingExclusions` | The array in the server's workspace configuration that the host fills with the workspace's excluded directories; see [Indexing exclusions](#indexing-exclusions). | | `hostIntegration` | Reserved. Core implements no host integration, so any ID is refused; see [Language server host integrations](#language-server-host-integrations). | +| `executesProjectCode` | `languageServers` 1. Whether the server runs code or configuration the workspace controls, such as build scripts it imports or project-local plugins it loads. Absent means `true`: the server starts only in a trusted workspace. Declare `false` only for a server that reads the project's files as text and runs nothing from them; see [Workspace trust](#workspace-trust). | | `requestMethods`, `commands`, `serializedCommands`, `forwardNotifications`, `state`, `remote` | What the plugin backend may ask of the running server and how the host keeps its state; see [Plugin-owned sessions](#plugin-owned-sessions). | One enabled plugin serves a language. Enabling a plugin, or confirming the @@ -1195,9 +1196,12 @@ host selects the process with exactly one of `languageID` (a language server), `buildSystemID` (a build provider), `vcsProviderID` (a VCS provider), and `backend: true` (the [plugin backend](#plugin-backend)), passes `{pluginDirectory, stateDirectory, workspaceStateDirectory?, logDirectory?, temporaryDirectory?, architecture, -settings?}`, and receives. `workspaceStateDirectory` may be omitted only when the selected +settings?, projectCodeAllowed?}`, and receives. `workspaceStateDirectory` may be omitted only when the selected process does not use `${workspaceStateDir}`; otherwise the request is `plugin.launch.invalidRequest`. The same error applies when a template uses `${logDir}` but `logDirectory` is absent, empty, or not absolute. +`projectCodeAllowed` is the workspace's trust as Core reports it; absent means +untrusted, and a process that would run project code is then +`plugin.launch.untrustedWorkspace` (see [Workspace trust](#workspace-trust)). | Field | Meaning | | --- | --- | @@ -1222,6 +1226,14 @@ without a provider, an undeclared VCS provider, and a plugin without a backend are `plugin.launch.unavailable`. Core never creates or reads any of these paths. +In a workspace the user has not trusted, a language server, a build provider +with a process of its own, and a VCS provider are +`plugin.launch.untrustedWorkspace` unless the declaration says the process runs +no project code; [Workspace trust](#workspace-trust) lists which. The plugin +backend and a debug adapter with a process of its own are not refused: they +run plugin code, and the requests that would run the project are refused on +their own. + ### Backend-resolved launch A server whose command line depends on what the plugin finds when it starts @@ -2220,6 +2232,26 @@ 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. +Processes that start without a user action follow the same decision. The host +passes `projectCodeAllowed` with every +[launch plan request](#process-start), and in an untrusted workspace Core +refuses with `plugin.launch.untrustedWorkspace`: + +- a language server, unless it declares `executesProjectCode: false` + (`languageServers` 1); a server that imports the build or loads project-local + plugins keeps the default; +- a build provider with a process of its own that declares + `executesProjectCode: true`; a provider that shares a language server + follows that server's declaration; +- every VCS provider, since a VCS client reads the repository's own + configuration, which can name programs to run (hooks, filters, extensions). + +`plugins.languageServers.decodeLaunch` checks the same rule again, so an answer +that arrives after the user revoked trust starts nothing. The host does not +start these processes in safe mode, shows that the project is in safe mode +where they would have appeared, and starts them once the user trusts the +workspace. + ### Model and outputs A model or dependency command prints to `stdout` (default) or to the @@ -5041,6 +5073,7 @@ command payload is a Core `invalid_request` failure instead. | `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`, `beforeLaunchTasks` or `buildOptions` part of a [translation file](#translations) does not fit the declarations; the host shows the next candidate or the manifest text | | `plugin.launch.invalidRequest` | Core | A launch plan request has an unusable directory or an unknown architecture | +| `plugin.launch.untrustedWorkspace` | Core | The process would run project code and the user has not trusted the workspace; see [Workspace trust](#workspace-trust) | | `plugin.launch.notBackend` | Core | `decodeLaunch` named a language server that the plugin backend does not launch | | `plugin.launch.invalidResult` | Core | A [backend-resolved launch](#backend-resolved-launch) answer is malformed, unknown in a field, or over a bound | | `plugin.launch.outsidePackage` | Core | The answer's packaged executable leaves the plugin package | diff --git a/shared/plugins/contract/v1/fixtures/languages/command-plans.json b/shared/plugins/contract/v1/fixtures/languages/command-plans.json index 7cc2dad2..cea8eab2 100644 --- a/shared/plugins/contract/v1/fixtures/languages/command-plans.json +++ b/shared/plugins/contract/v1/fixtures/languages/command-plans.json @@ -202,6 +202,7 @@ "pluginDirectory": "/plugins/node/versions/1.0.0", "stateDirectory": "/state/node", "workspaceStateDirectory": "/state/node/workspaces/abc", + "projectCodeAllowed": true, "architecture": "x86_64" }, "expected": { @@ -243,6 +244,7 @@ "pluginDirectory": "/plugins/node/versions/1.0.0", "stateDirectory": "/state/node", "workspaceStateDirectory": "/state/node/workspaces/abc", + "projectCodeAllowed": true, "architecture": "x86_64", "settings": { "heapMB": 4096, "logLevel": "debug", "telemetry": true } }, @@ -285,6 +287,7 @@ "pluginDirectory": "/plugins/node/versions/1.0.0", "stateDirectory": "/state/node", "workspaceStateDirectory": "/state/node/workspaces/abc", + "projectCodeAllowed": true, "architecture": "x86_64", "settings": { "heapMB": 99999, "logLevel": "verbose", "telemetry": "yes", "unknown": 1 } }, @@ -327,6 +330,7 @@ "pluginDirectory": "/plugins/node/versions/1.0.0", "stateDirectory": "/state/node", "workspaceStateDirectory": "/state/node/workspaces/abc", + "projectCodeAllowed": true, "architecture": "x86_64", "settings": { "heapMB": 1024 } }, @@ -369,6 +373,7 @@ "pluginDirectory": "/plugins/java/versions/1.0.0", "stateDirectory": "/state/java", "workspaceStateDirectory": "/state/java/workspaces/abc", + "projectCodeAllowed": true, "architecture": "arm64" }, "expected": { @@ -402,6 +407,7 @@ "pluginDirectory": "/plugins/java/versions/1.0.0", "stateDirectory": "/state/java", "workspaceStateDirectory": "/state/java/workspaces/abc", + "projectCodeAllowed": true, "architecture": "arm64" }, "expected": { @@ -442,6 +448,7 @@ "pluginDirectory": "/plugins/mix/versions/0.1.0", "stateDirectory": "/state/mix", "workspaceStateDirectory": "/state/mix/workspaces/abc", + "projectCodeAllowed": true, "architecture": "x86_64" }, "expected": { @@ -476,6 +483,7 @@ "pluginDirectory": "/plugins/mix/versions/0.1.0", "stateDirectory": "/state/mix", "workspaceStateDirectory": "/state/mix/workspaces/abc", + "projectCodeAllowed": true, "architecture": "x86_64" }, "expected": { @@ -544,6 +552,7 @@ "pluginDirectory": "/plugins/node/versions/1.0.0", "stateDirectory": "/state/node", "workspaceStateDirectory": "/state/node/workspaces/abc", + "projectCodeAllowed": true, "architecture": "x86_64", "logDirectory": "/logs/sessions/current/plugins/io.example/files" }, @@ -577,6 +586,90 @@ } }, "manifestArguments": ["--stdio", "--log=${logDir}/server.log"] + }, + { + "name": "a language server that runs project code waits until the workspace is trusted", + "plugin": "language-packaged-server.plugin.json", + "languageID": "php", + "operation": "languageServerLaunchPlan", + "request": { + "pluginDirectory": "/plugins/php/versions/1.0.0", + "stateDirectory": "/state/php", + "workspaceStateDirectory": "/state/php/workspaces/abc", + "architecture": "arm64" + }, + "expected": { + "status": "rejected", + "code": "plugin.launch.untrustedWorkspace" + } + }, + { + "name": "a language server that runs nothing from the project starts in an untrusted workspace", + "plugin": "language-server-untrusted.plugin.json", + "languageID": "yaml", + "operation": "languageServerLaunchPlan", + "request": { + "pluginDirectory": "/plugins/yaml/versions/0.1.0", + "stateDirectory": "/state/yaml", + "workspaceStateDirectory": "/state/yaml/workspaces/abc", + "architecture": "arm64" + }, + "expected": { + "status": "ok", + "plan": { + "owner": { "pluginID": "dev.lithe.fixture.language-server-untrusted", "version": "0.1.0" }, + "launch": { "kind": "systemCommand", "commands": ["yaml-language-server"] }, + "arguments": ["--stdio"], + "validationArguments": [], + "runtimeRequirements": [], + "requiredDirectories": [], + "requiredPackagePaths": [], + "sessionPolicy": { + "serverID": "yaml", + "requestMethods": [], + "commands": [], + "serializedCommands": [], + "forwardNotifications": [], + "remote": "supported", + "gates": [] + } + } + } + }, + { + "name": "a build provider on a shared language server follows that server's trust", + "plugin": "build-provider-language-server.plugin.json", + "buildSystemID": "mix", + "operation": "languageServerLaunchPlan", + "request": { + "pluginDirectory": "/plugins/mix/versions/0.1.0", + "stateDirectory": "/state/mix", + "workspaceStateDirectory": "/state/mix/workspaces/abc", + "architecture": "x86_64" + }, + "expected": { + "status": "rejected", + "code": "plugin.launch.untrustedWorkspace" + } + }, + { + "name": "a build provider process that runs project code waits until the workspace is trusted", + "plugin": "build-provider.plugin.json", + "buildSystemID": "gradle", + "operation": "languageServerLaunchPlan", + "request": { + "pluginDirectory": "/plugins/gradle/versions/0.1.0", + "stateDirectory": "/state/gradle", + "workspaceStateDirectory": "/state/gradle/workspaces/abc", + "architecture": "arm64", + "settings": { + "providerHeapMB": 2048 + } + }, + "expected": { + "status": "rejected", + "code": "plugin.launch.untrustedWorkspace" + } } ] } diff --git a/shared/plugins/contract/v1/fixtures/languages/language-server-launch-resolution.json b/shared/plugins/contract/v1/fixtures/languages/language-server-launch-resolution.json index 49d5d17f..4ff9dce1 100644 --- a/shared/plugins/contract/v1/fixtures/languages/language-server-launch-resolution.json +++ b/shared/plugins/contract/v1/fixtures/languages/language-server-launch-resolution.json @@ -9,6 +9,7 @@ "workspaceStateDirectory": "/state/metals/workspaces/abc", "logDirectory": "/logs/metals", "temporaryDirectory": "/tmp/metals", + "projectCodeAllowed": true, "architecture": "arm64" }, "cases": [ @@ -105,6 +106,20 @@ "code": "plugin.launch.invalidRequest" } }, + { + "name": "the first step waits until the workspace is trusted", + "operation": "languageServerLaunchPlan", + "requestEdits": [ + { + "op": "remove", + "path": "/projectCodeAllowed" + } + ], + "expected": { + "status": "rejected", + "code": "plugin.launch.untrustedWorkspace" + } + }, { "name": "a packaged answer becomes a start plan with its gates", "operation": "decodeLaunch", @@ -486,6 +501,27 @@ "status": "rejected", "code": "plugin.launch.invalidRequest" } + }, + { + "name": "decoding refuses an answer once trust is revoked", + "operation": "decodeLaunch", + "requestEdits": [ + { + "op": "set", + "path": "/projectCodeAllowed", + "value": false + } + ], + "result": { + "executable": { + "kind": "packaged", + "path": "server/bin/metals" + } + }, + "expected": { + "status": "rejected", + "code": "plugin.launch.untrustedWorkspace" + } } ] } diff --git a/shared/plugins/contract/v1/fixtures/languages/language-server-untrusted.plugin.json b/shared/plugins/contract/v1/fixtures/languages/language-server-untrusted.plugin.json new file mode 100644 index 00000000..09104ac5 --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/languages/language-server-untrusted.plugin.json @@ -0,0 +1,48 @@ +{ + "schemaVersion": 0, + "id": "dev.lithe.fixture.language-server-untrusted", + "displayName": "Untrusted Workspace Language Server Fixture", + "version": "0.1.0", + "pluginAPIVersion": 0, + "requires": { + "languageServers": 1, + "languages": 0 + }, + "vendor": { + "id": "dev.lithe", + "displayName": "Lithe", + "signatureRequirement": "publisherPackage" + }, + "permissions": [ + "languageServer.launch" + ], + "activationEvents": [ + "onLanguage:yaml" + ], + "languages": [ + { + "id": "yaml", + "displayName": "YAML", + "fileExtensions": [ + "yaml", + "yml" + ] + } + ], + "languageServers": [ + { + "languageID": "yaml", + "launch": { + "kind": "systemCommand", + "commands": [ + "yaml-language-server" + ] + }, + "arguments": [ + "--stdio" + ], + "validationArguments": [], + "executesProjectCode": false + } + ] +} diff --git a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json index 66b0f08b..dbecee8d 100644 --- a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json +++ b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json @@ -699,6 +699,8 @@ "expectedCode": "plugin.api.unsupported" }, {"name": "capability version 3 is not defined", "base": "build-static-file.plugin.json", "edits": [{"op": "set", "path": "/requires/buildSystems", "value": 3}], "expectedCode": "plugin.api.unsupported", "expectedField": "requires.buildSystems"}, + {"name": "languageServers capability version 2 is not defined", "base": "language-packaged-server.plugin.json", "edits": [{"op": "set", "path": "/requires/languageServers", "value": 2}], "expectedCode": "plugin.api.unsupported", "expectedField": "requires.languageServers"}, + {"name": "executesProjectCode needs languageServers 1", "base": "language-packaged-server.plugin.json", "edits": [{"op": "set", "path": "/languageServers/0/executesProjectCode", "value": false}], "expectedCode": "plugin.manifest.invalid", "expectedField": "requires.languageServers"}, { "name": "used capability missing from requires", "base": "build-provider-language-server.plugin.json", diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index a6cff7a2..adaee0ab 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -41,7 +41,7 @@ "commandInstallers": { "description": "Required exactly when commandInstallers is non-empty: installations of bare commands that systemCommand launches name, run by the host only after the user confirms them. Version 1 adds download installers: pinned per-platform archives the host downloads, checks and extracts into the plugin's managed directory.", "enum": [0, 1] }, "debugAdapters": { "description": "Required exactly when debugAdapters is non-empty. Covers bounded target argument and environment bindings and debugAdapters[].features and defaults. The DAP session itself is negotiated by the adapter in initialize.", "enum": [0] }, "executionProviders": { "enum": [0] }, - "languageServers": { "description": "Required exactly when languageServers is non-empty. Covers languageServers[].workspaceConfiguration and the session fields requestMethods, commands, serializedCommands, forwardNotifications, state, and remote.", "enum": [0] }, + "languageServers": { "description": "Required exactly when languageServers is non-empty. Covers languageServers[].workspaceConfiguration and the session fields requestMethods, commands, serializedCommands, forwardNotifications, state, and remote. Version 1 adds languageServers[].executesProjectCode.", "enum": [0, 1] }, "languages": { "description": "Required exactly when languages is non-empty. Covers languages[].grammar, a TextMate grammar, and languages[].configuration.", "enum": [0] }, "managedRuntimes": { "description": "Required exactly when managedRuntimes is present: approved pinned runtime archives, plugin-owned qualification and host-owned installation outside versioned packages. Version 1 adds optional artifact mirror URLs.", "enum": [0, 1] }, "outputLinkMatchers": { "description": "Required exactly when outputLinkMatchers is non-empty.", "enum": [0] }, @@ -1670,6 +1670,7 @@ "properties": { "languageID": { "type": "string" }, "languageIdentifier": { "type": "string", "minLength": 1 }, + "executesProjectCode": { "description": "languageServers 1. Whether the server runs code or configuration the workspace controls. Absent means true: the server starts only in a trusted workspace.", "type": "boolean" }, "workspaceConfiguration": { "description": "What the server reads through workspace/configuration and receives again in workspace/didChangeConfiguration. String leaves may be ${setting:} templates, including settings whose effect is immediate, and no other variable.", "type": "object" diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index 9cd0791c..86cc63ec 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -43,6 +43,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `languages` `0` | `languages[]`:语言 ID、文件扩展名,以及包内 TextMate [`grammar` 与 `configuration`](../contract/v1/README.md#grammars-and-editor-configuration);宿主从包里读取并在编辑器里应用,不启动进程 | ✅ | ✅ | [语言](domains/languages.md) | | `packageTrust` `0` | `vendor.bundledSignatureRequirement`:随宿主发布的发布者签名插件副本按来源信任 | ✅ | 未声明 | [包信任](domains/package-trust.md)、[Trust](../contract/v1/README.md#trust) | | `languageServers` `0` | `languageServers[]`(启动字段按[启动进程](../contract/v1/README.md#process-start)),包括[`workspaceConfiguration`](../contract/v1/README.md#workspace-configuration)、[`indexingExclusions`](../contract/v1/README.md#indexing-exclusions)和[插件自有服务器的会话字段](../contract/v1/README.md#plugin-owned-sessions) | ✅ | ✅¹ | [语言](domains/languages.md)、[Language servers](../contract/v1/README.md#language-servers) | +| `languageServers` `1` | 在 `0` 之上加 `languageServers[].executesProjectCode`:声明 `false` 的服务器可以在未信任的工作区启动;不写时按 `true`,只在信任后启动 | ✅ | 配套宿主接入后声明 | [工作区信任](../contract/v1/README.md#workspace-trust)、[Language servers](../contract/v1/README.md#language-servers) | | `executionProviders` `0` | `executionProviders[]`:用声明的命令运行和发现测试 | ✅ | 未声明 | [语言](domains/languages.md)、[Execution providers](../contract/v1/README.md#execution-providers) | | `settings` `0` | `settings[]`、`settingActions[]` 与 [`settingRegions[]`](../contract/v1/README.md#settings-regions)(设置页上的搜索关键词和插件视图),含[放置位置、作用域、生效方式、页面按钮](../contract/v1/README.md#placement-scope-effect-and-page-buttons) | ✅ | ✅¹ | [插件设置](domains/settings.md)、[Plugin settings](../contract/v1/README.md#plugin-settings) | | `sourceSettings` `0` | 真实配置来源表单、编译器页、私有暂存与显式保存 | ✅ | ✅ | [Source-backed settings editors](../contract/v1/README.md#source-backed-settings-editors) | @@ -160,6 +161,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `languages` `0` | `languages[]`: language IDs, file extensions, and packaged TextMate [`grammar` and `configuration`](../contract/v1/README.md#grammars-and-editor-configuration); the host reads them from the package and applies them in the editor without starting a process | ✅ | ✅ | [Languages](domains/languages.md) | | `packageTrust` `0` | `vendor.bundledSignatureRequirement`: origin-scoped trust for a host-sealed bundled copy of a publisher-signed plugin | ✅ | Not declared | [Package trust](domains/package-trust.md), [Trust](../contract/v1/README.md#trust) | | `languageServers` `0` | `languageServers[]` (launch fields as in [Process start](../contract/v1/README.md#process-start)), including [`workspaceConfiguration`](../contract/v1/README.md#workspace-configuration), [`indexingExclusions`](../contract/v1/README.md#indexing-exclusions) and the [session fields for a plugin's own server](../contract/v1/README.md#plugin-owned-sessions) | ✅ | ✅¹ | [Languages](domains/languages.md), [Language servers](../contract/v1/README.md#language-servers) | +| `languageServers` `1` | Extends `0` with `languageServers[].executesProjectCode`: a server that declares `false` starts in an untrusted workspace; absent means `true`, so it starts only after trust | ✅ | Declared with companion host integration | [Workspace trust](../contract/v1/README.md#workspace-trust), [Language servers](../contract/v1/README.md#language-servers) | | `executionProviders` `0` | `executionProviders[]`: run and discover tests through the declared commands | ✅ | Not declared | [Languages](domains/languages.md), [Execution providers](../contract/v1/README.md#execution-providers) | | `settings` `0` | `settings[]`, `settingActions[]`, and [`settingRegions[]`](../contract/v1/README.md#settings-regions) (search keywords and plugin views on settings pages), with [placement, scope, effect, and page buttons](../contract/v1/README.md#placement-scope-effect-and-page-buttons) | ✅ | ✅¹ | [Plugin settings](domains/settings.md), [Plugin settings](../contract/v1/README.md#plugin-settings) | | `sourceSettings` `0` | Native source forms, compiler pages, private staging and explicit Save | ✅ | ✅ | [Source-backed settings editors](../contract/v1/README.md#source-backed-settings-editors) | diff --git a/shared/plugins/reference/domains/languages.md b/shared/plugins/reference/domains/languages.md index 2a3848e9..c0baac61 100644 --- a/shared/plugins/reference/domains/languages.md +++ b/shared/plugins/reference/domains/languages.md @@ -61,6 +61,7 @@ | `initializationOptions` | 作为 LSP `initializationOptions` 发送的 JSON 对象;其中每个字符串值都是启动模板。 | | `indexingExclusions` | 服务器工作区配置里由宿主填入工作区排除目录的数组,见“索引排除”。 | | `hostIntegration` | 保留字段,见下一节。 | +| `executesProjectCode` | `languageServers` 1。服务器是否会运行工作区控制的代码或配置,例如导入的构建脚本、项目里的插件。不写时按 `true`:只在信任的工作区启动。只有把项目文件当文本读、不运行其中任何内容的服务器才写 `false`;见[工作区信任](../../contract/v1/README.md#workspace-trust)。 | | `requestMethods`、`commands`、`serializedCommands`、`forwardNotifications`、`state`、`remote` | 后端可以向运行中的服务器发什么,以及宿主怎样保存它的状态,见“插件自有会话”。 | 宿主拥有语言服务器进程的生命周期、LSP 会话,以及在提供者被停用时停止进程。 @@ -125,7 +126,7 @@ | 调用 | 宿主建好四个目录,必要时启动插件后端,用 `lithe/function/invoke` 调用 `function`,参数是 `resolveParams`(`serverID`、`platform`、四个目录、`settings`)和工作区 `context`。调用失败、超时,或工作区代次已变,这次启动就不产生进程 | | 应答 | `executable`(`{kind: "packaged", path}` 是包内只读文件;`{kind: "tool", tool}` 是插件自己定义的工具,由宿主按工具解析)、`arguments`、`environment`、`initializationOptions`、`workspaceConfiguration`、`gates`(最多 8 个)、`writablePaths`(最多 32 个,都在四个目录之内);不认识的字段会被拒绝 | | 解码 | 宿主把 `{manifest, languageID, request, result}` 交给 `plugins.languageServers.decodeLaunch`,得到普通的启动计划(`launch` 为 `packaged` 或 `tool`),`sessionPolicy` 另带应答的 `gates` | -| 拒绝码 | `plugin.launch.invalidResult`、`plugin.launch.outsidePackage`、`plugin.launch.undeclaredTool`、`plugin.launch.unwritablePath`、`plugin.launch.invalidRequest`、`plugin.launch.unavailable`、`plugin.launch.notBackend` | +| 拒绝码 | `plugin.launch.invalidResult`、`plugin.launch.outsidePackage`、`plugin.launch.undeclaredTool`、`plugin.launch.unwritablePath`、`plugin.launch.invalidRequest`、`plugin.launch.unavailable`、`plugin.launch.notBackend`、`plugin.launch.untrustedWorkspace`(工作区未信任;用户在两步之间撤销信任时,第二步同样拒绝) | ### 插件自有会话(`languageServers` 的会话字段) @@ -343,6 +344,7 @@ associations take priority. The editor checks a complete first line of up to | `initializationOptions` | A JSON object sent as the LSP `initializationOptions`. Every string value inside it is a launch template. | | `indexingExclusions` | The array in the server's workspace configuration that the host fills with the workspace's excluded directories; see "Indexing exclusions". | | `hostIntegration` | Reserved; see the next section. | +| `executesProjectCode` | `languageServers` 1. Whether the server runs code or configuration the workspace controls, such as build scripts it imports or project-local plugins. Absent means `true`: the server starts only in a trusted workspace. Declare `false` only for a server that reads project files as text and runs nothing from them; see [Workspace trust](../../contract/v1/README.md#workspace-trust). | | `requestMethods`, `commands`, `serializedCommands`, `forwardNotifications`, `state`, `remote` | What the backend may ask of the running server and how the host keeps its state; see "Plugin-owned sessions". | The host owns the language server process lifecycle, the LSP session, and stopping the process when the provider is disabled. @@ -407,7 +409,7 @@ When a server's command line depends on what is known only at start (a version i | Call | The host creates the four directories, starts the plugin backend if needed, and calls `function` through `lithe/function/invoke` with `resolveParams` (`serverID`, `platform`, the four directories, `settings`) and the workspace `context`. A failed or timed-out call, or a changed workspace generation, ends the start without a process | | Answer | `executable` (`{kind: "packaged", path}` is a read-only file in the package; `{kind: "tool", tool}` names a tool definition of the plugin, which the host resolves), `arguments`, `environment`, `initializationOptions`, `workspaceConfiguration`, `gates` (at most 8), and `writablePaths` (at most 32, all inside the four directories). An unknown field is refused | | Decoding | The host passes `{manifest, languageID, request, result}` to `plugins.languageServers.decodeLaunch`, which returns an ordinary launch plan (`launch` is `packaged` or `tool`); its `sessionPolicy` also carries the answer's `gates` | -| Rejections | `plugin.launch.invalidResult`, `plugin.launch.outsidePackage`, `plugin.launch.undeclaredTool`, `plugin.launch.unwritablePath`, `plugin.launch.invalidRequest`, `plugin.launch.unavailable`, `plugin.launch.notBackend` | +| Rejections | `plugin.launch.invalidResult`, `plugin.launch.outsidePackage`, `plugin.launch.undeclaredTool`, `plugin.launch.unwritablePath`, `plugin.launch.invalidRequest`, `plugin.launch.unavailable`, `plugin.launch.notBackend`, `plugin.launch.untrustedWorkspace` (the workspace is not trusted; the second step refuses too when the user revoked trust between the steps) | ### Plugin-owned sessions diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 324908f0..44ff5c5e 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,6 +14,7 @@ ## 待合入 +- [#141](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/141),[@1lck](https://github.com/1lck),**`languageServers` 1**(API-25、API-29、API-31):语言服务器新增可选 `executesProjectCode`(不写按 `true`),启动请求新增 `projectCodeAllowed`(不写按未信任,[1lck/Lithe-IDEA#2208](https://github.com/1lck/Lithe-IDEA/issues/2208))。未信任的工作区里,`plugins.declarative.languageServerLaunchPlan` 和 `plugins.languageServers.decodeLaunch` 只给声明 `executesProjectCode: false` 的语言服务器计划;自带进程的构建提供者按 `buildSystems[].provider.executesProjectCode` 判断,共用语言服务器的跟随该服务器;VCS 提供者一律不给计划。拒绝码是新的 `plugin.launch.untrustedWorkspace`。插件后端和独立调试适配器不受影响。用 `executesProjectCode` 要声明 `requires.languageServers: 1`。没有新增宿主方法、通知或 SDK 版本。 - [#139](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/139),[@1lck](https://github.com/1lck),**`buildSystems` 2**(API-29):构建提供者的 `application` 运行声明(含 `entrypoints: true`)可以通过 `debug.configurationType` 复用已注册的连接调试器。`lithe/build/prepareRun` 复用原有 `launchOptions.debug`,入口运行仍不带 `target`。已有服务运行声明继续适用旧版本。没有新增 RPC 方法、通知或 SDK 版本。 - [#135](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/135),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`toolDefinitions` 0 内的行为修正(API-23):外部安装的 `executableLayouts` 文件链接到另一个文件名时,`toolchains.candidates` 的待探针路径和 `toolchains.resolve` 的 `executable` 改为规范主目录下的布局路径,不再是链接目标。rustup 把 `cargo`、`rust-analyzer` 链接到自身、按启动时的名字决定运行哪个工具,以前 Core 返回 `rustup`,版本探针失败。链接目标的类型、可执行位和越界检查不变;同名链接仍返回规范路径。没有新增字段、版本号、宿主方法、通知或 SDK 版本。 @@ -55,6 +56,7 @@ | `executionProviders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `keymapImportProviders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `languageServers` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | +| `languageServers` | 1 | 待合入 | [#141](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/141) | | `languages` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `outputLinkMatchers` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `packageTrust` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | diff --git a/shared/plugins/sdk/e2e/plugin_sdk/mod.rs b/shared/plugins/sdk/e2e/plugin_sdk/mod.rs index d076e246..ce5e867e 100644 --- a/shared/plugins/sdk/e2e/plugin_sdk/mod.rs +++ b/shared/plugins/sdk/e2e/plugin_sdk/mod.rs @@ -438,6 +438,7 @@ pub fn run_sample_scenario(sample: &Sample) { "pluginDirectory": package, "stateDirectory": fixture.root.join("state"), "workspaceStateDirectory": fixture.root.join("workspace-state"), + "projectCodeAllowed": true, "architecture": if cfg!(target_arch = "aarch64") { "arm64" } else { "x86_64" }, } }), diff --git a/shared/plugins/sdk/e2e/plugin_sdk/native_build.rs b/shared/plugins/sdk/e2e/plugin_sdk/native_build.rs index 143ec600..09dab42a 100644 --- a/shared/plugins/sdk/e2e/plugin_sdk/native_build.rs +++ b/shared/plugins/sdk/e2e/plugin_sdk/native_build.rs @@ -40,6 +40,7 @@ pub fn run(sample: &Sample) { "manifest":manifest,"buildSystemID":BUILD_SYSTEM,"request":{ "pluginDirectory":sample.package,"stateDirectory":fixture.root.join("state"), "workspaceStateDirectory":fixture.root.join("workspace-state"), + "projectCodeAllowed":true, "architecture":if cfg!(target_arch="aarch64") {"arm64"} else {"x86_64"} }}), ); diff --git a/shared/plugins/sdk/e2e/plugin_sdk/vcs.rs b/shared/plugins/sdk/e2e/plugin_sdk/vcs.rs index c57f5348..c7fbfc23 100644 --- a/shared/plugins/sdk/e2e/plugin_sdk/vcs.rs +++ b/shared/plugins/sdk/e2e/plugin_sdk/vcs.rs @@ -166,6 +166,7 @@ pub fn run_vcs_scenario(node: &str) { "pluginDirectory": package, "stateDirectory": fixture.root.join("state"), "workspaceStateDirectory": fixture.root.join("workspace-state"), + "projectCodeAllowed": true, "architecture": if cfg!(target_arch = "aarch64") { "arm64" } else { "x86_64" }, } }),