summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <8000722+mhegazy@users.noreply.github.com>2026-10-15 15:27:49 -0700
committerGitHub <noreply@github.com>2026-10-15 15:27:49 -0700
commit9c9226b819bd986ebec9702477144fa9d5b3dfbe (patch)
tree9d36e560e82074f49fd66dd2543fa7aa219dfe35 /plugins
parent804a605993f42f911a974acb71edb37c34d506e8 (diff)
parenta5672a02491775c1022bd354f118816e88eeed51 (diff)
Merge pull request #6540 from anthropics/mhegazy/sg-portable-hook-output
security-guidance: leave Claude Code only fields out of hook output on other hosts
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/README.md8
-rw-r--r--plugins/security-guidance/hooks/_base.py41
-rw-r--r--plugins/security-guidance/hooks/ensure_agent_sdk.py10
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py7
-rw-r--r--plugins/security-guidance/tests/conftest.py3
-rw-r--r--plugins/security-guidance/tests/test_portable_output.py181
6 files changed, 243 insertions, 7 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md
index 518af894..610b3446 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`), and the SessionStart hook prints a separate `{"async": ...}` line first. A host that validates hook output against a closed schema rejects them. In portable mode they are left out, so every hook prints one JSON object with only the standard fields (`decision`, `reason`, `systemMessage`, `hookSpecificOutput`), and the SessionStart hook runs to completion before the host continues. 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/_base.py b/plugins/security-guidance/hooks/_base.py
index 44b205f0..f05a0094 100644
--- a/plugins/security-guidance/hooks/_base.py
+++ b/plugins/security-guidance/hooks/_base.py
@@ -94,6 +94,47 @@ PROVENANCE_BANNER = (
)
+# Output that only Claude Code reads: the `metrics` and `rewakeSummary` fields,
+# and the separate `{"async": ...}` line an async hook prints first. Other hosts
+# that run this plugin's hooks can validate hook output against a closed schema
+# and reject the whole output over a field or a second line they do not know,
+# which shows up as a hook error.
+_CLAUDE_CODE_OUTPUT_FIELDS = ("metrics", "rewakeSummary")
+
+
+def _detect_portable_output():
+ 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"))
+
+
+# Decided once, from the environment the host started the hook with: code the
+# hook runs in-process later can set these variables itself.
+_PORTABLE_OUTPUT = _detect_portable_output()
+
+
+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."""
+ return _PORTABLE_OUTPUT
+
+
+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 _read_plugin_version_int():
"""Encode plugin.json version "M.m.p" as M*10000 + m*100 + p so it fits the
bool|number metrics constraint. Returns 0 if unreadable."""
diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py
index f5d016db..f49e857d 100644
--- a/plugins/security-guidance/hooks/ensure_agent_sdk.py
+++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py
@@ -27,7 +27,7 @@ from pathlib import Path
# → ~/.claude/security. See _base.state_dir for resolution precedence. Re-aliased
# here to match the existing local name (state_dir was already a local var in
# main() and _maybe_emit_user_notice).
-from _base import state_dir as _resolve_state_dir
+from _base import portable_output, state_dir as _resolve_state_dir, write_hook_output
# Outcome codes for the sdk_bootstrap metric. Values are stable for telemetry.
NOOP_SYSTEM = 0 # claude_agent_sdk already importable in system python
@@ -765,7 +765,11 @@ if __name__ == "__main__":
# SessionStart runs before the user's first prompt; doing this in the
# background means the first commit-review of the session usually finds
# the venv ready.
- print(json.dumps({"async": True, "asyncTimeout": 180000}), flush=True)
+ #
+ # Not printed in portable mode: a host that reads stdout as one JSON
+ # document rejects a second line, and runs this hook to completion anyway.
+ if not portable_output():
+ print(json.dumps({"async": True, "asyncTimeout": 180000}), flush=True)
t0 = time.perf_counter()
try:
outcome, err_phase, err_kind = main()
@@ -859,4 +863,4 @@ if __name__ == "__main__":
"additionalContext": notice,
}
response["systemMessage"] = notice
- print(json.dumps(response), flush=True)
+ write_hook_output(response)
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index afc5c190..8a231f38 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -84,6 +84,7 @@ from _base import ( # noqa: E402,F401
_read_plugin_version_int, _PV, _USAGE, _USAGE_LOCK,
_PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics,
state_dir as _resolve_state_dir,
+ write_hook_output as _write_hook_output,
)
import extensibility # noqa: E402
from patterns import ( # noqa: E402,F401
@@ -294,7 +295,7 @@ def emit_metrics(
out["reason"] = additional_context
if system_message:
out["systemMessage"] = system_message
- print(json.dumps(out), flush=True)
+ _write_hook_output(out)
# =====================================================================
# State management
@@ -2512,7 +2513,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)
@@ -2588,7 +2589,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/conftest.py b/plugins/security-guidance/tests/conftest.py
index 11af0273..998401c2 100644
--- a/plugins/security-guidance/tests/conftest.py
+++ b/plugins/security-guidance/tests/conftest.py
@@ -128,7 +128,8 @@ def hook_env(tmp_path, stub_api):
"CLAUDE_PROJECT_DIR", "HTTP_PROXY", "HTTPS_PROXY",
"http_proxy", "https_proxy", "ALL_PROXY", "all_proxy",
"CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX",
- "CLAUDE_CODE_USE_FOUNDRY")}
+ "CLAUDE_CODE_USE_FOUNDRY",
+ "PLUGIN_ROOT", "SECURITY_GUIDANCE_PORTABLE_OUTPUT")}
env.update(GIT_ENV)
env.update({
"SECURITY_WARNINGS_STATE_DIR": str(state),
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..cad2052c
--- /dev/null
+++ b/plugins/security-guidance/tests/test_portable_output.py
@@ -0,0 +1,181 @@
+import json
+import os
+import subprocess
+import sys
+
+import pytest
+
+from conftest import (
+ HOOKS_DIR, 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))
+
+
+ def test_mode_is_not_changed_by_the_hook_process_itself(self, hook_env):
+ code = ("import os, _base\n"
+ "os.environ['CLAUDE_CODE_ENTRYPOINT'] = 'sdk-py'\n"
+ "_base.write_hook_output({'metrics': {'x': 1}, 'reason': 'r'})\n")
+ r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True,
+ cwd=HOOKS_DIR, env=_env(hook_env, PLUGIN_ROOT="/p"), timeout=60)
+ assert _objects(r.stdout) == [{"reason": "r"}], r.stderr
+
+
+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) == [{}]
+
+
+# SessionStart runs ensure_agent_sdk.py. The wrapper picks the branch without
+# installing anything: whether the SDK looks importable, and whether the
+# interpreter looks older than the SDK supports.
+SESSION_START_FIELDS = STOP_FIELDS | {"hookSpecificOutput"}
+_BOOTSTRAP = """
+import importlib.util, os, runpy, sys
+script, sdk, old_py = sys.argv[1:4]
+sys.path.insert(0, os.path.dirname(script))
+real = importlib.util.find_spec
+def find_spec(name, *a, **k):
+ if name == "claude_agent_sdk":
+ return object() if sdk == "present" else None
+ return real(name, *a, **k)
+importlib.util.find_spec = find_spec
+class V(tuple):
+ major, minor = property(lambda s: s[0]), property(lambda s: s[1])
+sys.version_info = V(((3, 9, 6) if old_py == "old" else (3, 12, 0)) + ("final", 0))
+sys.argv = [script]
+runpy.run_path(script, run_name="__main__")
+"""
+
+
+def _session_start(tmp_path, branch, **extra):
+ state = tmp_path / "state"
+ state.mkdir(exist_ok=True)
+ sdk, old_py = "absent", "new"
+ if branch == "noop":
+ sdk = "present"
+ elif branch == "concurrent_build":
+ (state / "agent-sdk-venv.building").touch()
+ elif branch == "failure":
+ (tmp_path / "file").write_text("")
+ state = tmp_path / "file" / "state"
+ elif branch == "notice":
+ old_py = "old"
+ env = {k: v for k, v in os.environ.items() if k not in HOST_MARKERS}
+ env.update(SECURITY_WARNINGS_STATE_DIR=str(state), HOME=str(tmp_path),
+ PYTHONDONTWRITEBYTECODE="1", **extra)
+ r = subprocess.run(
+ [sys.executable, "-c", _BOOTSTRAP, str(HOOKS_DIR / "ensure_agent_sdk.py"), sdk, old_py],
+ input="{}", capture_output=True, text=True, env=env, timeout=60,
+ )
+ return r.returncode, r.stdout, r.stderr
+
+
+SESSION_START_BRANCHES = ["noop", "concurrent_build", "failure", "notice"]
+
+
+class TestSessionStartOtherHost:
+ @pytest.mark.parametrize("branch", SESSION_START_BRANCHES)
+ def test_one_document_with_only_standard_fields(self, tmp_path, branch):
+ rc, so, se = _session_start(tmp_path, branch, PLUGIN_ROOT="/p")
+ assert rc == 0 and se == ""
+ out = json.loads(so) # the whole stream is one JSON document
+ assert set(out) <= SESSION_START_FIELDS, out
+ assert (out != {}) == (branch == "notice")
+
+ def test_notice_is_kept(self, tmp_path):
+ rc, so, se = _session_start(tmp_path, "notice", PLUGIN_ROOT="/p")
+ out = json.loads(so)
+ assert "Python" in out["systemMessage"]
+ assert out["hookSpecificOutput"] == {
+ "hookEventName": "SessionStart", "additionalContext": out["systemMessage"]}
+
+
+class TestSessionStartClaudeCodeUnchanged:
+ @pytest.mark.parametrize("branch,outcome", [
+ ("noop", 0), ("concurrent_build", 5), ("failure", 3), ("notice", 6)])
+ @pytest.mark.parametrize("extra", [
+ {},
+ {"PLUGIN_ROOT": "/p", "CLAUDECODE": "1"},
+ {"PLUGIN_ROOT": "/p", "SECURITY_GUIDANCE_PORTABLE_OUTPUT": "0"},
+ ])
+ def test_async_line_then_metrics(self, tmp_path, branch, outcome, extra):
+ rc, so, se = _session_start(tmp_path, branch, **extra)
+ assert rc == 0
+ first, second = _objects(so)
+ assert first == {"async": True, "asyncTimeout": 180000}
+ assert second["metrics"]["sdk_bootstrap"] == outcome
+ assert ("systemMessage" in second) == (branch == "notice")