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
4 changes: 4 additions & 0 deletions desktop/internal/core/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ type gitExecution struct {
// Source is the request's provenance: "background" for an automatic refresh, whose
// queries Core keeps silent unless QueryCategory names them; empty for unknown.
Source string `json:"source,omitempty"`
// ProjectCodeAllowed is false for a request of a workspace the user has not trusted
// (WithProjectCodeAllowed): Core starts no Git process for it and answers
// CodeGitUntrustedWorkspace. Nil keeps Core's default, which allows Git.
ProjectCodeAllowed *bool `json:"projectCodeAllowed,omitempty"`
}

// responseEnvelope is the response the kernel encodes (CoreResponse in the Rust protocol).
Expand Down
12 changes: 12 additions & 0 deletions desktop/internal/core/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package core

import (
"context"
"errors"
"fmt"
)

Expand Down Expand Up @@ -54,6 +55,10 @@ const (
// CodeGitCommitAuthorInvalid means a commit named an author that is not exactly
// "Name <email>"; nothing was committed.
CodeGitCommitAuthorInvalid ErrorCode = "git_commit_author_invalid"
// CodeGitUntrustedWorkspace means the request belongs to a workspace the user has not trusted
// (WithProjectCodeAllowed), so Core started no Git process: the repository's own configuration
// can name programs Git runs, such as core.fsmonitor and hooks.
CodeGitUntrustedWorkspace ErrorCode = "git_untrusted_workspace"
// CodeParseFailed means input or tool output could not be decoded into the stable
// contract. This package also uses it for a response it cannot decode.
CodeParseFailed ErrorCode = "parse_failed"
Expand Down Expand Up @@ -97,6 +102,13 @@ func (e *Error) Is(target error) bool {
return false
}

// IsGitUntrustedWorkspace reports whether err is Core refusing to run Git for a workspace the
// user has not trusted (CodeGitUntrustedWorkspace).
func IsGitUntrustedWorkspace(err error) bool {
var coreErr *Error
return errors.As(err, &coreErr) && coreErr.Code == CodeGitUntrustedWorkspace
}

// newParseError reports a response that violates the envelope contract.
func newParseError(command, message, details string) *Error {
return &Error{Command: command, Code: CodeParseFailed, Message: message, Details: details}
Expand Down
44 changes: 28 additions & 16 deletions desktop/internal/core/gitconsole.go
Original file line number Diff line number Diff line change
Expand Up @@ -822,26 +822,38 @@ func WithQueryCategory(ctx context.Context, category GitQueryCategory) context.C
return context.WithValue(ctx, gitQueryCategoryKey{}, category)
}

// gitExecutionOf is the Git policy of a request: a Git request of a context with a console
// asks Core to report the internal queries of the categories the console records, names the
// category the context gives, and marks an automatic refresh. Other requests, and a request
// with nothing to ask, keep Core's defaults.
type projectCodeAllowedKey struct{}

// WithProjectCodeAllowed returns a context whose requests belong to a workspace whose trust
// allowed reads when each request is sent. While it reports false, every request of the
// context, not only the git ones, tells Core to start no Git process: Core runs Git for other
// commands too, such as the ignore check of workspace.listDirectories, and the repository's
// own configuration can name programs Git runs (core.fsmonitor, hooks, filters).
func WithProjectCodeAllowed(ctx context.Context, allowed func() bool) context.Context {
return context.WithValue(ctx, projectCodeAllowedKey{}, allowed)
}

// gitExecutionOf is the Git policy of a request. A request of an untrusted workspace
// (WithProjectCodeAllowed) forbids Git, whatever its command. A Git request of a context with
// a console also asks Core to report the internal queries of the categories the console
// records, names the category the context gives, and marks an automatic refresh. A request
// with nothing to ask keeps Core's defaults.
func gitExecutionOf(ctx context.Context, command string) *gitExecution {
if !strings.HasPrefix(command, "git.") || gitConsoleUnrecorded[command] {
return nil
var execution gitExecution
if allowed, _ := ctx.Value(projectCodeAllowedKey{}).(func() bool); allowed != nil && !allowed() {
execution.ProjectCodeAllowed = new(false)
}
sink, _ := ctx.Value(gitConsoleKey{}).(*gitConsoleSink)
if sink == nil {
return nil
}
execution := gitExecution{ConsoleQueries: sink.console.recordedQueries()}
if len(execution.ConsoleQueries) > 0 {
execution.QueryCategory, _ = ctx.Value(gitQueryCategoryKey{}).(GitQueryCategory)
}
if refresh, _ := ctx.Value(gitRefreshKey{}).(bool); refresh {
execution.Source = "background"
if sink != nil && strings.HasPrefix(command, "git.") && !gitConsoleUnrecorded[command] {
execution.ConsoleQueries = sink.console.recordedQueries()
if len(execution.ConsoleQueries) > 0 {
execution.QueryCategory, _ = ctx.Value(gitQueryCategoryKey{}).(GitQueryCategory)
}
if refresh, _ := ctx.Value(gitRefreshKey{}).(bool); refresh {
execution.Source = "background"
}
}
if len(execution.ConsoleQueries) == 0 && execution.Source == "" {
if len(execution.ConsoleQueries) == 0 && execution.Source == "" && execution.ProjectCodeAllowed == nil {
return nil
}
return &execution
Expand Down
40 changes: 39 additions & 1 deletion desktop/internal/core/gitconsole_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"path/filepath"
"slices"
"strings"
"sync/atomic"
"testing"
"time"

Expand Down Expand Up @@ -329,6 +330,33 @@ func TestGitConsoleRecordsNothingForADetachedContext(t *testing.T) {
}
}

// A request of an untrusted workspace starts no Git process: Core answers
// CodeGitUntrustedWorkspace, the console keeps only the refusal (a record with no command), and
// the same context runs Git once the workspace is trusted (#2208).
func TestGitRequestOfAnUntrustedWorkspaceRunsNoGit(t *testing.T) {
repo := committedRepository(t)
client := NewClient()
console := NewGitConsole(nil)
console.RecordQueries([]GitQueryCategory{GitQueryReferences, GitQueryChecks})
var trusted atomic.Bool
ctx := WithProjectCodeAllowed(WithGitConsole(testContext(t), console, repo), trusted.Load)
if _, err := client.GitStatus(ctx, repo); !IsGitUntrustedWorkspace(err) {
t.Fatalf("GitStatus(untrusted) error = %v, want %s", err, CodeGitUntrustedWorkspace)
}
for _, record := range console.Snapshot().Records {
if record.Executable != "" || len(record.Arguments) != 0 || record.Error == "" {
t.Fatalf("an untrusted request recorded a command: %+v", record)
}
}
trusted.Store(true)
if _, err := client.GitStatus(ctx, repo); err != nil {
t.Fatalf("GitStatus(trusted) error: %v", err)
}
if commands := consoleCommands(console); !slices.Contains(commands, "status") {
t.Fatalf("console commands = %q, want the trusted status query", commands)
}
}

// consoleCommands are the Git subcommands of the console's records, in order.
func consoleCommands(console *GitConsole) []string {
var commands []string
Expand Down Expand Up @@ -399,12 +427,15 @@ func TestGitConsoleRecordsTheQueriesOfTheCategoriesItShows(t *testing.T) {

// Only a Git request with a console asks Core to report queries, of the categories the
// console records and under the category the context names; an automatic refresh names its
// provenance.
// provenance. Every request of an untrusted workspace forbids Git, whatever its command, since
// Core also runs Git for requests that are not Git's (#2208); the decision is read per request.
func TestGitExecutionOfAsksForTheCategoriesTheConsoleShows(t *testing.T) {
idea := WithGitConsole(context.Background(), NewGitConsole(nil), "/repo")
shown := NewGitConsole(nil)
shown.RecordQueries(GitConsolePreferences{ShowDiffQueries: true, ShowCheckQueries: true}.QueryCategories())
ctx := WithGitConsole(context.Background(), shown, "/repo")
var trusted atomic.Bool
gated := WithProjectCodeAllowed(ctx, trusted.Load)
cases := []struct {
name string
ctx context.Context
Expand All @@ -421,13 +452,20 @@ func TestGitExecutionOfAsksForTheCategoriesTheConsoleShows(t *testing.T) {
{"detached", WithGitConsole(ctx, nil, ""), "git.status", `null`},
{"never runs Git", ctx, "git.consolePresentation", `null`},
{"not Git", ctx, "core.ping", `null`},
{"untrusted", gated, "git.status", `{"consoleQueries":["diff","checks"],"projectCodeAllowed":false}`},
{"untrusted without console", WithProjectCodeAllowed(context.Background(), trusted.Load), "workspace.listDirectories", `{"projectCodeAllowed":false}`},
{"untrusted never runs Git", gated, "git.consolePresentation", `{"projectCodeAllowed":false}`},
}
for _, c := range cases {
got, err := json.Marshal(gitExecutionOf(c.ctx, c.command))
if err != nil || string(got) != c.want {
t.Fatalf("%s: gitExecution = %s (%v), want %s", c.name, got, err, c.want)
}
}
trusted.Store(true)
if got, err := json.Marshal(gitExecutionOf(gated, "core.ping")); err != nil || string(got) != `null` {
t.Fatalf("trusted: gitExecution = %s (%v), want null, Core's default", got, err)
}
}

// Every preference starts as IDEA's console, and each one turns on the category or display
Expand Down
19 changes: 19 additions & 0 deletions desktop/internal/core/plugin_session.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package core
import (
"context"
"encoding/json"
"errors"
"runtime"
)

Expand Down Expand Up @@ -150,6 +151,24 @@ type PluginBackendDirectories struct {
Architecture string `json:"architecture"`
Settings map[string]json.RawMessage `json:"settings,omitempty"`
ProjectSettings map[string]json.RawMessage `json:"projectSettings,omitempty"`
// ProjectCodeAllowed is whether the user trusts the workspace. Core plans no language
// server, build provider process or VCS provider that would run project code without it,
// and refuses them with LaunchUntrustedWorkspace. A plugin backend and a debug adapter of
// its own process are not refused; an adapter hosted in a language server is that
// server's launch, refused as the server is.
ProjectCodeAllowed bool `json:"projectCodeAllowed,omitempty"`
}

// LaunchUntrustedWorkspace is the code Core refuses a launch plan with when the process
// would run project code and the workspace is not trusted. The host leaves the process
// stopped and starts it once the user trusts the workspace.
const LaunchUntrustedWorkspace = "plugin.launch.untrustedWorkspace"

// IsLaunchUntrustedWorkspace reports whether err is Core's refusal of a launch for want of
// workspace trust.
func IsLaunchUntrustedWorkspace(err error) bool {
var rejection *MarketplaceRejection
return errors.As(err, &rejection) && rejection.Code == LaunchUntrustedWorkspace
}

// PluginArchitecture is this host's CPU in the plugin contract's names, which
Expand Down
2 changes: 1 addition & 1 deletion desktop/internal/core/plugin_session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -444,7 +444,7 @@ func TestRuntimeToolPlanKeepsAnEntryForNativeInstantiation(t *testing.T) {
t.Fatal(err)
}
root := t.TempDir()
plan, err := NewClient().PlanPluginLanguageServer(testContext(t), manifest, "script", PluginBackendDirectories{PluginDirectory: root, StateDirectory: t.TempDir(), Architecture: PluginArchitecture()})
plan, err := NewClient().PlanPluginLanguageServer(testContext(t), manifest, "script", PluginBackendDirectories{PluginDirectory: root, StateDirectory: t.TempDir(), Architecture: PluginArchitecture(), ProjectCodeAllowed: true})
if err != nil {
t.Fatal(err)
}
Expand Down
12 changes: 12 additions & 0 deletions desktop/internal/i18n/shared.generated.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions desktop/internal/pluginbackend/pluginbackend.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,10 @@ type StartRequest struct {
Settings map[string]json.RawMessage
// ProjectSettings is the separately captured project override layer.
ProjectSettings map[string]json.RawMessage
// ProjectCodeAllowed is whether the user trusts the workspace. Without it Core plans no
// language server, build provider process or VCS provider that would run project code
// (core.LaunchUntrustedWorkspace).
ProjectCodeAllowed bool
// Environment is added to the provider process environment. It is for host
// integration tests and host-owned facts, never plugin-controlled secrets.
Environment map[string]string
Expand Down Expand Up @@ -310,6 +314,7 @@ func (r *Runner) Start(ctx context.Context, request StartRequest) (Session, erro
Architecture: request.Architecture,
Settings: request.Settings,
ProjectSettings: request.ProjectSettings,
ProjectCodeAllowed: request.ProjectCodeAllowed,
}
var plan core.PluginBackendPlan
var err error
Expand Down
4 changes: 4 additions & 0 deletions desktop/internal/pluginhost/pluginhost.go
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,10 @@ func Declared() Capabilities {
// Version 1 adds installers that download a pinned archive instead of running
// a tool; the host extracts it below the plugin's managed command directory.
declared["commandInstallers"] = []int{0, 1}
// Version 1 adds a server's executesProjectCode: in a project in safe mode Core
// starts only the servers that declare false, and the status bar says why the
// others wait for trust (#2208).
declared["languageServers"] = []int{0, 1}
return declared
}

Expand Down
4 changes: 4 additions & 0 deletions desktop/internal/pluginhost/pluginhost_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ func TestDeclaredServesTheBaselineOfEveryWiredCapability(t *testing.T) {
if name == "commandInstallers" {
wanted = []int{0, 1}
}
// Safe mode starts the servers that declare the executesProjectCode version 1 adds as false.
if name == "languageServers" {
wanted = []int{0, 1}
}
if versions := declared[name]; !slices.Equal(versions, wanted) {
t.Fatalf("%s = %v, want %v", name, versions, wanted)
}
Expand Down
1 change: 1 addition & 0 deletions desktop/internal/pluginservice/backendlaunch.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ func (s *Service) resolveBackendLaunch(ctx context.Context, pluginID, version st
Architecture: start.Architecture,
Settings: start.Settings,
ProjectSettings: start.ProjectSettings,
ProjectCodeAllowed: start.ProjectCodeAllowed,
}
plan, err := s.kernel.PlanPluginLanguageServer(ctx, manifest, languageID, request)
if err != nil {
Expand Down
Loading
Loading