summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/tests
diff options
context:
space:
mode:
authorClaude <noreply@anthropic.com>2026-10-15 22:30:36 +0000
committerClaude <noreply@anthropic.com>2026-10-15 22:30:36 +0000
commitba27dfbea7ee01b2cbaf4fbfd6ed23c074b3ca88 (patch)
treef4dc2ef8188ed691fdc968d299be198548403642 /plugins/security-guidance/tests
parent7b5d1742310abe7d90f10aa574adfa0613226ec6 (diff)
parent7b2259ba542c313099b1f00be8b670f7aa0c63bb (diff)
Merge remote-tracking branch 'origin/main' into mhegazy/sg-no-credentials-notice
# Conflicts: # plugins/security-guidance/hooks/security_reminder_hook.py
Diffstat (limited to 'plugins/security-guidance/tests')
-rw-r--r--plugins/security-guidance/tests/conftest.py3
-rw-r--r--plugins/security-guidance/tests/test_portable_output.py181
-rw-r--r--plugins/security-guidance/tests/test_prompt_untracked_snapshot.py169
-rw-r--r--plugins/security-guidance/tests/test_repo_resolution.py41
-rw-r--r--plugins/security-guidance/tests/test_state_file.py197
-rw-r--r--plugins/security-guidance/tests/test_user_config_dir.py98
6 files changed, 680 insertions, 9 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
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")
diff --git a/plugins/security-guidance/tests/test_prompt_untracked_snapshot.py b/plugins/security-guidance/tests/test_prompt_untracked_snapshot.py
new file mode 100644
index 00000000..be0fc1ee
--- /dev/null
+++ b/plugins/security-guidance/tests/test_prompt_untracked_snapshot.py
@@ -0,0 +1,169 @@
+import json
+import os
+import shutil
+
+import pytest
+
+from conftest import (
+ VULN_PY, edit_payload, make_repo, metrics_of, run_hook, stop_payload, ups_payload,
+)
+
+OFF_SWITCHES = [
+ pytest.param({"ENABLE_STOP_REVIEW": "0"}, id="stop-review-off"),
+ pytest.param({"ENABLE_CODE_SECURITY_REVIEW": "0"}, id="all-reviews-off"),
+]
+OLD = "import os\nos.system(cmd)\n"
+
+
+@pytest.fixture
+def on(hook_env, tmp_path):
+ """hook_env with the Stop review on, and a `git` first on PATH that
+ records each call before running it."""
+ shim = tmp_path / "bin"
+ shim.mkdir()
+ log = tmp_path / "git.log"
+ log.write_text("")
+ (shim / "git").write_text(
+ f'#!/bin/sh\nprintf \'%s\\n\' "$*" >> "{log}"\nexec "{shutil.which("git")}" "$@"\n')
+ (shim / "git").chmod(0o755)
+ env = {k: v for k, v in hook_env.items() if k != "CLAUDE_CODE_REMOTE_SESSION_ID"}
+ env.update(HOME=str(tmp_path), PATH=f"{shim}{os.pathsep}{hook_env['PATH']}",
+ GIT_CALLS=str(log))
+ return env
+
+
+def _listed_untracked(env):
+ with open(env["GIT_CALLS"]) as f:
+ return any("ls-files --others" in line for line in f)
+
+
+def _state(env, session_id="s1"):
+ path = os.path.join(env["SECURITY_WARNINGS_STATE_DIR"],
+ f"security_warnings_state_{session_id}.json")
+ with open(path) as f:
+ return json.load(f)
+
+
+def _repo(tmp_path):
+ repo = make_repo(tmp_path / "repo", {"app.py": OLD})
+ (repo / "notes.txt").write_text("scratch\n")
+ return repo
+
+
+def _write_payload(cwd, file_path, content, session_id="s1"):
+ return {
+ "session_id": session_id,
+ "hook_event_name": "PostToolUse",
+ "tool_name": "Write",
+ "tool_input": {"file_path": str(file_path), "content": content},
+ "tool_response": {},
+ "cwd": str(cwd),
+ }
+
+
+def _reviewed(stub_api):
+ n = len(stub_api.calls)
+ del stub_api.calls[:]
+ return n > 0
+
+
+pytestmark = pytest.mark.skipif(os.name == "nt", reason="the git recorder is a sh script")
+
+
+class TestPrompt:
+ def test_review_on_takes_the_snapshot(self, tmp_path, on):
+ repo = _repo(tmp_path)
+ rc, _, _ = run_hook(ups_payload(repo), on)
+ assert rc == 0
+ assert _listed_untracked(on)
+ assert list(_state(on)["untracked_at_baseline"]) == ["notes.txt"]
+
+ @pytest.mark.parametrize("off", OFF_SWITCHES)
+ def test_review_off_does_not_list_the_worktree(self, tmp_path, on, off):
+ repo = _repo(tmp_path)
+ rc, _, _ = run_hook(ups_payload(repo), {**on, **off})
+ assert rc == 0
+ assert not _listed_untracked(on)
+ assert "untracked_at_baseline" not in _state(on)
+
+ @pytest.mark.parametrize("off", OFF_SWITCHES)
+ def test_review_off_write_filter_still_knows_what_was_there(self, tmp_path, on, off):
+ """The stash baseline is still captured: a full-file Write that keeps
+ a risky call from before the prompt is not reported as new."""
+ repo = _repo(tmp_path)
+ env = {**on, **off, "CLAUDE_PROJECT_DIR": str(repo)}
+ (repo / "app.py").write_text(OLD + "# edited before the prompt\n")
+ run_hook(ups_payload(repo), env)
+
+ _rc, out, _ = run_hook(_write_payload(repo, repo / "app.py", OLD + "print('x')\n"), env)
+ assert "additionalContext" not in out
+ _rc, out, _ = run_hook(_write_payload(
+ repo, repo / "app.py", OLD + "import pickle\npickle.loads(data)\n"), env)
+ assert "pickle" in out and "os.system" not in out
+
+ def test_review_off_uses_the_repo_hint_without_listing(self, tmp_path, on):
+ repo = _repo(tmp_path)
+ outside = tmp_path / "not-a-repo"
+ outside.mkdir()
+ (repo / "app.py").write_text(VULN_PY)
+ # The hint a commit review that resolved the repo leaves behind.
+ with open(os.path.join(on["SECURITY_WARNINGS_STATE_DIR"],
+ "security_warnings_state_s1.json"), "w") as f:
+ json.dump({"shown_warnings": [], "repo_root_hint": str(repo)}, f)
+ rc, _, _ = run_hook(ups_payload(outside), {**on, "ENABLE_STOP_REVIEW": "0"})
+ assert rc == 0
+ assert not _listed_untracked(on)
+ assert _state(on).get("baseline_sha")
+
+ def test_review_off_drops_the_snapshot_of_an_older_baseline(self, tmp_path, on):
+ repo = _repo(tmp_path)
+ run_hook(ups_payload(repo), on)
+ assert "untracked_at_baseline" in _state(on)
+ run_hook(ups_payload(repo), {**on, "ENABLE_STOP_REVIEW": "0"})
+ assert "untracked_at_baseline" not in _state(on)
+
+
+class TestTurn:
+ def test_review_on_reviews_only_new_untracked_files(self, tmp_path, on, stub_api):
+ repo = _repo(tmp_path)
+ (repo / "old_vuln.py").write_text(VULN_PY)
+ run_hook(ups_payload(repo), on)
+ _rc, out, _ = run_hook(stop_payload(repo), on)
+ assert metrics_of(out)["skip_reason"] == 9 # empty review set
+ assert not _reviewed(stub_api)
+
+ run_hook(ups_payload(repo), on)
+ (repo / "new_vuln.py").write_text(VULN_PY)
+ _rc, out, _ = run_hook(stop_payload(repo), on)
+ assert metrics_of(out)["files_reviewed"] == 1
+ assert _reviewed(stub_api)
+
+ @pytest.mark.parametrize("off", OFF_SWITCHES)
+ def test_review_switched_back_on_at_the_next_prompt(self, tmp_path, on, stub_api, off):
+ """Old untracked files are not reviewed as this turn's work."""
+ repo = _repo(tmp_path)
+ (repo / "old_vuln.py").write_text(VULN_PY)
+ run_hook(ups_payload(repo), {**on, **off})
+ run_hook(stop_payload(repo), {**on, **off})
+
+ run_hook(ups_payload(repo), on)
+ _rc, out, _ = run_hook(stop_payload(repo), on)
+ assert metrics_of(out)["skip_reason"] == 9
+ assert not _reviewed(stub_api)
+
+ def test_review_switched_back_on_after_an_interrupted_turn(self, tmp_path, on, stub_api):
+ """The interrupted turn's baseline is kept, so its edit is reviewed,
+ and the old untracked file beside it is not."""
+ off = {**on, "ENABLE_STOP_REVIEW": "0"}
+ repo = _repo(tmp_path)
+ (repo / "old_vuln.py").write_text(VULN_PY)
+ run_hook(ups_payload(repo), off)
+ (repo / "app.py").write_text(VULN_PY)
+ run_hook(edit_payload(repo, repo / "app.py"), off) # no Stop: interrupted
+ baseline = _state(on)["baseline_sha"]
+
+ run_hook(ups_payload(repo), on)
+ assert _state(on)["baseline_sha"] == baseline
+ _rc, out, _ = run_hook(stop_payload(repo), on)
+ assert metrics_of(out)["files_reviewed"] == 1
+ assert _reviewed(stub_api)
diff --git a/plugins/security-guidance/tests/test_repo_resolution.py b/plugins/security-guidance/tests/test_repo_resolution.py
index 8bcf24b9..30c94a7c 100644
--- a/plugins/security-guidance/tests/test_repo_resolution.py
+++ b/plugins/security-guidance/tests/test_repo_resolution.py
@@ -191,6 +191,10 @@ class TestRegexes:
"git -c core.editor=true -C sub commit --amend",
"git --git-dir=x/.git --work-tree=x commit -m x",
"git --git-dir x/.git commit -m x",
+ "git --no-pager commit -m x",
+ "git -p --no-optional-locks -c user.name=x --bare commit -m x",
+ 'git -c user.name="First Last" -c user.email=a@b.c commit -S -m x',
+ "git --git-dir='a b/.git' --namespace ns commit -m x",
"cd sub && git commit -m x",
"gt create -m x",
])
@@ -199,16 +203,29 @@ class TestRegexes:
@pytest.mark.parametrize("cmd", [
"git push", "git -C sub push origin main", 'git -C "a b" push',
- "git --work-tree x push -u origin HEAD", "gt submit",
+ "git --work-tree x push -u origin HEAD", "git --no-pager push",
+ 'git -c http.extraHeader="X-A: b" push', "git --config-env http.extraheader=TOK push", "gt submit",
])
def test_push_re(self, cmd):
assert hook._GIT_PUSH_RE.search(cmd)
- @pytest.mark.parametrize("cmd", ["git status", "git log --oneline", "echo commit"])
+ @pytest.mark.parametrize("cmd", ["git status", "git log --oneline", "echo commit",
+ "git commit-graph write --reachable", "git commit-tree HEAD^{tree}",
+ "git log --grep commit", "git stash push",
+ "git log --oneline commit", "git --no-pager log --grep commit",
+ "git merge --no-commit topic", "git --git-dir commit status",
+ "git --namespace commit log", "git --help commit",
+ 'git -c user.name="commit status'])
def test_commit_re_negative(self, cmd):
assert not hook._GIT_COMMIT_RE.search(cmd)
- @pytest.mark.parametrize("unit", ['-c "a"', "-c 'a'", "--no-a=b", "--a=b=c=d", "--git-dir x"])
+ @pytest.mark.parametrize("cmd", ["git stash push", "git log --grep push", "git commit-graph write",
+ "git --no-pager stash push", "git --no-pager log push"])
+ def test_push_re_negative(self, cmd):
+ assert not hook._GIT_PUSH_RE.search(cmd)
+
+ @pytest.mark.parametrize("unit", ['-c "a"', "-c 'a'", "--no-a=b", "--a=b=c=d", "--git-dir x",
+ "--no-pager", "-p", '-c a="b c"', "--namespace x"])
@pytest.mark.parametrize("regex,verb", [("_GIT_COMMIT_RE", "commit"), ("_GIT_PUSH_RE", "push")])
def test_global_option_prefix_is_linear(self, regex, verb, unit):
cre = getattr(hook, regex)
@@ -228,11 +245,19 @@ class TestHooksJson:
assert stop["command"].endswith('security_reminder_hook.py"')
assert stop["asyncRewake"] is True
bash = [g for g in cfg["hooks"]["PostToolUse"] if g.get("matcher") == "Bash"][0]
- ifs = {h.get("if") for h in bash["hooks"]}
- assert {"Bash(git commit:*)", "Bash(git push:*)", "Bash(git -C * commit *)",
- "Bash(git -C * push*)", "Bash(gt create:*)", "Bash(gt modify:*)",
- "Bash(gt submit:*)"} <= ifs
-
+ # One entry per kind, not per spelling: when Claude Code cannot parse
+ # a command it runs every entry, so each extra entry is one more process.
+ assert [h.get("if") for h in bash["hooks"]] == [
+ "Bash(git*commit*)", "Bash(git*push*)", "Bash(gt *)"]
+ assert all(h["asyncRewake"] is True and h["rewakeMessage"] for h in bash["hooks"])
+
+ @pytest.mark.parametrize("cmd", ["git stash push", "git commit-graph write --reachable",
+ "git log --grep commit", "gt log"])
+ def test_other_commands_the_if_patterns_let_through_do_nothing(self, workspace, hook_env, stub_api, cmd):
+ ws, repo = workspace
+ commit_file(repo, "app.py", VULN_PY)
+ rc, so, se = run_hook(bash_payload(repo, cmd, ""), hook_env)
+ assert rc == 0 and so.strip() == "" and not stub_api.calls
def _read_state(env):
diff --git a/plugins/security-guidance/tests/test_state_file.py b/plugins/security-guidance/tests/test_state_file.py
new file mode 100644
index 00000000..0d3a56b0
--- /dev/null
+++ b/plugins/security-guidance/tests/test_state_file.py
@@ -0,0 +1,197 @@
+import json
+import os
+import signal
+import subprocess
+import sys
+import time
+
+import pytest
+
+from conftest import HOOKS_DIR, make_repo, metrics_of, run_hook, stop_payload, ups_payload
+
+import session_state as ss
+
+
+@pytest.fixture
+def state_dir(tmp_path, monkeypatch):
+ d = tmp_path / "state"
+ d.mkdir()
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(d))
+ monkeypatch.delenv("CLAUDE_CODE_REMOTE_SESSION_ID", raising=False)
+ # Keep the legacy lock-file sweep and the debug log out of the real home.
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr(ss, "debug_log", lambda _msg: None)
+ return d
+
+
+def _seed(session_id="s1"):
+ ss.with_locked_state(session_id, lambda st: st.update(
+ baseline_sha="a" * 40, touched_paths=["x.py"],
+ untracked_at_baseline={f"dir/file_{i:05d}.py": i for i in range(1500)}))
+
+
+def _on_disk(state_dir, session_id="s1"):
+ return json.loads((state_dir / f"security_warnings_state_{session_id}.json").read_text())
+
+
+def _leftovers(state_dir):
+ return sorted(p.name for p in state_dir.iterdir() if p.name.endswith(".tmp"))
+
+
+_MARK_ONE = (
+ "import sys; sys.path.insert(0, sys.argv[1]); import session_state as s; "
+ "s.with_locked_state('s1', lambda st: st['shown_warnings'].append(sys.argv[2]))"
+)
+
+# A save that dies half-way through writing, as a hook killed on timeout does.
+_KILLED_MID_SAVE = """
+import json, os, signal, sys
+sys.path.insert(0, sys.argv[1])
+import session_state as s
+def dump(obj, f, **kw):
+ data = json.dumps(obj)
+ f.write(data[:len(data) // 2]); f.flush()
+ os.kill(os.getpid(), signal.SIGKILL)
+s.json.dump = dump
+s.with_locked_state('s1', lambda st: st['touched_paths'].append('y.py'))
+"""
+
+
+@pytest.mark.skipif(os.name == "nt", reason="rename into place is not used on Windows")
+class TestSaveIsAtomic:
+ def test_a_save_killed_part_way_keeps_the_previous_state(self, state_dir):
+ _seed()
+ r = subprocess.run([sys.executable, "-c", _KILLED_MID_SAVE, str(HOOKS_DIR)],
+ env=dict(os.environ))
+ assert r.returncode == -signal.SIGKILL
+ state = ss.load_state("s1")
+ assert state["baseline_sha"] == "a" * 40
+ assert state["touched_paths"] == ["x.py"]
+ assert len(state["untracked_at_baseline"]) == 1500
+ assert "state_resets" not in state
+
+ def test_no_temporary_file_is_left_behind(self, state_dir):
+ _seed()
+ ss.with_locked_state("s1", lambda st: st["touched_paths"].append("y.py"))
+ assert _on_disk(state_dir)["touched_paths"] == ["x.py", "y.py"]
+ assert _leftovers(state_dir) == []
+
+ def test_state_that_cannot_be_written_leaves_the_file_alone(self, state_dir):
+ _seed()
+ with pytest.raises(TypeError):
+ ss.save_state("s1", {"shown_warnings": [], "bad": object()})
+ assert _on_disk(state_dir)["baseline_sha"] == "a" * 40
+ assert _leftovers(state_dir) == []
+
+ def test_writes_in_place_where_the_directory_refuses_a_rename(self, state_dir, monkeypatch):
+ _seed()
+
+ def refuse(_src, _dst):
+ raise PermissionError("rename refused")
+ monkeypatch.setattr(ss.os, "replace", refuse)
+ ss.with_locked_state("s1", lambda st: st["touched_paths"].append("y.py"))
+ assert _on_disk(state_dir)["touched_paths"] == ["x.py", "y.py"]
+ assert _leftovers(state_dir) == []
+
+ def test_a_full_disk_leaves_the_previous_state(self, state_dir, monkeypatch):
+ _seed()
+
+ def full(_obj, f, **_kw):
+ f.write('{"shown_warn')
+ raise OSError(28, "No space left on device")
+ monkeypatch.setattr(ss.json, "dump", full)
+ ss.save_state("s1", {"shown_warnings": []})
+ assert _on_disk(state_dir)["baseline_sha"] == "a" * 40
+ assert _leftovers(state_dir) == []
+
+ def test_in_place_where_rename_is_not_used(self, state_dir, monkeypatch):
+ monkeypatch.setattr(ss, "_RENAME_INTO_PLACE", False)
+ monkeypatch.setattr(ss.os, "replace", lambda *_a: pytest.fail("renamed"))
+ _seed()
+ assert _on_disk(state_dir)["touched_paths"] == ["x.py"]
+
+
+@pytest.mark.skipif(ss.fcntl is None, reason="needs file locking")
+def test_concurrent_writers_all_land(state_dir):
+ """Eight hooks marking one warning each at the same moment keep all eight."""
+ for _round in range(5):
+ (state_dir / "security_warnings_state_s1.json").unlink(missing_ok=True)
+ procs = [subprocess.Popen([sys.executable, "-c", _MARK_ONE, str(HOOKS_DIR), f"k{i}"],
+ env=dict(os.environ)) for i in range(8)]
+ assert [p.wait() for p in procs] == [0] * 8
+ assert sorted(_on_disk(state_dir)["shown_warnings"]) == [f"k{i}" for i in range(8)]
+ assert _leftovers(state_dir) == []
+
+
+class TestStateLossIsCounted:
+ def test_missing_file_is_a_fresh_state(self, state_dir):
+ assert ss.load_state("s1") == {"shown_warnings": []}
+
+ @pytest.mark.parametrize("content", [
+ b"", b'{"baseline_sha": "abc", "touched_pa', b"42", b'{"baseline_sha": "\xff\xfe"}'])
+ def test_unreadable_file_is_counted(self, state_dir, content):
+ (state_dir / "security_warnings_state_s1.json").write_bytes(content)
+ assert ss.load_state("s1") == {"shown_warnings": [], "state_resets": 1}
+
+ def test_overwriting_another_hooks_save_is_counted_without_locking(
+ self, state_dir, monkeypatch):
+ monkeypatch.setattr(ss, "fcntl", None)
+ _seed()
+ assert "state_overwrites" not in _on_disk(state_dir)
+
+ def slow_hook(state):
+ # Another hook saves while this one is between its read and write.
+ time.sleep(0.01)
+ ss.save_state("s1", {**state, "touched_paths": ["x.py", "other.py"]})
+ state["shown_warnings"].append("k")
+ ss.with_locked_state("s1", slow_hook)
+ after = _on_disk(state_dir)
+ assert after["state_overwrites"] == 1
+ assert after["touched_paths"] == ["x.py"] # the other hook's save was lost
+
+ def test_a_concurrent_save_of_the_same_state_is_not_counted(self, state_dir, monkeypatch):
+ monkeypatch.setattr(ss, "fcntl", None)
+ _seed()
+
+ def reader(state):
+ ss.save_state("s1", dict(state)) # another hook that only read
+ return state["baseline_sha"]
+ assert ss.with_locked_state("s1", reader) == "a" * 40
+ assert "state_overwrites" not in _on_disk(state_dir)
+
+ def test_stop_reports_the_counts_once(self, tmp_path, hook_env):
+ repo = make_repo(tmp_path / "repo")
+ hook_env = {k: v for k, v in hook_env.items() if k != "CLAUDE_CODE_REMOTE_SESSION_ID"}
+ state_file = os.path.join(hook_env["SECURITY_WARNINGS_STATE_DIR"],
+ "security_warnings_state_s1.json")
+ run_hook(ups_payload(repo), hook_env)
+ _rc, stdout, _err = run_hook(stop_payload(repo), hook_env)
+ m = metrics_of(stdout)
+ assert "state_resets" not in m and "state_overwrites" not in m
+
+ with open(state_file, "w") as f:
+ f.write('{"baseline_sha": "abc", "touched_pa')
+ run_hook(ups_payload(repo), hook_env)
+ with open(state_file) as f:
+ state = json.load(f)
+ state["state_overwrites"] = 3
+ with open(state_file, "w") as f:
+ json.dump(state, f)
+ _rc, stdout, _err = run_hook(stop_payload(repo), hook_env)
+ m = metrics_of(stdout)
+ assert (m["state_resets"], m["state_overwrites"]) == (1, 3)
+
+ _rc, stdout, _err = run_hook(stop_payload(repo), hook_env)
+ m = metrics_of(stdout)
+ assert "state_resets" not in m and "state_overwrites" not in m
+
+
+def test_cleanup_removes_old_temporary_files(state_dir):
+ old = state_dir / "security_warnings_state_s1.json.a1b2c3.tmp"
+ new = state_dir / "security_warnings_state_s2.json.a1b2c3.tmp"
+ old.write_text("{}")
+ new.write_text("{}")
+ long_ago = time.time() - 31 * 24 * 60 * 60
+ os.utime(old, (long_ago, long_ago))
+ ss.cleanup_old_state_files()
+ assert not old.exists() and new.exists()
diff --git a/plugins/security-guidance/tests/test_user_config_dir.py b/plugins/security-guidance/tests/test_user_config_dir.py
new file mode 100644
index 00000000..7c8a1245
--- /dev/null
+++ b/plugins/security-guidance/tests/test_user_config_dir.py
@@ -0,0 +1,98 @@
+"""User-level claude-security-guidance.md and security-patterns files are
+found in the directory CLAUDE_CONFIG_DIR names, as well as in ~/.claude."""
+import json
+import os
+
+import pytest
+
+import extensibility
+
+MARKER = "MARKER_POLICY_LINE"
+PATTERNS = {"patterns": [{"rule_name": "marker_rule", "substrings": ["x"], "reminder": "r"}]}
+
+
+@pytest.fixture
+def home(tmp_path, monkeypatch):
+ h = tmp_path / "home"
+ h.mkdir()
+ monkeypatch.setenv("HOME", str(h))
+ monkeypatch.setenv("USERPROFILE", str(h))
+ monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
+ return h
+
+
+def write_user_files(d, marker=MARKER, rule="marker_rule"):
+ d.mkdir(parents=True, exist_ok=True)
+ (d / "claude-security-guidance.md").write_text(f"- {marker}\n")
+ patterns = {"patterns": [dict(PATTERNS["patterns"][0], rule_name=rule)]}
+ (d / "security-patterns.json").write_text(json.dumps(patterns))
+
+
+def load():
+ extensibility.load_for_session(None)
+ return extensibility.guidance_block(), [r["ruleName"] for r in extensibility.user_patterns()]
+
+
+def test_files_in_configured_dir_are_loaded(home, monkeypatch):
+ cfg = home / ".claude-work"
+ write_user_files(cfg)
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(cfg))
+ guidance, rules = load()
+ assert MARKER in guidance
+ assert rules == ["user:marker_rule"]
+
+
+def test_default_dir_still_loaded_when_config_dir_is_set(home, monkeypatch):
+ write_user_files(home / ".claude")
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(home / ".claude-work"))
+ guidance, rules = load()
+ assert MARKER in guidance
+ assert rules == ["user:marker_rule"]
+
+
+def test_both_dirs_loaded_default_first(home, monkeypatch):
+ write_user_files(home / ".claude", marker="FROM_DEFAULT", rule="default_rule")
+ cfg = home / ".claude-work"
+ write_user_files(cfg, marker="FROM_CONFIGURED", rule="configured_rule")
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(cfg))
+ guidance, rules = load()
+ assert guidance.index("FROM_DEFAULT") < guidance.index("FROM_CONFIGURED")
+ assert rules == ["user:default_rule", "user:configured_rule"]
+
+
+@pytest.mark.parametrize("spelling", ["{home}/.claude", "{home}/.claude/", "~/.claude", "{home}/link"])
+def test_config_dir_naming_the_default_dir_is_read_once(home, monkeypatch, spelling):
+ write_user_files(home / ".claude")
+ os.symlink(home / ".claude", home / "link")
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", spelling.format(home=home))
+ guidance, rules = load()
+ assert guidance.count(MARKER) == 1
+ assert rules == ["user:marker_rule"]
+
+
+@pytest.mark.parametrize("value", ["", " "])
+def test_empty_config_dir_is_not_set(home, monkeypatch, value):
+ write_user_files(home / ".claude")
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", value)
+ assert extensibility._user_config_dirs() == [str(home / ".claude")]
+ guidance, rules = load()
+ assert guidance.count(MARKER) == 1
+
+
+def test_tilde_in_config_dir_is_expanded(home, monkeypatch):
+ write_user_files(home / ".claude-work")
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", "~/.claude-work")
+ guidance, _ = load()
+ assert MARKER in guidance
+
+
+def test_project_files_unchanged(home, monkeypatch, tmp_path):
+ cfg = home / ".claude-work"
+ write_user_files(cfg, marker="FROM_USER")
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(cfg))
+ proj = tmp_path / "proj"
+ write_user_files(proj / ".claude", marker="FROM_PROJECT", rule="project_rule")
+ extensibility.load_for_session(str(proj))
+ guidance = extensibility.guidance_block()
+ assert guidance.index("FROM_USER") < guidance.index("FROM_PROJECT")
+ assert [r["ruleName"] for r in extensibility.user_patterns()] == ["user:marker_rule", "user:project_rule"]