Skip to content

Commit 656b9cd

Browse files
committed
fix(frontend): reject syntax nested too deep instead of crashing the scan (#233)
1 parent edb2589 commit 656b9cd

3 files changed

Lines changed: 107 additions & 2 deletions

File tree

‎docs/usage.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,10 @@ get_asgi_application()` in `asgi.py` or `email = forms.EmailField()` in a form c
8484
calls the analyzer sees, and a module-level `os.system(input())` is a finding in `<module>`.
8585
A function using syntax outside the supported subset is reported as an
8686
`unsupported-syntax` note and the other functions are still analysed; a file Python
87-
itself cannot parse is reported as a `syntax-error`. The coverage line and the JSON
87+
itself cannot parse is reported as a `syntax-error`, and so is a file whose syntax is
88+
nested more than 500 levels deep (a chain of hundreds of `+` or chained calls, which only
89+
generated code writes), which the analyzer does not follow; the other files are still
90+
analysed. The coverage line and the JSON
8891
report's per-file detail tell "no findings" from "nothing analysed".
8992

9093
Taint follows values between functions and across files through function summaries,

‎src/coretrace_python/frontend/ast_adapter.py‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,13 @@ class HIRBuildError(Exception):
1313
"""A source-located failure to represent parsed syntax as PyHIR."""
1414

1515

16+
# The frontend and the analyses after it recurse once per level of nesting: syntax nested
17+
# deeper, which Python parses in left-nested chains (``"a" + "b" + …``, ``x.f().g()…``)
18+
# and only generated code reaches, would exhaust Python's recursion limit (#233). The
19+
# bound leaves the later stages room below that limit, whatever the call stack.
20+
MAX_NESTING = 500
21+
22+
1623
_BINARY_OPERATORS = {
1724
ast.Add: "add",
1825
ast.Sub: "sub",
@@ -449,4 +456,21 @@ def module(self, tree: ast.Module) -> nodes.Module:
449456

450457

451458
def build_module(source: SourceFile, tree: ast.Module) -> nodes.Module:
452-
return AstHIRBuilder(source).module(tree)
459+
builder = AstHIRBuilder(source)
460+
too_deep = _nested_too_deep(tree)
461+
if too_deep is not None:
462+
builder.fail(too_deep, f"syntax nested more than {MAX_NESTING} levels deep, beyond what the analyzer follows")
463+
return builder.module(tree)
464+
465+
466+
def _nested_too_deep(tree: ast.AST) -> ast.AST | None:
467+
"""The first node nested more than ``MAX_NESTING`` levels below ``tree``, found
468+
without recursion; None when there is none."""
469+
470+
pending: list[tuple[ast.AST, int]] = [(tree, 0)]
471+
while pending:
472+
node, depth = pending.pop()
473+
if depth > MAX_NESTING:
474+
return node
475+
pending.extend((child, depth + 1) for child in ast.iter_child_nodes(node))
476+
return None

‎tests/test_deep_nesting.py‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
"""Acceptance tests for issue #233: syntax nested deeper than the analyzer follows.
2+
3+
The frontend and the analyses after it recurse once per level of nesting. Python parses
4+
left-nested chains of any length (``"a" + "b" + …``, ``a.b.b…``, ``x.strip().strip()…``),
5+
so the frontend rejects, before building PyHIR, a file whose syntax is nested deeper than
6+
``MAX_NESTING`` levels, as it rejects one it cannot represent: a ``syntax-error`` note
7+
for that file, and the rest of the project analysed. Syntax within the bound is analysed
8+
as before.
9+
"""
10+
11+
from __future__ import annotations
12+
13+
import json
14+
from pathlib import Path
15+
16+
import pytest
17+
18+
from coretrace_python.cli import main
19+
from coretrace_python.frontend import HIRBuildError, build_hir
20+
from coretrace_python.frontend.ast_adapter import MAX_NESTING
21+
from coretrace_python.source import SourceManager
22+
23+
24+
def chain(terms: int) -> str:
25+
return "X = " + " + ".join(['"ab"'] * terms) + "\n"
26+
27+
28+
@pytest.mark.parametrize(
29+
"text",
30+
[
31+
chain(3000),
32+
"X = a" + ".b" * 3000 + "\n",
33+
"import sys\nX = sys.argv[1]" + ".strip()" * 600 + "\n",
34+
],
35+
)
36+
def test_a_file_nested_too_deep_is_rejected_and_the_project_is_analysed(
37+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], text: str
38+
) -> None:
39+
root = tmp_path / "proj"
40+
root.mkdir()
41+
(root / "deep.py").write_text(text, encoding="utf-8")
42+
(root / "run.py").write_text("eval(input())\n", encoding="utf-8")
43+
monkeypatch.chdir(tmp_path)
44+
45+
assert main(["--check", "proj", "--format", "json"]) == 1
46+
captured = capsys.readouterr()
47+
report = json.loads(captured.out)
48+
49+
assert "Traceback" not in captured.err
50+
assert {(f["location"]["path"], f["rule_id"]) for f in report["findings"]} >= {
51+
("deep.py", "syntax-error"),
52+
("run.py", "dangerous-eval"),
53+
}
54+
(note,) = [f for f in report["findings"] if f["rule_id"] == "syntax-error"]
55+
assert f"nested more than {MAX_NESTING} levels" in note["message"]
56+
57+
58+
def test_the_rejection_names_where_the_nesting_goes_too_deep() -> None:
59+
with pytest.raises(HIRBuildError, match=rf"^a\.py:1:\d+: .*nested more than {MAX_NESTING}"):
60+
build_hir(SourceManager().add_source("a.py", chain(3000)))
61+
62+
63+
def test_syntax_within_the_bound_is_analysed(
64+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
65+
) -> None:
66+
root = tmp_path / "proj"
67+
root.mkdir()
68+
terms = MAX_NESTING - 10
69+
(root / "run.py").write_text(
70+
"import os\nimport sys\n\nX = sys.argv[1]" + ' + "ab"' * terms + "\nos.system(X)\n",
71+
encoding="utf-8",
72+
)
73+
monkeypatch.chdir(tmp_path)
74+
75+
assert main(["--check", "proj", "--format", "json"]) == 1
76+
report = json.loads(capsys.readouterr().out)
77+
78+
assert [f["rule_id"] for f in report["findings"]] == ["command-injection"]

0 commit comments

Comments
 (0)