1010which the rounds met them.
1111
1212The 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
1718from __future__ import annotations
2021import json
2122import subprocess
2223import sys
23- from collections import Counter
24+ from collections . abc import Mapping
2425from pathlib import Path
2526
2627import pytest
2728
2829from coretrace_python import engine
29- from coretrace_python .analysis import AnalysisManager
3030from coretrace_python .cfg import CFGAnalysis
3131from coretrace_python .frontend import build_hir
32- from coretrace_python .interprocedural import CallGraphAnalysis , FunctionSummary , SummaryAnalysis
32+ from coretrace_python .interprocedural import CallGraphAnalysis , SummaryAnalysis
3333from coretrace_python .interprocedural .summaries import summarize
3434from coretrace_python .ir .ssa import SSAAnalysis
3535from 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.
199198CYCLE_OF_MODULES = {
200199 "pkg/__init__.py" : "" ,
201200 "pkg/a.py" : "import os\n \n from pkg import b\n \n \n def a(x):\n b.b(x)\n os.system(x)\n \n \n def 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 \n from pkg import m{ following } \n \n \n def 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 \n from pkg import m0\n \n \n def 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 \n def 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