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 /plugins/security-guidance/tests | |
| 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.
Diffstat (limited to 'plugins/security-guidance/tests')
| -rw-r--r-- | plugins/security-guidance/tests/conftest.py | 3 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_portable_output.py | 96 |
2 files changed, 97 insertions, 2 deletions
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") |
