diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-15 16:31:46 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-15 16:31:46 +0000 |
| commit | ced6733eee6aa246e2af55ce0c71e38c01a50141 (patch) | |
| tree | 1c7abeca25d5625d06934d3ea1141cf554edcd92 | |
| parent | d876712c3801b10bb1258da9b8f71fa7b41320e4 (diff) | |
security-guidance: print one JSON document from the SessionStart hook on other hostsmhegazy/sg-portable-session-start
On a host other than Claude Code the SessionStart hook printed an async
declaration line and then a metrics line. A host that reads hook output as
one JSON document with a closed schema rejects that.
In portable mode the hook now skips the async line and prints one object
with only the standard fields. The portable-mode helpers move to _base.py so
both hook scripts share them, and the mode is decided once at start-up.
Output under Claude Code is unchanged.
| -rw-r--r-- | plugins/security-guidance/README.md | 2 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/_base.py | 41 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/ensure_agent_sdk.py | 10 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 32 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/conftest.py | 3 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_portable_output.py | 96 |
6 files changed, 147 insertions, 37 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md index 61bd2449..610b3446 100644 --- a/plugins/security-guidance/README.md +++ b/plugins/security-guidance/README.md @@ -64,7 +64,7 @@ SECURITY_REVIEW_MODEL=claude-opus-5-5 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. +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 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 71e0c73e..c17d6265 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 @@ -199,37 +200,6 @@ 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) - - # Extra keys emit_metrics appends to every row this invocation emits. _TAIL_METRICS: Dict[str, Any] = {} 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 index 86016a4e..cad2052c 100644 --- a/plugins/security-guidance/tests/test_portable_output.py +++ b/plugins/security-guidance/tests/test_portable_output.py @@ -1,9 +1,12 @@ import json +import os +import subprocess +import sys import pytest from conftest import ( - STUB_VULN, VULN_PY, edit_payload, metrics_of, run_hook, stop_payload, ups_payload, + 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. @@ -66,6 +69,15 @@ class TestOtherHost: 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", [ {}, @@ -85,3 +97,85 @@ class TestClaudeCodeUnchanged: 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") |
