mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-03 10:18:18 +00:00
The decision of the maintainer on the ninth session's menu, answer 9 (.kiro/handover.md,
untracked, 1340-1343 as it stood on 2026-11-27; the option as offered, 1451-1452):
> 9. The ledger in the image. Answer: "Decide the key now": a digest of the tree's files
> (the `fingerprint` of the `provenance` stage is no digest), one ledger per digest under
> the runs directory; a design note is shown to the maintainer before any code.
The design note (/tmp/opencode/s10_c10_design_note.md, 299 lines) was reviewed in five
rounds before it was shown, and shown to the maintainer whole on 2026-11-27 with its three
questions. The maintainer's answers came on 2026-11-28, through the question tool, each the
recommended option as offered: "Stand as written (Recommended)" on the note's rule of reading
and writing (its section 3.3), "With the runs, by last use (Recommended)" on how long a ledger
stays (section 3.5), and "Build it now (Recommended)". The dated note on task 3.1 of
.kiro/specs/contributor-scan/tasks.md (lines 459-502) carries the rule as approved.
The fault: the image mounts the target read-only, so the ledger a scan writes into the tree
(<target>/.openultrasast/calibration/false_positive_learnings.json) cannot be written there,
the scan records ledger_not_written, and the next scan in the image starts without the
learnings of the one before.
What changed
- src/openultrasast/tree_digest.py: tree_digest(target, runs_directory) (line 48), a sha256
over one entry per file in path order (the length of the path, a colon, the path, a tab,
the sha256 of the bytes), after a version line. Left out: links, the directories a scan
ignores (IGNORED_DIRS, so that the tree's ledger does not change its own key) and the runs
directory, whichever way it is reached (by device and inode). A file that cannot be read
and a directory that cannot be listed are named "unreadable"; a directory that can be
listed but not searched raises, as the scan's own reading of the tree does.
- src/openultrasast/digest_ledger.py: the ledger of a digest, calibration/<digest>.json under
the runs directory, in the JSON of the tree's ledger. read_digest_ledger (line 47) reads it
and marks it as used; settle_digest_ledger (line 65) applies the rule.
The tree took the write: the ledger is removed. The tree refused: the ledger is written
with its own entries and this scan's new ones, never one whose finding id the tree's
ledger has, only when that differs from its content, and removed when that would leave it
empty. No write: a ledger whose every entry the tree's ledger also has is removed. One that
could not be read (a file that is not a ledger, whatever its top level or its depth) is
taken for empty and goes, unless the tree refused and this scan wrote it. It is written
through a temporary file of the writer's own and a rename (line 112).
- src/openultrasast/cli.py: the stage tree_digest, before any stage reads the tree
(cli.py:603-605); _read_ledgers (cli.py:1085-1099), the tree's ledger and then the
digest's, the tree's entry winning by finding id; _persist_calibration_feedback
(cli.py:1101-1136), which writes the tree's ledger when its content would differ from what
it held, also when only the digest's entries are new to it; the manifest's ledger block
(cli.py:731-735); a notice when the digest's ledger could not be written or removed
(cli.py:755).
- src/openultrasast/run.py: prune_expired_ledgers (run.py:112), called by prune_scan_runs
(run.py:71-99). Under calibration/ of the same two locations as the runs, a ledger, or the
temporary file it was written through, last used OPENULTRASAST_RUNS_RETENTION_DAYS days
ago is removed; 0 keeps all. Files called something else, links and directories stay. A
removal that fails is said once and costs the scan nothing.
- src/openultrasast/reports.py: write_manifest takes ledger (reports.py:212, 254-255). The
ledger_not_written sentence names the digest's ledger when it holds the learnings
(reports.py:461-467, chosen at 479-483).
- README.md, docs/examples.md, docs/architecture.md and
.agents/skills/openultrasast-scan/SKILL.md say where the learnings of a read-only tree go,
and what removes them.
Two departures from recorded decisions, both put to the maintainer in the note and accepted
with it:
- The tree's ledger is written when a scan learns nothing new, because the digest's entries
are new to it. The decision of 2026-11-24 says it "is written only when a scan learns
something" (spec.json:68).
- A ledger of a digest is removed when it expires, and its time is changed when a scan reads
it. The decision of 2026-11-24 says "the scan's own run and anything not named like a run
are never touched" (spec.json:73), and dates a run by its id, where a ledger is dated by
its use.
Measured
- The built function gives the note's prototype's digest for the four-file subject
(915506a8...) and for libpng's copy (1dcd664f...): s10_c10_port.out.
- In the image, on the final code. A probe image of openultrasast:dev (3f959b31f2f2) with
the tree's package copied over it, built at 09:06:36Z and holding the tree's 297 .py files
(s10_c10_image_probe/03_probe_sources.out, s10_c10_sources_still_equal4.out). Standard
mode, no key, network none. The four C files of contrib/examples of libpng and their
README, copied fresh and mounted read-only at /target; a scratch runs directory mounted at
/reports with the wrapper's OPENULTRASAST_RUNS_DIR=/reports (s10_c10_image_probe.sh,
stamps 09:06:36Z to 09:09:14Z, 2026-11-28).
- The first scan learns four entries and keeps them in /reports/calibration/<digest>.json:
calibrations_applied=0, project_score 26, the manifest's ledger {digest_ledger: written,
learnings_read: {digest: 0, tree: 0}} (10_, 11_). The report names the file.
- The second scan of the same bytes reads them: calibrations_applied=2 on two files,
project_score 59, penalty_total 32.0, learnings_read 4 from the digest's ledger,
digest_ledger "left as it was" (20_, 21_). The file's time is that of the second scan's
read, 09:07:19Z (22_).
- The digest the scan took in the image equals the one taken on the host for the same
files (s10_c10_image_digest_host4.out). The target is unchanged
(s10_c10_image_target_same4.out).
- Three earlier runs of this probe and of the native run below, each on the code as it
stood before a later correction of the same rule (the value for a ledger that could not
be read; a ledger whose top level is not an object; one nested too deep), gave the same
numbers. Their stamps: 08:12:50Z to 08:17:31Z, 08:23:38Z to 08:27:42Z and 08:50:15Z to
08:54:17Z. They are kept as s10_c10_image_probe_run1, _run2, s10_c10_native_run1,
_run2 and _run3; of the third image run s10_c10_image_probe_run3.out and the host,
target and sources checks numbered 3 remain, since s10_c10_image_probe_run3 is empty.
Its files were read by the reviewer in round two.
- The shipped image, the control, on the same files: calibrations_applied=0 and
project_score 26 on both scans, no ledger block and no ledger (30_ to 42_).
- Natively, on a fresh copy of the same five files, the network off (s10_c10_native.sh,
09:09:14Z to 09:10:38Z): the first scan writes the tree's ledger (calibrations_applied=0,
project_score 26, digest_ledger none), the second reads it (calibrations_applied=2,
project_score 59, learnings_read 4 from the tree's ledger), and no ledger of a digest is
made (s10_c10_native/10_ to 22_).
- The probe left no container (2 before, 2 after: 00_, 91_) and its image is removed (90_,
92_).
Tests
- tests/test_tree_digest.py (7) and tests/test_digest_ledger.py (11, one over nine contents
a file may hold); seven tests in tests/test_scan_output_location.py, six through the scan
(three over two cases) and one on _read_ledgers; six in tests/test_run_pruning.py; one
sentence in tests/test_reports.py. The scan test of a refused write selects its run by
name now, since the runs directory holds calibration/ as well.
- RED on an archive of e231b78 with the final test files: the two unit files do not import
(s10_c10_red14.out); the scan, pruning and report files give 15 failed, 101 passed
(s10_c10_red13.out; the tree's tree_digest.py and digest_ledger.py were copied into that
archive, since the test file imports both, and cli.py, run.py and reports.py were HEAD's).
On the tree before each fix: the test of a ledger that is not a JSON object failed
(s10_c10_red8.out), and so did the content nested too deep and its scan test
(s10_c10_red12.out).
- GREEN on the final tree: 134 passed over the five files (s10_c10_green9.out); 873 passed
over the 60 files of the scan path (s10_c10_wide4_full.out; the list is
s10_c10_testfiles.txt); the docs and skills tests, with the strict site build, 11 passed
(s10_c10_docs_tests4.out; no page changed after it).
- Gates on the final tree: ten zeros (s10_c10e_exits.txt), the three gate outputs equal to
the baseline.
- Review: three rounds against e231b78, by one reviewer subagent, read-only; no
docker and no wrapper run, the probes read from their files. Round one blocked
on one finding and measured it end to end on a scratch tree: a ledger of a
digest whose top level is not a JSON object raised AttributeError in the tree's
loader and stopped the scan (exit 1), against the note's "a cache must not stop
a scan". Round two approved with remarks, which the code and the tests took:
RecursionError joined the tuple (digest_ledger.py:57), with a ninth content in
the unit test and a scan test of a ledger that is not a ledger, red before the
fix (s10_c10_red12.out). Round three approved the code, the tests and the dated
note, and blocked on one sentence of this message, which named
s10_c10_image_probe_run3 as kept: that directory is empty. On the final tree the
reviewer measured the scan past a digest's ledger nested 5000 deep (exit 0,
"unreadable", the file removed) and passed 30000 contents through
read_digest_ledger, with none let through; it re-ran the five files (134
passed), the docs and skills files with two scan files outside the sixty (20
passed), ruff, mypy (297 files) and the comparison of the three gate outputs
with the baseline, the gates themselves not run; it recomputed the three
digests, matched the tree's 297 .py files to the fourth probe image's list, and
read the fourth image and native runs. The third image run's files were read in
round two, before they were lost. The sentence was reworded as the reviewer
wrote it.
By reading, not measured
- A pre-push run does not go through _run_scan, and src/openultrasast/push names no ledger:
nothing changes there.
- ousast benchmark and the MCP server call _run_scan and get the rule as a scan does.
- mark_all of the hunt tooling lists the children of a runs root it is given; it has no
caller under src.
Found and not fixed, for the maintainer
- The note says the digest stage's seconds are in the manifest. No stage's are: a stage's
time is in trace/events.jsonl (stage_start and stage_end), and so is this one's. The pages
and the dated note do not repeat the sentence.
- The report's sentence (reports.py:461-467) says this scan's learnings are kept in the
ledger of the digest whenever that file holds some of them (cli.py:1131-1133). A new
learning whose finding id the tree's ledger already holds is left out by the rule; the
tree's version stands, and the new evidence text is in the run directory alone. The
sentence is the note's as approved.
- The tree's own ledger stops the scan when its top level is not a JSON object, or when it
is nested too deep (calibration.py:157-159, read at cli.py:610 outside any stage). That
is older than this commit; the ledger of a digest does not.
- read_digest_ledger raises when calibration/ cannot be searched, as the tree's ledger does
when .openultrasast/calibration cannot (digest_ledger.py:53).
- By reading: a tree whose runs directory is the target itself gets another digest at every
scan, since its run directory is made inside the target before the stage. Such a tree can
be written, so its own ledger takes the learnings and no ledger of a digest is made.
- docs/architecture.md draws no provenance stage, which cli.py runs between
entry_point_mapping and rank.
- The wrapper builds its image only when the image is missing: until a rebuild, a scan
through it runs the shipped code, which has none of this.
- The notice of a removed ledger names the runs directory as the scan sees it (/reports in
the image), not the host's path.
Not checked
- the whole test suite; Windows; ops/shell/ousast.ps1 (not read for this commit); two scans
of one tree at once; the wrapper and the compose route (the probe used docker run with the
wrapper's mount and override); a removal that fails on a real cache; Docker Desktop, where
a directory mounted twice may not keep one inode.
682 lines
28 KiB
Python
682 lines
28 KiB
Python
import json
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from openultrasast.cli import main
|
|
from openultrasast.complexity.hints import TestHint
|
|
from openultrasast.complexity.map import ComplexityMap, Hotspot
|
|
from openultrasast.findings import StaticFinding
|
|
from openultrasast.reports import scan_exit_code, write_manifest, write_markdown_report, write_sarif_report
|
|
from openultrasast.run import ScanRun
|
|
from openultrasast.stages import Stage, plan_for_mode, record_completed, stages_payload
|
|
from openultrasast.verification import verify_finding
|
|
|
|
|
|
def test_sarif_report_uses_finding_ids_and_evidence_properties(tmp_path: Path) -> None:
|
|
finding = _finding()
|
|
verification = verify_finding(finding)
|
|
output = tmp_path / "report.sarif"
|
|
|
|
write_sarif_report([finding], [verification], output)
|
|
|
|
payload = json.loads(output.read_text())
|
|
result = payload["runs"][0]["results"][0]
|
|
|
|
assert payload["version"] == "2.1.0"
|
|
assert result["partialFingerprints"]["openultrasastFindingId"] == finding.finding_id
|
|
assert result["properties"]["finding_id"] == finding.finding_id
|
|
assert result["properties"]["evidence_level"] == "static_corroboration"
|
|
assert result["properties"]["verification"]["status"] == "accepted"
|
|
|
|
|
|
def test_manifest_links_shared_artifacts_by_finding_id(tmp_path: Path) -> None:
|
|
run = ScanRun(scan_id="scan-1", root=tmp_path / "run", target=tmp_path / "repo")
|
|
run.root.mkdir()
|
|
finding = _finding()
|
|
verification = verify_finding(finding)
|
|
artifacts = {
|
|
"findings": run.root / "findings.json",
|
|
"verification": run.root / "verification.json",
|
|
"markdown": run.root / "report.md",
|
|
"sarif": run.root / "report.sarif",
|
|
}
|
|
output = run.root / "manifest.json"
|
|
|
|
write_manifest(run=run, findings=[finding], verifications=[verification], artifact_paths=artifacts, path=output)
|
|
|
|
payload = json.loads(output.read_text())
|
|
manifest_finding = payload["findings"][0]
|
|
|
|
assert payload["scan_id"] == "scan-1"
|
|
assert manifest_finding["finding_id"] == finding.finding_id
|
|
assert manifest_finding["verification_status"] == "accepted"
|
|
assert manifest_finding["artifact_refs"]["sarif"] == "report.sarif"
|
|
assert "stages" not in payload
|
|
|
|
|
|
def test_manifest_includes_requested_completed_skipped_stages(tmp_path: Path) -> None:
|
|
run = ScanRun(scan_id="scan-1", root=tmp_path / "run", target=tmp_path / "repo")
|
|
run.root.mkdir()
|
|
finding = _finding()
|
|
artifacts = {
|
|
"findings": run.root / "findings.json",
|
|
"verification": run.root / "verification.json",
|
|
"markdown": run.root / "report.md",
|
|
"sarif": run.root / "report.sarif",
|
|
}
|
|
output = run.root / "manifest.json"
|
|
plan = record_completed(plan_for_mode("quick"), Stage.STATIC)
|
|
|
|
write_manifest(
|
|
run=run,
|
|
findings=[finding],
|
|
verifications=[verify_finding(finding)],
|
|
artifact_paths=artifacts,
|
|
path=output,
|
|
stages=stages_payload(plan),
|
|
)
|
|
|
|
payload = json.loads(output.read_text())
|
|
assert payload["stages"] == {"requested": ["static"], "completed": ["static"], "skipped": []}
|
|
assert payload["findings"][0]["finding_id"] == finding.finding_id
|
|
|
|
|
|
def test_markdown_report_includes_verification_status(tmp_path: Path) -> None:
|
|
finding = _finding()
|
|
output = tmp_path / "report.md"
|
|
|
|
write_markdown_report([finding], output, [verify_finding(finding)])
|
|
|
|
text = output.read_text()
|
|
assert "## Inventory" in text
|
|
assert "Verification: `accepted`" in text
|
|
assert finding.finding_id in text
|
|
assert "worth-fixing" not in text.lower()
|
|
assert "worth_fixing" not in text.lower()
|
|
|
|
|
|
def test_markdown_report_includes_complexity_map(tmp_path: Path) -> None:
|
|
finding = _finding()
|
|
output = tmp_path / "report.md"
|
|
hint = TestHint(
|
|
path="app.py",
|
|
function_name="admin",
|
|
gap="no_adjacent_test",
|
|
test_kind="http-contract",
|
|
reason="no adjacent test file for app.py::admin; recommend http-contract.",
|
|
)
|
|
hotspot = Hotspot(
|
|
path="app.py",
|
|
function_name="admin",
|
|
score=6.5,
|
|
band="high",
|
|
signals={"loc": 12, "has_adjacent_test": False},
|
|
rationale="high band: nested public route",
|
|
test_hint=hint,
|
|
inventory_finding_ids=(finding.finding_id,),
|
|
)
|
|
write_markdown_report(
|
|
[finding],
|
|
output,
|
|
[verify_finding(finding)],
|
|
complexity_map=ComplexityMap(hotspots=(hotspot,), heuristic_only=True),
|
|
)
|
|
|
|
text = output.read_text()
|
|
inventory_at = text.index("## Inventory")
|
|
map_at = text.index("## Complexity map")
|
|
assert inventory_at < map_at
|
|
map_section = text[map_at:]
|
|
assert "app.py::admin" in map_section
|
|
assert "Gap: `no_adjacent_test`" in map_section
|
|
assert "Recommended test: `http-contract`" in map_section
|
|
|
|
|
|
def test_markdown_report_labels_hits_as_inventory_not_worth_fixing(tmp_path: Path) -> None:
|
|
finding = _finding()
|
|
output = tmp_path / "report.md"
|
|
|
|
write_markdown_report([finding], output, [verify_finding(finding)])
|
|
|
|
text = output.read_text()
|
|
inventory_at = text.index("## Inventory")
|
|
finding_at = text.index(f"## {finding.title}")
|
|
assert inventory_at < finding_at
|
|
assert "worth-fixing" not in text.lower()
|
|
|
|
|
|
def test_scan_exit_code_policy() -> None:
|
|
finding = _finding()
|
|
verification = verify_finding(finding)
|
|
|
|
assert scan_exit_code([finding], [verification], "never") == 0
|
|
assert scan_exit_code([finding], [verification], "findings") == 1
|
|
assert scan_exit_code([], [], "findings") == 0
|
|
assert scan_exit_code([finding], [verification], "verified") == 1
|
|
assert scan_exit_code([], [], "verified") == 0
|
|
|
|
|
|
def test_scan_exit_code_unknown_policy() -> None:
|
|
with pytest.raises(ValueError, match="unknown fail policy"):
|
|
scan_exit_code([], [], "maybe")
|
|
|
|
|
|
def test_cli_scan_writes_sarif_manifest_and_honors_fail_policy(tmp_path: Path, monkeypatch) -> None: # type: ignore[no-untyped-def]
|
|
repo = tmp_path / "repo"
|
|
repo.mkdir()
|
|
(repo / "app.py").write_text("@app.route('/admin')\ndef admin():\n return eval(request.data)\n")
|
|
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
|
|
|
|
assert main(["scan", str(repo), "--mode", "quick", "--fail-on", "verified"]) == 1
|
|
|
|
run_dir = sorted((repo / ".runs").iterdir())[-1]
|
|
sarif = json.loads((run_dir / "report.sarif").read_text())
|
|
manifest = json.loads((run_dir / "manifest.json").read_text())
|
|
|
|
finding_id = manifest["findings"][0]["finding_id"]
|
|
assert sarif["runs"][0]["results"][0]["properties"]["finding_id"] == finding_id
|
|
assert manifest["findings"][0]["artifact_refs"]["verification_json"] == "verification.json"
|
|
|
|
|
|
def test_quick_scan_report_is_inventory_without_map_or_docker(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
from openultrasast import tool_hunter
|
|
from openultrasast.complexity import map as complexity_map
|
|
|
|
repo = tmp_path / "repo"
|
|
repo.mkdir()
|
|
(repo / "app.py").write_text("@app.route('/admin')\ndef admin():\n return eval(request.data)\n")
|
|
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
|
|
|
|
docker_argv: list[list[str]] = []
|
|
original_run = subprocess.run
|
|
|
|
def guarded_run(command, *args, **kwargs): # type: ignore[no-untyped-def]
|
|
argv = list(command) if isinstance(command, list | tuple) else [command]
|
|
if argv and Path(str(argv[0])).name == "docker":
|
|
docker_argv.append(argv)
|
|
raise AssertionError(f"quick scan must not start docker: {argv}")
|
|
return original_run(command, *args, **kwargs)
|
|
|
|
def fail(message: str): # type: ignore[no-untyped-def]
|
|
def _fail(*args, **kwargs): # type: ignore[no-untyped-def]
|
|
raise AssertionError(message)
|
|
|
|
return _fail
|
|
|
|
monkeypatch.setattr(subprocess, "run", guarded_run)
|
|
monkeypatch.setattr(complexity_map, "build_complexity_map", fail("quick scan must not build a complexity map"))
|
|
monkeypatch.setattr(tool_hunter, "run_tool_hunter", fail("quick scan must not start a hunter model"))
|
|
|
|
assert main(["scan", str(repo), "--mode", "quick"]) == 0
|
|
|
|
run_dir = sorted((repo / ".runs").iterdir())[-1]
|
|
report = (run_dir / "report.md").read_text()
|
|
manifest = json.loads((run_dir / "manifest.json").read_text())
|
|
|
|
assert "## Inventory" in report
|
|
assert "worth-fixing" not in report.lower()
|
|
assert not (run_dir / "complexity_map.json").exists()
|
|
assert docker_argv == []
|
|
assert manifest["stages"]["requested"] == ["static"]
|
|
assert manifest["stages"]["completed"] == ["static"]
|
|
assert manifest["stages"]["skipped"] == []
|
|
assert "complexity" not in manifest
|
|
assert "complexity_map" not in manifest.get("artifacts", {})
|
|
assert not any(entry.get("reason") == "hunter_model_unavailable" for entry in manifest.get("degradations", []))
|
|
|
|
|
|
def test_standard_scan_writes_complexity_map_without_docker(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
|
|
repo = tmp_path / "repo"
|
|
repo.mkdir()
|
|
(repo / "app.py").write_text("@app.route('/admin')\ndef admin():\n return eval(request.data)\n")
|
|
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
|
|
|
|
docker_argv: list[list[str]] = []
|
|
original_run = subprocess.run
|
|
|
|
def guarded_run(command, *args, **kwargs): # type: ignore[no-untyped-def]
|
|
argv = list(command) if isinstance(command, list | tuple) else [command]
|
|
if argv and Path(str(argv[0])).name == "docker":
|
|
docker_argv.append(argv)
|
|
raise AssertionError(f"standard scan must not start docker: {argv}")
|
|
return original_run(command, *args, **kwargs)
|
|
|
|
monkeypatch.setattr(subprocess, "run", guarded_run)
|
|
|
|
assert main(["scan", str(repo), "--mode", "standard"]) == 0
|
|
|
|
run_dir = sorted((repo / ".runs").iterdir())[-1]
|
|
map_path = run_dir / "complexity_map.json"
|
|
manifest = json.loads((run_dir / "manifest.json").read_text())
|
|
complexity_map = json.loads(map_path.read_text())
|
|
|
|
assert map_path.is_file()
|
|
assert complexity_map["heuristic_only"] is True
|
|
assert isinstance(complexity_map["hotspots"], list)
|
|
assert complexity_map["hotspots"]
|
|
assert docker_argv == []
|
|
assert manifest["stages"]["requested"] == ["static", "map"]
|
|
assert manifest["stages"]["completed"] == ["static", "map"]
|
|
assert manifest["stages"]["skipped"] == []
|
|
assert manifest["complexity"]["hotspot_count"] == len(complexity_map["hotspots"])
|
|
assert manifest["complexity"]["heuristic_only"] is True
|
|
assert manifest["artifacts"]["complexity_map"] == "complexity_map.json"
|
|
report = (run_dir / "report.md").read_text()
|
|
assert "## Inventory" in report
|
|
assert "## Complexity map" in report
|
|
assert "Gap:" in report
|
|
assert "## Worth fixing" not in report
|
|
|
|
|
|
def test_standard_scan_records_hunter_model_unavailable_when_model_unset(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
|
|
repo = tmp_path / "repo"
|
|
repo.mkdir()
|
|
(repo / "app.py").write_text("@app.route('/admin')\ndef admin():\n return eval(request.data)\n")
|
|
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
|
|
|
|
assert main(["scan", str(repo), "--mode", "standard"]) == 0
|
|
|
|
run_dir = sorted((repo / ".runs").iterdir())[-1]
|
|
manifest = json.loads((run_dir / "manifest.json").read_text())
|
|
degradations = manifest.get("degradations", [])
|
|
|
|
assert any(entry.get("reason") == "hunter_model_unavailable" for entry in degradations)
|
|
hunter_skip = next(entry for entry in degradations if entry.get("reason") == "hunter_model_unavailable")
|
|
assert hunter_skip["stage"] in {"map", "hunter_pool"}
|
|
assert manifest["complexity"]["heuristic_only"] is True
|
|
assert (run_dir / "complexity_map.json").is_file()
|
|
|
|
|
|
def test_manifest_includes_complexity_summary(tmp_path: Path) -> None:
|
|
run = ScanRun(scan_id="scan-1", root=tmp_path / "run", target=tmp_path / "repo")
|
|
run.root.mkdir()
|
|
finding = _finding()
|
|
artifacts = {
|
|
"findings": run.root / "findings.json",
|
|
"verification": run.root / "verification.json",
|
|
"markdown": run.root / "report.md",
|
|
"sarif": run.root / "report.sarif",
|
|
"complexity_map": run.root / "complexity_map.json",
|
|
}
|
|
output = run.root / "manifest.json"
|
|
|
|
write_manifest(
|
|
run=run,
|
|
findings=[finding],
|
|
verifications=[verify_finding(finding)],
|
|
artifact_paths=artifacts,
|
|
path=output,
|
|
complexity={"hotspot_count": 3, "heuristic_only": True},
|
|
)
|
|
|
|
payload = json.loads(output.read_text())
|
|
assert payload["complexity"] == {"hotspot_count": 3, "heuristic_only": True}
|
|
assert payload["artifacts"]["complexity_map"] == "complexity_map.json"
|
|
|
|
|
|
def _finding() -> StaticFinding:
|
|
return StaticFinding(
|
|
finding_id="python-unsafe-eval:app.py:3",
|
|
path="app.py",
|
|
title="Dynamic Python execution needs review",
|
|
severity="high",
|
|
confidence="medium",
|
|
evidence_level="static_corroboration",
|
|
rationale="Static pattern matched.",
|
|
line=3,
|
|
function_name="admin",
|
|
reachability_status="reachable",
|
|
reachability_evidence=[
|
|
{
|
|
"kind": "route",
|
|
"access_level": "public",
|
|
"line": 1,
|
|
"end_line": 3,
|
|
"function_name": "admin",
|
|
"conditions": [],
|
|
}
|
|
],
|
|
reachability_conditions=[],
|
|
tags=["syscall_entry"],
|
|
ranking_priority=3.0,
|
|
)
|
|
|
|
|
|
def _pattern_finding(rule: str, path: str, line: int) -> StaticFinding:
|
|
from dataclasses import replace
|
|
|
|
base = _finding()
|
|
return replace(base, finding_id=f"{rule}:{path}:{line}", path=path, line=line, title=f"{rule} needs review")
|
|
|
|
|
|
def test_a_pattern_rule_with_many_sites_is_summarised_not_repeated(tmp_path: Path) -> None:
|
|
"""contributor-scan 2.11. libpng emitted 198 sections, 163 of them asserting that `memcpy` and `strcpy`
|
|
are PRESENT in a library that uses them correctly throughout. That is the noise developers have learned
|
|
to skip in every other tool, and shipping it costs the findings beside it their credibility."""
|
|
crowded = [_pattern_finding("c-unsafe-copy", f"src/f{i}.c", i) for i in range(20)]
|
|
output = tmp_path / "report.md"
|
|
|
|
write_markdown_report(crowded, output)
|
|
|
|
text = output.read_text()
|
|
assert "## Proposed, not corroborated" in text
|
|
assert "20 site(s) across 20 file(s)" in text
|
|
assert text.count("## c-unsafe-copy needs review") == 0, "twenty sections for one rule is the noise"
|
|
assert "`findings.json`" in text, "counted, never dropped"
|
|
|
|
|
|
def test_a_pattern_rule_with_few_sites_keeps_its_sections(tmp_path: Path) -> None:
|
|
"""One `python-flask-debug` is a finding a contributor can act on, and must not be summarised away."""
|
|
output = tmp_path / "report.md"
|
|
|
|
write_markdown_report([_pattern_finding("python-flask-debug", "app.py", 17)], output)
|
|
|
|
text = output.read_text()
|
|
assert "## python-flask-debug needs review" in text
|
|
assert "## Proposed, not corroborated" not in text
|
|
|
|
|
|
def test_a_reasoned_claim_keeps_its_section_whatever_its_rung(tmp_path: Path) -> None:
|
|
"""An obligation or model finding sits at `suspicion` too, but it is a claim about a site rather than an
|
|
observation that an API exists. Twenty of them are twenty findings, not one property of the codebase."""
|
|
from dataclasses import replace
|
|
|
|
base = _finding()
|
|
reasoned = [
|
|
replace(base, finding_id=f"obligation:protected_read:api/u.py:{i}", evidence_level="suspicion", path="api/u.py", line=i)
|
|
for i in range(20)
|
|
]
|
|
output = tmp_path / "report.md"
|
|
|
|
write_markdown_report(reasoned, output)
|
|
|
|
assert output.read_text().count(f"## {base.title}") == 20
|
|
|
|
|
|
def test_the_report_says_what_was_looked_for_and_what_cannot_be_decided(tmp_path: Path) -> None:
|
|
"""contributor-scan 2.16, Req 5.6. `c/memory` scored zero true positives across 89k lines of C for a
|
|
structural reason -- it models string CALLS and libpng overflows through arithmetic. A silent scan
|
|
reading as a clean bill of health is worse than a noisy one, because the reader acts on it."""
|
|
output = tmp_path / "report.md"
|
|
coverage = [
|
|
{
|
|
"language": "c",
|
|
"family": "memory",
|
|
"regions": 121,
|
|
"modelled": 9,
|
|
"description": "Misuse of unbounded string and format APIs",
|
|
"limits": "Models CALLS, not arithmetic. It cannot decide an overflow expressed as an index.",
|
|
}
|
|
]
|
|
|
|
write_markdown_report([], output, coverage=coverage)
|
|
|
|
text = output.read_text()
|
|
assert "## What was analysed" in text
|
|
assert "| c | `memory` | 121 | 9 |" in text, "what it looked for, counted from the fact table itself"
|
|
assert "### Stated limits" in text
|
|
assert "cannot decide an overflow expressed as an index" in text
|
|
assert "silence here means no fact table covered the code, not that the code is safe" in text
|
|
|
|
|
|
def test_a_scan_that_made_no_claims_states_no_limits(tmp_path: Path) -> None:
|
|
"""A report with no model layer has nothing to disclaim; the section would be noise."""
|
|
output = tmp_path / "report.md"
|
|
|
|
write_markdown_report([_finding()], output)
|
|
|
|
assert "## What was analysed" not in output.read_text()
|
|
|
|
|
|
def test_a_model_suspicion_is_grouped_like_a_pattern_match(tmp_path: Path) -> None:
|
|
"""contributor-scan 2.17, Req 5.5's other half.
|
|
|
|
A model suspicion is what the enumerator proposed at a site the graph could NOT decide, affirmed by a
|
|
judge with no coverage there -- a pattern match with an opinion attached. It reads like a reasoned claim
|
|
because a model produced it, and on vampi it was 38 of 60 findings on a 520-line application.
|
|
"""
|
|
from dataclasses import replace
|
|
|
|
base = _finding()
|
|
suspicions = [
|
|
replace(
|
|
base,
|
|
finding_id=f"model:injection:api/f{i}.py:{i}:jsonify",
|
|
evidence_level="suspicion",
|
|
rung="suspicion",
|
|
path=f"api/f{i}.py",
|
|
line=i,
|
|
rationale="the model resolved no flow here; its sink table may not cover this API",
|
|
)
|
|
for i in range(20)
|
|
]
|
|
output = tmp_path / "report.md"
|
|
|
|
write_markdown_report(suspicions, output)
|
|
|
|
text = output.read_text()
|
|
assert "`model:injection`" in text, "grouped by family, since the rule is always `model`"
|
|
assert "20 site(s)" in text
|
|
assert text.count(f"## {base.title}") == 0
|
|
|
|
|
|
def test_an_obligation_finding_is_not_grouped_away(tmp_path: Path) -> None:
|
|
"""It sits at `suspicion` too, but it comes from a structural analysis rather than a guess. Collapsing
|
|
it would hide a detector -- which an earlier attempt at this rule did, and six tests caught it."""
|
|
from dataclasses import replace
|
|
|
|
base = _finding()
|
|
obligations = [
|
|
replace(base, finding_id=f"obligation:protected_read:api/u.py:{i}", evidence_level="suspicion", rung="suspicion", line=i)
|
|
for i in range(20)
|
|
]
|
|
output = tmp_path / "report.md"
|
|
|
|
write_markdown_report(obligations, output)
|
|
|
|
assert output.read_text().count(f"## {base.title}") == 20
|
|
|
|
|
|
def test_an_entailed_model_finding_keeps_its_section(tmp_path: Path) -> None:
|
|
"""The rung is the product. Whatever the model layer DECIDED is never summarised away."""
|
|
from dataclasses import replace
|
|
|
|
base = _finding()
|
|
entailed = [
|
|
replace(base, finding_id=f"model:injection:app.py:{i}:execute", evidence_level="suspicion", rung="model_entailed", line=i)
|
|
for i in range(20)
|
|
]
|
|
output = tmp_path / "report.md"
|
|
|
|
write_markdown_report(entailed, output)
|
|
|
|
assert output.read_text().count(f"## {base.title}") == 20
|
|
|
|
|
|
def test_a_sharded_graph_is_stated_in_the_report(tmp_path) -> None: # type: ignore[no-untyped-def]
|
|
"""A graph built in parts cannot see a flow that crosses the parts, and the reader has no way to know
|
|
that from the findings alone."""
|
|
from openultrasast.reports import write_markdown_report
|
|
|
|
path = tmp_path / "report.md"
|
|
write_markdown_report(
|
|
[],
|
|
path,
|
|
[],
|
|
coverage=[{"language": "php", "family": "injection", "regions": 3, "modelled": 12, "limits": ""}],
|
|
degradations=[
|
|
{"stage": "model", "reason": "cpg_sharded", "shards": 2},
|
|
{"stage": "model", "reason": "files_unparsed", "count": 1, "files": ["big.php"]},
|
|
],
|
|
)
|
|
text = path.read_text()
|
|
assert "### What could not be analysed" in text
|
|
assert "built in 2 parts" in text
|
|
assert "is not visible to any question asked here" in text
|
|
assert "`big.php`" in text
|
|
|
|
|
|
def test_a_clean_scan_states_no_coverage_gaps(tmp_path) -> None: # type: ignore[no-untyped-def]
|
|
from openultrasast.reports import write_markdown_report
|
|
|
|
path = tmp_path / "report.md"
|
|
write_markdown_report(
|
|
[],
|
|
path,
|
|
[],
|
|
coverage=[{"language": "php", "family": "injection", "regions": 3, "modelled": 12, "limits": ""}],
|
|
degradations=[],
|
|
)
|
|
assert "### What could not be analysed" not in path.read_text()
|
|
|
|
|
|
def test_every_recorded_scan_degradation_is_rendered(tmp_path) -> None: # type: ignore[no-untyped-def]
|
|
"""pre-push 17.2 / Req 9.2: the eight degradations cli.py records and the report used to drop."""
|
|
from openultrasast.reports import write_markdown_report
|
|
|
|
reasons = [
|
|
{"stage": "model", "reason": "learning_endpoint_unavailable"},
|
|
{"stage": "model", "reason": "cpg_unavailable"},
|
|
{"stage": "overlay", "reason": "facts_unavailable", "detail": "missing table"},
|
|
{"stage": "obligations", "reason": "facts_unavailable"},
|
|
{"stage": "obligations", "reason": "policy_invalid", "detail": "bad toml"},
|
|
{"stage": "model", "reason": "model_withheld_execution_budget"},
|
|
{"stage": "budget", "reason": "max_findings_exceeded", "requested": 5, "actual": 9},
|
|
{"stage": "map", "reason": "hunter_model_unavailable"},
|
|
{"stage": "regress", "reason": "regress_retired"},
|
|
{"stage": "x", "reason": "not_yet_described"},
|
|
]
|
|
path = tmp_path / "report.md"
|
|
write_markdown_report([], path, [], degradations=reasons)
|
|
text = path.read_text()
|
|
for needle in (
|
|
"No model endpoint is configured",
|
|
"Joern engine is not installed",
|
|
"fact tables for the `overlay` stage",
|
|
"fact tables for the `obligations` stage",
|
|
"`obligations` policy could not be loaded",
|
|
"time budget leaves no room",
|
|
"first 5 of 9 findings",
|
|
"needs a model and none is available",
|
|
"the sandboxed snippet stage was retired on 2026-10-13",
|
|
"execution proof comes from the search-with-proof arm",
|
|
"`not_yet_described`",
|
|
):
|
|
assert needle in text, needle
|
|
|
|
|
|
def test_a_failed_judge_call_is_reported_as_unasked_and_not_as_a_no(tmp_path) -> None:
|
|
"""With a key set and the network off, 16 judge calls failed in one scan and each dropped its claim as a
|
|
`no` would; the report then said less than that of a run without an endpoint.
|
|
"""
|
|
from openultrasast.reports import write_markdown_report
|
|
|
|
path = tmp_path / "report.md"
|
|
write_markdown_report(
|
|
[],
|
|
path,
|
|
[],
|
|
degradations=[
|
|
{"stage": "model", "reason": "judge_calls_failed", "count": 3},
|
|
{"stage": "model", "reason": "judge_withheld", "questions": 5},
|
|
],
|
|
)
|
|
section = path.read_text().split("### What could not be analysed", 1)[1]
|
|
assert "3 judge call(s) gave no decision" in section
|
|
assert "went unanswered: its finding is not in this report, and that is not a `no` from the judge" in section
|
|
assert "5 further question(s) were refused in the question being put, and no question after it was put to the judge" in section
|
|
|
|
|
|
def test_an_unwritable_ledger_is_stated_in_the_report(tmp_path) -> None: # type: ignore[no-untyped-def]
|
|
"""What was not written, and where this scan's learnings are instead: a reader told only a code cannot
|
|
find them."""
|
|
path = tmp_path / "report.md"
|
|
write_markdown_report(
|
|
[],
|
|
path,
|
|
[],
|
|
degradations=[
|
|
{
|
|
"stage": "record_calibration",
|
|
"reason": "ledger_not_written",
|
|
"detail": "[Errno 30] Read-only file system: '/target/.openultrasast/calibration/false_positive_learnings.json'",
|
|
}
|
|
],
|
|
)
|
|
section = path.read_text().split("### What could not be analysed", 1)[1]
|
|
assert (
|
|
"The false-positive ledger in the analysed tree could not be written, so this scan's learnings are kept "
|
|
"only in this run directory and the next scan starts without them. [Errno 30] Read-only file system: "
|
|
"'/target/.openultrasast/calibration/false_positive_learnings.json'"
|
|
) in section
|
|
assert "`ledger_not_written`" not in section
|
|
|
|
|
|
def test_an_unwritable_ledger_kept_by_digest_names_the_file_the_next_scan_reads(tmp_path) -> None: # type: ignore[no-untyped-def]
|
|
"""When the learnings are kept in the ledger of the tree's digest, the sentence says where: a reader told only a
|
|
code cannot find them."""
|
|
path = tmp_path / "report.md"
|
|
kept = "/reports/calibration/" + "a" * 64 + ".json"
|
|
write_markdown_report(
|
|
[],
|
|
path,
|
|
[],
|
|
degradations=[
|
|
{
|
|
"stage": "record_calibration",
|
|
"reason": "ledger_not_written",
|
|
"detail": "[Errno 30] Read-only file system: '/target/.openultrasast'",
|
|
"kept_in": kept,
|
|
}
|
|
],
|
|
)
|
|
section = path.read_text().split("### What could not be analysed", 1)[1]
|
|
assert (
|
|
"The false-positive ledger in the analysed tree could not be written, so this scan's learnings are kept in "
|
|
f"the ledger of this tree's digest under the runs directory, at `{kept}`, and the next scan of the same "
|
|
"bytes reads them. [Errno 30] Read-only file system: '/target/.openultrasast'"
|
|
) in section
|
|
assert "only in this run directory" not in section
|
|
|
|
|
|
def test_quick_scan_names_a_language_nothing_covers(tmp_path, monkeypatch, capsys) -> None: # type: ignore[no-untyped-def]
|
|
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(tmp_path / "runs"))
|
|
"""pre-push 17.2 / Req 9.2: a Go-only tree is not a silent zero."""
|
|
(tmp_path / "run.go").write_text('package main\n\nimport "os/exec"\n\nfunc run(c string) { exec.Command("sh", "-c", c).Run() }\n')
|
|
assert main(["scan", str(tmp_path), "--mode", "quick"]) == 0
|
|
assert "notice: language not covered: go (1 files)" in capsys.readouterr().out
|
|
report = next((tmp_path / "runs").iterdir()) / "report.md"
|
|
assert "Not a clean result for go (1 files)" in report.read_text()
|
|
|
|
|
|
@pytest.mark.parametrize("fail_on, expected", [("never", 0), ("findings", 1), ("verified", 1)])
|
|
def test_deep_scan_records_retirement_without_running_snippets(tmp_path, monkeypatch, fail_on, expected):
|
|
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(tmp_path / "runs"))
|
|
(tmp_path / "app.py").write_text("@app.route('/admin')\ndef admin():\n return eval(request.data)\n")
|
|
|
|
def guard(command, *args, **kwargs):
|
|
argv = list(command) if isinstance(command, list | tuple) else [command]
|
|
assert not argv or Path(str(argv[0])).name != "docker", "deep scan must not start Docker"
|
|
return original_run(command, *args, **kwargs)
|
|
|
|
original_run = subprocess.run
|
|
monkeypatch.setattr(subprocess, "run", guard)
|
|
assert main(["scan", str(tmp_path), "--mode", "deep", "--fail-on", fail_on]) == expected
|
|
run_dir = next((tmp_path / "runs").iterdir())
|
|
manifest = json.loads((run_dir / "manifest.json").read_text())
|
|
retired = {"stage": "regress", "reason": "regress_retired"}
|
|
assert manifest["stages"] == {
|
|
"requested": ["static", "map", "regress"],
|
|
"completed": ["static", "map"],
|
|
"skipped": [retired],
|
|
}
|
|
assert manifest["degradations"].count(retired) == 1
|
|
assert "verdicts" not in manifest["artifacts"]
|
|
assert "worth_fixing" not in manifest
|
|
assert not (run_dir / "verdicts.json").exists()
|
|
assert "execution proof comes from the search-with-proof arm" in (run_dir / "report.md").read_text()
|