mirror of
https://github.com/Twigpine/zero.git
synced 2026-11-09 18:08:31 -10:00
* 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]>
205 lines
6.3 KiB
Go
205 lines
6.3 KiB
Go
package cli
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/Gitlawb/zero/internal/agent"
|
|
"github.com/Gitlawb/zero/internal/config"
|
|
"github.com/Gitlawb/zero/internal/sandbox"
|
|
"github.com/Gitlawb/zero/internal/sessions"
|
|
"github.com/Gitlawb/zero/internal/specmode"
|
|
"github.com/Gitlawb/zero/internal/zeroruntime"
|
|
)
|
|
|
|
func TestRunExecUseSpecCreatesDraftSession(t *testing.T) {
|
|
workspaceRoot := t.TempDir()
|
|
store := sessions.NewStore(sessions.StoreOptions{RootDir: t.TempDir(), Now: fixedCLISpecTime})
|
|
provider := &submitSpecExecProvider{}
|
|
var stdout bytes.Buffer
|
|
var stderr bytes.Buffer
|
|
|
|
exitCode := runWithDeps([]string{
|
|
"exec",
|
|
"--cwd", workspaceRoot,
|
|
"--use-spec",
|
|
"--spec-model", "draft-model",
|
|
"--spec-reasoning-effort", "high",
|
|
"-o", "json",
|
|
"plan the review flow",
|
|
}, &stdout, &stderr, appDeps{
|
|
getwd: func() (string, error) {
|
|
return workspaceRoot, nil
|
|
},
|
|
resolveConfig: func(_ string, overrides config.Overrides) (config.ResolvedConfig, error) {
|
|
model := "default-model"
|
|
if overrides.Provider.Model != "" {
|
|
model = overrides.Provider.Model
|
|
}
|
|
return config.ResolvedConfig{
|
|
ActiveProvider: "test",
|
|
Provider: config.ProviderProfile{
|
|
Name: "test",
|
|
ProviderKind: config.ProviderKindOpenAICompatible,
|
|
BaseURL: "http://127.0.0.1/v1",
|
|
Model: model,
|
|
},
|
|
MaxTurns: 3,
|
|
}, nil
|
|
},
|
|
resolveMCPConfig: func(string, bool) (config.MCPConfig, error) {
|
|
return config.MCPConfig{}, nil
|
|
},
|
|
newProvider: func(config.ProviderProfile) (zeroruntime.Provider, error) {
|
|
return provider, nil
|
|
},
|
|
newSessionStore: func() *sessions.Store {
|
|
return store
|
|
},
|
|
newSandboxStore: func() (*sandbox.GrantStore, error) {
|
|
return sandbox.NewGrantStore(sandbox.StoreOptions{FilePath: t.TempDir() + "/grants.json"})
|
|
},
|
|
now: fixedCLISpecTime,
|
|
})
|
|
|
|
if exitCode != exitSuccess {
|
|
t.Fatalf("exit = %d stderr=%s stdout=%s", exitCode, stderr.String(), stdout.String())
|
|
}
|
|
events := decodeJSONLines(t, stdout.String())
|
|
if !slicesContains(jsonEventTypes(events), string(agent.StopReasonSpecReviewRequired)) {
|
|
t.Fatalf("missing spec_review_required event in %v", jsonEventTypes(events))
|
|
}
|
|
items, err := store.List()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(items) != 1 {
|
|
t.Fatalf("session count = %d, want 1: %#v", len(items), items)
|
|
}
|
|
draft := items[0]
|
|
if draft.SessionKind != sessions.SessionKindSpecDraft || draft.SpecStatus != sessions.SpecStatusDraft {
|
|
t.Fatalf("unexpected draft session: %#v", draft)
|
|
}
|
|
if draft.SpecID == "" || !strings.Contains(filepath.ToSlash(draft.SpecFilePath), ".zero/specs/") {
|
|
t.Fatalf("draft spec metadata missing: %#v", draft)
|
|
}
|
|
if draft.SpecDraftModelID != "draft-model" || draft.ModelID != "draft-model" || draft.SpecDraftReasoning != "high" {
|
|
t.Fatalf("draft model metadata = %#v", draft)
|
|
}
|
|
if len(provider.requests) != 1 {
|
|
t.Fatalf("provider request count = %d, want 1", len(provider.requests))
|
|
}
|
|
if !provider.requestIncludesTool(specmode.SubmitToolName) {
|
|
t.Fatalf("provider tools missing submit_spec: %#v", provider.requests[0].Tools)
|
|
}
|
|
}
|
|
|
|
func TestParseExecUseSpecRejectsResume(t *testing.T) {
|
|
_, _, err := parseExecArgs([]string{"--use-spec", "--resume", "zero_1", "plan"})
|
|
if err == nil || !strings.Contains(err.Error(), "cannot be combined") {
|
|
t.Fatalf("expected --use-spec/--resume validation, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestParseExecSpecOverridesRequireUseSpec(t *testing.T) {
|
|
for _, tc := range []struct {
|
|
name string
|
|
args []string
|
|
want string
|
|
}{
|
|
{
|
|
name: "spec model",
|
|
args: []string{"--spec-model", "gpt-5", "plan"},
|
|
want: "--spec-model requires --use-spec",
|
|
},
|
|
{
|
|
name: "spec reasoning effort",
|
|
args: []string{"--spec-reasoning-effort", "high", "plan"},
|
|
want: "--spec-reasoning-effort requires --use-spec",
|
|
},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
_, _, err := parseExecArgs(tc.args)
|
|
if err == nil || !strings.Contains(err.Error(), tc.want) {
|
|
t.Fatalf("expected %q validation, got %v", tc.want, err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestRunExecUseSpecRejectsSpecialistTag(t *testing.T) {
|
|
exitCode, _, stderr := runExecWithEcho(t, []string{"exec", "--use-spec", "--tag", "specialist", "plan"})
|
|
if exitCode != exitUsage {
|
|
t.Fatalf("exit = %d, want %d stderr=%s", exitCode, exitUsage, stderr)
|
|
}
|
|
if !strings.Contains(stderr, "specialist child session") {
|
|
t.Fatalf("expected --use-spec specialist tag validation, got %q", stderr)
|
|
}
|
|
}
|
|
|
|
func TestRunExecUseSpecRejectsFiltersThatHideSubmitSpec(t *testing.T) {
|
|
for _, args := range [][]string{
|
|
{"exec", "--use-spec", "--disabled-tools", specmode.SubmitToolName, "plan"},
|
|
{"exec", "--use-spec", "--enabled-tools", "read_file", "plan"},
|
|
} {
|
|
t.Run(strings.Join(args, " "), func(t *testing.T) {
|
|
exitCode, _, stderr := runExecWithEcho(t, args)
|
|
if exitCode != exitUsage {
|
|
t.Fatalf("exit = %d, want %d stderr=%s", exitCode, exitUsage, stderr)
|
|
}
|
|
if !strings.Contains(stderr, "submit_spec") {
|
|
t.Fatalf("expected submit_spec validation, got %q", stderr)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
type submitSpecExecProvider struct {
|
|
requests []zeroruntime.CompletionRequest
|
|
}
|
|
|
|
func (provider *submitSpecExecProvider) StreamCompletion(ctx context.Context, request zeroruntime.CompletionRequest) (<-chan zeroruntime.StreamEvent, error) {
|
|
provider.requests = append(provider.requests, request)
|
|
arguments, _ := json.Marshal(map[string]string{
|
|
"title": "Review Flow",
|
|
"plan": "# Goal\n\nAdd the review flow.",
|
|
})
|
|
ch := make(chan zeroruntime.StreamEvent, 4)
|
|
select {
|
|
case <-ctx.Done():
|
|
close(ch)
|
|
return ch, ctx.Err()
|
|
case ch <- zeroruntime.StreamEvent{Type: zeroruntime.StreamEventToolCallStart, ToolCallID: "call-1", ToolName: specmode.SubmitToolName}:
|
|
}
|
|
ch <- zeroruntime.StreamEvent{Type: zeroruntime.StreamEventToolCallDelta, ToolCallID: "call-1", ArgumentsFragment: string(arguments)}
|
|
ch <- zeroruntime.StreamEvent{Type: zeroruntime.StreamEventToolCallEnd, ToolCallID: "call-1"}
|
|
ch <- zeroruntime.StreamEvent{Type: zeroruntime.StreamEventDone}
|
|
close(ch)
|
|
return ch, nil
|
|
}
|
|
|
|
func (provider *submitSpecExecProvider) requestIncludesTool(name string) bool {
|
|
if len(provider.requests) == 0 {
|
|
return false
|
|
}
|
|
for _, tool := range provider.requests[0].Tools {
|
|
if tool.Name == name {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func slicesContains(values []string, value string) bool {
|
|
for _, candidate := range values {
|
|
if candidate == value {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|