diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-11-12 23:14:11 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-11-12 23:14:11 +0000 |
| commit | 2628ed66b623e902bc560d8605a045effcda9556 (patch) | |
| tree | ea10277f56f7ecaf3c4f3ee587e87d56d320f91f /plugins | |
| parent | 23c304a6387ed2fa207ceff27646d8514ee75235 (diff) | |
security-guidance: custom rule globs can use bracesmhegazy/sg-brace-globs
`*.{ts,tsx}` in paths or exclude_paths means either. The number of
combinations is bounded, per glob and over all rules. The README lists
MAX_COMMIT_REVIEWS_PER_HOUR.
Co-authored-by: mhegazy <mhegazy@anthropic.com>
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/README.md | 1 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/extensibility.py | 123 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_custom_rule_brace_globs.py | 187 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_custom_rule_stats.py | 3 |
4 files changed, 301 insertions, 13 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md index 46049569..8f7a1be6 100644 --- a/plugins/security-guidance/README.md +++ b/plugins/security-guidance/README.md @@ -72,6 +72,7 @@ On the default API host, a claude.ai token (`sk-ant-oat`) that arrives as `ANTHR | `ENABLE_CODE_SECURITY_REVIEW=0` | on | Disable all LLM reviews (Stop hook + commit/push) | | `ENABLE_STOP_REVIEW=0` | on | Disable only the Stop-hook diff review, keeping commit/push reviews. Useful for multi-agent / shared-worktree setups where another agent can move HEAD between a worker's turns | | `ENABLE_COMMIT_REVIEW=0` | on | Disable layer 3 (agentic commit review) | +| `MAX_COMMIT_REVIEWS_PER_HOUR=<n>` | `20` | The most commit reviews, and separately the most push reviews, that one session runs in a rolling hour. A commit or push past the limit still goes through, without a review and without a message; a later push can still review the commit. Must be a whole number; `0` runs none. It counts reviews, not tokens or cost, and does not limit the Stop-hook diff review | | `SECURITY_GUIDANCE_PERSIST_SESSIONS=1` | unset | Keep the reviewer's own Claude Code runs as session transcripts (see [Privacy and data handling](#privacy-and-data-handling)) | ### Hook output for other hosts diff --git a/plugins/security-guidance/hooks/extensibility.py b/plugins/security-guidance/hooks/extensibility.py index 7f434371..6dd8d470 100644 --- a/plugins/security-guidance/hooks/extensibility.py +++ b/plugins/security-guidance/hooks/extensibility.py @@ -83,10 +83,13 @@ def load_for_session(cwd: Optional[str]) -> None: a malformed config file produces a debug_log entry, never a crash. """ global _guidance_block, _user_patterns, _refused_regexes, _match_roots + global _brace_forms_left _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() + _forms_cache.clear() + _brace_forms_left = _BRACE_BUDGET try: _guidance_block = _wrap_guidance(_load_guidance(cwd)) except Exception as e: @@ -420,6 +423,9 @@ def _validate_pattern(entry: Any, source: str) -> Optional[Dict[str, Any]]: if not isinstance(paths, list) or not isinstance(exclude, list): debug_log(f"extensibility: skipping {name}: paths/exclude_paths must be lists") return None + for glob in (*paths, *exclude): + if isinstance(glob, str): + _glob_forms(glob, name) # now, so the log can name the rule 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"] = ( @@ -431,7 +437,8 @@ def _validate_pattern(entry: Any, source: str) -> Optional[Dict[str, Any]]: 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.""" + the full path and the path inside the project, `**/` can match no folder, and + `{a,b}` is either.""" full = path if os.path.isabs(path) else "/" + path rels = _rels_cache.get(full) if rels is None: @@ -444,7 +451,7 @@ def _rule_covers(path: str, include: Tuple[str, ...], exclude: Tuple[str, ...]) def _glob_match(path: str, include: Tuple[str, ...], exclude: Tuple[str, ...]) -> bool: """The reading of globs before _rule_covers, kept for edit_stats: full path - or file name only, and `**/` needs a folder.""" + or file name only, `**/` needs a folder, and braces are literal.""" norm = path.replace(os.sep, "/") base = os.path.basename(norm) def _hit(globs: Tuple[str, ...]) -> bool: @@ -496,7 +503,7 @@ def _has_redos_structure(regex: str) -> bool: _SHAPE_PLAIN_PATHS = 1 # a `paths` glob with a folder and no leading `*` _SHAPE_PLAIN_EXCLUDE = 2 # the same in `exclude_paths` _SHAPE_MID_STARS = 4 # `/**/` inside a glob -_SHAPE_BRACES = 8 # `{a,b}`, which fnmatch takes literally +_SHAPE_BRACES = 8 # `{`, as in `{a,b}` _SHAPE_LEADING = 16 # starts with `/` or `./` _SHAPE_REGEX_REFUSED = 32 # a rule dropped by the slow-regex check _SHAPE_REGEX_COUNTED = 64 # a loaded regex repeats a repeated group by count @@ -533,20 +540,112 @@ def _zero_depth_forms(glob: str) -> Tuple[str, ...]: return tuple(forms) +# Globs that braces may stand for: in one glob, and in all the rules loaded, +# counted with their `**/` forms. Real rules list a few file types and folders; +# this bounds what a project's file can cost. A glob beyond either is read as it +# is written. User files load first, so a project's cannot use up their share. +_MAX_BRACE_FORMS = 256 +_MAX_BRACE_GLOB_LEN = 1000 +_BRACE_BUDGET = 4096 +_brace_forms_left = _BRACE_BUDGET +# glob -> its _glob_forms. +_forms_cache: Dict[str, Tuple[Tuple[str, str, bool], ...]] = {} + + +def _brace_group(glob: str) -> Optional[Tuple[int, Tuple[int, ...], int]]: + """The first `{...}` with a comma of its own: where it opens, its commas, + where it closes. Braces inside `[...]` are members of that set.""" + stack: List[Tuple[int, List[int]]] = [] + found = None + i, last_set_end = 0, glob.rfind("]") + while i < len(glob): + c = glob[i] + if c == "[" and i < last_set_end: + # As fnmatch reads a set: `]` right after `[` or `[!` is a member. + start = i + 2 if glob.startswith("!", i + 1) else i + 1 + end = glob.find("]", start + 1) + if end > 0: + i = end + elif c == "{": + stack.append((i, [])) + elif c == "," and stack: + stack[-1][1].append(i) + elif c == "}" and stack: + opened, commas = stack.pop() + if commas and (found is None or opened < found[0]): + found = (opened, tuple(commas), i) + i += 1 + return found + + +def _brace_forms(glob: str) -> Optional[Tuple[str, ...]]: + """`glob`, and the globs its braces stand for: `*.{ts,tsx}` is also `*.ts` + and `*.tsx`. None when there are too many. Braces with no comma are literal.""" + todo, done = [glob], [] + while todo: + form = todo.pop() + group = _brace_group(form) + if group is None: + done.append(form) + continue + opened, commas, closed = group + if len(todo) + len(done) + len(commas) + 1 > _MAX_BRACE_FORMS: + return None + edges = (opened,) + commas + (closed,) + rest = form[closed + 1:] + for a, b in zip(edges, edges[1:]): + option = form[a + 1:b].strip() + # `{src,}/**` would leave `/**`, which takes in every file. + if option or opened or not rest.startswith("/"): + todo.append(form[:opened] + option + rest) + # The glob as written stays, for a name that has braces in it. + return tuple(dict.fromkeys([glob] + [f for f in done if f])) + + +def _glob_forms(glob: str, rule_name: str = "") -> Tuple[Tuple[str, str, bool], ...]: + """The globs `glob` stands for, each as (glob, its literal end, whether it + has a folder in it), in the filesystem's case.""" + global _brace_forms_left + if glob in _forms_cache: + return _forms_cache[glob] + braces = (glob,) + if "{" in glob and "," in glob: + fits = _brace_forms_left > 0 and len(glob) <= _MAX_BRACE_GLOB_LEN + braces = (_brace_forms(glob) if fits else None) or () + forms = tuple((b, f) for b in braces for f in _zero_depth_forms(b)) + if not braces or (len(braces) > 1 and len(forms) > _brace_forms_left): + debug_log(f"extensibility: {rule_name}: too many combinations in braces, " + f"read as written: {glob!r:.80}") + # Finding out that it does not fit has a cost too. + _brace_forms_left -= _MAX_BRACE_FORMS + forms = tuple((glob, f) for f in _zero_depth_forms(glob)) + elif len(braces) > 1: + _brace_forms_left -= len(forms) + out = [] + for b, f in forms: + # 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. + folder = "/" in b.replace("\\", "/") + f = os.path.normcase(f) + out.append((f, f[max(f.rfind(c) for c in "*?[]") + 1:], folder)) + _forms_cache[glob] = tuple(out) + return _forms_cache[glob] + + def _wider_glob_match(path: str, rels: Tuple[str, ...], include: Tuple[str, ...], exclude: Tuple[str, ...]) -> bool: """_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)] - inside = [n for rel in rels for n in (rel, "/" + rel, "./" + rel)] + (`rels`), `**/` able to match no folder, and braces as alternatives.""" + full = path.replace(os.sep, "/") + names = [os.path.normcase(n) for n in (full, full.lstrip("/"), os.path.basename(full))] + inside = names + [os.path.normcase(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 + inside if "/" in g.replace("\\", "/") else names)) + # The literal end first: compiling a glob is the slow part, and most of + # the options in braces end differently. + return any(n.endswith(tail) and fnmatch.fnmatchcase(n, form) for g in globs + for form, tail, folder in _glob_forms(g) + for n in (inside if folder else names)) if include and not _hit(include): return False if exclude and _hit(exclude): diff --git a/plugins/security-guidance/tests/test_custom_rule_brace_globs.py b/plugins/security-guidance/tests/test_custom_rule_brace_globs.py new file mode 100644 index 00000000..6cef5689 --- /dev/null +++ b/plugins/security-guidance/tests/test_custom_rule_brace_globs.py @@ -0,0 +1,187 @@ +"""`{a,b}` in a custom rule's glob means either.""" +import fnmatch +import itertools +import time + +import pytest + +import extensibility + +from test_custom_rule_path_globs import _hits, _module_state, _rule # noqa: F401 + +CASES = [ + # glob, file inside the project, applies + ("*.{ts,tsx}", "src/a.ts", True), + ("*.{ts,tsx}", "src/lib/a.tsx", True), + ("*.{ts,tsx}", "src/a.js", False), + ("*.{ts,tsx}", "src/a.ts.bak", False), + ("**/*.{ts,tsx}", "config.ts", True), + ("**/*.{ts,tsx}", "src/lib/a.tsx", True), + ("**/*.{ts,tsx}", "src/a.py", False), + ("{src,lib}/**", "src/x/a.py", True), + ("{src,lib}/**", "lib/a.py", True), + ("{src,lib}/**", "other/a.py", False), + ("src/{a,b}/**/*.{ts,js}", "src/b/a.js", True), + ("src/{a,b}/**/*.{ts,js}", "src/c/a.js", False), + ("./{src,lib}/*.ts", "lib/a.ts", True), + ("*.{ts,{m,c}ts}", "a.mts", True), + ("*.{ts,{m,c}ts}", "a.xts", False), + ("*.{test,spec}.ts", "src/a.spec.ts", True), + ("*.{ts, tsx}", "a.tsx", True), + # An empty option before `/` does not turn the glob into "every file". + ("{src,}/**", "src/a.ts", True), + ("{src,}/**", "lib/a.ts", False), + ("{,src}/*.ts", "lib/a.ts", False), + ("{{,x},src}{,y}/**", "lib/a.ts", False), + # More combinations than anyone counts. + ("{src,lib,app,packages}/**/*.{js,jsx,ts,tsx,mjs,cjs,mts,cts,vue}", "app/x/a.vue", True), + ("config{,.local}.ts", "config.ts", True), + ("config{,.local}.ts", "config.local.ts", True), + # A set keeps its braces, and one option is not a choice. + ("[{,}].ts", "{.ts", True), + ("[{,}].ts", "ts", False), + ("a{b}.ts", "a{b}.ts", True), + ("a{b}.ts", "ab.ts", False), + ("*.{ts,tsx", "a.ts", False), + # An option with no folder in it is about the file name. + ("{test*,src/**}", "tests/x/a.py", False), + ("{test*,src/**}", "x/test_a.py", True), + ("{test*,src/**}", "src/a.py", True), +] + + +@pytest.fixture(autouse=True) +def _fresh_forms(monkeypatch): + monkeypatch.setattr(extensibility, "_forms_cache", {}) + monkeypatch.setattr(extensibility, "_brace_forms_left", extensibility._BRACE_BUDGET) + + +@pytest.mark.parametrize("glob,rel,applies", CASES) +def test_braces_in_paths(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_braces_in_exclude_paths(glob, rel, applies, tmp_path, monkeypatch): + project = _rule(tmp_path, monkeypatch, exclude=[glob]) + assert bool(_hits(project, rel)) is not applies + + +def test_an_exclude_silences_only_its_own_rule(tmp_path, monkeypatch): + project = _rule(tmp_path, monkeypatch, exclude=["*.{js,ts}"]) + extensibility.load_for_session(str(project)) + import security_reminder_hook as hook + hits = [r for r, _ in hook.check_patterns(str(project / "a.js"), "NEEDLE(eval(x))\n")] + assert "eval_injection" in hits and "user:r" not in hits + + +@pytest.mark.parametrize("glob", ["{a,b}.ts", "*.{ts,tsx}", "x{,y}", "{a,{b,c}}"]) +def test_a_name_with_the_braces_in_it_still_matches(glob): + name = glob.replace("*", "z") + assert extensibility._wider_glob_match("/p/" + name, (), (glob,), ()) + + +@pytest.mark.parametrize("glob,forms", [ + ("*.ts", {"*.ts"}), + ("{a,b}", {"{a,b}", "a", "b"}), + ("{{a,b}}", {"{{a,b}}", "{a}", "{b}"}), + ("{a,b}{c,d}", {"{a,b}{c,d}", "ac", "ad", "bc", "bd"}), + ("{a,}", {"{a,}", "a"}), + ("{a,}/b", {"{a,}/b", "a/b"}), + ("{/a,/b}/c", {"{/a,/b}/c", "/a/c", "/b/c"}), + ("x/{a,}/b", {"x/{a,}/b", "x/a/b", "x//b"}), + ("{,}", {"{,}"}), + ("a}{b,c}", {"a}{b,c}", "a}b", "a}c"}), + ("{x{a,b}", {"{x{a,b}", "{xa", "{xb"}), + ("[{a,b]{c,d}", {"[{a,b]{c,d}", "[{a,b]c", "[{a,b]d"}), + ("[!]{]{c,d}", {"[!]{]{c,d}", "[!]{]c", "[!]{]d"}), + ("[{a,b}", {"[{a,b}", "[a", "[b"}), + ("", {""}), +]) +def test_forms(glob, forms): + assert set(extensibility._brace_forms(glob)) == forms + + +def test_up_to_the_cap_is_expanded_and_over_it_is_not(): + cap = extensibility._MAX_BRACE_FORMS + at = "{" + ",".join(map(str, range(cap))) + "}" + assert len(extensibility._brace_forms(at)) == cap + 1 + assert extensibility._brace_forms(at[:-1] + ",x}") is None + + +def _over_cap(): + return "src/*.{" + ",".join(f"e{i}" for i in range(extensibility._MAX_BRACE_FORMS)) + ",ts}" + + +def test_an_over_cap_glob_is_read_as_written_and_the_log_names_the_rule(tmp_path, monkeypatch): + log = [] + monkeypatch.setattr(extensibility, "debug_log", log.append) + project = _rule(tmp_path, monkeypatch, include=[_over_cap(), "lib/*.{ts,js}"]) + assert not _hits(project, "src/a.ts") + assert _hits(project, "lib/a.ts") + assert [m for m in log if "too many combinations" in m and " r:" in m] + + +def test_the_budget_is_shared_by_all_rules_and_starts_again_each_load(tmp_path, monkeypatch): + monkeypatch.setattr(extensibility, "_BRACE_BUDGET", 5) + project = _rule(tmp_path, monkeypatch, include=["a.{ts,js}", "b.{ts,js}"]) + for _ in range(2): + assert _hits(project, "a.ts") + assert not _hits(project, "b.ts") + + +def test_plain_globs_need_no_budget(tmp_path, monkeypatch): + monkeypatch.setattr(extensibility, "_BRACE_BUDGET", 0) + project = _rule(tmp_path, monkeypatch, include=["src/**/*.ts", "a{b}.py"]) + assert _hits(project, "src/a.ts") and _hits(project, "a{b}.py") + + +@pytest.mark.parametrize("glob", [ + "{a,b}" * 200, + "{" * 20000 + "a,b" + "}" * 20000, + "{a," * 20000, + "[" * 20000 + "{a,b}", + "[{" * 10000 + "]" + "{a,b}" * 20, + "{" + "a," * 50000 + "}", +]) +def test_a_hostile_glob_is_quick(glob): + started = time.perf_counter() + extensibility._brace_forms(glob) + assert time.perf_counter() - started < 5 + + +@pytest.mark.parametrize("glob", [ + "**/r/**/x/**/y/**/z{a,b}{c,d}{e,f}{g,h}{i,j}/**", + "*{*a,*b}*{*c,*d}*{*e,*f}*{*g,*h}*", +]) +def test_a_project_full_of_hostile_rules_is_bounded(glob): + """Whole matching cost, no literal end to help, 500 different globs.""" + globs = tuple(f"{i}{glob}" for i in range(500)) + plain = tuple(g.replace("{", "(").replace("}", ")") for g in globs) + started = time.perf_counter() + sizes = [len(extensibility._glob_forms(g)) - len(extensibility._glob_forms(p)) + for g, p in zip(globs, plain)] + assert 0 < sum(sizes) <= extensibility._BRACE_BUDGET + assert not extensibility._wider_glob_match("/p/src/lib/a.ts", ("src/lib/a.ts",), globs, ()) + assert time.perf_counter() - started < 20 + + +def test_many_globs_that_do_not_fit_are_given_up_on_quickly(): + started = time.perf_counter() + for i in range(5000): + extensibility._glob_forms(f"{i}" + "{a,b}" * 190) + assert time.perf_counter() - started < 10 + + +def _matches(name, glob): + """One glob against one file name, through the plugin's matcher.""" + return any(name.endswith(tail) and fnmatch.fnmatchcase(name, form) + for form, tail, _ in extensibility._glob_forms(glob) if form == glob) + + +def test_the_quick_check_agrees_with_fnmatch(): + globs = ["".join(g) for n in range(5) for g in itertools.product("a*?[]!", repeat=n)] + for glob in globs: + for name in ("", "a", "aa", "ab", "a-b", "a]", "]", "[a", "!", "a!"): + assert _matches(name, glob) == fnmatch.fnmatchcase(name, glob), (name, glob) diff --git a/plugins/security-guidance/tests/test_custom_rule_stats.py b/plugins/security-guidance/tests/test_custom_rule_stats.py index 41bf9141..f0d0f86e 100644 --- a/plugins/security-guidance/tests/test_custom_rule_stats.py +++ b/plugins/security-guidance/tests/test_custom_rule_stats.py @@ -43,7 +43,8 @@ def test_the_wider_reading_never_loses_an_include(glob, tmp_path): ("/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), + ("*.{ts,js}", "config.ts", False, True), + ("*.{ts,js}", "config.py", False, False), ]) def test_readings(glob, f, now, wider, tmp_path): path = str(tmp_path.joinpath(*f.split("/"))) |
