diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-12 18:49:01 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-14 12:12:19 +0000 |
| commit | 26eea79bd04d30a6b38f3a4c89f4596c44a91128 (patch) | |
| tree | 691710ebe207c7119f6c3b41e5777ee52f8bc546 /plugins | |
| parent | f359d43b406057f1a8cdbc4ea93b827642c162e6 (diff) | |
security-guidance: leave Claude Code only fields out of hook output on other hosts
The hooks print metrics and rewakeSummary in their JSON output. A host that validates hook output against a closed schema rejects the whole line, so every Stop and PostToolUse shows a hook error there.
When the host passes PLUGIN_ROOT and does not identify itself as Claude Code, print only the standard fields. Blocking findings and guidance are kept. SECURITY_GUIDANCE_PORTABLE_OUTPUT=1/0 forces it either way. Output under Claude Code is unchanged.
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/README.md | 8 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 37 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_portable_output.py | 87 |
3 files changed, 129 insertions, 3 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md index 58736a85..b3d16f18 100644 --- a/plugins/security-guidance/README.md +++ b/plugins/security-guidance/README.md @@ -58,6 +58,14 @@ SECURITY_REVIEW_MODEL=claude-opus-5-5 | `ENABLE_STOP_REVIEW=0` | on | Disable only the Stop-hook diff review, keeping commit/push reviews. Useful for multi-agent / shared-worktree setups where another agent can move HEAD between a worker's turns | | `ENABLE_COMMIT_REVIEW=0` | on | Disable layer 3 (agentic commit review) | +### Hook output for other hosts + +```bash +SECURITY_GUIDANCE_PORTABLE_OUTPUT=1 # default: detected +``` + +The hooks' JSON output carries two fields that only Claude Code reads (`metrics` and `rewakeSummary`). A host that validates hook output against a closed schema rejects them. In portable mode they are left out and only the standard fields remain (`decision`, `reason`, `systemMessage`, `hookSpecificOutput`). It turns on by itself when the host passes `PLUGIN_ROOT` and does not identify itself as Claude Code; set the variable to `1` or `0` to force it either way. + ### Higher-recall mode ```bash diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index e8df7a1c..0326d1f2 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -198,6 +198,37 @@ CONTINUATION_SUFFIX = ( "response." ) +# Output fields that only Claude Code reads. Other hosts that run this plugin's +# hooks can validate hook output against a closed schema and reject the whole +# line over a field they do not know, which shows up as a hook error on every +# turn. +_CLAUDE_CODE_OUTPUT_FIELDS = ("metrics", "rewakeSummary") + + +def _portable_output(): + """True when stdout should carry only the standard hook output fields. + + SECURITY_GUIDANCE_PORTABLE_OUTPUT=1 or =0 forces it on or off. Otherwise it + is on only when the host passes PLUGIN_ROOT and does not identify itself as + Claude Code, so Claude Code and direct invocations are unchanged.""" + forced = os.environ.get("SECURITY_GUIDANCE_PORTABLE_OUTPUT", "").strip().lower() + if forced in ("1", "true", "yes", "on"): + return True + if forced in ("0", "false", "no", "off"): + return False + if os.environ.get("CLAUDECODE") or os.environ.get("CLAUDE_CODE_ENTRYPOINT"): + return False + return bool(os.environ.get("PLUGIN_ROOT")) + + +def _write_hook_output(out): + """Print one hook output line. In portable mode the Claude Code only + fields are left out; what remains (possibly `{}`) is still valid output.""" + if _portable_output(): + out = {k: v for k, v in out.items() if k not in _CLAUDE_CODE_OUTPUT_FIELDS} + print(json.dumps(out), flush=True) + + def emit_metrics( metrics, rewake_summary=None, @@ -296,7 +327,7 @@ def emit_metrics( } if system_message: out["systemMessage"] = system_message - print(json.dumps(out), flush=True) + _write_hook_output(out) # ===================================================================== # State management @@ -2335,7 +2366,7 @@ def main(): # Another spawn for this same tool_use_id already claimed the # work (compound matched multiple `if` configs). Emit a single # metric so telemetry can count how often the de-dupe kicks in. - print(json.dumps({"metrics": {"bash_hook_dedup": True}}), flush=True) + _write_hook_output({"metrics": {"bash_hook_dedup": True}}) sys.exit(0) if _GIT_COMMIT_RE.search(cmd): handle_commit_review_posttooluse(input_data) @@ -2411,7 +2442,7 @@ def main(): "hookEventName": "PostToolUse", "additionalContext": PROVENANCE_TAG + "\n\n" + "\n\n".join(all_guidance), } - print(json.dumps(output)) + _write_hook_output(output) elif all_guidance: # Defensive: pattern rules disabled but guidance somehow set (shouldn't happen) print(json.dumps({ diff --git a/plugins/security-guidance/tests/test_portable_output.py b/plugins/security-guidance/tests/test_portable_output.py new file mode 100644 index 00000000..86016a4e --- /dev/null +++ b/plugins/security-guidance/tests/test_portable_output.py @@ -0,0 +1,87 @@ +import json + +import pytest + +from conftest import ( + STUB_VULN, VULN_PY, edit_payload, metrics_of, run_hook, stop_payload, ups_payload, +) + +# What a host with a closed hook output schema accepts. +STOP_FIELDS = {"continue", "decision", "reason", "stopReason", "suppressOutput", "systemMessage"} +POST_TOOL_USE_FIELDS = STOP_FIELDS | {"hookSpecificOutput"} +HOST_MARKERS = ("CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "PLUGIN_ROOT", + "SECURITY_GUIDANCE_PORTABLE_OUTPUT") + + +def _env(hook_env, **extra): + env = {k: v for k, v in hook_env.items() if k not in HOST_MARKERS} + env.update(extra) + return env + + +def _objects(stdout): + lines = [l for l in stdout.splitlines() if l.strip()] + return [json.loads(l) for l in lines] + + +def _review_with_finding(workspace, env, stub_api): + ws, repo = workspace + stub_api.vulns = [STUB_VULN] + run_hook(ups_payload(repo), env) + (repo / "app.py").write_text(VULN_PY) + run_hook(edit_payload(repo, repo / "app.py", VULN_PY), env) + return run_hook(stop_payload(repo), env) + + +class TestOtherHost: + def test_stop_skip_path_prints_only_standard_fields(self, workspace, hook_env): + ws, repo = workspace + rc, so, se = run_hook(stop_payload(repo), _env(hook_env, PLUGIN_ROOT=str(ws))) + assert rc == 0 + assert _objects(so) == [{}] + + def test_stop_finding_keeps_the_block_and_the_guidance(self, workspace, hook_env, stub_api): + rc, so, se = _review_with_finding(workspace, _env(hook_env, PLUGIN_ROOT="/p"), stub_api) + (out,) = _objects(so) + assert set(out) <= STOP_FIELDS, out + assert out["decision"] == "block" + assert "command_injection" in out["reason"] + assert "command_injection" in se + + def test_pattern_warning_keeps_the_guidance(self, workspace, hook_env): + ws, repo = workspace + env = _env(hook_env, PLUGIN_ROOT="/p") + (repo / "app.py").write_text(VULN_PY) + rc, so, se = run_hook(edit_payload(repo, repo / "app.py", VULN_PY), env) + assert rc == 0 + (out,) = _objects(so) + assert set(out) <= POST_TOOL_USE_FIELDS, out + assert out["hookSpecificOutput"]["additionalContext"] + + def test_kill_switch_path(self, workspace, hook_env): + ws, repo = workspace + env = _env(hook_env, PLUGIN_ROOT="/p", SECURITY_GUIDANCE_DISABLE="1") + rc, so, se = run_hook(stop_payload(repo), env) + assert rc == 0 + assert all(set(o) <= STOP_FIELDS for o in _objects(so)) + + +class TestClaudeCodeUnchanged: + @pytest.mark.parametrize("extra", [ + {}, + {"PLUGIN_ROOT": "/p", "CLAUDECODE": "1"}, + {"PLUGIN_ROOT": "/p", "CLAUDE_CODE_ENTRYPOINT": "cli"}, + {"PLUGIN_ROOT": "/p", "SECURITY_GUIDANCE_PORTABLE_OUTPUT": "0"}, + ]) + def test_metrics_and_summary_are_still_sent(self, workspace, hook_env, stub_api, extra): + rc, so, se = _review_with_finding(workspace, _env(hook_env, **extra), stub_api) + (out,) = _objects(so) + assert out["metrics"]["vulns_found"] == 1 + assert out["rewakeSummary"] + assert out["decision"] == "block" + + def test_forced_on_under_claude_code(self, workspace, hook_env): + ws, repo = workspace + env = _env(hook_env, CLAUDECODE="1", SECURITY_GUIDANCE_PORTABLE_OUTPUT="1") + rc, so, se = run_hook(stop_payload(repo), env) + assert metrics_of(so) is None and _objects(so) == [{}] |
