diff options
| author | Claude <noreply@anthropic.com> | 2026-11-10 17:28:34 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-11-10 17:28:34 +0000 |
| commit | e40ebd818bd1c6ab39ac9d8aaf6f85baef19b1db (patch) | |
| tree | 2cdcff0390fafd87523147c647ef3e2afdf6a26c /plugins | |
| parent | dceb15d50832e6adf380bedc26dde03d251324b9 (diff) | |
Stop custom rule regexes that run too long
Co-authored-by: mhegazy <mhegazy@anthropic.com>
Diffstat (limited to 'plugins')
3 files changed, 208 insertions, 5 deletions
diff --git a/plugins/security-guidance/hooks/extensibility.py b/plugins/security-guidance/hooks/extensibility.py index 10df6b79..79d4c43e 100644 --- a/plugins/security-guidance/hooks/extensibility.py +++ b/plugins/security-guidance/hooks/extensibility.py @@ -43,6 +43,9 @@ import fnmatch import json import os import re +import subprocess +import sys +import time from typing import Any, Dict, List, Optional, Tuple from _base import debug_log @@ -75,8 +78,10 @@ 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, _regex_seconds_left _refused_regexes = 0 + _regex_seconds_left = REGEX_TIME_LIMIT_S + _stopped_regexes.clear() try: _guidance_block = _wrap_guidance(_load_guidance(cwd)) except Exception as e: @@ -574,3 +579,84 @@ def edit_stats(file_path: str, cwd: Optional[str], project_dir: Optional[str]) - # A custom regex that takes at least this long is reported, in seconds. SLOW_REGEX_S = 0.1 + +# A project's own files can make a custom regex arbitrarily slow, and the shape +# check at load cannot catch every slow pattern. So they run in a child process +# that can be stopped, on every platform: re holds the GIL, so a thread cannot +# interrupt a search, and Windows has no setitimer. +# Seconds of child process time per hook run. +REGEX_TIME_LIMIT_S = 3.0 +_regex_seconds_left = REGEX_TIME_LIMIT_S +# Regexes stopped in this hook run. They are not tried again. +_stopped_regexes: set = set() + +_REGEX_WORKER = """ +import faulthandler, json, re, sys, time +job = json.load(sys.stdin) +# Ends this process if the hook that started it is killed first. +faulthandler.dump_traceback_later(job["limit"] + 1, exit=True) +for regex in job["regexes"]: + started = time.perf_counter() + try: + hit = bool(re.search(regex, job["content"])) + except Exception: + hit = False + print(int(hit), time.perf_counter() - started, flush=True) +""" + + +def search_custom_regexes(regexes: List[str], content: str) -> List[bool]: + """Whether each regex is found in content. A regex that does not finish in + time counts as not found and is left out for the rest of this hook run; + the ones after it are still searched while time remains.""" + global slowest_regex, _regex_seconds_left + found = [False] * len(regexes) + waiting = [i for i, r in enumerate(regexes) if r not in _stopped_regexes] + while waiting and _regex_seconds_left > 0.05: + limit = _regex_seconds_left / 2 # one stuck regex leaves time for the rest + started = time.monotonic() + timed_out = False + try: + done = subprocess.run( + [sys.executable, "-I", "-S", "-c", _REGEX_WORKER], + input=json.dumps({ + "regexes": [regexes[i] for i in waiting], + "content": content, + "limit": limit, + }).encode("ascii"), + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=limit) + lines = done.stdout + if done.returncode: + raise OSError(f"exit {done.returncode}") + except subprocess.TimeoutExpired as e: + timed_out = True + lines = e.stdout or b"" + except (OSError, TypeError, ValueError, subprocess.SubprocessError) as e: + # As it was before the limit: no worse than a machine with no child. + debug_log(f"extensibility: regex worker failed: {e}") + return _search_here(regexes, content) + _regex_seconds_left -= time.monotonic() - started + results = lines.split(b"\n")[:-1][:len(waiting)] # whole lines only + for i, line in zip(waiting, results): + hit, seconds = line.split() + found[i] = hit == b"1" + slowest_regex = max(slowest_regex, float(seconds)) + waiting = waiting[len(results):] + if timed_out and waiting: + stuck = regexes[waiting.pop(0)] + _stopped_regexes.add(stuck) + slowest_regex = max(slowest_regex, limit) + debug_log(f"extensibility: stopped a custom regex after {limit:.1f} s: {stuck!r:.60}") + if waiting: + debug_log(f"extensibility: no time left for {len(waiting)} custom regexes") + return found + + +def _search_here(regexes: List[str], content: str) -> List[bool]: + found = [] + for regex in regexes: + try: + found.append(bool(re.search(regex, content))) + except Exception: + found.append(False) + return found diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index b02dcab7..26e85785 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -744,6 +744,8 @@ def check_patterns(file_path, content): if cell_sources is not None: content = cell_sources + custom_searches = [] # (where in matches the rule goes, its pattern) + for pattern in list(SECURITY_PATTERNS) + extensibility.user_patterns(): # path_filter is a gate: when present, the rule only applies to # matching paths. Distinct from path_check, which is itself a @@ -771,19 +773,25 @@ def check_patterns(file_path, content): break if not matched and "regex" in pattern and content: - started = time.perf_counter() + if "_source" in pattern: # a custom rule: searched below + custom_searches.append((len(matches), pattern)) + continue try: if re.search(pattern["regex"], content): matched = True except Exception: pass - if "_source" in pattern: # a custom rule - extensibility.slowest_regex = max( - extensibility.slowest_regex, time.perf_counter() - started) if matched: matches.append((pattern["ruleName"], pattern["reminder"])) + if custom_searches: + found = extensibility.search_custom_regexes( + [pattern["regex"] for _, pattern in custom_searches], content) + for (where, pattern), hit in reversed(list(zip(custom_searches, found))): + if hit: + matches.insert(where, (pattern["ruleName"], pattern["reminder"])) + return matches def extract_content_from_input(tool_name, tool_input, tool_response=None): diff --git a/plugins/security-guidance/tests/test_custom_regex_time_limit.py b/plugins/security-guidance/tests/test_custom_regex_time_limit.py new file mode 100644 index 00000000..1579884c --- /dev/null +++ b/plugins/security-guidance/tests/test_custom_regex_time_limit.py @@ -0,0 +1,109 @@ +"""Custom rule regexes run with a time limit, so a slow rule cannot hold a hook.""" +import subprocess +import time + +import pytest + +import extensibility +import security_reminder_hook as hook + +SLOW = "(a+){2,}$" +SLOW_TEXT = "a" * 40 + "!" + + +def _rule(name, regex): + return {"ruleName": "user:" + name, "reminder": name, "regex": regex, "_source": "t"} + + +@pytest.fixture(autouse=True) +def fresh(monkeypatch): + monkeypatch.setattr(extensibility, "_regex_seconds_left", 30.0) + monkeypatch.setattr(extensibility, "_stopped_regexes", set()) + monkeypatch.setattr(extensibility, "slowest_regex", 0.0) + monkeypatch.setattr(hook, "SECURITY_PATTERNS", [ + {"ruleName": "builtin", "reminder": "builtin", "substrings": ["danger"]}]) + + +def _short_limit(monkeypatch, seconds=3.0): + monkeypatch.setattr(extensibility, "_regex_seconds_left", seconds) + + +def _check(monkeypatch, rules, content): + monkeypatch.setattr(extensibility, "_user_patterns", rules) + return [name for name, _ in hook.check_patterns("a.py", content)] + + +def test_found_and_not_found(monkeypatch): + rules = [_rule("yes", r"needle\d"), _rule("no", "absent")] + assert _check(monkeypatch, rules, "x needle1") == ["user:yes"] + + +def test_non_ascii_content_is_searched(monkeypatch): + assert _check(monkeypatch, [_rule("r", "é+z")], "caféz \udc80") == ["user:r"] + + +def test_order_stays_built_in_then_custom_as_listed(monkeypatch): + substring = {"ruleName": "user:sub", "reminder": "sub", "substrings": ["needle"], "_source": "t"} + rules = [_rule("first", "needle"), substring, _rule("third", "needle")] + assert _check(monkeypatch, rules, "danger needle") == [ + "builtin", "user:first", "user:sub", "user:third"] + + +def test_slow_rule_is_stopped_and_the_others_still_run(monkeypatch): + _short_limit(monkeypatch) + rules = [_rule("before", "a!"), _rule("slow", SLOW), _rule("after", "a!")] + started = time.perf_counter() + got = _check(monkeypatch, rules, "danger " + SLOW_TEXT) + assert time.perf_counter() - started < 8 + assert got == ["builtin", "user:before", "user:after"] + assert extensibility.slowest_regex >= 1.0 + + +def test_stopped_rule_is_not_tried_again(monkeypatch): + _short_limit(monkeypatch) + rules = [_rule("slow", SLOW), _rule("other", "a")] + assert _check(monkeypatch, rules, SLOW_TEXT) == ["user:other"] + monkeypatch.setattr(extensibility, "_regex_seconds_left", 30.0) + started = time.perf_counter() + assert _check(monkeypatch, rules, SLOW_TEXT) == ["user:other"] + assert time.perf_counter() - started < 5 + + +def test_nothing_runs_when_the_time_is_gone(monkeypatch): + _short_limit(monkeypatch, 0) + assert _check(monkeypatch, [_rule("r", "a")], "a") == [] + + +def test_load_starts_a_new_allowance(monkeypatch, tmp_path): + monkeypatch.setattr(extensibility, "_regex_seconds_left", 0) + monkeypatch.setattr(extensibility, "_stopped_regexes", {"x"}) + monkeypatch.setattr(extensibility, "_load_guidance", lambda cwd: "") + monkeypatch.setattr(extensibility, "_load_user_patterns", lambda cwd: []) + monkeypatch.setattr(extensibility, "_guidance_block", "") + monkeypatch.setattr(extensibility, "_user_patterns", []) + monkeypatch.setattr(extensibility, "_refused_regexes", 0) + extensibility.load_for_session(str(tmp_path)) + assert extensibility._regex_seconds_left == extensibility.REGEX_TIME_LIMIT_S + assert not extensibility._stopped_regexes + + +def test_no_child_without_a_custom_regex(monkeypatch): + def boom(*a, **k): + raise AssertionError("started a child") + monkeypatch.setattr(subprocess, "run", boom) + assert _check(monkeypatch, [], "danger") == ["builtin"] + # A rule the path filter turns away needs no search either. + rule = dict(_rule("r", "x"), path_filter=lambda p: False) + assert _check(monkeypatch, [rule], "x") == [] + + +def test_worker_that_cannot_start_falls_back(monkeypatch): + def fail(*a, **k): + raise OSError("no") + monkeypatch.setattr(subprocess, "run", fail) + assert _check(monkeypatch, [_rule("r", "x")], "x") == ["user:r"] + + +def test_worker_that_fails_falls_back(monkeypatch): + monkeypatch.setattr(extensibility, "_REGEX_WORKER", "import sys; sys.exit(1)") + assert _check(monkeypatch, [_rule("r", "x")], "x") == ["user:r"] |
