fix(patterns): anchor MP2 regex to prevent catastrophic backtracking
Summary
The first MP2 pattern (Context Window Stuffing) uses a nested structure ((\S)(?!\2).{1,19}?)\1{20,} that is vulnerable to catastrophic backtracking (ReDoS). On non-matching inputs of moderate size (>500 chars), the regex engine explores exponential backtracking paths due to the lazy .{1,19}? quantifier inside a backreference-repeated group.
Changes
static_patterns_memory_poisoning.py: Replace the vulnerable pattern with(.{2,20}?)\1{20,}which detects repeated substrings without the expensive negative lookahead inside a repeated group.- New test file:
tests/nodes/analyzers/test_mp2_regex_backtracking.py— validates both correct detection of repeated content and bounded execution time on adversarial inputs.
Before / After
# Before — exponential backtracking on non-matching input
(r"((\S)(?!\2).{1,19}?)\1{20,}", 0.8)
# After — linear-time matching, same detection capability
(r"(.{2,20}?)\1{20,}", 0.8)
Testing
- 6 new tests: 3 for correct detection, 3 for bounded execution time
- Full test suite passes (775 tests, excluding pre-existing upstream issue in
test_llm_utils.py)
Fixes #151
Both issues addressed:
-
Lint fixed — removed unused
signalandsysimports fromtest_mp2_regex_backtracking.py.ruff checkpasses clean. -
Whitespace-bearing stuffing false negative fixed — replaced
len(set(captured.strip())) <= 1with a whitespace-aware check: we now compute unique non-whitespace chars and only suppress when both (a) there's at most one unique non-whitespace char AND (b) no interior whitespace is present. This means:"=" * 80→ suppressed ✓ (single non-ws char, no spaces)"x " * 30→ detected ✓ (single non-ws char, but has interior whitespace = genuine stuffing)"ab" * 30→ detected ✓ (multiple non-ws chars)
-
Tests added:
test_separator_line_not_detected(separators suppressed) andtest_whitespace_bearing_stuffing_detected(space-bearing payloads not suppressed).
Branch rebased on latest main.