Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions rust/contracts/application-boundary.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
30 changes: 26 additions & 4 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -1156,14 +1156,28 @@ 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
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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
9 changes: 8 additions & 1 deletion rust/crates/core/src/tests/declarative_plugins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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"
}
}))
Expand Down Expand Up @@ -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"
}
}))
Expand Down Expand Up @@ -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"
},
}))
Expand Down Expand Up @@ -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",
Expand Down
94 changes: 94 additions & 0 deletions rust/crates/core/src/tests/git_workspace_trust.rs
Original file line number Diff line number Diff line change
@@ -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}");
}
1 change: 1 addition & 0 deletions rust/crates/core/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
1 change: 1 addition & 0 deletions rust/crates/core/src/tests/plugin_run_debug.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
},
}))
Expand Down
22 changes: 22 additions & 0 deletions rust/crates/core/src/tests/vcs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!({
Expand Down Expand Up @@ -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))
Expand Down
45 changes: 45 additions & 0 deletions rust/crates/git/src/execution_policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,14 @@ pub struct GitExecutionOptions {
/// [`GitExecutionOptions::for_command`]; it is never read from the request.
#[serde(skip)]
pub command_category: Option<QueryCategory>,
/// 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 {
Expand All @@ -47,6 +55,7 @@ impl Default for GitExecutionOptions {
console_queries: Vec::new(),
query_category: None,
command_category: None,
project_code_allowed: true,
}
}
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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() {
Expand Down
4 changes: 3 additions & 1 deletion rust/crates/git/src/history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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")
Expand Down
Loading
Loading