diff options
| author | Claude <noreply@anthropic.com> | 2026-11-10 02:52:07 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-11-10 02:52:07 +0000 |
| commit | c8e3f6ff35367b0a9ad285ab5a4f3d72cbc0ded1 (patch) | |
| tree | cff3dda52092ca11bd8903cde9bc0dabece1f5e0 /plugins | |
| parent | dceb15d50832e6adf380bedc26dde03d251324b9 (diff) | |
security-guidance: custom rule globs can be relative to the projectmhegazy/sg-custom-rule-globs
Co-authored-by: mhegazy <mhegazy@anthropic.com>
Diffstat (limited to 'plugins')
4 files changed, 188 insertions, 27 deletions
diff --git a/plugins/security-guidance/hooks/extensibility.py b/plugins/security-guidance/hooks/extensibility.py index 10df6b79..5c83eb9e 100644 --- a/plugins/security-guidance/hooks/extensibility.py +++ b/plugins/security-guidance/hooks/extensibility.py @@ -40,6 +40,7 @@ Trust model: """ import fnmatch +import functools import json import os import re @@ -64,6 +65,9 @@ _user_patterns: List[Dict[str, Any]] = [] _refused_regexes = 0 # Seconds the slowest custom regex took in this hook. Telemetry only. slowest_regex = 0.0 +# The folder a custom rule's globs are relative to: the project's own. +_match_roots: Tuple[Optional[str], ...] = () +_rels_cache: Dict[str, Tuple[str, ...]] = {} # ── public API ─────────────────────────────────────────────────────────────── @@ -75,8 +79,11 @@ def load_for_session(cwd: Optional[str]) -> None: Called from the hook's main() before dispatching. Failures are non-fatal — a malformed config file produces a debug_log entry, never a crash. """ - global _guidance_block, _user_patterns, _refused_regexes + global _guidance_block, _user_patterns, _refused_regexes, _match_roots _refused_regexes = 0 + env_project = os.environ.get("CLAUDE_PROJECT_DIR") or None + _match_roots = tuple(_project_dirs(cwd)[:1]) or ((env_project,) if env_project else ()) + _rels_cache.clear() try: _guidance_block = _wrap_guidance(_load_guidance(cwd)) except Exception as e: @@ -412,13 +419,28 @@ def _validate_pattern(entry: Any, source: str) -> Optional[Dict[str, Any]]: rule["_globs"] = (tuple(paths), tuple(exclude)) # read by edit_stats # Capture as defaults so the lambda doesn't share state across rules. rule["path_filter"] = ( - lambda p, _inc=tuple(paths), _exc=tuple(exclude): _glob_match(p, _inc, _exc) + lambda p, _inc=tuple(paths), _exc=tuple(exclude): _rule_covers(p, _inc, _exc) ) return rule +def _rule_covers(path: str, include: Tuple[str, ...], exclude: Tuple[str, ...]) -> bool: + """Whether a rule's globs let it apply to `path`, as check_patterns hands it + over (POSIX absolute paths without their leading `/`). Globs are read against + the full path and the path inside the project, and `**/` can match no folder.""" + full = path if os.path.isabs(path) else "/" + path + rels = _rels_cache.get(full) + if rels is None: + # As written, and resolved: a linked folder is matched by either name. + rels = _rels_cache[full] = tuple(dict.fromkeys( + r for d in _match_roots + for r in (_inside(d, full, resolve=False), _inside(d, full)) if r is not None)) + return _wider_glob_match(full, rels, include, exclude) + + def _glob_match(path: str, include: Tuple[str, ...], exclude: Tuple[str, ...]) -> bool: - """Match a path against include/exclude globs. ``**`` matches any depth.""" + """The reading of globs before _rule_covers, kept for edit_stats: full path + or file name only, and `**/` needs a folder.""" norm = path.replace(os.sep, "/") base = os.path.basename(norm) def _hit(globs: Tuple[str, ...]) -> bool: @@ -495,7 +517,8 @@ def _shape_bits(globs: Tuple[str, ...], plain: int) -> int: return bits -def _zero_depth_forms(glob: str) -> List[str]: +@functools.lru_cache(maxsize=512) +def _zero_depth_forms(glob: str) -> Tuple[str, ...]: """`glob`, and the globs left when each `**/` matches no folder.""" forms = [glob] for form in forms: @@ -503,21 +526,23 @@ def _zero_depth_forms(glob: str) -> List[str]: shorter = form[:m.start()] + form[m.end():] if shorter and shorter not in forms and len(forms) < 16: forms.append(shorter) - return forms + return tuple(forms) def _wider_glob_match(path: str, rels: Tuple[str, ...], include: Tuple[str, ...], exclude: Tuple[str, ...]) -> bool: - """What _glob_match would say if globs were also read against the path - inside the project (`rels`), and `**/` could match no folder.""" + """_glob_match, with globs also read against the path inside the project + (`rels`), and `**/` able to match no folder.""" norm = path.replace(os.sep, "/") names = [norm, norm.lstrip("/"), os.path.basename(norm)] - for rel in rels: - names += [rel, "/" + rel, "./" + rel] + inside = [n for rel in rels for n in (rel, "/" + rel, "./" + rel)] def _hit(globs: Tuple[str, ...]) -> bool: + # A glob with no folder in it is about the file name: `*` crosses `/`, + # so against the path inside the project `test*` would take in a tree. return any(fnmatch.fnmatch(n, f) for g in globs - for f in _zero_depth_forms(g) for n in names) + for f in _zero_depth_forms(g) + for n in (names + inside if "/" in g.replace("\\", "/") else names)) if include and not _hit(include): return False if exclude and _hit(exclude): @@ -525,11 +550,12 @@ def _wider_glob_match(path: str, rels: Tuple[str, ...], return True -def _inside(root: Optional[str], path: str) -> Optional[str]: +def _inside(root: Optional[str], path: str, resolve: bool = True) -> Optional[str]: if not root: return None + normal = os.path.realpath if resolve else os.path.normpath try: - rel = os.path.relpath(os.path.realpath(path), os.path.realpath(root)) + rel = os.path.relpath(normal(path), normal(root)) except (OSError, ValueError): return None if rel == os.pardir or rel.startswith(os.pardir + os.sep): @@ -537,16 +563,13 @@ def _inside(root: Optional[str], path: str) -> Optional[str]: return rel.replace(os.sep, "/") -def edit_stats(file_path: str, cwd: Optional[str], project_dir: Optional[str]) -> Dict[str, int]: - """Counts for one edit; empty for a user with no custom rules. - Telemetry only.""" +def edit_stats(file_path: str) -> Dict[str, int]: + """Counts for one edit; empty for a user with no custom rules. cr_gain and + cr_loss are rule and edit pairs that _rule_covers decides differently from + the older reading. Telemetry only.""" stats: Dict[str, int] = {} shapes = _SHAPE_REGEX_REFUSED if _refused_regexes else 0 gain = loss = 0 - # From both folders: in a worktree the session's own is the one that fits. - rels = tuple(dict.fromkeys( - r for r in (_inside(d, file_path) for d in (cwd, project_dir)) if r is not None - )) if _user_patterns else () for rule in _user_patterns: include, exclude = rule.get("_globs", ((), ())) if include or exclude: @@ -554,7 +577,7 @@ def edit_stats(file_path: str, cwd: Optional[str], project_dir: Optional[str]) - shapes |= _shape_bits(exclude, _SHAPE_PLAIN_EXCLUDE) try: now = _glob_match(file_path.lstrip("/"), include, exclude) - wider = _wider_glob_match(file_path, rels, include, exclude) + wider = _rule_covers(file_path.lstrip("/"), include, exclude) except Exception: continue gain += wider and not now diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index b02dcab7..4ad4db42 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -3317,8 +3317,7 @@ def main(): rule_stats = None if ENABLE_PATTERN_RULES: try: - rule_stats = extensibility.edit_stats( - file_path, input_data.get("cwd"), os.environ.get("CLAUDE_PROJECT_DIR")) + rule_stats = extensibility.edit_stats(file_path) except Exception as e: debug_log(f"custom rule stats failed: {e}") record_touched_path(session_id, file_path, rule_stats) diff --git a/plugins/security-guidance/tests/test_custom_rule_path_globs.py b/plugins/security-guidance/tests/test_custom_rule_path_globs.py new file mode 100644 index 00000000..bf792763 --- /dev/null +++ b/plugins/security-guidance/tests/test_custom_rule_path_globs.py @@ -0,0 +1,140 @@ +"""Custom rule globs can be relative to the project, and `**/` can match no folder.""" +import json +import sys + +import pytest + +import extensibility +from conftest import git, make_repo + +import security_reminder_hook as hook + +CASES = [ + # glob, file inside the project, applies + ("src/*.ts", "src/a.ts", True), + ("src/**", "src/lib/a.ts", True), + ("src/**/*.ts", "src/a.ts", True), + ("src/**/*.ts", "src/lib/a.ts", True), + ("**/src/**/*.ts", "src/a.ts", True), + ("./src/**", "src/a.ts", True), + ("/src/**", "src/a.ts", True), + ("*.py", "x/y.py", True), + ("src/**", "lib/a.ts", False), + ("src/*.ts", "other/src.ts", False), + ("**/vendor/**", "src/a.ts", False), +] + + +@pytest.fixture(autouse=True) +def _module_state(monkeypatch): + monkeypatch.setattr(extensibility, "_user_patterns", []) + monkeypatch.setattr(extensibility, "_match_roots", ()) + monkeypatch.setattr(extensibility, "_rels_cache", {}) + + +def _commit(project): + git(project, "add", "-A") + git(project, "commit", "-q", "-m", "rules") + + +def _rule(tmp_path, monkeypatch, include=None, exclude=None): + project = make_repo(tmp_path / "p", {"README": "x\n"}) + (project / ".claude").mkdir() + entry = {"rule_name": "r", "substrings": ["NEEDLE("], "reminder": "x"} + if include: + entry["paths"] = include + if exclude: + entry["exclude_paths"] = exclude + (project / ".claude" / "security-patterns.json").write_text(json.dumps({"patterns": [entry]})) + _commit(project) + monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(project)) + monkeypatch.setenv("HOME", str(tmp_path / "home")) + monkeypatch.setenv("USERPROFILE", str(tmp_path / "home")) + monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False) + return project + + +def _hits(project, rel, cwd=None): + extensibility.load_for_session(str(cwd or project)) + return [r for r, _ in hook.check_patterns(str(project / rel), "NEEDLE(1)\n")] + + +@pytest.mark.parametrize("glob,rel,applies", CASES) +def test_paths_inside_the_project(glob, rel, applies, tmp_path, monkeypatch): + project = _rule(tmp_path, monkeypatch, include=[glob]) + assert bool(_hits(project, rel)) is applies + + +@pytest.mark.parametrize("glob,rel,applies", CASES) +def test_excludes_read_the_same_way(glob, rel, applies, tmp_path, monkeypatch): + project = _rule(tmp_path, monkeypatch, exclude=[glob]) + assert bool(_hits(project, rel)) is not applies + + +def test_a_glob_that_matched_before_still_matches(tmp_path, monkeypatch): + project = _rule(tmp_path, monkeypatch, include=["**/src/**"]) + assert _hits(project, "src/lib/a.ts") + + +def test_an_absolute_glob(tmp_path, monkeypatch): + project = _rule(tmp_path, monkeypatch) + rules = project / ".claude" / "security-patterns.json" + entry = json.loads(rules.read_text()) + entry["patterns"][0]["paths"] = [project.as_posix() + "/src/**"] + rules.write_text(json.dumps(entry)) + _commit(project) + assert _hits(project, "src/a.ts") + assert not _hits(project, "lib/a.ts") + + +def test_the_session_moved_to_a_subfolder(tmp_path, monkeypatch): + project = _rule(tmp_path, monkeypatch, include=["src/**"]) + (project / "src").mkdir() + assert _hits(project, "src/a.ts", cwd=project / "src") + + +def test_a_file_outside_the_project(tmp_path, monkeypatch): + project = _rule(tmp_path, monkeypatch, include=["src/**"]) + outside = tmp_path / "elsewhere" + outside.mkdir() + extensibility.load_for_session(str(project)) + assert not [r for r, _ in hook.check_patterns(str(outside / "a.ts"), "NEEDLE(1)\n")] + + +def test_each_load_starts_from_its_own_folders(tmp_path, monkeypatch): + project = _rule(tmp_path, monkeypatch, include=["src/**"]) + extensibility.load_for_session(str(project)) + assert extensibility._rule_covers(str(project / "src/a.ts").lstrip("/"), ("src/**",), ()) + monkeypatch.delenv("CLAUDE_PROJECT_DIR") + extensibility.load_for_session(str(tmp_path)) + assert not extensibility._rule_covers(str(project / "src/a.ts").lstrip("/"), ("src/**",), ()) + + +def test_the_folder_the_session_is_in_does_not_decide(tmp_path, monkeypatch): + project = _rule(tmp_path, monkeypatch, include=["lib/**"]) + (project / "src").mkdir() + assert not _hits(project, "src/lib/a.ts") + assert not _hits(project, "src/lib/a.ts", cwd=project / "src") + + +def test_a_glob_with_no_folder_is_about_the_file_name(tmp_path, monkeypatch): + project = _rule(tmp_path, monkeypatch, exclude=["test*"]) + assert _hits(project, "tests/x/a.py") + assert not _hits(project, "x/test_a.py") + + +def test_a_subfolder_of_a_linked_worktree(tmp_path, monkeypatch): + project = _rule(tmp_path, monkeypatch, include=["src/**"]) + tree = tmp_path / "tree" + git(project, "worktree", "add", "-q", "-b", "side", str(tree)) + (tree / "pkg").mkdir() + assert _hits(tree, "src/a.ts", cwd=tree / "pkg") + + +@pytest.mark.skipif(sys.platform == "win32", reason="needs symlink privilege") +def test_a_linked_folder_by_the_name_in_the_project(tmp_path, monkeypatch): + project = _rule(tmp_path, monkeypatch, exclude=["vendor/**"]) + other = tmp_path / "other" + other.mkdir() + (project / "vendor").symlink_to(other, target_is_directory=True) + assert not _hits(project, "vendor/a.ts") diff --git a/plugins/security-guidance/tests/test_custom_rule_stats.py b/plugins/security-guidance/tests/test_custom_rule_stats.py index fcad3130..60d34f02 100644 --- a/plugins/security-guidance/tests/test_custom_rule_stats.py +++ b/plugins/security-guidance/tests/test_custom_rule_stats.py @@ -72,21 +72,20 @@ def _stats(repo, env, files, cwd=None): return {k: v for k, v in m.items() if k.startswith("cr_")}, outs -def test_rules_that_would_start_to_apply(env, workspace): +def test_rules_the_older_reading_missed(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): +def test_excludes_the_older_reading_missed(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] + assert "additionalContext" not in outs[0] def test_no_extra_save_of_the_state(env, workspace, monkeypatch, tmp_path): @@ -108,7 +107,7 @@ def test_worktree_outside_the_project(env, workspace, tmp_path): 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)) + stats = extensibility.edit_stats(str(tree / "src" / "a.ts")) assert stats["cr_gain"] == 1 |
