From 964d0e1dbfc0e2a3a408f3badfb61df081555d2b Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Fri, 4 Dec 2026 20:25:55 -0800 Subject: [PATCH 1/4] fix(regex): refuse a user regex that overflows or nests too deep re.compile raises OverflowError for a repeat count that does not fit and RecursionError for groups nested too deep, not re.error. The process_metrics and contract loaders caught only re.error, so such a pattern crashed with a traceback instead of a refusal. One compile_user_regex helper maps all three to ValueError. It is used at the two loader compile sites, and at the branch-filter glob compile (repos/l0/branches.py), which compiles user-derived text. The manifest catches ValueError from parse_counter, so it refuses too without a change of its own. The remaining re.compile in environment/instructions.py compiles module-level literals only and is unchanged. Signed-off-by: Nikolay Petrov --- ...1204_120000_napetrov_user-regex-refusal.md | 3 ++ dokimi/dokimi/context/contract.py | 22 +++++++--- dokimi/dokimi/repos/l0/branches.py | 4 +- dokimi/dokimi/repos/process_metrics.py | 5 ++- dokimi/dokimi/user_regex.py | 21 ++++++++++ dokimi/tests/test_context_consistency.py | 7 ++++ dokimi/tests/test_import_architecture.py | 2 +- dokimi/tests/test_repo_manifest.py | 1 + dokimi/tests/test_repo_process_metrics.py | 3 ++ dokimi/tests/test_user_regex.py | 40 +++++++++++++++++++ 10 files changed, 98 insertions(+), 10 deletions(-) create mode 100644 dokimi/changelog.d/20261204_120000_napetrov_user-regex-refusal.md create mode 100644 dokimi/dokimi/user_regex.py create mode 100644 dokimi/tests/test_user_regex.py diff --git a/dokimi/changelog.d/20261204_120000_napetrov_user-regex-refusal.md b/dokimi/changelog.d/20261204_120000_napetrov_user-regex-refusal.md new file mode 100644 index 0000000000..859cd2d506 --- /dev/null +++ b/dokimi/changelog.d/20261204_120000_napetrov_user-regex-refusal.md @@ -0,0 +1,3 @@ +### Fixed + +- **A regex a user writes that Python cannot compile is refused, not a traceback.** `re.compile` raises `OverflowError` for a repeat count that does not fit (`a{999999999999}`) and `RecursionError` for groups nested too deep, not the `re.error` the `process_metrics` and contract loaders caught. Those patterns now refuse as bad input (exit 2, `Error: ...`) instead of crashing: a `process_metrics` counter in the repo manifest and a `trace consistency --contract` pattern. diff --git a/dokimi/dokimi/context/contract.py b/dokimi/dokimi/context/contract.py index 020dbf1963..0afde557ca 100644 --- a/dokimi/dokimi/context/contract.py +++ b/dokimi/dokimi/context/contract.py @@ -12,6 +12,7 @@ from dokimi.context import shell from dokimi.files import refuse_device +from dokimi.user_regex import compile_user_regex if TYPE_CHECKING: from dokimi.context.consistency import Event, Run @@ -82,6 +83,20 @@ def _pattern(value: Any, where: str) -> str: raise ValueError(f"{where} wants a regex or a list of regexes, got {value!r}") +def _action_patterns(where: str, name: Any, spec: dict[str, Any]) -> dict[str, re.Pattern[str]]: + """The regex of each matcher key of one action (every key but `tool` and `change`); a bad one is a ValueError.""" + patterns: dict[str, re.Pattern[str]] = {} + for k, v in spec.items(): + if k in ("tool", "change"): + continue + source = _pattern(v, f"{where}: action {name!r}: `{k}`") + try: + patterns[str(k)] = compile_user_regex(source) + except ValueError as exc: + raise ValueError(f"{where}: action {name!r}: bad regex ({exc})") from exc + return patterns + + def parse_contract(data: Any, where: str = "contract") -> dict[str, Any]: if not isinstance(data, dict) or not isinstance(data.get("actions"), dict): raise ValueError(f"{where}: want `actions:` (name -> matcher) and `rules:`") @@ -93,12 +108,7 @@ def parse_contract(data: Any, where: str = "contract") -> dict[str, Any]: change = spec.get("change", "") if "change" in spec and change not in CHANGES: raise ValueError(f"{where}: action {name!r}: `change` wants add or modify, got {change!r}") - try: - patterns = {str(k): re.compile(_pattern(v, f"{where}: action {name!r}: `{k}`")) - for k, v in spec.items() if k not in ("tool", "change")} - except re.error as exc: - raise ValueError(f"{where}: action {name!r}: bad regex ({exc})") from exc - actions[str(name)] = Matcher(tools, patterns, change) + actions[str(name)] = Matcher(tools, _action_patterns(where, name, spec), change) rules = [] raw_rules = data.get("rules") or [] if not isinstance(raw_rules, list): diff --git a/dokimi/dokimi/repos/l0/branches.py b/dokimi/dokimi/repos/l0/branches.py index 10f7987470..749605c661 100644 --- a/dokimi/dokimi/repos/l0/branches.py +++ b/dokimi/dokimi/repos/l0/branches.py @@ -20,6 +20,8 @@ import yaml +from dokimi.user_regex import compile_user_regex + from . import workflows if TYPE_CHECKING: @@ -311,7 +313,7 @@ class _Glob: def __init__(self, atoms: list[list[str]]) -> None: self.pattern = "".join(a + q for a, q in atoms) + r"\Z" # the regex it matches as - self._atoms = [(re.compile(a), q) for a, q in atoms] + self._atoms = [(compile_user_regex(a), q) for a, q in atoms] def _skip(self, at: set[int]) -> set[int]: """``at`` and each atom after a run of optional atoms (``?``, ``*``) that starts at one of them.""" diff --git a/dokimi/dokimi/repos/process_metrics.py b/dokimi/dokimi/repos/process_metrics.py index 9b28589b1c..5f0fc0e60c 100644 --- a/dokimi/dokimi/repos/process_metrics.py +++ b/dokimi/dokimi/repos/process_metrics.py @@ -40,6 +40,7 @@ from typing import Any from dokimi.repos.event_format import TOOL_KINDS, followed_path, plain_path +from dokimi.user_regex import compile_user_regex COUNTER_FIELDS = ("text", "output", "any") @@ -69,8 +70,8 @@ def parse_counter(name: str, value: Any) -> Counter: if where not in COUNTER_FIELDS: raise ValueError(f"process_metrics/{name}: match must be one of {', '.join(COUNTER_FIELDS)}, got {where!r}") try: - return Counter(re.compile(regex), where) - except re.error as exc: + return Counter(compile_user_regex(regex), where) + except ValueError as exc: raise ValueError(f"process_metrics/{name}: not a valid regex: {exc}") from exc diff --git a/dokimi/dokimi/user_regex.py b/dokimi/dokimi/user_regex.py new file mode 100644 index 0000000000..d49f39af10 --- /dev/null +++ b/dokimi/dokimi/user_regex.py @@ -0,0 +1,21 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Compile a regex a user wrote, with every refusal as a ``ValueError``. + +``re.compile`` refuses a pattern in three ways: ``re.error`` for a bad pattern, ``OverflowError`` for a repeat +count that does not fit (``a{999999999999}``) and ``RecursionError`` for groups nested too deep. None of the three +is a ``ValueError``; the loaders caught only ``re.error``, so the other two escaped as a traceback. +""" + +from __future__ import annotations + +import re + + +def compile_user_regex(text: str) -> re.Pattern[str]: + """``re.compile(text)``, with each of the three refusals raised as a ``ValueError`` carrying its message.""" + try: + return re.compile(text) + except (re.error, OverflowError, RecursionError) as exc: + raise ValueError(str(exc)) from exc diff --git a/dokimi/tests/test_context_consistency.py b/dokimi/tests/test_context_consistency.py index 9414bab8ba..cca1480779 100644 --- a/dokimi/tests/test_context_consistency.py +++ b/dokimi/tests/test_context_consistency.py @@ -131,6 +131,13 @@ def test_a_pattern_that_is_not_a_regex_is_refused(value): parse_contract({"actions": {"test": {"tool": "Bash", "command": value}}, "rules": []}) +@pytest.mark.parametrize("value", ["a{999999999999}", "(" * 2000 + ")" * 2000]) +def test_a_regex_that_overflows_or_nests_too_deep_is_refused(value): + """re.compile raises OverflowError or RecursionError for these; the contract refuses them as bad input.""" + with pytest.raises(ValueError, match="bad regex"): + parse_contract({"actions": {"test": {"tool": "Bash", "command": value}}, "rules": []}) + + def test_two_valid_strategies_are_diversity_not_instability(): runs = [_run(f"g{i}", GREP, GREP, EDIT, TEST) for i in range(3)] + \ [_run(f"r{i}", READ, EDIT, TEST, READ, EDIT, TEST) for i in range(3)] diff --git a/dokimi/tests/test_import_architecture.py b/dokimi/tests/test_import_architecture.py index 4b9438e119..a7d5220df9 100644 --- a/dokimi/tests/test_import_architecture.py +++ b/dokimi/tests/test_import_architecture.py @@ -82,7 +82,7 @@ "dokimi.llm_pricing", "dokimi.measure", "dokimi.process", "dokimi.process_hooks", "dokimi.process_io", "dokimi.atomic_write", "dokimi.digest", "dokimi.files", "dokimi.frontmatter", "dokimi.model_names", "dokimi.provenance", "dokimi.records", "dokimi.registry", "dokimi.utils", "dokimi.write_probe", - "dokimi.yaml_unique", "dokimi.pattern_glob", + "dokimi.yaml_unique", "dokimi.pattern_glob", "dokimi.user_regex", "dokimi.judge_rule", "dokimi.spend", "dokimi.text_spans", "dokimi.code_spans", "dokimi.dokimi_commit", # Token/cost record the LLM chokepoint fills; it lives under metrics/ but diff --git a/dokimi/tests/test_repo_manifest.py b/dokimi/tests/test_repo_manifest.py index aea327d0aa..d0c0748189 100644 --- a/dokimi/tests/test_repo_manifest.py +++ b/dokimi/tests/test_repo_manifest.py @@ -117,6 +117,7 @@ def test_valid_repo_passes_and_reports_tasks_and_guidance(tmp_path): (lambda m: m.update(surprise=1), "surprise"), (lambda m: m.pop("entry_points"), "entry_points"), (lambda m: m.update(process_metrics={"bazel": "bazel("}), "process_metrics/bazel: not a valid regex"), + (lambda m: m.update(process_metrics={"bazel": "a{999999999999}"}), "process_metrics/bazel: not a valid regex"), (lambda m: m.update(process_metrics={"icpx": {"regex": "icpx", "match": "stderr"}}), "match"), (lambda m: m.update(process_metrics={"bad name": "x"}), "process_metrics"), (lambda m: m.update(process_metrics={"icpx": {"regex": "icpx", "mach": "output"}}), "mach"), diff --git a/dokimi/tests/test_repo_process_metrics.py b/dokimi/tests/test_repo_process_metrics.py index 7e5017424e..326b0ba921 100644 --- a/dokimi/tests/test_repo_process_metrics.py +++ b/dokimi/tests/test_repo_process_metrics.py @@ -68,6 +68,9 @@ def test_counters_search_text_output_or_both(): @pytest.mark.parametrize("value, needle", [ ("bazel(", "not a valid regex"), ({"regex": "[a-"}, "not a valid regex"), + # re.compile raises OverflowError and RecursionError for these, not re.error: a refusal, not a traceback + ("a{999999999999}", "not a valid regex"), + ("(" * 2000 + ")" * 2000, "not a valid regex"), ({"regex": "x", "match": "stderr"}, "match must be one of"), ({"match": "text"}, "give a regex"), ("", "give a regex"), diff --git a/dokimi/tests/test_user_regex.py b/dokimi/tests/test_user_regex.py new file mode 100644 index 0000000000..c2ada657ba --- /dev/null +++ b/dokimi/tests/test_user_regex.py @@ -0,0 +1,40 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""compile_user_regex: each refusal of re.compile is a ValueError, at every site that compiles user text.""" + +import pytest + +from dokimi.repos.l0.branches import _filter_regex +from dokimi.user_regex import compile_user_regex + + +@pytest.mark.parametrize("text", ["bazel(", "[a-", "a{999999999999}", "(" * 2000 + ")" * 2000]) +def test_each_refusal_of_re_compile_is_a_value_error(text): + with pytest.raises(ValueError): + compile_user_regex(text) + + +def test_a_valid_pattern_compiles_to_the_same_pattern(): + assert compile_user_regex(r"\bbazel\b").pattern == r"\bbazel\b" + + +@pytest.mark.parametrize("pattern", [ + "a{999999999999}", + "(" * 3000 + ")" * 3000, + "[" * 2000, + "?" * 5000, + "*" * 5000 + "[a-z]+", + "**" * 3000, + "a{2}b", + "release/[0-9]+.x", +]) +def test_a_branch_filter_that_overflows_or_nests_is_parsed_not_raised(pattern): # test-quality: ok must-not-raise smoke test + """The filter compiles one character or one validated class per atom, so no text a workflow holds makes it raise. + A guard: the site does not raise on these inputs with or without the helper.""" + assert isinstance(_filter_regex(pattern).pattern, str) + + +def test_a_branch_filter_still_matches_the_branches_it_names(): + assert _filter_regex("release/*").match("release/1.x") + assert not _filter_regex("release/*").match("release/1/x") From 4eb699354f73674a845d9eba341b33eb4539b95b Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Fri, 4 Dec 2026 23:13:40 -0800 Subject: [PATCH 2/4] fix(contract): refuse a list pattern whose element is not a regex A list-valued matcher key was joined with `|`, each element wrapped in `(?:...)`, and only the joined pattern was compiled. `["a)|(?:b"]` joins to two groups and was accepted, though the element is not a regex. Each element is now compiled on its own and refused by name. A list whose elements are each a regex compiles to the same pattern as before. A list where one element refers to a group of another is refused now, since that element is not a regex alone. Signed-off-by: Nikolay Petrov --- ...0261204_130000_napetrov_list-pattern-elements.md | 8 ++++++++ dokimi/dokimi/context/contract.py | 13 +++++++++++-- dokimi/tests/test_context_consistency.py | 11 +++++++++++ 3 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 dokimi/changelog.d/20261204_130000_napetrov_list-pattern-elements.md diff --git a/dokimi/changelog.d/20261204_130000_napetrov_list-pattern-elements.md b/dokimi/changelog.d/20261204_130000_napetrov_list-pattern-elements.md new file mode 100644 index 0000000000..d4056123d8 --- /dev/null +++ b/dokimi/changelog.d/20261204_130000_napetrov_list-pattern-elements.md @@ -0,0 +1,8 @@ + + +### Fixed + +- **A list of regexes in a `trace consistency --contract` action is checked one element at a time.** The list was joined with `|`, each element wrapped in `(?:...)`, and only the joined pattern was compiled, so `["a)|(?:b"]` was accepted (it joins to two groups) though `a)|(?:b` is not a regex. Each element is now compiled on its own, and a bad one is refused by name as `bad regex`. A list whose elements are each a regex compiles to the same pattern as before. The behaviour change: a list in which one element refers to a group of another (`["(a)", "\1"]`, `["(?Pa)", "(?P=x)"]`) is now refused, since that element is not a regex on its own; it was accepted before. diff --git a/dokimi/dokimi/context/contract.py b/dokimi/dokimi/context/contract.py index 0afde557ca..f74e777e7f 100644 --- a/dokimi/dokimi/context/contract.py +++ b/dokimi/dokimi/context/contract.py @@ -75,9 +75,18 @@ def _names(value: Any, where: str) -> tuple[str, ...]: def _pattern(value: Any, where: str) -> str: """A regex, or a list of them as one alternation; anything else (a number, a mapping) is refused, - so that `[pytest, tox]` is not read as the character class `['pytest', 'tox']`.""" + so that `[pytest, tox]` is not read as the character class `['pytest', 'tox']`. Each element must be a regex + on its own: joined, `a)|(?:b` would compile as two groups and pass. So a list element cannot refer to a group + of another element (`["(a)", "\\1"]`), though the joined pattern compiled before.""" if isinstance(value, list) and value: - return "|".join(f"(?:{p})" for p in _names(value, where)) + parts = [] + for p in _names(value, where): + try: + compile_user_regex(p) + except ValueError as exc: + raise ValueError(f"{where}: element {p!r}: bad regex ({exc})") from exc + parts.append(f"(?:{p})") + return "|".join(parts) if isinstance(value, str): return value raise ValueError(f"{where} wants a regex or a list of regexes, got {value!r}") diff --git a/dokimi/tests/test_context_consistency.py b/dokimi/tests/test_context_consistency.py index cca1480779..62120355e4 100644 --- a/dokimi/tests/test_context_consistency.py +++ b/dokimi/tests/test_context_consistency.py @@ -131,6 +131,17 @@ def test_a_pattern_that_is_not_a_regex_is_refused(value): parse_contract({"actions": {"test": {"tool": "Bash", "command": value}}, "rules": []}) +@pytest.mark.parametrize("value", [ + ["a)|(?:b"], [r"\bpytest\b", "a)|(?:b"], ["(", "x"], + ["(a)", "\\1"], ["(?Pa)", "(?P=x)"], # each joins to a pattern that compiled before; alone, neither element does +]) +def test_each_element_of_a_list_pattern_must_be_a_valid_regex_on_its_own(value): + """Joined with `|` and each wrapped in `(?:...)`, `a)|(?:b` compiles; it is not a regex on its own. The + backreference cases are refused on the same rule: `\\1` alone is not a regex.""" + with pytest.raises(ValueError, match="bad regex"): + parse_contract({"actions": {"test": {"tool": "Bash", "command": value}}, "rules": []}) + + @pytest.mark.parametrize("value", ["a{999999999999}", "(" * 2000 + ")" * 2000]) def test_a_regex_that_overflows_or_nests_too_deep_is_refused(value): """re.compile raises OverflowError or RecursionError for these; the contract refuses them as bad input.""" From bb8453528997a64d2838f07b964fd5ded3d78f81 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Sat, 5 Dec 2026 22:19:44 -0800 Subject: [PATCH 3/4] docs: correct regex refusal exit codes Thread: PRRT_kwDOVBg7g87AQkB0 Signed-off-by: Nikolay Petrov --- .../changelog.d/20261204_120000_napetrov_user-regex-refusal.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dokimi/changelog.d/20261204_120000_napetrov_user-regex-refusal.md b/dokimi/changelog.d/20261204_120000_napetrov_user-regex-refusal.md index 859cd2d506..66e8d76692 100644 --- a/dokimi/changelog.d/20261204_120000_napetrov_user-regex-refusal.md +++ b/dokimi/changelog.d/20261204_120000_napetrov_user-regex-refusal.md @@ -1,3 +1,3 @@ ### Fixed -- **A regex a user writes that Python cannot compile is refused, not a traceback.** `re.compile` raises `OverflowError` for a repeat count that does not fit (`a{999999999999}`) and `RecursionError` for groups nested too deep, not the `re.error` the `process_metrics` and contract loaders caught. Those patterns now refuse as bad input (exit 2, `Error: ...`) instead of crashing: a `process_metrics` counter in the repo manifest and a `trace consistency --contract` pattern. +- **A regex a user writes that Python cannot compile is refused, not a traceback.** `re.compile` raises `OverflowError` for a repeat count that does not fit (`a{999999999999}`) and `RecursionError` for groups nested too deep, not the `re.error` the `process_metrics` and contract loaders caught. A `trace consistency --contract` pattern that triggers either error is refused with exit 2 and `Error: ...`. If a `process_metrics` counter in a repo manifest triggers either error, `eval check` and `repo run` report a manifest error with `✗` and exit 1. From b8abf83d57828949ced3547440a06d16c17ef5d4 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Sat, 5 Dec 2026 23:04:28 -0800 Subject: [PATCH 4/4] fix(contract): refuse a backreference in a list pattern A list pattern is joined into one alternation, so a group number shifts when the elements are joined: `(a)\1` after `(x)` refers to `(x)` and the action misses a call it should match. Refuse `\1`-`\99`, `(?P=name)` and `(?(1)...)` in a list element; a single string keeps them. A digit in a character class or an escaped backslash is not a reference. The run consistency doc describes the rule. Signed-off-by: Nikolay Petrov --- ...000_napetrov_list-pattern-backreference.md | 3 ++ dokimi/docs/run-consistency.md | 6 +++- dokimi/dokimi/context/contract.py | 34 ++++++++++++++++++- dokimi/tests/test_context_consistency.py | 25 ++++++++++++++ 4 files changed, 66 insertions(+), 2 deletions(-) create mode 100644 dokimi/changelog.d/20261205_223000_napetrov_list-pattern-backreference.md diff --git a/dokimi/changelog.d/20261205_223000_napetrov_list-pattern-backreference.md b/dokimi/changelog.d/20261205_223000_napetrov_list-pattern-backreference.md new file mode 100644 index 0000000000..ccbc96267d --- /dev/null +++ b/dokimi/changelog.d/20261205_223000_napetrov_list-pattern-backreference.md @@ -0,0 +1,3 @@ +### Fixed + +- **A list-valued contract pattern refuses a backreference** — a list such as `command: ['(x)', '(a)\1']` joins its elements into one alternation, and a group number shifts when they are joined, so `\1` then named the `(x)` group and the action missed a call it should have matched. `contract` now refuses a `\1`-`\99`, a `(?P=name)` or a `(?(1)...)` in a list element with `a backreference is refused in a list pattern`. A single-string pattern keeps its backreferences and matches as before. diff --git a/dokimi/docs/run-consistency.md b/dokimi/docs/run-consistency.md index c3df6f782f..dd7794708a 100644 --- a/dokimi/docs/run-consistency.md +++ b/dokimi/docs/run-consistency.md @@ -156,7 +156,11 @@ file: a contract that wants an edit reports it missing, so name `Bash:find` / `Bash:xargs` in the edit action if agents edit that way. A regex value may be a list (`command: [pytest, tox]`), read as one alternation; -a number or a mapping is refused. +a number or a mapping is refused. Each element must be a regex on its own, so a +list element cannot refer to a group of another element. A list element also cannot +carry a backreference (`\1`-`\99`, `(?P=name)` or `(?(1)...)`): joined, the group numbers shift, +so `(a)\1` after `(x)` would refer to `(x)`, and the contract refuses it. A single +string keeps its backreferences. ### Added files and changed files diff --git a/dokimi/dokimi/context/contract.py b/dokimi/dokimi/context/contract.py index f74e777e7f..2473f62e5d 100644 --- a/dokimi/dokimi/context/contract.py +++ b/dokimi/dokimi/context/contract.py @@ -73,11 +73,40 @@ def _names(value: Any, where: str) -> tuple[str, ...]: raise ValueError(f"{where} wants a name or a list of names, got {value!r}") +def _has_backreference(source: str) -> bool: + """A group reference by number or name: `\\1`-`\\99`, `(?P=name)` or a conditional `(?(1)...)`. An escaped + backslash (`\\\\1`) is not one, and neither is anything in a character class, where `\\1` is an octal escape.""" + i, in_class = 0, False + while i < len(source): + c = source[i] + if c == "\\": + if not in_class and i + 1 < len(source) and source[i + 1] in "123456789": + return True + i += 2 + elif in_class: + in_class = c != "]" + i += 1 + elif c == "[": + in_class = True + i += 1 + if source.startswith("^", i): + i += 1 + if source.startswith("]", i): # a `]` first in the class is a literal + i += 1 + elif source.startswith("(?P=", i) or (source.startswith("(?(", i) and source[i + 3:i + 4].isdigit()): + return True + else: + i += 1 + return False + + def _pattern(value: Any, where: str) -> str: """A regex, or a list of them as one alternation; anything else (a number, a mapping) is refused, so that `[pytest, tox]` is not read as the character class `['pytest', 'tox']`. Each element must be a regex on its own: joined, `a)|(?:b` would compile as two groups and pass. So a list element cannot refer to a group - of another element (`["(a)", "\\1"]`), though the joined pattern compiled before.""" + of another element (`["(a)", "\\1"]`), though the joined pattern compiled before. Nor can it carry a + backreference of its own: joined after another element, group numbers shift, so `(a)\\1` after `(x)` refers + to `(x)` (a `(?P=name)` is refused for the same reason). A single string keeps its backreferences.""" if isinstance(value, list) and value: parts = [] for p in _names(value, where): @@ -85,6 +114,9 @@ def _pattern(value: Any, where: str) -> str: compile_user_regex(p) except ValueError as exc: raise ValueError(f"{where}: element {p!r}: bad regex ({exc})") from exc + if _has_backreference(p): + raise ValueError(f"{where}: element {p!r}: a backreference is refused in a list pattern, " + "since the group numbers shift when the elements are joined") parts.append(f"(?:{p})") return "|".join(parts) if isinstance(value, str): diff --git a/dokimi/tests/test_context_consistency.py b/dokimi/tests/test_context_consistency.py index ae4b5380e5..17deca4720 100644 --- a/dokimi/tests/test_context_consistency.py +++ b/dokimi/tests/test_context_consistency.py @@ -143,6 +143,31 @@ def test_each_element_of_a_list_pattern_must_be_a_valid_regex_on_its_own(value): parse_contract({"actions": {"test": {"tool": "Bash", "command": value}}, "rules": []}) +@pytest.mark.parametrize("value", [ + [r"(x)", r"(a)\1"], [r"(a)\1", "b"], [r"(?Pa)(?P=n)", "b"], [r"(a)(b)\2"], [r"(a)\1"], + [r"(x)", r"(a)(?(1)b|c)"], +]) +def test_a_backreference_in_a_list_pattern_is_refused(value): + """Joined, the elements get new group numbers: `(a)\\1` after `(x)` refers to `(x)`, so the alternation + does not match `aa`, though `(a)\\1` alone does. A single string keeps its backreferences.""" + with pytest.raises(ValueError, match="backreference"): + parse_contract({"actions": {"test": {"tool": "Bash", "command": value}}, "rules": []}) + + +@pytest.mark.parametrize("element, text", [(r"a\\1", "a\\1"), (r"[\1]x", "\x01x"), (r"[]\1]", "]")]) +def test_a_digit_that_is_not_a_backreference_is_allowed_in_a_list(element, text): + """`\\\\1` is a backslash and a 1; `[\\1]` is an octal escape in a character class, not a group.""" + c = parse_contract({"actions": {"test": {"tool": "Bash", "command": [element, "b"]}}, + "rules": [{"requires": "test"}]}) + assert check_contract(_run("r", ("Bash", {"command": text})), c) == [] + + +def test_a_backreference_in_a_single_string_pattern_still_matches(): + c = parse_contract({"actions": {"test": {"tool": "Bash", "command": r"(a)\1"}}, "rules": [{"requires": "test"}]}) + assert check_contract(_run("r", ("Bash", {"command": "aa"})), c) == [] + assert check_contract(_run("r", ("Bash", {"command": "ab"})), c) == ["requires: test"] + + @pytest.mark.parametrize("value", ["a{999999999999}", "(" * 2000 + ")" * 2000]) def test_a_regex_that_overflows_or_nests_too_deep_is_refused(value): """re.compile raises OverflowError or RecursionError for these; the contract refuses them as bad input."""