Skip to content

Commit f0cab6c

Browse files
committed
fix(engine): iterate an import cycle's summaries until they settle
Starting from empty summaries, the iteration stopped at MAX_PROJECT_ITERATIONS published summaries that missed what later iterations add, so a dependency still on its way read as no taint: a parameter returned at the end of a 22-module cycle was lost, and a sink at the end of a 30-module cycle was missed, on main too. The loop now runs until the index settles and the bound is gone; a comment at the loop states why it settles. The cross-module test runs --check in a subprocess with a timeout instead of asserting the bound, and two 30-module cycles are checked.
1 parent e5e51de commit f0cab6c

2 files changed

Lines changed: 70 additions & 23 deletions

File tree

‎src/coretrace_python/engine.py‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,6 @@
185185
_PROJECT_DEPENDANTS: frozenset[AnyAnalysis] = frozenset(
186186
a for a in ALL_ANALYSES if a.name in _PROJECT_DEPENDANT_NAMES
187187
)
188-
MAX_PROJECT_ITERATIONS = 20
189188

190189

191190
class ProjectSummariesUpdated(TransformationPass):
@@ -848,7 +847,17 @@ def _analyse_managers(
848847
)
849848
for manager in managers.values():
850849
manager.provide(ProjectSummaries, index)
851-
for _ in range(MAX_PROJECT_ITERATIONS):
850+
# Iterated until the index settles, with no bound: stopped earlier, summaries that
851+
# started empty would miss what later iterations add, a dependency still on its way
852+
# reading as no taint. It settles because each iteration can only add: the index holds
853+
# the same symbols from the start, and in every round of a module's fixpoint the rules
854+
# that read the index join what they read (a call's dependencies and records, heap
855+
# stores, merges), while those that do not join (a nonlocal record not summarized yet,
856+
# ``kept``, reachability, ``unsupported``, ``static``) depend on the code and the round
857+
# only. Each round's table thus grows with the index, the fixpoint too, in a finite
858+
# domain: the parameters, symbols and call records of the code. A rule reading the
859+
# index without joining would break this, and the loop's termination with it.
860+
while True:
852861
updated = SummaryIndex(
853862
{
854863
**seed.summaries,

‎tests/test_summary_fixpoint.py‎

Lines changed: 59 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,9 @@
1010
which the rounds met them.
1111
1212
The modules of an import cycle iterate their summaries together. Their own functions
13-
now start from the summaries a module's fixpoint starts from, so the iteration grows to
14-
its fixpoint instead of running to its bound.
13+
now start from the summaries a module's fixpoint starts from, and the iteration goes on
14+
until the index settles, however deep the cycle: no bound stops it while a dependency is
15+
still on its way.
1516
"""
1617

1718
from __future__ import annotations
@@ -20,16 +21,15 @@
2021
import json
2122
import subprocess
2223
import sys
23-
from collections import Counter
24+
from collections.abc import Mapping
2425
from pathlib import Path
2526

2627
import pytest
2728

2829
from coretrace_python import engine
29-
from coretrace_python.analysis import AnalysisManager
3030
from coretrace_python.cfg import CFGAnalysis
3131
from coretrace_python.frontend import build_hir
32-
from coretrace_python.interprocedural import CallGraphAnalysis, FunctionSummary, SummaryAnalysis
32+
from coretrace_python.interprocedural import CallGraphAnalysis, SummaryAnalysis
3333
from coretrace_python.interprocedural.summaries import summarize
3434
from coretrace_python.ir.ssa import SSAAnalysis
3535
from coretrace_python.source import SourceManager
@@ -194,8 +194,7 @@ def run_summary(callee):
194194
# The modules of an import cycle are analysed together, their summaries iterated until
195195
# the index of the project's summaries stops changing. ``THREE_FUNCTIONS`` across three
196196
# modules: a call from one member to another used to be a call to an unknown symbol on
197-
# the first iteration and a project call on the next, and the iteration never settled
198-
# before its bound.
197+
# the first iteration and a project call on the next, and the iteration never settled.
199198
CYCLE_OF_MODULES = {
200199
"pkg/__init__.py": "",
201200
"pkg/a.py": "import os\n\nfrom pkg import b\n\n\ndef a(x):\n b.b(x)\n os.system(x)\n\n\ndef run():\n a(input())\n",
@@ -204,23 +203,62 @@ def run_summary(callee):
204203
}
205204

206205

207-
def test_a_call_cycle_across_modules_converges_before_the_bound(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
206+
def project_findings(tmp_path: Path, files: Mapping[str, str]) -> list[tuple[str, str, int, str | None]]:
207+
"""The findings of ``--check`` on a project of several files, by path in the project,
208+
failing the test instead of waiting when the analysis does not end."""
209+
208210
root = tmp_path / "project"
209-
for path, text in CYCLE_OF_MODULES.items():
211+
for path, text in files.items():
210212
(root / path).parent.mkdir(parents=True, exist_ok=True)
211213
(root / path).write_text(text, encoding="utf-8")
212-
extractions: Counter[str] = Counter()
213-
summaries_of = engine._summaries_of
214+
try:
215+
completed = subprocess.run(
216+
[sys.executable, "-m", "coretrace_python", "--check", str(root), "--format", "json"],
217+
capture_output=True,
218+
text=True,
219+
check=False,
220+
timeout=TIMEOUT,
221+
)
222+
except subprocess.TimeoutExpired:
223+
pytest.fail(f"the analysis did not end within {TIMEOUT} s")
224+
report = json.loads(completed.stdout)
225+
return [
226+
(f["rule_id"], f["location"]["path"], f["location"]["line"], f["metadata"].get("verdict"))
227+
for f in report["findings"]
228+
]
229+
230+
231+
def test_a_call_cycle_across_modules_converges(tmp_path: Path) -> None:
232+
assert project_findings(tmp_path, CYCLE_OF_MODULES) == [("command-injection", "pkg/a.py", 12, "vulnerability")]
233+
234+
235+
# Starting from empty summaries, an index that has not settled yet misses what later
236+
# iterations add: stopped there, a dependency still on its way would read as no taint.
237+
# A cycle deeper than the 20 iterations the loop used to stop at.
238+
DEPTH = 30
239+
240+
241+
def deep_cycle(last: str, caller: str) -> dict[str, str]:
242+
"""``DEPTH`` modules in an import cycle, each ``m<i>.f`` returning ``m<i+1>.f(x)``,
243+
the last doing ``last`` with ``x`` first; ``pkg/app.py`` holds ``caller``."""
244+
245+
files = {"pkg/__init__.py": "", "pkg/app.py": caller}
246+
for i in range(DEPTH):
247+
following = (i + 1) % DEPTH
248+
own = last if i == DEPTH - 1 else ""
249+
files[f"pkg/m{i}.py"] = f"import os\n\nfrom pkg import m{following}\n\n\ndef f(x):\n{own} return m{following}.f(x)\n"
250+
return files
251+
252+
253+
def test_a_parameter_returned_at_the_end_of_a_deep_cycle_reaches_the_caller(tmp_path: Path) -> None:
254+
caller = "import os\n\nfrom pkg import m0\n\n\ndef run():\n os.system(m0.f(input()))\n"
255+
findings = project_findings(tmp_path, deep_cycle(" if x:\n return x\n", caller))
256+
257+
assert findings == [("command-injection", "pkg/app.py", 7, "vulnerability")]
214258

215-
def counted(manager: AnalysisManager) -> dict[str, FunctionSummary]:
216-
extractions[manager.module.name] += 1
217-
return summaries_of(manager)
218259

219-
monkeypatch.setattr(engine, "_summaries_of", counted)
220-
analysis = engine.analyze_project(root, [engine.BUNDLED_PLUGINS])
260+
def test_a_sink_at_the_end_of_a_deep_cycle_is_reported_at_the_caller(tmp_path: Path) -> None:
261+
caller = "from pkg import m0\n\n\ndef run():\n m0.f(input())\n"
262+
findings = project_findings(tmp_path, deep_cycle(" if x:\n os.system(x)\n", caller))
221263

222-
# Once per iteration, and once more for the module's results.
223-
assert max(extractions[name] for name in ("pkg.a", "pkg.b", "pkg.c")) <= engine.MAX_PROJECT_ITERATIONS
224-
assert [
225-
(f.rule_id, Path(str(f.span.source_id)).name, f.span.start_line, f.metadata["verdict"]) for f in analysis.findings
226-
] == [("command-injection", "a.py", 12, "vulnerability")]
264+
assert findings == [("command-injection", "pkg/app.py", 5, "vulnerability")]

0 commit comments

Comments
 (0)