Files
zero/internal/cli/plugin_activate_test.go
beardthelionandKevin Codex a880ce80a6 feat: gate project-scoped hooks, plugins, and MCP servers behind workspace trust (#529)
* feat(workspacetrust): add exact-match trust store for project config gating

* feat(hooks): add ExcludeProject option to LoadConfig

* feat(plugins): add ExcludeProject option to Load

* feat(cli): gate project hooks and plugins behind workspace trust

Trust check lives inside newHookDispatcherWithExtra and activatePlugins
(fail-closed by construction); trustRoot is the original launch dir so a
--worktree run inherits the source repo's trust. Callers OR the skip
reports and emit one combined stderr notice.

* feat(cli): add zero trust command (trust/list/remove)

* fix(review): key spec-draft trust on the original launch dir; cover trust CLI edge branches

Spec-draft runs (zero exec --use-spec --worktree) passed the reassigned
worktree path as trustRoot, dropping a trusted repo's project hooks
(fail-closed, but breaks worktree-inheritance). Thread the captured
pre-worktree trustRoot into execSpecDraftRun. Add tests for the trust
'remove' too-many-args and --help branches, and a resolveTrust comment
noting the per-chokepoint check must not be hoisted to callers.

* test(cli): end-to-end trust-gate coverage through agent.Run and exec --worktree

Drives the real agent loop with a fake tool-calling provider so a project
beforeTool hook actually fires (or is gated away) through production code:
gate blocks a tool call via agent.Run, and --worktree / --use-spec --worktree
key trust on the original launch dir. All three are load-bearing (RED when the
gate or the trustRoot threading regresses).

* style(cli): gofmt struct alignment in exec_spec.go

* fix(workspacetrust): compare stored trust entries literally, no symlink re-resolution

External adversarial review (codex) found a false positive: IsTrusted
re-normalized stored entries on every check (Abs+EvalSymlinks), so a trusted
path later replaced by a symlink to attacker content re-resolved to the new
target and matched. Stored entries are already canonical (normalized once at
Trust time); compare them as literals and only normalize the incoming query.
Add a regression test for the symlink-retarget case.

* feat(mcp): gate project-scoped MCP servers behind workspace trust

Closes the P0 an external adversarial review (codex) found: project
./.zero/config.json stdio MCP servers spawned before the hook/plugin gate,
an ungated arbitrary-execution path that could also self-trust the workspace.
Add ExcludeProject to config.ResolveMCP (skips the project layer) and thread a
fail-closed trust check into every MCP spawn site (exec, TUI setup+refresh,
mcp tools list, mcp check); reporting sites stay ungated. Verified the sole
server-command exec (mcp/client.go) is reachable only through the now-gated
RegisterTools paths.

* test(cli): cover default-mode beforeTool firing through the trust gate

Assert a project beforeTool hook fires in the default auto and ask permission
modes (not only under unsafe), and is blocked when the workspace is untrusted,
so the gate is verified in the mode a normal run actually uses.

* docs(cli): note MCP servers in zero trust help text and doc comment

The gate covers project hooks, plugins, and MCP servers, but the help string and
runTrust doc comment listed only hooks and plugins.

* test(cli): make workspace-trust tests portable on macOS and Windows

setTrustConfigRoot set HOME on darwin, but config.UserConfigDir is XDG-first
there (=$HOME/.config), so tests wrote trust.json and user hooks.json where the
code never read them; set XDG_CONFIG_HOME on every non-Windows platform instead.

writeMarkerHook shells out to /bin/sh, absent on Windows, so its trusted-case
marker never appeared; skip it there like writeMarkerHookScript already does.

TestRunTrustAddThenList compared `trust list` output (canonicalized via
EvalSymlinks) against the raw cwd, which diverges on the Windows runner's 8.3
short names (RUNNER~1 -> runneradmin); compare the resolved path, and add
TestRunTrustListShowsCanonicalPath to exercise that via a symlink on any platform.

* feat(cli): surface the project MCP skip in the workspace-trust notice

Project MCP servers were dropped silently in an untrusted workspace: the trust
notice covered hooks and plugins but not MCP, and app.go discarded the
resolveTrust error. registerMCPToolsForWorkspace now returns a trustSkip, gated
on a new projectMCPConfigExists check plus the previously-dropped store-read
error, and emitTrustNotice is variadic so the exec, spec-draft, interactive, and
`mcp tools list` paths all fold in the MCP skip.

The skip drives the notice only; the gate stays on resolveTrust/excludeProject,
so a trusted workspace is unaffected and an untrusted one still fails closed.

* fix(cli): print zero trust --help to stdout with a success exit

zero trust -h/--help/help routed usage to stderr with the usage exit code, unlike
every other subcommand (mcp, sandbox, skills, cron, ...) which prints help to
stdout and returns success. Align it; the unknown-subcommand path still writes to
stderr with the usage exit code.

* fix(cli): gate oauth MCP login and surface mcp-check trust notice

Two project-scoped MCP activation sites were left outside the workspace
trust gate.

zero mcp oauth login loaded a project-defined OAuth server from an
untrusted workspace and ran the full discovery/registration/token-exchange
flow against its configured URL. Gate resolveOAuthServer with resolveTrust
so an untrusted clone's ./.zero/config.json OAuth server is dropped before
login, and emit the same one-line trust notice the other spawn sites use.

zero mcp check already gated the project layer but discarded the trust-check
result and never emitted the notice, so a gated project server read as a
bare "not configured". Emit the notice on the not-found branch.

The three remaining ungated resolveMCPConfig(cwd, false) sites (backends
doctor/snapshot and the extensions listing) are enumeration-only and stay
ungated.

* test(cli): adapt MCP startup-skip tests to two-arg resolveMCPConfig

---------

Co-authored-by: Kevin Codex <[email protected]>
2026-07-09 10:51:09 +08:00

224 lines
7.4 KiB
Go

package cli
import (
"bytes"
"context"
"errors"
"os"
"path/filepath"
"testing"
"github.com/Gitlawb/zero/internal/hooks"
"github.com/Gitlawb/zero/internal/plugins"
"github.com/Gitlawb/zero/internal/tools"
)
// fakePluginDeps builds appDeps whose loadPlugins returns the supplied plugins and
// whose skillsDir points at an empty dir, so activatePlugins can be exercised
// without touching the real plugin roots.
func fakePluginDeps(t *testing.T, loaded []plugins.LoadedPlugin) appDeps {
t.Helper()
skillsDir := t.TempDir()
return appDeps{
getwd: func() (string, error) { return t.TempDir(), nil },
loadPlugins: func(plugins.LoadOptions) (plugins.LoadResult, error) {
return plugins.LoadResult{Plugins: loaded}, nil
},
skillsDir: func() string { return skillsDir },
}
}
func TestActivatePluginsRegistersToolAndCollectsHooks(t *testing.T) {
pluginDir := t.TempDir()
loaded := []plugins.LoadedPlugin{{
ID: "zero.demo",
Name: "Demo",
Enabled: true,
Source: plugins.SourceProject,
PluginDir: pluginDir,
Tools: []plugins.ToolExtension{{
Name: "demo_lookup",
Description: "lookup",
Command: "true",
Permission: plugins.PermissionPrompt,
}},
Hooks: []plugins.HookExtension{{
Name: "pre",
Event: plugins.HookBeforeTool,
Command: "guard.sh",
}},
}}
registry := tools.NewRegistry()
var stderr bytes.Buffer
workspace := t.TempDir()
activation := activatePlugins(workspace, registry, fakePluginDeps(t, loaded), &stderr, workspace)
if _, ok := registry.Get("demo_lookup"); !ok {
t.Fatalf("plugin tool not registered into the bootstrap registry")
}
if len(activation.hooks) != 1 || activation.hooks[0].Event != hooks.EventBeforeTool {
t.Fatalf("expected one beforeTool plugin hook, got %#v", activation.hooks)
}
if activation.hooks[0].ID != "zero.demo.pre" {
t.Fatalf("plugin hook id = %q, want namespaced zero.demo.pre", activation.hooks[0].ID)
}
if stderr.Len() != 0 {
t.Fatalf("unexpected stderr for a clean activation: %s", stderr.String())
}
}
func TestActivatePluginsRegistersPluginSkillTool(t *testing.T) {
pluginDir := t.TempDir()
skillDir := filepath.Join(pluginDir, "skills", "demo-skill")
if err := os.MkdirAll(skillDir, 0o755); err != nil {
t.Fatal(err)
}
skillMd := filepath.Join(skillDir, "SKILL.md")
if err := os.WriteFile(skillMd, []byte("---\nname: demo-skill\n---\nplugin skill body"), 0o644); err != nil {
t.Fatal(err)
}
loaded := []plugins.LoadedPlugin{{
ID: "zero.skills",
Name: "Skills",
Enabled: true,
Source: plugins.SourceProject,
PluginDir: pluginDir,
Skills: []plugins.PathExtension{{Name: "demo-skill", Path: skillMd}},
}}
registry := tools.NewRegistry()
registry.Register(tools.NewSkillTool(t.TempDir())) // core skill tool, like the real bootstrap
var stderr bytes.Buffer
workspace := t.TempDir()
activation := activatePlugins(workspace, registry, fakePluginDeps(t, loaded), &stderr, workspace)
if len(activation.skillRoots) != 1 {
t.Fatalf("expected one plugin skill root, got %#v", activation.skillRoots)
}
skillTool, ok := registry.Get("skill")
if !ok {
t.Fatal("skill tool missing after activation")
}
// The re-registered skill tool resolves the plugin skill by name.
res := skillTool.Run(context.Background(), map[string]any{"name": "demo-skill"})
if res.Status != tools.StatusOK {
t.Fatalf("plugin skill not resolvable via the agent skill tool: %q (%s)", res.Status, res.Output)
}
}
func TestActivatePluginsSurfacesLoadDiagnostics(t *testing.T) {
// Load succeeds (no top-level error) but reports a per-plugin diagnostic for a
// plugin it had to skip. activatePlugins must forward that diagnostic to stderr
// rather than dropping it, so a skipped plugin is never silent.
deps := appDeps{
getwd: func() (string, error) { return t.TempDir(), nil },
loadPlugins: func(plugins.LoadOptions) (plugins.LoadResult, error) {
return plugins.LoadResult{
Diagnostics: []plugins.Diagnostic{{
Kind: plugins.DiagnosticSchema,
Message: "schemaVersion: Expected schemaVersion 1.",
}},
}, nil
},
skillsDir: func() string { return t.TempDir() },
}
registry := tools.NewRegistry()
var stderr bytes.Buffer
workspace := t.TempDir()
activatePlugins(workspace, registry, deps, &stderr, workspace)
if stderr.Len() == 0 {
t.Fatal("a load diagnostic must be surfaced on stderr")
}
if !bytes.Contains(stderr.Bytes(), []byte("Expected schemaVersion 1")) {
t.Fatalf("stderr should carry the diagnostic message, got %q", stderr.String())
}
}
func TestActivatePluginsFailsOpenOnLoadError(t *testing.T) {
deps := appDeps{
loadPlugins: func(plugins.LoadOptions) (plugins.LoadResult, error) {
return plugins.LoadResult{}, errors.New("boom")
},
skillsDir: func() string { return t.TempDir() },
}
registry := tools.NewRegistry()
var stderr bytes.Buffer
workspace := t.TempDir()
activation := activatePlugins(workspace, registry, deps, &stderr, workspace)
if len(activation.hooks) != 0 || len(activation.skillRoots) != 0 {
t.Fatalf("a load error must yield an inert activation, got %#v", activation)
}
if stderr.Len() == 0 {
t.Fatalf("a load error should be surfaced as a warning on stderr")
}
}
func TestActivatePluginsWarnsOnMalformedPluginButKeepsGood(t *testing.T) {
good := plugins.LoadedPlugin{
ID: "zero.good",
Name: "Good",
Enabled: true,
Source: plugins.SourceProject,
PluginDir: t.TempDir(),
Tools: []plugins.ToolExtension{{Name: "good_tool", Command: "true", Permission: plugins.PermissionPrompt}},
}
bad := plugins.LoadedPlugin{
ID: "zero.bad",
Name: "Bad",
Enabled: true,
Source: plugins.SourceProject,
PluginDir: t.TempDir(),
Tools: []plugins.ToolExtension{{Name: "bad_tool", Command: "", Permission: plugins.PermissionPrompt}},
}
registry := tools.NewRegistry()
var stderr bytes.Buffer
workspace := t.TempDir()
activatePlugins(workspace, registry, fakePluginDeps(t, []plugins.LoadedPlugin{bad, good}), &stderr, workspace)
if _, ok := registry.Get("good_tool"); !ok {
t.Fatal("the good plugin tool must still register despite a malformed sibling")
}
if _, ok := registry.Get("bad_tool"); ok {
t.Fatal("the malformed plugin tool must not register")
}
if stderr.Len() == 0 {
t.Fatal("a malformed plugin should produce a warning on stderr")
}
}
func TestNewHookDispatcherWithExtraFoldsPluginHooks(t *testing.T) {
// Keep the hook audit store inside a temp dir rather than the user's real data
// directory (the audit path is derived from XDG_DATA_HOME).
t.Setenv("XDG_DATA_HOME", t.TempDir())
workspace := t.TempDir()
extra := []hooks.Definition{{
ID: "zero.demo.pre",
Event: hooks.EventBeforeTool,
Command: "guard.sh",
Enabled: true,
}}
dispatcher, _ := newHookDispatcherWithExtra(workspace, extra, workspace)
if dispatcher == nil {
t.Fatal("dispatcher should never be nil for a clean workspace")
}
// Drive a beforeTool dispatch: the plugin hook runs, proving it is part of the
// active hook set (not merely returned as data).
outcome := dispatcher.Dispatch(context.Background(), hooks.DispatchInput{
Event: hooks.EventBeforeTool,
ToolName: "bash",
})
// With no real guard.sh on PATH the command fails to launch, which for a
// beforeTool hook is advisory (fails OPEN), so the call is recorded as having
// run exactly one hook.
if outcome.Ran != 1 {
t.Fatalf("expected the plugin beforeTool hook to run, Ran=%d", outcome.Ran)
}
}