summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/tests
diff options
context:
space:
mode:
authorMohamed Hegazy <8000722+mhegazy@users.noreply.github.com>2026-11-09 17:01:09 -0800
committerGitHub <noreply@github.com>2026-11-09 17:01:09 -0800
commit4e39a22ba3e8139c20992ea534fec644c2ef0cd1 (patch)
tree91c7dda10972ab95c257c66e313c224aee5dfb9f /plugins/security-guidance/tests
parentea686bae367e20a4092b2fd4327ffd299bb60f24 (diff)
parent9ea2fbca5b6c62113e011a8f183bb336a26f9883 (diff)
Merge pull request #7030 from anthropics/mhegazy/sg-custom-rule-counts
security-guidance: count how custom rules are written
Diffstat (limited to 'plugins/security-guidance/tests')
-rw-r--r--plugins/security-guidance/tests/test_custom_rule_stats.py180
-rw-r--r--plugins/security-guidance/tests/test_repo_resolution.py17
-rw-r--r--plugins/security-guidance/tests/test_turn_commits_metric.py11
3 files changed, 196 insertions, 12 deletions
diff --git a/plugins/security-guidance/tests/test_custom_rule_stats.py b/plugins/security-guidance/tests/test_custom_rule_stats.py
new file mode 100644
index 00000000..fcad3130
--- /dev/null
+++ b/plugins/security-guidance/tests/test_custom_rule_stats.py
@@ -0,0 +1,180 @@
+"""Counts about custom rules on the Stop row. They change no rule's outcome."""
+import json
+import os
+
+import pytest
+
+import extensibility
+
+from conftest import edit_payload, git, metrics_of, run_hook, stop_payload, ups_payload
+
+GLOBS = ["*.ts", "**/*.ts", "**/src/**", "**/src/**/*.ts", "src/**", "src/*.ts", "src/**/*.ts", "/src/**",
+ "./src/**", "src", "*.{ts,js}", "config.ts", "[!t]*.ts", "**/[!t]*.ts", "src/?.ts"]
+FILES = ["config.ts", "t.ts", "src/a.ts", "src/t.ts", "src/lib/a.ts", "src/lib/deep/t.ts", "other/a.ts"]
+
+
+@pytest.fixture(autouse=True)
+def _home_without_user_rules(tmp_path, monkeypatch):
+ """A home directory without the user's own rules and guidance."""
+ home = tmp_path / "home"
+ home.mkdir()
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("USERPROFILE", str(home))
+ monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
+ monkeypatch.setattr(extensibility, "_guidance_block", "")
+ monkeypatch.setattr(extensibility, "_user_patterns", [])
+
+
+@pytest.mark.parametrize("glob", GLOBS)
+def test_the_wider_reading_never_loses_an_include(glob, tmp_path):
+ for f in FILES:
+ path = str(tmp_path.joinpath(*f.split("/")))
+ if extensibility._glob_match(path.lstrip("/"), (glob,), ()):
+ assert extensibility._wider_glob_match(path, (f,), (glob,), ())
+
+
+@pytest.mark.parametrize("glob,f,now,wider", [
+ ("src/**", "src/a.ts", False, True),
+ ("src/*.ts", "src/lib/a.ts", False, True), # `*` still crosses `/`
+ ("src/**/*.ts", "src/a.ts", False, True),
+ ("**/src/**/*.ts", "src/a.ts", False, True),
+ ("**/src/**/*.ts", "src/lib/a.ts", True, True),
+ ("/src/**", "src/a.ts", False, True),
+ ("*.ts", "src/lib/deep/t.ts", True, True),
+ ("src/**", "other/a.ts", False, False),
+ ("*.{ts,js}", "config.ts", False, False),
+])
+def test_readings(glob, f, now, wider, tmp_path):
+ path = str(tmp_path.joinpath(*f.split("/")))
+ assert extensibility._glob_match(path.lstrip("/"), (glob,), ()) is now
+ assert extensibility._wider_glob_match(path, (f,), (glob,), ()) is wider
+
+
+def _rules(repo, *rules, name="security-patterns.json"):
+ (repo / ".claude").mkdir(exist_ok=True)
+ (repo / ".claude" / name).write_text(json.dumps({"patterns": [
+ dict({"rule_name": f"r{i}", "substrings": ["NEEDLE("], "reminder": "x"}, **r)
+ for i, r in enumerate(rules)]}))
+ git(repo, "add", "-A")
+ git(repo, "commit", "-q", "-m", "rules")
+
+
+def _stats(repo, env, files, cwd=None):
+ env = {**env, "CLAUDE_PROJECT_DIR": str(repo)}
+ run_hook(ups_payload(repo), env)
+ outs = []
+ for name in files:
+ p = repo / name
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text("NEEDLE(1)\n")
+ outs.append(run_hook(edit_payload(cwd or repo, p, "NEEDLE(1)\n"), env)[1])
+ m = metrics_of(run_hook(stop_payload(repo), env)[1])
+ return {k: v for k, v in m.items() if k.startswith("cr_")}, outs
+
+
+def test_rules_that_would_start_to_apply(env, workspace):
+ _, repo = workspace
+ _rules(repo, {"paths": ["src/**"]}, {"paths": ["*.ts"]})
+ stats, outs = _stats(repo, env, ["src/a.ts", "src/b.ts"])
+ assert stats == {"cr_rules": 2, "cr_shapes": 1, "cr_gain": 2}
+ # The rule that does not apply today still does not.
+ assert all("additionalContext" in o for o in outs)
+
+
+def test_excludes_that_would_start_to_apply(env, workspace):
+ _, repo = workspace
+ _rules(repo, {"exclude_paths": ["src/**"]})
+ stats, outs = _stats(repo, env, ["src/a.ts"])
+ assert stats == {"cr_rules": 1, "cr_shapes": 2, "cr_loss": 1}
+ assert "additionalContext" in outs[0]
+
+
+def test_no_extra_save_of_the_state(env, workspace, monkeypatch, tmp_path):
+ import diffstate
+ import session_state
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "st"))
+ saves = []
+ real = session_state.save_state
+ monkeypatch.setattr(session_state, "save_state", lambda *a: saves.append(a) or real(*a))
+ diffstate.record_touched_path("s9", "/a.ts", {"cr_rules": 1, "cr_gain": 1})
+ assert len(saves) == 1
+ assert saves[0][1]["custom_rules"] == {"cr_rules": 1, "cr_gain": 1}
+ assert saves[0][1]["touched_paths"] == ["/a.ts"]
+
+
+def test_worktree_outside_the_project(env, workspace, tmp_path):
+ _, repo = workspace
+ _rules(repo, {"paths": ["src/**"]})
+ tree = tmp_path / "tree"
+ git(repo, "worktree", "add", "-q", "-b", "side", str(tree))
+ extensibility.load_for_session(str(tree))
+ stats = extensibility.edit_stats(str(tree / "src" / "a.ts"), str(tree), str(repo))
+ assert stats["cr_gain"] == 1
+
+
+def test_they_come_after_the_review_keys(env, workspace):
+ _, repo = workspace
+ _rules(repo, {"paths": ["src/**"]})
+ e = {**env, "CLAUDE_PROJECT_DIR": str(repo)}
+ run_hook(ups_payload(repo), e)
+ run_hook(edit_payload(repo, repo / "src" / "a.ts", "NEEDLE("), e)
+ keys = list(metrics_of(run_hook(stop_payload(repo), e)[1]))
+ assert "cr_rules" in keys
+ first = min(i for i, k in enumerate(keys) if k.startswith("cr_"))
+ assert not [k for k in keys[first:] if not k.startswith(("cr_", "launcher"))]
+
+
+@pytest.mark.parametrize("rule,bits", [
+ ({"paths": ["**/src/**/*.ts"]}, 4),
+ ({"paths": ["*.{ts,js}"]}, 8),
+ ({"paths": ["/src/**"]}, 16),
+ ({"regex": "(a+)+$"}, 32),
+ ({"regex": "(a+){2,}$"}, 64),
+ ({"regex": "(a+){20}$"}, 64),
+ ({"regex": "([A-Za-z0-9+/]{4}){10,}"}, 0),
+])
+def test_shapes(rule, bits, env, workspace):
+ _, repo = workspace
+ _rules(repo, rule)
+ stats, _ = _stats(repo, env, ["other/a.ts"])
+ assert stats.get("cr_shapes", 0) == bits
+
+
+def test_a_slow_regex_is_timed(env, workspace):
+ _, repo = workspace
+ _rules(repo, {"substrings": [], "regex": "(a+){2,}$"})
+ env = {**env, "CLAUDE_PROJECT_DIR": str(repo)}
+ run_hook(ups_payload(repo), env)
+ run_hook(edit_payload(repo, repo / "n.txt", "a" * 23 + "!"), env)
+ m = metrics_of(run_hook(stop_payload(repo), env)[1])
+ assert m["cr_slow_ms"] >= 100
+
+
+def test_no_custom_rules_no_keys(env, workspace):
+ _, repo = workspace
+ assert _stats(repo, env, ["src/a.ts"])[0] == {}
+
+
+def test_reported_once(env, workspace):
+ _, repo = workspace
+ _rules(repo, {"paths": ["src/**"]})
+ assert _stats(repo, env, ["src/a.ts"])[0]
+ m = metrics_of(run_hook(stop_payload(repo), env)[1])
+ assert not [k for k in m if k.startswith("cr_")]
+
+
+def test_a_subagent_stop_leaves_them_for_the_turn(env, workspace):
+ _, repo = workspace
+ _rules(repo, {"paths": ["src/**"]})
+ e = {**env, "CLAUDE_PROJECT_DIR": str(repo)}
+ run_hook(ups_payload(repo), e)
+ run_hook(edit_payload(repo, repo / "src" / "a.ts", "NEEDLE("), e)
+ run_hook(stop_payload(repo, event="SubagentStop"), e)
+ m = metrics_of(run_hook(stop_payload(repo), e)[1])
+ assert m["cr_gain"] == 1
+
+
+def test_wrong_kind_in_state_does_not_break_the_hook(env, workspace):
+ _, repo = workspace
+ _rules(repo, {"paths": [5]}, {"paths": ["src/**"]})
+ assert _stats(repo, env, ["src/a.ts"])[0]["cr_rules"] == 2
diff --git a/plugins/security-guidance/tests/test_repo_resolution.py b/plugins/security-guidance/tests/test_repo_resolution.py
index 30c94a7c..bd1840f4 100644
--- a/plugins/security-guidance/tests/test_repo_resolution.py
+++ b/plugins/security-guidance/tests/test_repo_resolution.py
@@ -261,20 +261,15 @@ class TestHooksJson:
def _read_state(env):
+ # The review model cache is JSON in this directory too.
d = env["SECURITY_WARNINGS_STATE_DIR"]
- files = [e.path for e in os.scandir(d) if e.name.endswith(".json")]
- assert files, os.listdir(d)
+ files = [e.path for e in os.scandir(d)
+ if e.name.startswith("security_warnings_state_") and e.name.endswith(".json")]
+ assert len(files) == 1, os.listdir(d)
with open(files[0]) as f:
return json.load(f)
-def _read_state_or_empty(env):
- d = env["SECURITY_WARNINGS_STATE_DIR"]
- if not any(e.name.endswith(".json") for e in os.scandir(d)):
- return {}
- return _read_state(env)
-
-
class TestCommitReview:
def test_cwd_is_repo_unchanged(self, workspace, hook_env, stub_api):
ws, repo = workspace
@@ -334,7 +329,7 @@ class TestCommitReview:
m = metrics_of(so)
assert m.get("skip_reason") is None, m
assert m["repo_resolution"] == rr.RES_SHA_SCAN and m["files_reviewed"] == 1
- assert "repo_root_hint" not in _read_state_or_empty(hook_env)
+ assert "repo_root_hint" not in _read_state(hook_env)
def test_workspace_cwd_sha_scan_via_project_dir(self, workspace, hook_env, tmp_path):
ws, repo = workspace
@@ -429,7 +424,7 @@ class TestPushSweep:
m = metrics_of(so)
assert m["push_sweep"] is True and m["repo_resolution"] == rr.RES_SHA_SCAN, m
assert m.get("skip_reason") != 26
- assert "repo_root_hint" not in _read_state_or_empty(hook_env)
+ assert "repo_root_hint" not in _read_state(hook_env)
def test_cwd_is_repo_dash_C_other_repo(self, workspace, hook_env, tmp_path):
ws, repo = workspace
diff --git a/plugins/security-guidance/tests/test_turn_commits_metric.py b/plugins/security-guidance/tests/test_turn_commits_metric.py
index fd74b082..cf3dc99a 100644
--- a/plugins/security-guidance/tests/test_turn_commits_metric.py
+++ b/plugins/security-guidance/tests/test_turn_commits_metric.py
@@ -25,6 +25,16 @@ def _session_id_from_the_payload(monkeypatch):
monkeypatch.delenv("CLAUDE_CODE_REMOTE_SESSION_ID", raising=False)
+@pytest.fixture(autouse=True)
+def _home_without_user_rules(tmp_path, monkeypatch):
+ """A home directory without the user's own rules, whose keys could fill the row."""
+ home = tmp_path / "home"
+ home.mkdir()
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("USERPROFILE", str(home))
+ monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
+
+
def session_state_file(hook_env):
[path] = [p for p in Path(hook_env["SECURITY_WARNINGS_STATE_DIR"]).glob("security_warnings_state_*.json")]
return path
@@ -358,7 +368,6 @@ def test_parts_are_capped(tmp_path, monkeypatch):
def test_old_commit_records_are_removed(tmp_path, monkeypatch):
monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path))
- monkeypatch.setenv("HOME", str(tmp_path))
diffstate.note_seen_commits("s1", ["abc1234"])
diffstate.note_seen_commits("s2", ["abc1234"])
os.utime(session_state.get_commit_log_file("s1"), (1, 1))