Repository navigation
fix(hooks): prevent a malformed hooks.json from disabling beforeTool blocks #1211
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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) | ||
| } | ||
|
Comment on lines
+204
to
+210
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| } | ||
| } | ||
| return b.String() | ||
| } | ||
|
Comment on lines
+191
to
+214
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
|
|
||
| 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 == "" { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
Comment on lines
+388
to
+401
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| }, | ||
| 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) | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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, | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| Audit: audit, | ||
| Cwd: workspaceRoot, | ||
| Execution: runner, | ||
| }), skip | ||
| } | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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()) | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Script executed:
Repository: Twigpine/zero
Length of output: 2659
Script executed:
Repository: Twigpine/zero
Length of output: 48183
Script executed:
Repository: Twigpine/zero
Length of output: 24207
Web query:
Unicode U+2028 line separator mandatory line break text rendering UAX14 BK line break propertyResult:
Script executed:
Repository: Twigpine/zero
Length of output: 19799
Web query:
Qt QTextEdit plain text U+2028 line separator rendered line break documentationResult:
Script executed:
Repository: Twigpine/zero
Length of output: 10335
Escape Unicode line separators in diagnostic text.
If a workspace path contains U+2028 followed by a forged check, a line-separator-aware renderer can display it as a separate report line. Escape Unicode line separators before printing diagnostics, and add a regression test.
Suggested fix