mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-03 18:28:19 +00:00
The maintainer's answer of 2026-11-27 to question 2 of the ninth session's menu, "Record and stop
asking", as offered: "a failed judge call adds a degradation to the manifest, with the count; the
report says those questions went unasked; after one transport failure the remaining questions are
not asked." Measured by the ninth session: with a key in the environment and no network, 16 judge
calls failed in one scan of a four-file subject, three attempts each, and each dropped its claim
as a "no" would (model/pipeline.py); the manifest counted model_calls 16 and recorded no failure,
and the report said less than that of a run without an endpoint.
What changed:
- model/scan.py, `_CountingClient`: a call that raises is counted in `failed` and ends the asking.
The calls left in the question being put are refused without reaching the client (`refused`),
and the driver withholds the judge from every question after it, as it does when the budget runs
out. An answer with no decision in it (empty, not JSON, no boolean `vulnerable`) is counted in
`failed` as well and does not end the asking. The graph still arbitrates every region.
- Two degradations, each with a sentence under "What could not be analysed" (reports.py) and a
line in the scan skill's list:
- `judge_calls_failed`, `count`: the judge calls that gave no decision.
- `judge_withheld`, `questions`: the judge calls refused after the failure in the question
being put. Of the questions after it the report says that none was put to the judge; they are
not counted, because some of them would have put nothing to the judge.
- model/pipeline.py: the parsing half of `_ask` is moved as it was into `judge_decision`, so the
driver reads a decision the way `_ask` does. `_ask` returns what it returned.
- The claim of every such question is still dropped, as before: "Keep the claim" was not chosen.
The session's two readings of the decision, open to correction:
- A transport failure is read as a judge call that raised, whatever the exception. The transport
has already made its three attempts for what is transient (provider/openrouter.py), so one
raised call ends the asking for the whole scan. That holds for a connection failure and for a
timeout, and also for a request the endpoint refuses with an error status, where the transport
makes one attempt: there the scan withholds every later question, where before it dropped that
claim alone and went on. The judge_withheld line says so in the report.
- A failed judge call is read as a call that raised or a call whose answer gave no decision. Both
are counted.
Measured on fresh copies of the four C files the ninth session used, with a placeholder key and
the network off (the scratch is /tmp/opencode/s10_c2_* and is not kept):
- Native, in a network namespace without routes: one "judge call failed" line, file_targets=4,
findings=15, exit 0, 45 s (s10_c2_native_key3.out). The ninth session's run of the same bytes:
16 lines, 68 s.
- In a probe image built from openultrasast:dev 3f959b31f2f2 with src copied over, network none:
one line, file_targets=4, findings=15, exit 0, 43 s (s10_c2_image_key3.out). The ninth
session's run: 16 lines, 65 s. The probe image is removed.
- Both manifests: model_calls 1, judge_calls_failed with count 1, judge_withheld with questions
7; report.md carries the two sentences (s10_c2_native_inspect3.out, s10_c2_image_inspect3.out).
The findings are the 15 the ninth session recorded with a key and without one.
Tests, one at a time, each red before its code:
- test_a_judge_that_cannot_be_reached_is_recorded_and_asked_no_further: on a git archive of
HEAD, assert 120 == 1; after, one call, model_calls 1, ten regions arbitrated, the two
degradations with count 1 and questions 5.
- test_a_judge_answer_with_no_decision_in_it_is_counted_and_the_rest_are_still_asked: red with
no degradation; after, count 120 and no judge_withheld.
- test_a_failed_judge_call_is_reported_as_unasked_and_not_as_a_no: red with the two bare
reasons; after, the two sentences. The three red runs, with the package imported from the
archive, are in s10_c2_red8.out: 3 failed, 1 passed.
- GREEN: 657 passed over the 39 test files that name degradations, scan_repository, model_calls
or write_markdown_report (s10_c2_green9.out); 214 passed over ten model, report and skill files
(s10_c2_green8.out). ruff, mypy, the three gates and compileall pass, and the gates print what
they printed before (s10_c2c_exits.txt). `git diff --check` exits 0. No whole-suite run: that is
step 9.
- The review took three rounds on one reviewer. Round one approved a first shape that counted the
withheld regions, and remarked that a region with several families was counted as withheld while
its first family had been put to the judge; its other remarks changed the second sentence,
`__all__` and a docstring. Round two blocked the sum that replaced that count: it added judge
calls to region-and-family questions under one name. The count is of judge calls now. Round
three approved this diff, on the condition that this message carry the measured numbers.
By reading, not measured: a pre-push run makes no judge call (push/runner.py and push/policy.py
pass no client and an execution budget), so the two reasons cannot arise there.
Found and not fixed, for the maintainer:
- .agents/skills/openultrasast-scan/SKILL.md:68-70 and docs/where-we-stand.md:349-350 say that
`learning_endpoint_unavailable` has no line in report.md. It has had one since f555dee
(2026-10-02).
- The citations of scan.py in docs/detection-techniques.md: of 24, 19 sit one, two or seven lines
further down after this commit (5 do not move, 9 move by one line, 1 by two, 9 by seven).
771 lines
35 KiB
Python
771 lines
35 KiB
Python
"""contributor-scan task 1.2: the repository driver (Req 3).
|
|
|
|
Pair scoring built one CPG per pair and asked one region. A repository has thousands of regions, and the two
|
|
things that were free at pair scale are the two that dominate here:
|
|
|
|
* **CPG construction.** A build is 5-30s on a 40-line excerpt. Building one per region would make a
|
|
repository scan unusable, so the driver builds ONE and reuses it.
|
|
* **Model calls.** The enumerator caps candidates at 8 per region, which says nothing about a scan with two
|
|
thousand regions. The budget is therefore a total for the run, spent on the highest-ranked regions first,
|
|
and whatever it does not reach is COUNTED rather than quietly dropped.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
def _region(path="a.py", function="run", families=("injection",), rank=1.0): # type: ignore[no-untyped-def]
|
|
from openultrasast.model.regions import ScanRegion
|
|
|
|
return ScanRegion(path=path, function=function, language="python", families=families, rank=rank, source="entry_point")
|
|
|
|
|
|
class _Backend:
|
|
"""Counts builds, so the one-CPG-per-scan promise is testable rather than asserted."""
|
|
|
|
def __init__(self, fail: bool = False) -> None:
|
|
self.builds = 0
|
|
self._fail = fail
|
|
|
|
def available(self) -> bool:
|
|
return True
|
|
|
|
def build(self, root): # type: ignore[no-untyped-def]
|
|
from openultrasast.cpg.backend import CpgResult
|
|
|
|
self.builds += 1
|
|
if self._fail:
|
|
return None
|
|
return CpgResult(cpg_path=Path("cpg.bin"), run=lambda q, p: [])
|
|
|
|
|
|
class _AnsweringJudge:
|
|
"""The judge as it is when the endpoint answers: one call per question put to it, each answered `yes`."""
|
|
|
|
def __init__(self) -> None:
|
|
self.calls = 0
|
|
|
|
def complete(self, **kw): # type: ignore[no-untyped-def]
|
|
from openultrasast.tool_hunter import ChatResponse
|
|
|
|
self.calls += 1
|
|
return ChatResponse(content='{"vulnerable": true}')
|
|
|
|
|
|
def _ten_files_with_six_sinks(tmp_path): # type: ignore[no-untyped-def]
|
|
"""Ten identical files with six sinks each, in two families: twenty questions that each put six to the judge."""
|
|
source = (
|
|
"import os\nimport subprocess\n\n\ndef run(cmd):\n"
|
|
" os.system(cmd)\n subprocess.call(cmd, shell=True)\n eval(cmd)\n"
|
|
" exec(cmd)\n open(cmd).read()\n os.popen(cmd)\n"
|
|
)
|
|
for i in range(10):
|
|
(tmp_path / f"f{i}.py").write_text(source)
|
|
return tuple(_region(path=f"f{i}.py", families=("injection", "path")) for i in range(10))
|
|
|
|
|
|
def test_one_cpg_is_built_for_the_whole_repository() -> None:
|
|
from openultrasast.model.scan import scan_repository
|
|
|
|
backend = _Backend()
|
|
regions = tuple(_region(path=f"f{i}.py") for i in range(20))
|
|
scan_repository(Path("/repo"), regions, backend=backend, client=None, model="")
|
|
assert backend.builds == 1, "a build per region would make a repository scan unusable"
|
|
|
|
|
|
def test_a_failed_build_yields_an_empty_result_not_an_exception() -> None:
|
|
from openultrasast.model.scan import scan_repository
|
|
|
|
result = scan_repository(Path("/repo"), (_region(),), backend=_Backend(fail=True), client=None, model="")
|
|
assert result.findings == ()
|
|
assert any("cpg_build_failed" in str(d) for d in result.degradations)
|
|
|
|
|
|
def test_an_exhausted_budget_withholds_the_judge_and_not_the_graph(tmp_path) -> None:
|
|
"""Req 3.2, 3.3: the budget bounds MODEL CALLS. Arbitration is free and must keep running.
|
|
|
|
The driver used to break the region loop when the budget ran out, spending a paid limit to stop unpaid
|
|
work. On VAmPI that left 16 of 22 regions unexamined and missed a BOLA the graph entails for nothing.
|
|
|
|
Real files on disk, because the driver enumerates candidates from them. A region pointing at a path that
|
|
does not exist yields no candidates, no model calls, and a budget that never trips -- which would make
|
|
this test pass for the wrong reason.
|
|
"""
|
|
from openultrasast.model.scan import ScanBudget, scan_repository
|
|
|
|
class _Client:
|
|
def complete(self, **kw): # type: ignore[no-untyped-def]
|
|
from openultrasast.tool_hunter import ChatResponse
|
|
|
|
return ChatResponse(content='{"vulnerable": true}')
|
|
|
|
source = "import os\n\n\ndef run(cmd):\n os.system(cmd)\n"
|
|
for i in range(50):
|
|
(tmp_path / f"f{i}.py").write_text(source)
|
|
regions = tuple(_region(path=f"f{i}.py") for i in range(50))
|
|
|
|
result = scan_repository(
|
|
tmp_path,
|
|
regions,
|
|
backend=_Backend(),
|
|
client=_Client(),
|
|
model="m",
|
|
budget=ScanBudget(max_model_calls=5, max_regions=50),
|
|
)
|
|
assert result.model_calls > 0, "the driver must enumerate candidates and ask the judge about them"
|
|
assert result.regions_scanned == 50, "every region is still arbitrated; only the judge is withheld"
|
|
assert result.regions_unjudged == 0
|
|
assert result.regions_unasked > 0, "the regions the budget could not afford a judge for are counted"
|
|
assert any("budget_exhausted" in str(d) for d in result.degradations)
|
|
|
|
|
|
def test_a_region_the_budget_could_not_afford_is_not_reported_as_clean(tmp_path) -> None:
|
|
"""`unasked` is the honesty counter: silent-because-decided and silent-because-unaffordable differ."""
|
|
from openultrasast.model.scan import ScanBudget, scan_repository
|
|
|
|
class _Client:
|
|
def complete(self, **kw): # type: ignore[no-untyped-def]
|
|
from openultrasast.tool_hunter import ChatResponse
|
|
|
|
return ChatResponse(content='{"vulnerable": true}')
|
|
|
|
source = "import os\n\n\ndef run(cmd):\n os.system(cmd)\n"
|
|
for i in range(10):
|
|
(tmp_path / f"f{i}.py").write_text(source)
|
|
regions = tuple(_region(path=f"f{i}.py") for i in range(10))
|
|
|
|
generous = scan_repository(
|
|
tmp_path, regions, backend=_Backend(), client=_Client(), model="m", budget=ScanBudget(max_model_calls=500, max_regions=10)
|
|
)
|
|
starved = scan_repository(
|
|
tmp_path, regions, backend=_Backend(), client=_Client(), model="m", budget=ScanBudget(max_model_calls=1, max_regions=10)
|
|
)
|
|
|
|
assert generous.regions_unasked == 0, "nothing went unasked when the budget covered the run"
|
|
assert starved.regions_unasked > generous.regions_unasked
|
|
assert starved.regions_scanned == generous.regions_scanned == 10
|
|
|
|
|
|
def test_a_judge_that_cannot_be_reached_is_recorded_and_asked_no_further(tmp_path) -> None:
|
|
"""A failed judge call is no verdict. It used to be read as one: with a key set and the network off, every
|
|
call failed, three attempts each, each dropped its claim as a `no` would, and nothing recorded it. The first
|
|
failure is now counted and the questions after it are not put to the judge.
|
|
"""
|
|
from openultrasast.model.scan import ScanBudget, scan_repository
|
|
|
|
class _Unreachable(_AnsweringJudge):
|
|
def complete(self, **kw): # type: ignore[no-untyped-def]
|
|
self.calls += 1
|
|
raise ConnectionError("network is unreachable")
|
|
|
|
regions = _ten_files_with_six_sinks(tmp_path)
|
|
budget = ScanBudget(max_model_calls=500, max_regions=10)
|
|
|
|
agreeing = _AnsweringJudge()
|
|
scan_repository(tmp_path, regions, backend=_Backend(), client=agreeing, model="m", budget=budget)
|
|
per_question = agreeing.calls // 20
|
|
assert agreeing.calls == per_question * 20 and per_question > 1, "twenty questions with the same calls each, more than one"
|
|
|
|
judge = _Unreachable()
|
|
result = scan_repository(tmp_path, regions, backend=_Backend(), client=judge, model="m", budget=budget)
|
|
|
|
assert judge.calls == 1, "a judge that could not be reached is not asked again"
|
|
assert result.model_calls == 1, "the call that was made and failed is counted as one"
|
|
assert result.regions_scanned == 10, "the graph still arbitrated every region"
|
|
failed = [dict(d) for d in result.degradations if d.get("reason") == "judge_calls_failed"]
|
|
assert failed == [{"stage": "model", "reason": "judge_calls_failed", "count": 1}]
|
|
withheld = [dict(d) for d in result.degradations if d.get("reason") == "judge_withheld"]
|
|
# The judge calls refused after the failure in the first question. The nineteen questions after it (the
|
|
# other family of the first region, and nine regions with both of theirs) are not counted here: the count
|
|
# is of judge calls, and the report says of the rest that none was put to the judge.
|
|
assert withheld == [{"stage": "model", "reason": "judge_withheld", "questions": per_question - 1}]
|
|
|
|
|
|
def test_a_judge_answer_with_no_decision_in_it_is_counted_and_the_rest_are_still_asked(tmp_path) -> None:
|
|
"""An answer that decides nothing drops its claim as a call that raises does. The judge was reached, so the
|
|
questions after it are still put; the scan counts the failures and goes on.
|
|
"""
|
|
from openultrasast.model.scan import ScanBudget, scan_repository
|
|
|
|
class _Rambling(_AnsweringJudge):
|
|
def complete(self, **kw): # type: ignore[no-untyped-def]
|
|
from openultrasast.tool_hunter import ChatResponse
|
|
|
|
self.calls += 1
|
|
return ChatResponse(content="I cannot say.")
|
|
|
|
regions = _ten_files_with_six_sinks(tmp_path)
|
|
budget = ScanBudget(max_model_calls=500, max_regions=10)
|
|
|
|
agreeing = _AnsweringJudge()
|
|
scan_repository(tmp_path, regions, backend=_Backend(), client=agreeing, model="m", budget=budget)
|
|
judge = _Rambling()
|
|
result = scan_repository(tmp_path, regions, backend=_Backend(), client=judge, model="m", budget=budget)
|
|
|
|
assert judge.calls == agreeing.calls, "a judge that answered is asked the next question"
|
|
assert result.findings == ()
|
|
failed = [dict(d) for d in result.degradations if d.get("reason") == "judge_calls_failed"]
|
|
assert failed == [{"stage": "model", "reason": "judge_calls_failed", "count": judge.calls}]
|
|
assert not [d for d in result.degradations if d.get("reason") == "judge_withheld"]
|
|
|
|
|
|
def test_the_budget_is_spent_on_the_highest_ranked_regions_first() -> None:
|
|
from openultrasast.model.scan import ScanBudget, scan_repository
|
|
|
|
seen: list[str] = []
|
|
|
|
class _Backend2(_Backend):
|
|
def build(self, root): # type: ignore[no-untyped-def]
|
|
from openultrasast.cpg.backend import CpgResult
|
|
|
|
self.builds += 1
|
|
return CpgResult(cpg_path=Path("c.bin"), run=lambda q, p: (seen.append(str(p.get("function"))), [])[1])
|
|
|
|
regions = (_region(path="low.py", function="low", rank=0.1), _region(path="high.py", function="high", rank=1.0))
|
|
scan_repository(Path("/repo"), regions, backend=_Backend2(), client=None, model="", budget=ScanBudget(max_regions=1))
|
|
assert seen and seen[0] == "high", f"budget spent on the wrong region first: {seen}"
|
|
|
|
|
|
def test_findings_are_ordered_by_rung_before_rank() -> None:
|
|
"""Req 3.1: what the model established outranks what the LLM merely proposed."""
|
|
from openultrasast.model.ladder import Rung
|
|
from openultrasast.model.pipeline import ModelFinding
|
|
from openultrasast.model.scan import _ordered
|
|
|
|
findings = [
|
|
(ModelFinding(site="a", family="injection", rung=Rung.SUSPICION), 1.0),
|
|
(ModelFinding(site="b", family="injection", rung=Rung.ENTAILED), 0.1),
|
|
(ModelFinding(site="c", family="injection", rung=Rung.CORROBORATED), 0.5),
|
|
]
|
|
assert [f.site for f in _ordered(findings)] == ["b", "c", "a"]
|
|
|
|
|
|
def test_the_result_reports_what_the_model_arbitrated() -> None:
|
|
"""Req 1.5: a user should see how much of the result the model established, not have to infer it."""
|
|
from openultrasast.model.scan import scan_repository
|
|
|
|
result = scan_repository(Path("/repo"), (_region(),), backend=_Backend(), client=None, model="")
|
|
assert set(result.by_rung) >= {"model_entailed", "model_corroborated", "suspicion"}
|
|
assert result.regions_scanned == 1
|
|
|
|
|
|
def test_a_region_is_only_asked_about_families_it_carries() -> None:
|
|
from openultrasast.model.scan import scan_repository
|
|
|
|
asked: list[str] = []
|
|
|
|
class _B(_Backend):
|
|
def build(self, root): # type: ignore[no-untyped-def]
|
|
from openultrasast.cpg.backend import CpgResult
|
|
|
|
self.builds += 1
|
|
return CpgResult(cpg_path=Path("c.bin"), run=lambda q, p: (asked.append(q), [])[1])
|
|
|
|
scan_repository(Path("/repo"), (_region(families=("injection",)),), backend=_B(), client=None, model="")
|
|
assert "dominance" not in asked and "config" not in asked
|
|
|
|
|
|
def test_the_driver_issues_one_query_invocation_per_kind_not_one_per_region(tmp_path) -> None:
|
|
"""Task 1.4: JVM startup, not CPG construction, is what dominates a repository scan.
|
|
|
|
Before batching the driver issued one `joern --script` call per region per family. A ten-line Python file
|
|
admits six families, so it cost six JVM launches and over four minutes; a thousand regions would have
|
|
taken about fifty hours. The whole scan's questions now go in one invocation per query kind.
|
|
"""
|
|
from openultrasast.model.scan import scan_repository
|
|
|
|
invocations: list[str] = []
|
|
|
|
class _CountingBackend:
|
|
def available(self): # type: ignore[no-untyped-def]
|
|
return True
|
|
|
|
def build(self, root): # type: ignore[no-untyped-def]
|
|
from openultrasast.cpg.backend import CpgResult
|
|
|
|
def run(query, params): # type: ignore[no-untyped-def]
|
|
invocations.append(f"single:{query}")
|
|
return []
|
|
|
|
def run_batch(query, requests): # type: ignore[no-untyped-def]
|
|
invocations.append(f"batch:{query}")
|
|
return {rid: [] for rid in requests}
|
|
|
|
result = CpgResult(cpg_path=Path("c.bin"), run=run)
|
|
object.__setattr__(result, "run_batch", run_batch)
|
|
return result
|
|
|
|
source = "import os\n\n\ndef run(cmd):\n os.system(cmd)\n"
|
|
for i in range(30):
|
|
(tmp_path / f"f{i}.py").write_text(source)
|
|
regions = tuple(_region(path=f"f{i}.py", families=("injection", "path")) for i in range(30))
|
|
|
|
scan_repository(tmp_path, regions, backend=_CountingBackend(), client=None, model="")
|
|
assert not any(i.startswith("single:") for i in invocations), f"unbatched calls remain: {invocations[:4]}"
|
|
# 30 regions x 2 families would have been 60 invocations; batching makes it one per query kind.
|
|
assert len(invocations) <= 3, f"expected one invocation per query kind, got {len(invocations)}"
|
|
|
|
|
|
class _SlowBackend:
|
|
"""A backend whose build and whose queries each cost a measurable, distinguishable amount of time."""
|
|
|
|
def __init__(self, build_cost: float, query_cost: float) -> None:
|
|
self.build_cost = build_cost
|
|
self.query_cost = query_cost
|
|
|
|
def available(self) -> bool:
|
|
return True
|
|
|
|
def build(self, root): # type: ignore[no-untyped-def]
|
|
import time
|
|
|
|
from openultrasast.cpg.backend import CpgResult
|
|
|
|
time.sleep(self.build_cost)
|
|
return CpgResult(cpg_path=Path("cpg.bin"), run=self._run)
|
|
|
|
def _run(self, query, params): # type: ignore[no-untyped-def]
|
|
import time
|
|
|
|
time.sleep(self.query_cost)
|
|
return []
|
|
|
|
|
|
def test_the_scan_reports_where_its_wall_clock_went() -> None:
|
|
"""contributor-scan 2.2/2.3: build against query is a decision input, and a total cannot answer it.
|
|
|
|
Whether a warm Joern server would buy anything depends on the ratio between a CPG build and the queries
|
|
over it. Reporting one figure for the scan makes that question unanswerable from an artifact.
|
|
"""
|
|
from openultrasast.model.scan import scan_repository
|
|
|
|
result = scan_repository(
|
|
Path("/repo"),
|
|
(_region(),),
|
|
backend=_SlowBackend(build_cost=0.30, query_cost=0.10),
|
|
client=None,
|
|
model="",
|
|
)
|
|
|
|
assert result.build_seconds >= 0.29, "the build was not timed"
|
|
assert result.query_seconds >= 0.09, "the queries were not timed"
|
|
assert result.seconds >= result.build_seconds + result.query_seconds
|
|
assert result.arbitrate_seconds == round(max(result.seconds - result.build_seconds - result.query_seconds, 0.0), 2)
|
|
|
|
|
|
def test_a_failed_build_still_reports_what_the_build_cost() -> None:
|
|
"""A build that fails after two minutes is the most important timing in the artifact, not the least."""
|
|
from openultrasast.model.scan import scan_repository
|
|
|
|
result = scan_repository(Path("/repo"), (_region(),), backend=_Backend(fail=True), client=None, model="")
|
|
|
|
assert result.build_seconds >= 0.0
|
|
assert result.query_seconds == 0.0, "nothing was queried"
|
|
|
|
|
|
def test_only_an_entry_point_gets_the_interprocedural_question(tmp_path) -> None:
|
|
"""contributor-scan 2.4: the trust boundary decides, not convenience.
|
|
|
|
An entry point's parameters ARE attacker input and a sink it reaches is its responsibility, so its
|
|
question follows the call graph. A file the walker fell back to has neither property: treating an
|
|
arbitrary helper's parameters as untrusted is what the repository default was protecting against.
|
|
"""
|
|
from openultrasast.model.regions import ScanRegion
|
|
from openultrasast.model.scan import ENTRY_POINT_CALL_DEPTH, _grouped, _spec_for
|
|
|
|
def region(source: str, function: str | None) -> ScanRegion:
|
|
return ScanRegion(path="a.py", function=function, language="python", families=("injection",), rank=1.0, source=source)
|
|
|
|
spec = _spec_for("injection", "python")
|
|
assert spec is not None
|
|
handler = region("entry_point", "get_by_username")
|
|
fallback = region("file_fallback", None)
|
|
named_but_not_an_entry_point = region("file_fallback", "helper")
|
|
|
|
grouped = _grouped((("0", handler, spec), ("1", fallback, spec), ("2", named_but_not_an_entry_point, spec)))["taint"]
|
|
|
|
assert grouped["0"]["parameterSources"] == "true"
|
|
assert grouped["0"]["callDepth"] == str(ENTRY_POINT_CALL_DEPTH)
|
|
for rid in ("1", "2"):
|
|
assert grouped[rid]["parameterSources"] == "false"
|
|
assert grouped[rid]["callDepth"] == "0", "following calls from an arbitrary function is not sound"
|
|
|
|
|
|
def test_the_call_depth_is_bounded() -> None:
|
|
"""'Every method reachable from a handler' is most of a repository, and an unbounded question is slow."""
|
|
from openultrasast.model.scan import ENTRY_POINT_CALL_DEPTH
|
|
|
|
assert 0 < ENTRY_POINT_CALL_DEPTH <= 5
|
|
|
|
|
|
def test_the_scan_reports_query_time_per_kind() -> None:
|
|
"""contributor-scan 2.3: which query costs the time is the whole server-mode decision.
|
|
|
|
On libpng the phase split taint 243.3s / config 10.7s over two invocations, against ~13s of fixed
|
|
startup each. A single total cannot tell startup from evaluation, and the two lead to opposite answers.
|
|
"""
|
|
from openultrasast.model.scan import scan_repository
|
|
|
|
regions = (
|
|
_region(path="a.py", families=("injection",)),
|
|
_region(path="b.py", families=("config_secrets",)),
|
|
)
|
|
result = scan_repository(Path("/repo"), regions, backend=_Backend(), client=None, model="")
|
|
|
|
assert set(result.query_seconds_by_kind) == {"taint", "config"}
|
|
assert sum(result.query_seconds_by_kind.values()) <= result.query_seconds + 0.05
|
|
|
|
|
|
def test_one_defect_is_one_finding_however_many_regions_reach_it(tmp_path) -> None:
|
|
"""contributor-scan 2.9. Task 2.4 let a region's question follow the call graph, and the moment it did,
|
|
many entry points could reach one shared sink: libpng reported the same site twenty-six times. A
|
|
contributor shown the same defect twenty-six times learns to scroll past it."""
|
|
from openultrasast.model.ladder import Rung
|
|
from openultrasast.model.pipeline import ModelFinding
|
|
from openultrasast.model.scan import _deduplicated
|
|
|
|
same = [
|
|
(ModelFinding(site="wpng.c:335:main", family="memory", rung=Rung.SUSPICION, witness="w"), 0.2),
|
|
(ModelFinding(site="wpng.c:335:main", family="memory", rung=Rung.ENTAILED, witness="w"), 1.0),
|
|
(ModelFinding(site="wpng.c:335:main", family="memory", rung=Rung.SUSPICION, witness="w"), 0.5),
|
|
]
|
|
|
|
kept = _deduplicated(same)
|
|
|
|
assert len(kept) == 1
|
|
finding, rank = kept[0]
|
|
assert finding.rung is Rung.ENTAILED, "the strongest rung survives"
|
|
assert finding.reached_from == 3, "and the count is what the duplication was worth"
|
|
assert rank == 1.0
|
|
|
|
|
|
def test_two_families_at_one_site_stay_two_findings() -> None:
|
|
"""`echo $_GET[...]` is an injection question and an output-encoding question, with different answers."""
|
|
from openultrasast.model.ladder import Rung
|
|
from openultrasast.model.pipeline import ModelFinding
|
|
from openultrasast.model.scan import _deduplicated
|
|
|
|
both = [
|
|
(ModelFinding(site="app.php:9:show", family="injection", rung=Rung.ENTAILED), 1.0),
|
|
(ModelFinding(site="app.php:9:show", family="output_encoding", rung=Rung.ENTAILED), 1.0),
|
|
]
|
|
|
|
assert len(_deduplicated(both)) == 2
|
|
|
|
|
|
def test_a_query_the_engine_could_not_answer_is_recorded_not_ignored() -> None:
|
|
"""contributor-scan 5.7. A 117k-line PHP CPG threw while loading, so every query returned nothing -- and
|
|
the scan reported 500 regions examined, no findings, and no degradation. A failed query and a clean
|
|
repository looked identical.
|
|
|
|
This is the failure mode the rung ladder cannot catch: every other honesty counter labels a VERDICT, and
|
|
here none was produced to label.
|
|
"""
|
|
from openultrasast.cpg.backend import CpgResult
|
|
from openultrasast.model.scan import scan_repository
|
|
|
|
class _Backend:
|
|
def available(self) -> bool:
|
|
return True
|
|
|
|
def build(self, root, **kwargs): # type: ignore[no-untyped-def]
|
|
return CpgResult(cpg_path=Path("cpg.bin"), run=lambda q, p: [], run_batch=lambda q, r: None)
|
|
|
|
result = scan_repository(Path("/repo"), (_region(),), backend=_Backend(), client=None, model="")
|
|
|
|
failures = [d for d in result.degradations if d.get("reason") == "query_failed"]
|
|
assert failures, "a query that could not be asked must be reported"
|
|
kinds = {d["kind"] for d in failures}
|
|
assert "taint" in kinds, "the taint failure is recorded"
|
|
assert "evidence" in kinds, "and so is the evidence pass that runs before it -- phase 0 of flow-aware-ranking"
|
|
assert result.findings == ()
|
|
|
|
|
|
def test_a_region_cap_that_hides_most_of_a_repository_is_reported(tmp_path: Path) -> None:
|
|
"""Paid Memberships Pro yields 4,463 regions from 637 files. A default budget of 500 examines 11% of it,
|
|
and a report that does not say so invites its silence to be read as a clean bill of health for the rest.
|
|
"""
|
|
from openultrasast.model.regions import ScanRegion
|
|
from openultrasast.model.scan import ScanBudget, scan_repository
|
|
|
|
class _Backend:
|
|
def available(self) -> bool:
|
|
return True
|
|
|
|
def build(self, root, *, language=""): # type: ignore[no-untyped-def]
|
|
from openultrasast.cpg.backend import CpgResult
|
|
|
|
return CpgResult(cpg_path=Path("cpg.bin"), run=lambda query, params: [])
|
|
|
|
regions = [
|
|
ScanRegion(path=f"f{n}.py", function="handler", language="python", families=("injection",), rank=0.5, source="entry_point")
|
|
for n in range(30)
|
|
]
|
|
for region in regions:
|
|
(tmp_path / region.path).write_bytes(b"print(1)\n")
|
|
result = scan_repository(tmp_path, regions, backend=_Backend(), budget=ScanBudget(max_model_calls=0, max_regions=10))
|
|
|
|
truncated = [d for d in result.degradations if d.get("reason") == "regions_truncated"]
|
|
assert truncated, "the cap hid two thirds of the regions and said nothing"
|
|
assert truncated[0]["examined"] == 10 and truncated[0]["total"] == 30
|
|
|
|
|
|
def test_tier_zero_pairs_are_not_asked_and_nothing_else_is_skipped(tmp_path: Path) -> None:
|
|
"""Phase 1 of flow-aware-ranking. A pair with no sink of its family in reach cannot yield a flow, so its
|
|
taint request is never issued -- and every other pair's request still is."""
|
|
from openultrasast.model.regions import ScanRegion
|
|
from openultrasast.model.scan import ScanBudget, scan_repository
|
|
|
|
issued: list[dict[str, object]] = []
|
|
|
|
class _Backend:
|
|
def available(self) -> bool:
|
|
return True
|
|
|
|
def build(self, root, *, language=""): # type: ignore[no-untyped-def]
|
|
from openultrasast.cpg.backend import CpgResult
|
|
|
|
def batch(kind, requests): # type: ignore[no-untyped-def]
|
|
if any(p.get("evidenceOnly") == "true" for p in requests.values()):
|
|
# Every family but the first has no sink in reach.
|
|
return {
|
|
rid: [{"kind": "summary", "sinks": 1 if i == 0 else 0, "sourceLocal": True, "familyInRepo": True}]
|
|
+ (
|
|
[
|
|
{
|
|
"kind": "sink",
|
|
"sink": "os.system(x)",
|
|
"sinkLine": "4",
|
|
"sinkMethod": "run",
|
|
"sinkArity": 1,
|
|
"sinkArg0Literal": False,
|
|
"cleansedOnCall": False,
|
|
}
|
|
]
|
|
if i == 0
|
|
else []
|
|
)
|
|
for i, rid in enumerate(requests)
|
|
}
|
|
issued.append({"kind": kind, "count": len(requests)})
|
|
return {rid: [] for rid in requests}
|
|
|
|
names = [str(p) for p in root.rglob("*.py")]
|
|
return CpgResult(
|
|
cpg_path=Path("cpg.bin"),
|
|
run=lambda q, p: [],
|
|
run_batch=lambda kind, requests: {
|
|
"__census__": [{"methods": len(names), "files": len(names), "file_names": names}],
|
|
**batch(kind, requests),
|
|
},
|
|
)
|
|
|
|
region = ScanRegion(
|
|
path="a.py", function="run", language="python", families=("injection", "path", "deserialization"), rank=0.9, source="entry_point"
|
|
)
|
|
(tmp_path / "a.py").write_bytes(b"print(1)\n")
|
|
result = scan_repository(tmp_path, [region], backend=_Backend(), budget=ScanBudget(max_model_calls=0))
|
|
|
|
taint = next(i for i in issued if i["kind"] == "taint")
|
|
assert taint["count"] == 1, "only the pair with a sink in reach is asked"
|
|
assert result.requests_pruned == 2, "and the two tier-0 pairs are counted, not silently dropped"
|
|
assert not any(d.get("reason") == "query_failed" for d in result.degradations)
|
|
|
|
|
|
_SINK_ROW = {
|
|
"kind": "sink",
|
|
"sink": "os.system(x)",
|
|
"sinkLine": "4",
|
|
"sinkMethod": "run",
|
|
"sinkArity": 1,
|
|
"sinkArg0Literal": False,
|
|
"cleansedOnCall": False,
|
|
}
|
|
|
|
|
|
def _sinks_of(family: str) -> tuple[str, ...]:
|
|
"""The sink names a request for ``family`` carries, which is how a request names its family."""
|
|
from openultrasast.model.scan import _spec_for
|
|
from openultrasast.model.specs import TaintSpec
|
|
|
|
spec = _spec_for(family, "python")
|
|
assert isinstance(spec, TaintSpec)
|
|
return tuple(spec.sinks)
|
|
|
|
|
|
def _by_question(requests): # type: ignore[no-untyped-def]
|
|
"""The requests of one pass, keyed by the question each asks: its file and its family's sinks."""
|
|
return {(str(p["file"]), tuple(p["sinks"])): p for p in requests}
|
|
|
|
|
|
class _RecordingBackend:
|
|
"""Keeps every request the scan asks, the evidence pass and the arbitration apart."""
|
|
|
|
def __init__(self, vectors) -> None: # type: ignore[no-untyped-def]
|
|
self._vectors = vectors
|
|
self.evidence: list[dict[str, object]] = []
|
|
self.arbitration: list[dict[str, object]] = []
|
|
|
|
def available(self) -> bool:
|
|
return True
|
|
|
|
def build(self, root, *, language=""): # type: ignore[no-untyped-def]
|
|
from openultrasast.cpg.backend import CpgResult
|
|
|
|
names = [str(p) for p in root.rglob("*.py")]
|
|
|
|
def batch(kind, requests): # type: ignore[no-untyped-def]
|
|
if any(p.get("evidenceOnly") == "true" for p in requests.values()):
|
|
self.evidence.extend(dict(p) for p in requests.values())
|
|
return {rid: self._vectors(p) for rid, p in requests.items()}
|
|
if kind == "taint":
|
|
self.arbitration.extend(dict(p) for p in requests.values())
|
|
return {rid: [] for rid in requests}
|
|
|
|
return CpgResult(
|
|
cpg_path=Path("cpg.bin"),
|
|
run=lambda q, p: [],
|
|
run_batch=lambda kind, requests: {
|
|
"__census__": [{"methods": len(names), "files": len(names), "file_names": names}],
|
|
**batch(kind, requests),
|
|
},
|
|
)
|
|
|
|
|
|
def _scan_two_depths(tmp_path: Path, vectors): # type: ignore[no-untyped-def]
|
|
"""Scan an entry point, whose question follows the call graph, and a file the walker fell back on, whose
|
|
question does not. Each asks ``injection`` and ``deserialization``."""
|
|
from openultrasast.model.regions import ScanRegion
|
|
from openultrasast.model.scan import ScanBudget, scan_repository
|
|
|
|
families = ("injection", "deserialization")
|
|
regions = [
|
|
ScanRegion(path="handler.py", function="handle", language="python", families=families, rank=0.9, source="entry_point"),
|
|
ScanRegion(path="fallback.py", function=None, language="python", families=families, rank=0.9, source="file_fallback"),
|
|
]
|
|
for region in regions:
|
|
(tmp_path / region.path).write_bytes(b"print(1)\n")
|
|
backend = _RecordingBackend(vectors)
|
|
result = scan_repository(tmp_path, regions, backend=backend, client=None, model="", budget=ScanBudget(max_model_calls=0))
|
|
return result, backend
|
|
|
|
|
|
def _deserialization_absent(params): # type: ignore[no-untyped-def]
|
|
"""The engine's rows on a repository that holds `injection` sinks and no `deserialization` sink at all."""
|
|
if tuple(params["sinks"]) == _sinks_of("deserialization"):
|
|
return [{"kind": "summary", "sinks": 0, "sourceLocal": False, "familyInRepo": False}]
|
|
return [{"kind": "summary", "sinks": 1, "sourceLocal": True, "familyInRepo": True}, _SINK_ROW]
|
|
|
|
|
|
def _sink_in_every_scope(_params): # type: ignore[no-untyped-def]
|
|
return [{"kind": "summary", "sinks": 1, "sourceLocal": True, "familyInRepo": True}, _SINK_ROW]
|
|
|
|
|
|
def test_a_family_absent_from_the_repository_is_never_asked_at_any_call_depth(tmp_path: Path) -> None:
|
|
"""contributor-scan 5.14, first rule: repository-level, exact at any `callDepth`. Paid Memberships Pro never
|
|
calls `unserialize`, and 487 of its `deserialization` questions were asked of nothing. When no file of the
|
|
repository holds a sink of a family, no scope can hold one either, so the family is not asked of an entry
|
|
point, whose question follows the call graph, any more than of a file the walker fell back on."""
|
|
result, backend = _scan_two_depths(tmp_path, _deserialization_absent)
|
|
|
|
asked = set(_by_question(backend.arbitration))
|
|
assert asked == {("handler.py", _sinks_of("injection")), ("fallback.py", _sinks_of("injection"))}, (
|
|
"a family with no sink anywhere in the repository reached the engine"
|
|
)
|
|
deferred = {(q.identity.path, q.identity.family, q.reason) for q in result.scope.deferred}
|
|
assert deferred == {("handler.py", "deserialization", "tier_zero"), ("fallback.py", "deserialization", "tier_zero")}
|
|
|
|
|
|
def test_the_evidence_that_prunes_a_question_is_asked_over_that_question_s_own_scope(tmp_path: Path) -> None:
|
|
"""contributor-scan 5.14, second rule: scope-level, exact at `callDepth=0` only. Above zero the sink may live
|
|
in a reachable method in another file, so a vector computed over the region's own file would defer a question
|
|
that could have found a flow. The evidence pass is therefore asked about the scope the arbiter would have
|
|
been: the same request, at the arbiter's own call depth."""
|
|
from openultrasast.model.scan import ENTRY_POINT_CALL_DEPTH
|
|
|
|
_, backend = _scan_two_depths(tmp_path, _sink_in_every_scope)
|
|
|
|
evidence_by_question = {key: {k: v for k, v in p.items() if k != "evidenceOnly"} for key, p in _by_question(backend.evidence).items()}
|
|
assert {key[0]: p["callDepth"] for key, p in evidence_by_question.items()} == {
|
|
"handler.py": str(ENTRY_POINT_CALL_DEPTH),
|
|
"fallback.py": "0",
|
|
}
|
|
assert evidence_by_question == _by_question(backend.arbitration), (
|
|
"the scope that prunes a question drifted from the scope that arbitrates it"
|
|
)
|
|
|
|
|
|
def test_the_budget_is_spent_by_evidence_when_asked(tmp_path: Path) -> None:
|
|
"""Phase 2 of flow-aware-ranking. With `order_by_evidence`, the evidence pass runs over every region and
|
|
the region cap is cut from the (tier, score) order, so a low-ranked region with an open sink and a
|
|
local source is examined before a top-ranked region with no sink in reach. Off, the static order holds."""
|
|
from openultrasast.model.regions import ScanRegion
|
|
from openultrasast.model.scan import ScanBudget, scan_repository
|
|
|
|
class _Backend:
|
|
def __init__(self) -> None:
|
|
self.taint_files: list[list[str]] = []
|
|
self.evidence_sizes: list[int] = []
|
|
|
|
def available(self) -> bool:
|
|
return True
|
|
|
|
def build(self, root, *, language=""): # type: ignore[no-untyped-def]
|
|
from openultrasast.cpg.backend import CpgResult
|
|
|
|
def batch(kind, requests): # type: ignore[no-untyped-def]
|
|
if any(p.get("evidenceOnly") == "true" for p in requests.values()):
|
|
self.evidence_sizes.append(len(requests))
|
|
out = {}
|
|
for rid, params in requests.items():
|
|
hot = str(params.get("file", "")).endswith("low.py")
|
|
out[rid] = [{"kind": "summary", "sinks": 1 if hot else 0, "sourceLocal": hot, "familyInRepo": True}] + (
|
|
[
|
|
{
|
|
"kind": "sink",
|
|
"sink": "os.system(x)",
|
|
"sinkLine": "4",
|
|
"sinkMethod": "run",
|
|
"sinkArity": 1,
|
|
"sinkArg0Literal": False,
|
|
"cleansedOnCall": False,
|
|
}
|
|
]
|
|
if hot
|
|
else []
|
|
)
|
|
return out
|
|
if kind == "taint":
|
|
self.taint_files.append(sorted({str(p.get("file", "")) for p in requests.values()}))
|
|
return {rid: [] for rid in requests}
|
|
|
|
names = [str(p) for p in root.rglob("*.py")]
|
|
return CpgResult(
|
|
cpg_path=Path("cpg.bin"),
|
|
run=lambda q, p: [],
|
|
run_batch=lambda kind, requests: {
|
|
"__census__": [{"methods": len(names), "files": len(names), "file_names": names}],
|
|
**batch(kind, requests),
|
|
},
|
|
)
|
|
|
|
top = ScanRegion(path="top.py", function="handle", language="python", families=("injection",), rank=1.0, source="entry_point")
|
|
low = ScanRegion(path="low.py", function="run", language="python", families=("injection",), rank=0.3, source="entry_point")
|
|
|
|
(tmp_path / "top.py").write_bytes(b"print(1)\n")
|
|
(tmp_path / "low.py").write_bytes(b"print(2)\n")
|
|
static = _Backend()
|
|
scan_repository(tmp_path, [top, low], backend=static, budget=ScanBudget(max_model_calls=0, max_regions=1))
|
|
assert static.evidence_sizes == [1] and static.taint_files == [], (
|
|
"static order: the budget holds `top`, whose pair is tier 0 and pruned"
|
|
)
|
|
|
|
ordered = _Backend()
|
|
result = scan_repository(
|
|
tmp_path, [top, low], backend=ordered, budget=ScanBudget(max_model_calls=0, max_regions=1, order_by_evidence=True)
|
|
)
|
|
assert ordered.evidence_sizes == [2], "the evidence pass covers every region, not only the budget"
|
|
assert ordered.taint_files == [["low.py"]], "and the budget is spent on the region the evidence points at"
|
|
assert result.tier_counts == {0: 1, 4: 1}
|