From 1ad75f7cc4adc001b83df974422a487f26a3bd2c Mon Sep 17 00:00:00 2001 From: EddieMurphy <142191175+EddieMurphy89@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:00:55 +0800 Subject: [PATCH] fix(hooks): reject dangling junctions and merge current main --- internal/cli/backends.go | 61 +++++++- internal/cli/backends_test.go | 88 +++++++++++ internal/cli/extensions.go | 19 ++- internal/cli/hook_dispatch.go | 28 ++-- internal/cli/hook_dispatch_test.go | 79 ++++++++++ internal/hooks/dispatch.go | 62 +++++--- internal/hooks/dispatch_test.go | 54 +++++++ internal/hooks/hooks.go | 48 ++++++ internal/hooks/hooks_test.go | 140 +++++++++++++++++- internal/hooks/hooks_windows_test.go | 41 +++++ internal/zerocommands/backend_snapshots.go | 45 +++++- .../zerocommands/backend_snapshots_test.go | 27 ++++ 12 files changed, 647 insertions(+), 45 deletions(-) create mode 100644 internal/cli/hook_dispatch_test.go create mode 100644 internal/hooks/hooks_windows_test.go diff --git a/internal/cli/backends.go b/internal/cli/backends.go index df17a50c29..07859cd56c 100644 --- a/internal/cli/backends.go +++ b/internal/cli/backends.go @@ -1,6 +1,7 @@ package cli import ( + "errors" "fmt" "io" "strings" @@ -137,15 +138,26 @@ func backendLifecycleSnapshot(deps appDeps) (zerocommands.BackendLifecycleSnapsh } hookResult, err := deps.loadHooks(hooks.LoadOptions{Cwd: cwd}) + hooksIncomplete := false if err != nil { - return zerocommands.BackendLifecycleSnapshot{}, err + if !errors.Is(err, hooks.ErrInvalidConfig) { + return zerocommands.BackendLifecycleSnapshot{}, err + } + // Keep the available layers and mark the snapshot as partial rather than + // hiding every configured backend behind one broken hooks.json. + hooksIncomplete = true } pluginResult, err := deps.loadPlugins(plugins.LoadOptions{Cwd: cwd}) if err != nil { return zerocommands.BackendLifecycleSnapshot{}, err } - return zerocommands.NewBackendLifecycleSnapshot(servers, hookResult.Config.Hooks, pluginResult.Plugins), nil + snapshot := zerocommands.NewBackendLifecycleSnapshot(servers, hookResult.Config.Hooks, pluginResult.Plugins) + snapshot.HooksIncomplete = hooksIncomplete + if hooksIncomplete { + snapshot.HooksDiagnostics = zerocommands.HookDiagnosticSnapshots(hookResult.Diagnostics) + } + return snapshot, nil } func backendDoctorReport(deps appDeps) (zerocommands.BackendDoctorReport, error) { @@ -161,7 +173,7 @@ func backendDoctorReport(deps appDeps) (zerocommands.BackendDoctorReport, error) return zerocommands.BackendDoctorReport{}, err } hookResult, err := deps.loadHooks(hooks.LoadOptions{Cwd: cwd}) - if err != nil { + if err != nil && !errors.Is(err, hooks.ErrInvalidConfig) { return zerocommands.BackendDoctorReport{}, err } pluginResult, err := deps.loadPlugins(plugins.LoadOptions{Cwd: cwd}) @@ -176,6 +188,31 @@ func backendDoctorReport(deps appDeps) (zerocommands.BackendDoctorReport, error) }), nil } +func escapeControl(value string) string { + var b strings.Builder + for _, r := range value { + switch r { + case '\n': + b.WriteString(`\n`) + case '\r': + b.WriteString(`\r`) + case '\t': + b.WriteString(`\t`) + case '\u2028', '\u2029': + fmt.Fprintf(&b, `\u%04x`, r) + default: + if r < 0x20 || r == 0x7f { + fmt.Fprintf(&b, `\x%02x`, r) + } else if r >= 0x80 && r <= 0x9f { + fmt.Fprintf(&b, `\u%04x`, r) + } else { + b.WriteRune(r) + } + } + } + return b.String() +} + func formatBackendLifecycleSnapshot(snapshot zerocommands.BackendLifecycleSnapshot) string { lines := []string{"Zero Backends:"} lines = append(lines, fmt.Sprintf(" MCP servers: %d", len(snapshot.MCPServers))) @@ -201,7 +238,23 @@ func formatBackendLifecycleSnapshot(snapshot zerocommands.BackendLifecycleSnapsh lines = append(lines, fmt.Sprintf(" - %s [%s] %s%s", server.Name, server.Type, detail, suffix)) } - lines = append(lines, fmt.Sprintf(" Hooks: %d", len(snapshot.Hooks))) + hooksSummary := fmt.Sprintf(" Hooks: %d", len(snapshot.Hooks)) + if snapshot.HooksIncomplete { + hooksSummary += " (incomplete; hooks.json could not be fully loaded)" + } + lines = append(lines, hooksSummary) + if len(snapshot.HooksDiagnostics) > 0 { + for _, diagnostic := range snapshot.HooksDiagnostics { + target := diagnostic.Path + if diagnostic.FieldPath != "" { + if target != "" { + target += ": " + } + target += diagnostic.FieldPath + } + lines = append(lines, fmt.Sprintf(" ! [%s] %s: %s", escapeControl(diagnostic.Kind), escapeControl(target), escapeControl(diagnostic.Message))) + } + } for _, hook := range snapshot.Hooks { label := hook.Name if label == "" { diff --git a/internal/cli/backends_test.go b/internal/cli/backends_test.go index 20b38fecf2..920dffd470 100644 --- a/internal/cli/backends_test.go +++ b/internal/cli/backends_test.go @@ -375,3 +375,91 @@ func TestBackendDoctorHelperProcess(t *testing.T) { os.Exit(0) } } + +func TestRunBackendsJSONIncludesRedactedHookDiagnostics(t *testing.T) { + cwd := t.TempDir() + secret := "sk-proj-" + strings.Repeat("b", 23) + "0" + deps := appDeps{ + getwd: func() (string, error) { return cwd, nil }, + resolveMCPConfig: func(string, bool) (config.MCPConfig, error) { + return config.MCPConfig{}, nil + }, + loadHooks: func(hooks.LoadOptions) (hooks.LoadResult, error) { + return hooks.LoadResult{ + Config: hooks.Config{Enabled: true, Hooks: []hooks.Definition{{ + ID: "zero.preflight", + Event: hooks.EventBeforeTool, + Command: "sh", + Enabled: true, + }}}, + Diagnostics: []hooks.Diagnostic{{ + Kind: hooks.DiagnosticIO, + Source: hooks.SourceUser, + Path: "https://alice:hunter2@example.com/hooks.json", + Message: "api_key=" + secret, + }}, + }, hooks.ErrInvalidConfig + }, + loadPlugins: func(plugins.LoadOptions) (plugins.LoadResult, error) { + return plugins.LoadResult{}, nil + }, + } + + var stdout bytes.Buffer + var stderr bytes.Buffer + exitCode := runWithDeps([]string{"backends", "--json"}, &stdout, &stderr, deps) + if exitCode != exitSuccess { + t.Fatalf("exitCode = %d stderr=%s", exitCode, stderr.String()) + } + if strings.Contains(stdout.String(), secret) || strings.Contains(stdout.String(), "hunter2") { + t.Fatalf("backend JSON leaked hook diagnostic material:\n%s", stdout.String()) + } + var snapshot zerocommands.BackendLifecycleSnapshot + if err := json.Unmarshal(stdout.Bytes(), &snapshot); err != nil { + t.Fatalf("backend JSON failed to decode: %v\n%s", err, stdout.String()) + } + if !snapshot.HooksIncomplete || len(snapshot.HooksDiagnostics) != 1 { + t.Fatalf("expected incomplete hook snapshot with diagnostics: %#v", snapshot) + } + if len(snapshot.Hooks) != 1 || snapshot.Hooks[0].ID != "zero.preflight" { + t.Fatalf("partial snapshot dropped valid hook: %#v", snapshot.Hooks) + } + if snapshot.HooksDiagnostics[0].Kind != string(hooks.DiagnosticIO) || snapshot.HooksDiagnostics[0].Message == "" { + t.Fatalf("unexpected hook diagnostic snapshot: %#v", snapshot.HooksDiagnostics[0]) + } +} + +func TestFormatBackendLifecycleSnapshotIncludesPathAndField(t *testing.T) { + snapshot := zerocommands.BackendLifecycleSnapshot{ + HooksIncomplete: true, + HooksDiagnostics: []zerocommands.HookDiagnosticSnapshot{{ + Kind: string(hooks.DiagnosticSchema), + Path: "/tmp/hooks.json", + FieldPath: "hooks.0.command", + Message: "Expected a non-empty string.", + }}, + } + out := formatBackendLifecycleSnapshot(snapshot) + if !strings.Contains(out, "/tmp/hooks.json: hooks.0.command") { + t.Fatalf("missing path+field in diagnostic output: %q", out) + } +} + +func TestFormatBackendLifecycleSnapshotEscapesControlCharacters(t *testing.T) { + snapshot := zerocommands.BackendLifecycleSnapshot{ + HooksIncomplete: true, + HooksDiagnostics: []zerocommands.HookDiagnosticSnapshot{{ + Kind: "io\n[pass] forged", + Path: "/tmp/ws\n[pass] forged", + FieldPath: "", + Message: "bad\nline\tvalue", + }}, + } + out := formatBackendLifecycleSnapshot(snapshot) + if strings.Contains(out, "\n[pass] forged\n") { + t.Fatalf("diagnostic output contains raw injected newline: %q", out) + } + if !strings.Contains(out, `\n[pass] forged`) { + t.Fatalf("diagnostic output did not escape newline: %q", out) + } +} diff --git a/internal/cli/extensions.go b/internal/cli/extensions.go index 0e8f2b8947..aa7f755881 100644 --- a/internal/cli/extensions.go +++ b/internal/cli/extensions.go @@ -208,20 +208,35 @@ func runHooks(args []string, stdout io.Writer, stderr io.Writer, deps appDeps) i return writeAppError(stderr, "failed to resolve workspace: "+err.Error(), exitCrash) } result, err := deps.loadHooks(hooks.LoadOptions{Cwd: cwd}) + incomplete := false if err != nil { - return writeAppError(stderr, redaction.ErrorMessage(err, redaction.Options{}), exitCrash) + if !errors.Is(err, hooks.ErrInvalidConfig) { + return writeAppError(stderr, redaction.ErrorMessage(err, redaction.Options{}), exitCrash) + } + // The loader returns the valid layers and diagnostics alongside + // ErrInvalidConfig. Reporting commands must still show that partial + // state instead of exiting before the operator can see what broke. + incomplete = true } if options.json { payload := struct { Hooks hooks.Config `json:"hooks"` Diagnostics []hooks.Diagnostic `json:"diagnostics"` - }{Hooks: result.Config, Diagnostics: result.Diagnostics} + Incomplete bool `json:"incomplete"` + Error string `json:"error,omitempty"` + }{Hooks: result.Config, Diagnostics: result.Diagnostics, Incomplete: incomplete} + if err != nil { + payload.Error = redaction.ErrorMessage(err, redaction.Options{}) + } if err := writePrettyJSON(stdout, redaction.RedactValue(payload, redaction.Options{})); err != nil { return exitCrash } return exitSuccess } output := redaction.RedactString(hooks.FormatList(result.Config, result.Diagnostics), redaction.Options{}) + if incomplete { + output += "\nHook policy is incomplete: " + redaction.ErrorMessage(err, redaction.Options{}) + } if _, err := fmt.Fprintln(stdout, output); err != nil { return exitCrash } diff --git a/internal/cli/hook_dispatch.go b/internal/cli/hook_dispatch.go index 0d47a56029..e755377165 100644 --- a/internal/cli/hook_dispatch.go +++ b/internal/cli/hook_dispatch.go @@ -1,6 +1,7 @@ package cli import ( + "errors" "fmt" "io" "os" @@ -49,11 +50,13 @@ func resolveTrust(trustRoot string) (excludeProject bool, trustCheckErrored bool } // newHookDispatcher builds the per-session hooks dispatcher for a workspace, -// merging user + project hooks.json and wiring the audit store. It fails OPEN: -// any load or setup error yields a nil dispatcher, which Dispatch treats as a -// no-op, so a malformed hooks config can never wedge tool execution. With no -// hooks configured the dispatcher selects nothing and runs no commands, so the -// hot path stays free of overhead until a user opts in via hooks.json. +// merging user + project hooks.json and wiring the audit store. A missing +// config yields an empty dispatcher; an existing but unreadable or unparseable +// hooks.json yields a dispatcher whose beforeTool gate fails closed. Other +// setup errors keep the historical fail-open behaviour (nil dispatcher), so a +// broken audit store cannot wedge tool execution. With no hooks configured the +// dispatcher selects nothing and runs no commands, so the hot path stays free +// of overhead until a user opts in via hooks.json. // // trustRoot is the original launch directory (resolved before any --worktree // reassignment); the project layer loads only when that root is trusted. @@ -81,8 +84,12 @@ func newHookDispatcherWithExtra(workspaceRoot string, extra []hooks.Definition, } loaded, err := hooks.LoadConfig(hooks.LoadOptions{Cwd: workspaceRoot, ExcludeProject: excludeProject}) + configError := "" if err != nil { - return nil, skip + if !errors.Is(err, hooks.ErrInvalidConfig) { + return nil, skip + } + configError = err.Error() } var audit *hooks.AuditStore if store, err := hooks.NewAuditStore(hooks.AuditStoreOptions{}); err == nil { @@ -112,10 +119,11 @@ func newHookDispatcherWithExtra(workspaceRoot string, extra []hooks.Definition, runner = runners[0] } return hooks.NewDispatcher(hooks.DispatcherOptions{ - Config: config, - Audit: audit, - Cwd: workspaceRoot, - Execution: runner, + Config: config, + ConfigError: configError, + Audit: audit, + Cwd: workspaceRoot, + Execution: runner, }), skip } diff --git a/internal/cli/hook_dispatch_test.go b/internal/cli/hook_dispatch_test.go new file mode 100644 index 0000000000..7f3f12c264 --- /dev/null +++ b/internal/cli/hook_dispatch_test.go @@ -0,0 +1,79 @@ +package cli + +import ( + "bytes" + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/Twigpine/zero/internal/hooks" +) + +func TestNewHookDispatcherFailsClosedOnMalformedConfig(t *testing.T) { + home := t.TempDir() + configHome := filepath.Join(home, ".config") + dataHome := filepath.Join(home, ".local", "share") + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", configHome) + t.Setenv("XDG_DATA_HOME", dataHome) + + userHooks := filepath.Join(configHome, "zero", "hooks.json") + if err := os.MkdirAll(filepath.Dir(userHooks), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(userHooks, []byte("{"), 0o600); err != nil { + t.Fatal(err) + } + + dispatcher, _ := newHookDispatcher(t.TempDir(), "") + if dispatcher == nil { + t.Fatal("newHookDispatcher returned nil for an invalid user config") + } + outcome := dispatcher.Dispatch(context.Background(), hooks.DispatchInput{ + Event: hooks.EventBeforeTool, + ToolName: "bash", + }) + if !outcome.Blocked { + t.Fatalf("outcome = %#v, want blocked", outcome) + } + if outcome.BlockedBy != "hook-config" { + t.Fatalf("BlockedBy = %q, want hook-config", outcome.BlockedBy) + } + if !strings.Contains(outcome.Reason, "hook config could not be loaded") { + t.Fatalf("Reason = %q", outcome.Reason) + } +} + +func TestRunHooksListReportsInvalidConfigAsIncomplete(t *testing.T) { + home := t.TempDir() + configHome := filepath.Join(home, ".config") + dataHome := filepath.Join(home, ".local", "share") + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", configHome) + t.Setenv("XDG_DATA_HOME", dataHome) + + userHooks := filepath.Join(configHome, "zero", "hooks.json") + if err := os.MkdirAll(filepath.Dir(userHooks), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(userHooks, []byte("{"), 0o600); err != nil { + t.Fatal(err) + } + + var stdout, stderr bytes.Buffer + code := runHooks([]string{"list"}, &stdout, &stderr, appDeps{ + getwd: func() (string, error) { return t.TempDir(), nil }, + loadHooks: hooks.LoadConfig, + }) + if code != exitSuccess { + t.Fatalf("runHooks exit = %d, stderr = %q", code, stderr.String()) + } + if !strings.Contains(stdout.String(), "Hook policy is incomplete") { + t.Fatalf("stdout missing incomplete marker: %q", stdout.String()) + } + if !strings.Contains(stdout.String(), "unexpected end of JSON input") { + t.Fatalf("stdout missing diagnostic: %q", stdout.String()) + } +} diff --git a/internal/hooks/dispatch.go b/internal/hooks/dispatch.go index 245aa36a74..84ca4f1bb4 100644 --- a/internal/hooks/dispatch.go +++ b/internal/hooks/dispatch.go @@ -51,16 +51,19 @@ type commandResult struct { // logic can be tested without spawning processes. type commandRunner func(ctx context.Context, command string, args []string, stdin []byte, cwd string, env []string) commandResult -// DispatcherOptions configures a Dispatcher. +// DispatcherOptions configures a Dispatcher. ConfigError is set when +// hooks.json exists but could not be loaded; Dispatch blocks beforeTool rather +// than running with an unknown policy. type DispatcherOptions struct { - Config Config - Audit *AuditStore // optional; when set, every run is recorded - Cwd string // working directory for hook commands - Env []string // extra environment entries appended to the process env - Timeout time.Duration // per-command timeout (defaults to defaultHookTimeout) - Execution *execution.Runner // routes hook subprocesses through sandbox policy - now func() time.Time - run commandRunner + Config Config + ConfigError string // set when hooks.json exists but could not be loaded + Audit *AuditStore // optional; when set, every run is recorded + Cwd string // working directory for hook commands + Env []string // extra environment entries appended to the process env + Timeout time.Duration // per-command timeout (defaults to defaultHookTimeout) + Execution *execution.Runner // routes hook subprocesses through sandbox policy + now func() time.Time + run commandRunner } // Dispatcher selects and runs the hooks configured for a lifecycle event, @@ -68,13 +71,14 @@ type DispatcherOptions struct { // blocks the tool; hooks for other events are advisory (failures are recorded // but do not interrupt the run). type Dispatcher struct { - config Config - audit *AuditStore - cwd string - env []string - timeout time.Duration - now func() time.Time - run commandRunner + config Config + configError string + audit *AuditStore + cwd string + env []string + timeout time.Duration + now func() time.Time + run commandRunner } // NewDispatcher builds a Dispatcher. A zero/empty config yields a dispatcher that @@ -97,13 +101,14 @@ func NewDispatcher(options DispatcherOptions) *Dispatcher { } } return &Dispatcher{ - config: options.Config, - audit: options.Audit, - cwd: options.Cwd, - env: options.Env, - timeout: timeout, - now: now, - run: run, + config: options.Config, + configError: options.ConfigError, + audit: options.Audit, + cwd: options.Cwd, + env: options.Env, + timeout: timeout, + now: now, + run: run, } } @@ -157,6 +162,17 @@ func (dispatcher *Dispatcher) Dispatch(ctx context.Context, input DispatchInput) if dispatcher == nil { return outcome } + if dispatcher.configError != "" { + // The config file exists but could not be read or parsed. The policy it + // contained is unknown; block a blocking event rather than selecting from + // an empty/partial config. Advisory events can still run the valid layers. + if blocksOn(input.Event) { + outcome.Blocked = true + outcome.BlockedBy = "hook-config" + outcome.Reason = "hook config could not be loaded: " + dispatcher.configError + return outcome + } + } selected := Select(dispatcher.config, SelectInput{Event: input.Event, ToolName: input.ToolName}) if len(selected) == 0 { return outcome diff --git a/internal/hooks/dispatch_test.go b/internal/hooks/dispatch_test.go index 23d38f8574..bcdfe0daf6 100644 --- a/internal/hooks/dispatch_test.go +++ b/internal/hooks/dispatch_test.go @@ -270,3 +270,57 @@ func TestDispatchBeforeToolFailsClosedWhenHookTimesOut(t *testing.T) { t.Fatalf("Reason = %q, want a timeout reason", outcome.Reason) } } + +func TestDispatchBeforeToolFailsClosedWhenConfigCouldNotBeLoaded(t *testing.T) { + dispatcher := NewDispatcher(DispatcherOptions{ConfigError: "invalid hook config: /tmp/hooks.json: unexpected EOF"}) + + outcome := dispatcher.Dispatch(context.Background(), DispatchInput{Event: EventBeforeTool, ToolName: "bash"}) + + if !outcome.Blocked { + t.Fatalf("outcome = %#v, want blocked", outcome) + } + if outcome.Ran != 0 { + t.Fatalf("Ran = %d, want 0", outcome.Ran) + } + if !strings.Contains(outcome.Reason, "hook config could not be loaded") { + t.Fatalf("Reason = %q", outcome.Reason) + } +} + +func TestDispatchNonBlockingEventDoesNotVetoOnConfigError(t *testing.T) { + dispatcher := NewDispatcher(DispatcherOptions{ConfigError: "invalid hook config: /tmp/hooks.json: unexpected EOF"}) + + outcome := dispatcher.Dispatch(context.Background(), DispatchInput{Event: EventAfterTool, ToolName: "bash"}) + + if outcome.Blocked { + t.Fatalf("outcome = %#v, want non-blocking", outcome) + } +} + +func TestDispatchAdvisoryHookRunsWhenConfigCouldNotBeLoaded(t *testing.T) { + ran := 0 + runner := func(context.Context, string, []string, []byte, string, []string) commandResult { + ran++ + return commandResult{ExitCode: 0} + } + config := Config{Enabled: true, Hooks: []Definition{{ + ID: "zero.advisory", + Event: EventAfterTool, + Command: "audit", + Enabled: true, + }}} + dispatcher := NewDispatcher(DispatcherOptions{ + Config: config, + ConfigError: "invalid hook config: /tmp/hooks.json: unexpected EOF", + run: runner, + }) + + outcome := dispatcher.Dispatch(context.Background(), DispatchInput{Event: EventAfterTool, ToolName: "bash"}) + + if outcome.Blocked { + t.Fatalf("outcome = %#v, want non-blocking", outcome) + } + if ran != 1 || outcome.Ran != 1 { + t.Fatalf("advisory hook ran=%d outcome.Ran=%d, want 1", ran, outcome.Ran) + } +} diff --git a/internal/hooks/hooks.go b/internal/hooks/hooks.go index 8a3e95d502..663b15653c 100644 --- a/internal/hooks/hooks.go +++ b/internal/hooks/hooks.go @@ -183,6 +183,12 @@ var ( storeLocks = map[string]*sync.Mutex{} ) +// ErrInvalidConfig marks a hooks.json that exists but cannot be read or +// parsed, or that contains a schema-invalid hook definition. A missing file is +// the documented default and is not an error; callers turn this sentinel into +// a fail-closed beforeTool gate. +var ErrInvalidConfig = errors.New("invalid hook config") + func ResolvePaths(options ResolvePathOptions) (Paths, error) { cwd, err := resolveCwd(options.Cwd) if err != nil { @@ -206,6 +212,10 @@ func ResolvePaths(options ResolvePathOptions) (Paths, error) { }, nil } +// LoadConfig merges the user and project hook layers. It returns the partial +// result together with ErrInvalidConfig when an existing layer cannot be read, +// parsed, or validated; a missing file is the documented default and is not an +// error. func LoadConfig(options LoadOptions) (LoadResult, error) { paths, err := ResolvePaths(ResolvePathOptions{Cwd: options.Cwd, Env: options.Env}) if err != nil { @@ -234,6 +244,18 @@ func LoadConfig(options LoadOptions) (LoadResult, error) { paths.UserConfigPath = userConfigPath paths.ProjectConfigPath = projectConfigPath + for _, diagnostic := range diagnostics { + // A malformed or unreadable layer means the policy it contained is + // unknown. Do not merge past it and run with a partial policy. + switch diagnostic.Kind { + case DiagnosticIO, DiagnosticJSON, DiagnosticSchema: + return LoadResult{ + Config: mergeLayers(layers, &diagnostics), + Diagnostics: diagnostics, + Paths: paths, + }, fmt.Errorf("%w: %s: %s", ErrInvalidConfig, diagnostic.Path, diagnostic.Message) + } + } return LoadResult{ Config: mergeLayers(layers, &diagnostics), Diagnostics: diagnostics, @@ -629,6 +651,13 @@ func readLayer(source ConfigSource, path string, diagnostics *[]Diagnostic) (hoo data, err := os.ReadFile(path) if err != nil { if errors.Is(err, os.ErrNotExist) { + // os.ReadFile follows symlinks, so a dangling hooks.json symlink (or a + // dangling parent such as a trusted workspace's .zero) also reports + // ENOENT. Lstat tells "never existed" from "exists but its target is + // gone"; the latter is an unreadable policy, not a default. + if danglingSymlinkInPath(path) { + *diagnostics = append(*diagnostics, Diagnostic{Kind: DiagnosticIO, Source: source, Path: path, Message: "hooks.json path contains a symlink whose target does not exist"}) + } return hookLayer{}, false } *diagnostics = append(*diagnostics, Diagnostic{Kind: DiagnosticIO, Source: source, Path: path, Message: err.Error()}) @@ -648,6 +677,25 @@ func readLayer(source ConfigSource, path string, diagnostics *[]Diagnostic) (hoo return hookLayer{source: source, path: path, config: config, enabledSet: enabledSet, hookEnabledSet: hookEnabledSet}, true } +// danglingSymlinkInPath reports whether path or any parent component is a +// symlink whose target does not exist. os.ReadFile follows symlinks and +// reports ENOENT for both a missing file and a dangling one; this check lets +// the loader treat the latter as an unreadable policy instead of a first run. +func danglingSymlinkInPath(path string) bool { + for current := path; ; current = filepath.Dir(current) { + if _, err := os.Lstat(current); err == nil { + if _, statErr := os.Stat(current); errors.Is(statErr, os.ErrNotExist) { + return true + } + } + parent := filepath.Dir(current) + if parent == current { + break + } + } + return false +} + func readSingleConfig(path string) (Config, error) { diagnostics := []Diagnostic{} layer, ok := readLayer(SourceProject, path, &diagnostics) diff --git a/internal/hooks/hooks_test.go b/internal/hooks/hooks_test.go index f24b6d1b46..f733b05fea 100644 --- a/internal/hooks/hooks_test.go +++ b/internal/hooks/hooks_test.go @@ -2,6 +2,7 @@ package hooks import ( "encoding/json" + "errors" "os" "path/filepath" "reflect" @@ -33,6 +34,38 @@ func TestResolvePathsUsesXDGLocations(t *testing.T) { } } +func TestLoadConfigRejectsMalformedExistingLayer(t *testing.T) { + dir := t.TempDir() + projectConfigPath := filepath.Join(dir, "hooks.json") + if err := os.WriteFile(projectConfigPath, []byte("{"), 0o600); err != nil { + t.Fatalf("write hooks: %v", err) + } + + _, err := LoadConfig(LoadOptions{ + UserConfigPath: filepath.Join(dir, "missing-user-hooks.json"), + ProjectConfigPath: projectConfigPath, + }) + if !errors.Is(err, ErrInvalidConfig) { + t.Fatalf("LoadConfig error = %v, want ErrInvalidConfig", err) + } +} + +func TestLoadConfigRejectsUnreadableExistingLayer(t *testing.T) { + dir := t.TempDir() + projectConfigPath := filepath.Join(dir, "hooks.json") + if err := os.Mkdir(projectConfigPath, 0o700); err != nil { + t.Fatalf("mkdir hooks: %v", err) + } + + _, err := LoadConfig(LoadOptions{ + UserConfigPath: filepath.Join(dir, "missing-user-hooks.json"), + ProjectConfigPath: projectConfigPath, + }) + if !errors.Is(err, ErrInvalidConfig) { + t.Fatalf("LoadConfig error = %v, want ErrInvalidConfig", err) + } +} + func TestLoadConfigLayersProjectOverridesAndDiagnostics(t *testing.T) { dir := t.TempDir() userConfigPath := filepath.Join(dir, "user-hooks.json") @@ -197,11 +230,11 @@ func TestLoadConfigRejectsMatchersOnLifecycleHooks(t *testing.T) { UserConfigPath: filepath.Join(dir, "missing-user-hooks.json"), ProjectConfigPath: projectConfigPath, }) - if err != nil { - t.Fatalf("LoadConfig returned error: %v", err) + if !errors.Is(err, ErrInvalidConfig) { + t.Fatalf("LoadConfig error = %v, want ErrInvalidConfig", err) } if len(result.Config.Hooks) != 0 { - t.Fatalf("expected invalid hooks to be skipped: %#v", result.Config.Hooks) + t.Fatalf("expected invalid hooks to be omitted from the partial result: %#v", result.Config.Hooks) } if !hasHookDiagnostic(result.Diagnostics, DiagnosticSchema, "", "hooks.0.matcher") { t.Fatalf("missing matcher diagnostic: %#v", result.Diagnostics) @@ -439,6 +472,107 @@ func TestAuditStoreAppendsAndSkipsMalformedLines(t *testing.T) { } } +func TestLoadConfigRejectsDanglingSymlink(t *testing.T) { + dir := t.TempDir() + link := filepath.Join(dir, "hooks.json") + if err := os.Symlink(filepath.Join(dir, "missing-target.json"), link); err != nil { + t.Skipf("symlink unavailable: %v", err) + } + + result, err := LoadConfig(LoadOptions{ + UserConfigPath: filepath.Join(dir, "missing-user-hooks.json"), + ProjectConfigPath: link, + }) + if !errors.Is(err, ErrInvalidConfig) { + t.Fatalf("LoadConfig error = %v, want ErrInvalidConfig", err) + } + if !hasHookDiagnostic(result.Diagnostics, DiagnosticIO, "", "") { + t.Fatalf("missing dangling-symlink diagnostic: %#v", result.Diagnostics) + } +} + +func TestLoadConfigRejectsDanglingParentSymlink(t *testing.T) { + dir := t.TempDir() + workspace := filepath.Join(dir, "workspace") + if err := os.MkdirAll(workspace, 0o700); err != nil { + t.Fatal(err) + } + if err := os.Symlink(filepath.Join(dir, "missing-zero"), filepath.Join(workspace, ".zero")); err != nil { + t.Skipf("symlink unavailable: %v", err) + } + projectConfigPath := filepath.Join(workspace, ".zero", "hooks.json") + + result, err := LoadConfig(LoadOptions{ + UserConfigPath: filepath.Join(dir, "missing-user-hooks.json"), + ProjectConfigPath: projectConfigPath, + }) + if !errors.Is(err, ErrInvalidConfig) { + t.Fatalf("LoadConfig error = %v, want ErrInvalidConfig", err) + } + if !hasHookDiagnostic(result.Diagnostics, DiagnosticIO, "", "") { + t.Fatalf("missing dangling-parent diagnostic: %#v", result.Diagnostics) + } +} + +func TestLoadConfigRejectsSchemaInvalidLayer(t *testing.T) { + dir := t.TempDir() + projectConfigPath := filepath.Join(dir, "hooks.json") + writeHookJSON(t, projectConfigPath, map[string]any{ + "hooks": []any{map[string]any{ + "id": "zero.bad", + "event": "beforeTool", + "matcher": "bash", + "command": 42, + }}, + }) + + result, err := LoadConfig(LoadOptions{ + UserConfigPath: filepath.Join(dir, "missing-user-hooks.json"), + ProjectConfigPath: projectConfigPath, + }) + if !errors.Is(err, ErrInvalidConfig) { + t.Fatalf("LoadConfig error = %v, want ErrInvalidConfig", err) + } + if !hasHookDiagnostic(result.Diagnostics, DiagnosticSchema, "", "hooks.0.command") { + t.Fatalf("missing schema diagnostic: %#v", result.Diagnostics) + } +} + +func TestLoadConfigKeepsValidLayerWhenAnotherLayerIsInvalid(t *testing.T) { + dir := t.TempDir() + userConfigPath := filepath.Join(dir, "user-hooks.json") + projectConfigPath := filepath.Join(dir, "project-hooks.json") + writeHookJSON(t, userConfigPath, map[string]any{ + "enabled": true, + "hooks": []any{map[string]any{ + "id": "zero.advisory", + "event": "afterTool", + "command": "node", + "args": []string{"audit.mjs"}, + }}, + }) + if err := os.WriteFile(projectConfigPath, []byte("{"), 0o600); err != nil { + t.Fatalf("write malformed project hooks: %v", err) + } + + result, err := LoadConfig(LoadOptions{ + UserConfigPath: userConfigPath, + ProjectConfigPath: projectConfigPath, + }) + if !errors.Is(err, ErrInvalidConfig) { + t.Fatalf("LoadConfig error = %v, want ErrInvalidConfig", err) + } + if len(result.Config.Hooks) != 1 || result.Config.Hooks[0].ID != "zero.advisory" { + t.Fatalf("partial result dropped the valid user hook: %#v", result.Config.Hooks) + } + if !hasHookDiagnostic(result.Diagnostics, DiagnosticJSON, "", "") { + t.Fatalf("missing JSON diagnostic: %#v", result.Diagnostics) + } + if result.Paths.UserConfigPath != userConfigPath || result.Paths.ProjectConfigPath != projectConfigPath { + t.Fatalf("paths = %#v", result.Paths) + } +} + func writeHookJSON(t *testing.T, path string, value any) { t.Helper() if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { diff --git a/internal/hooks/hooks_windows_test.go b/internal/hooks/hooks_windows_test.go new file mode 100644 index 0000000000..00ee64ac87 --- /dev/null +++ b/internal/hooks/hooks_windows_test.go @@ -0,0 +1,41 @@ +//go:build windows + +package hooks + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "testing" +) + +func TestLoadConfigRejectsDanglingJunctionParent(t *testing.T) { + dir := t.TempDir() + workspace := filepath.Join(dir, "workspace") + if err := os.MkdirAll(workspace, 0o700); err != nil { + t.Fatal(err) + } + target := filepath.Join(dir, "junction-target") + if err := os.MkdirAll(target, 0o700); err != nil { + t.Fatal(err) + } + link := filepath.Join(workspace, ".zero") + if out, err := exec.Command("cmd", "/c", "mklink", "/J", link, target).CombinedOutput(); err != nil { + t.Skipf("mklink /J unavailable: %v (%s)", err, out) + } + if err := os.RemoveAll(target); err != nil { + t.Fatal(err) + } + + result, err := LoadConfig(LoadOptions{ + UserConfigPath: filepath.Join(dir, "missing-user-hooks.json"), + ProjectConfigPath: filepath.Join(link, "hooks.json"), + }) + if !errors.Is(err, ErrInvalidConfig) { + t.Fatalf("LoadConfig error = %v, want ErrInvalidConfig", err) + } + if !hasHookDiagnostic(result.Diagnostics, DiagnosticIO, "", "") { + t.Fatalf("missing dangling-junction diagnostic: %#v", result.Diagnostics) + } +} diff --git a/internal/zerocommands/backend_snapshots.go b/internal/zerocommands/backend_snapshots.go index 3bfcf8300c..cb42678649 100644 --- a/internal/zerocommands/backend_snapshots.go +++ b/internal/zerocommands/backend_snapshots.go @@ -82,10 +82,49 @@ type PluginSnapshot struct { // the operator a single payload describing the full extensibility // surface. The three inner slices are always non-nil so JSON // output is `[]` and never `null`. +// BackendLifecycleSnapshot bundles the typed snapshots for the three backend +// surfaces that the WorkSplit PRD places in Gnanam's lane: MCP servers, hooks, +// and plugins. `zero doctor` and the headless `zero config` command can return +// one of these to give the operator a single payload describing the full +// extensibility surface. The three inner slices are always non-nil so JSON +// output is `[]` and never `null`. +// +// HooksIncomplete is true when hooks.json could not be fully loaded and the +// hook list is only the valid remainder. type BackendLifecycleSnapshot struct { - MCPServers []MCPServerSnapshot `json:"mcpServers"` - Hooks []HookSnapshot `json:"hooks"` - Plugins []PluginSnapshot `json:"plugins"` + MCPServers []MCPServerSnapshot `json:"mcpServers"` + Hooks []HookSnapshot `json:"hooks"` + Plugins []PluginSnapshot `json:"plugins"` + HooksIncomplete bool `json:"hooksIncomplete,omitempty"` + HooksDiagnostics []HookDiagnosticSnapshot `json:"hooksDiagnostics,omitempty"` +} + +// HookDiagnosticSnapshot is a redacted projection of a hooks loader +// diagnostic, safe to include in the backends --json lifecycle report. +type HookDiagnosticSnapshot struct { + Kind string `json:"kind,omitempty"` + Source string `json:"source,omitempty"` + Path string `json:"path,omitempty"` + HookID string `json:"hookId,omitempty"` + FieldPath string `json:"fieldPath,omitempty"` + Message string `json:"message,omitempty"` +} + +// HookDiagnosticSnapshots redacts and copies loader diagnostics for reporting. +// It never returns nil so JSON output is [] rather than null. +func HookDiagnosticSnapshots(diagnostics []hooks.Diagnostic) []HookDiagnosticSnapshot { + out := make([]HookDiagnosticSnapshot, 0, len(diagnostics)) + for _, diagnostic := range diagnostics { + out = append(out, HookDiagnosticSnapshot{ + Kind: string(diagnostic.Kind), + Source: string(diagnostic.Source), + Path: redactSnapshotString(diagnostic.Path), + HookID: redactSnapshotString(diagnostic.HookID), + FieldPath: redactSnapshotString(diagnostic.FieldPath), + Message: redactSnapshotString(diagnostic.Message), + }) + } + return out } // MCPServerSnapshotFromServer converts a single mcp.Server into its diff --git a/internal/zerocommands/backend_snapshots_test.go b/internal/zerocommands/backend_snapshots_test.go index 18322d2dd9..ce70ef82b3 100644 --- a/internal/zerocommands/backend_snapshots_test.go +++ b/internal/zerocommands/backend_snapshots_test.go @@ -482,3 +482,30 @@ func TestNewBackendLifecycleSnapshotBundlesAndDefaultsNilsToEmpty(t *testing.T) t.Fatalf("expected one of each, got %#v", full) } } + +func TestHookDiagnosticSnapshotsRedactsSensitiveValues(t *testing.T) { + if got := HookDiagnosticSnapshots(nil); got == nil || len(got) != 0 { + t.Fatalf("expected non-nil empty diagnostics, got %#v", got) + } + diagnostics := []hooks.Diagnostic{{ + Kind: hooks.DiagnosticIO, + Source: hooks.SourceUser, + Path: "https://alice:hunter2@example.com/hooks.json", + HookID: "zero.guard", + FieldPath: "hooks.0.command", + Message: "api_key=sk-live-supersecret", + }} + snapshots := HookDiagnosticSnapshots(diagnostics) + if len(snapshots) != 1 { + t.Fatalf("expected one snapshot, got %#v", snapshots) + } + encoded, err := json.Marshal(snapshots) + if err != nil { + t.Fatalf("json.Marshal returned error: %v", err) + } + for _, secret := range []string{"hunter2", "sk-live-supersecret"} { + if strings.Contains(string(encoded), secret) { + t.Fatalf("snapshot leaked %q: %s", secret, encoded) + } + } +}