feat(contributor-scan): a scan writes its run to the user cache, and the ledger only when it learns (3.1, part A)

Where a scan writes. A native scan now creates its run under the user cache,
~/.cache/openultrasast/runs/<scan-id>/ by default ($XDG_CACHE_HOME when it is
set and absolute), prints run_dir=<path> once, and no longer writes anything
under the analysed tree. OPENULTRASAST_RUNS_DIR still wins: an absolute value
is used as given, a relative one resolves against the working directory.
Pre-push storage is unchanged.

The calibration ledger, by maintainer decision: .openultrasast/calibration/
stays the store, and a scan writes the false-positive ledger into the tree
only when its content would change. On a read-only tree the scan records
ledger_not_written, with a sentence in the report, and completes; before, a
read-only target with one rejected finding crashed before report.md existed.

benchmarks/repos/measure.py follows the printed run directory. It read the
run from under the scanned copy, which would have recorded every repository
as failed, and it also read a stale run left in a copy.

Tests: tests/test_scan_output_location.py drives the real CLI and compares
the whole tree before and after; tests/test_repo_measure.py pins the
measurement script; an autouse fixture keeps every test's scan runs out of
the developer's cache; fourteen test files follow the run to its new place.
README, docs/examples.md and the scan skill name the ledger as the one write
a scan makes. _run_scan is touched by one line and stays over the complexity
cap.

Task 3.1 stays open for part B, the readable summary.
This commit is contained in:
Marius Ciepluch
2026-11-24 15:33:35 +01:00
parent d45fc98c4e
commit 6edae3a585
29 changed files with 509 additions and 50 deletions
+10
View File
@@ -24,6 +24,16 @@ def _repos_offline(monkeypatch: pytest.MonkeyPatch, tmp_path_factory: pytest.Tem
monkeypatch.setenv("OPENULTRASAST_REPO_CACHE", str(tmp_path_factory.mktemp("repo-cache")))
@pytest.fixture(autouse=True)
def _scan_runs_under_tmp_path(monkeypatch: pytest.MonkeyPatch, tmp_path_factory: pytest.TempPathFactory) -> None:
"""A scan run never lands in the developer's real cache, whatever a test forgets to redirect.
The default run root is `~/.cache/openultrasast/runs`, so a test that scans without naming a location
would write there. The override points every such test at its own temporary directory instead.
"""
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(tmp_path_factory.mktemp("scan-runs")))
@pytest.fixture
def assert_cold_import(): # type: ignore[no-untyped-def]
"""Run ``code`` in a fresh interpreter and assert it exits 0.
+1 -1
View File
@@ -142,7 +142,7 @@ evidence = "memcpy copies attacker-controlled input"
""".strip()
+ "\n"
)
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", ".runs")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
assert main(["benchmark", str(manifest_path), "--mode", "quick"]) == 0
+43 -1
View File
@@ -6,7 +6,7 @@ from pathlib import Path
import pytest
from openultrasast.config import RetiredConfigError, load_config, load_dotenv, write_resolved_config
from openultrasast.config import ResolvedConfig, RetiredConfigError, load_config, load_dotenv, write_resolved_config
def test_load_config_reads_toml(tmp_path: Path) -> None:
@@ -185,3 +185,45 @@ def test_load_dotenv_sets_missing_keys_only(tmp_path: Path, monkeypatch) -> None
assert os.environ["OPENROUTER_API_KEY"] == "already-set"
assert os.environ["S3_REGION"] == "us-east-1"
def test_runs_dir_defaults_to_the_user_cache(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.delenv("OPENULTRASAST_RUNS_DIR", raising=False)
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache"))
assert Path(load_config(None).runs_dir) == tmp_path / "cache" / "openultrasast" / "runs"
@pytest.mark.parametrize("xdg", ["", "relative/cache"])
def test_an_empty_or_relative_xdg_cache_home_falls_back_to_the_home_cache(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, xdg: str
) -> None:
monkeypatch.delenv("OPENULTRASAST_RUNS_DIR", raising=False)
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setenv("XDG_CACHE_HOME", xdg)
assert Path(load_config(None).runs_dir) == tmp_path / ".cache" / "openultrasast" / "runs"
def test_the_runs_dir_override_wins_and_an_absolute_one_is_used_as_given(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache"))
link = tmp_path / "link"
link.symlink_to(tmp_path, target_is_directory=True)
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(link / "runs"))
assert Path(load_config(None).runs_dir) == link / "runs"
def test_a_relative_runs_dir_override_is_taken_from_the_working_directory(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
working = tmp_path / "working"
working.mkdir()
monkeypatch.chdir(working)
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", ".runs")
assert Path(load_config(None).runs_dir) == working / ".runs"
def test_a_config_built_without_the_loader_follows_the_same_override(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(tmp_path / "runs"))
assert ResolvedConfig().runs_dir == str(tmp_path / "runs")
+2 -1
View File
@@ -70,8 +70,9 @@ def test_retired_regress_stage_is_skipped_by_name(tmp_path: Path, monkeypatch: p
from openultrasast.cli import main
(tmp_path / "app.py").write_text("import os\n\n\ndef run(cmd):\n os.system(cmd)\n")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(tmp_path / "runs"))
assert main(["scan", str(tmp_path), "--mode", "deep"]) in {0, 1}
runs = sorted((tmp_path / ".openultrasast" / "runs").iterdir())
runs = sorted((tmp_path / "runs").iterdir())
manifest = json.loads((runs[-1] / "manifest.json").read_text())
reasons = {item["reason"] for item in manifest.get("degradations", [])}
assert "regress_retired" in reasons
+2 -2
View File
@@ -142,7 +142,7 @@ def test_standard_scan_emits_fusion_artifact_and_manifest_block(tmp_path: Path,
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", ".runs")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
assert main(["scan", str(repo), "--mode", "standard"]) == 0
run_dir = sorted((repo / ".runs").iterdir())[-1]
@@ -159,7 +159,7 @@ def test_quick_scan_does_not_emit_fusion(tmp_path: Path, monkeypatch: pytest.Mon
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", ".runs")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
assert main(["scan", str(repo), "--mode", "quick"]) == 0
run_dir = sorted((repo / ".runs").iterdir())[-1]
+1 -1
View File
@@ -25,7 +25,7 @@ def _run(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, *, config_body: str |
repo = tmp_path / "repo"
repo.mkdir(parents=True)
(repo / "app.py").write_text(_VULN_WITH_SECRET)
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", ".runs")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
argv = ["scan", str(repo), "--mode", "quick"]
if config_body is not None:
cfg = tmp_path / "openultrasast.toml"
+1 -1
View File
@@ -80,7 +80,7 @@ def test_standard_mode_writes_hunter_trajectory_and_manifest_ref(tmp_path: Path,
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", ".runs")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
assert main(["scan", str(repo), "--mode", "standard", "--fail-on", "verified"]) == 1
+1 -1
View File
@@ -29,7 +29,7 @@ def _repo(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
repo = tmp_path / "repo"
repo.mkdir()
(repo / "app.py").write_text(APP)
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", ".runs")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
monkeypatch.setenv("OPENULTRASAST_SANDBOX_PROBE", "0")
return repo
+1 -1
View File
@@ -36,7 +36,7 @@ def test_rejected_finding_demotes_its_scope_on_the_next_scan(tmp_path: Path, mon
(repo / "app.py").write_text("@app.route('/x')\ndef view():\n return eval(request.data)\n")
# Helper eval with no entry point -> unknown reachability -> rejected -> learning.
(repo / "lib.py").write_text("def helper(x):\n return eval(x)\n")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", ".runs")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
ledger = repo / ".openultrasast" / "calibration" / "false_positive_learnings.json"
# --- First scan: produces the learning, applies nothing yet ---------------
+24
View File
@@ -0,0 +1,24 @@
"""benchmarks/repos/measure.py reads the scan's run from the `run_dir=` line the scan prints, so it follows the run
into the user cache (it used to look under the scanned copy and recorded every repository as failed)."""
import importlib.util
from pathlib import Path
def _measure(): # type: ignore[no-untyped-def]
spec = importlib.util.spec_from_file_location("measure", Path(__file__).resolve().parents[1] / "benchmarks" / "repos" / "measure.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def test_measure_finds_the_scan_run_where_the_scan_puts_it(tmp_path: Path) -> None:
repo = tmp_path / "repo"
repo.mkdir()
(repo / "app.py").write_text("@app.route('/admin')\ndef admin():\n return eval(request.data)\n")
outcome = _measure()._scan(repo, "quick")
assert outcome["completed"] is True, outcome
assert outcome["findings_total"] == 1
assert not (repo / ".openultrasast" / "runs").exists()
+34 -7
View File
@@ -167,7 +167,7 @@ def test_cli_scan_writes_sarif_manifest_and_honors_fail_policy(tmp_path: Path, m
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", ".runs")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
assert main(["scan", str(repo), "--mode", "quick", "--fail-on", "verified"]) == 1
@@ -187,7 +187,7 @@ def test_quick_scan_report_is_inventory_without_map_or_docker(tmp_path: Path, mo
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", ".runs")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
docker_argv: list[list[str]] = []
original_run = subprocess.run
@@ -232,7 +232,7 @@ def test_standard_scan_writes_complexity_map_without_docker(tmp_path: Path, monk
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", ".runs")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
docker_argv: list[list[str]] = []
original_run = subprocess.run
@@ -276,7 +276,7 @@ def test_standard_scan_records_hunter_model_unavailable_when_model_unset(tmp_pat
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", ".runs")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
assert main(["scan", str(repo), "--mode", "standard"]) == 0
@@ -569,17 +569,44 @@ def test_every_recorded_scan_degradation_is_rendered(tmp_path) -> None: # type:
assert needle in text, needle
def test_quick_scan_names_a_language_nothing_covers(tmp_path, capsys) -> None: # type: ignore[no-untyped-def]
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_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 / ".openultrasast" / "runs").iterdir()) / "report.md"
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):
@@ -590,7 +617,7 @@ def test_deep_scan_records_retirement_without_running_snippets(tmp_path, monkeyp
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 / ".openultrasast" / "runs").iterdir())
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"] == {
+1 -1
View File
@@ -59,7 +59,7 @@ def test_disabled_rule_via_ledger_does_not_fire_in_scan(tmp_path: Path, monkeypa
ledger_dir = repo / ".openultrasast" / "calibration"
ledger_dir.mkdir(parents=True)
(ledger_dir / "rule_policy.json").write_text(json.dumps({"python-unsafe-eval": {"status": "disabled"}}))
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", ".runs")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
assert main(["scan", str(repo), "--mode", "quick"]) == 0
+48 -5
View File
@@ -1,13 +1,56 @@
import json
from pathlib import Path
import pytest
from openultrasast.config import load_config
from openultrasast.run import create_scan_run
def test_create_scan_run_writes_directories_and_config(tmp_path: Path) -> None:
def _runs(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
"""The default run root for this test, with the user's cache pointed away from the real one."""
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache"))
monkeypatch.delenv("OPENULTRASAST_RUNS_DIR", raising=False)
return tmp_path / "cache" / "openultrasast" / "runs"
def test_create_scan_run_writes_directories_and_config_under_the_user_cache(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
runs = _runs(tmp_path, monkeypatch)
target = tmp_path / "repo"
target.mkdir()
run = create_scan_run(target, load_config(None))
assert run.root == runs / run.scan_id
assert (run.root / "preprocess").is_dir()
recorded = json.loads((run.root / "resolved_config.json").read_text())
assert recorded["runs_dir"] == str(runs)
assert run.target == target.resolve()
assert list(target.iterdir()) == []
def test_a_relative_runs_dir_is_taken_from_the_working_directory_not_the_target(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
working = tmp_path / "working"
working.mkdir()
target = tmp_path / "repo"
target.mkdir()
monkeypatch.chdir(working)
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", ".runs")
run = create_scan_run(target, load_config(None))
assert run.root == working / ".runs" / run.scan_id
assert list(target.iterdir()) == []
def test_an_absolute_runs_dir_is_used_as_given(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
elsewhere = tmp_path / "elsewhere"
elsewhere.mkdir()
link = tmp_path / "link"
link.symlink_to(elsewhere, target_is_directory=True)
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(link / "runs"))
run = create_scan_run(tmp_path, load_config(None))
assert run.root.exists()
assert (run.root / "preprocess").is_dir()
assert (run.root / "resolved_config.json").is_file()
assert run.root.parent.name == "runs"
assert run.root == link / "runs" / run.scan_id
assert (elsewhere / "runs" / run.scan_id).is_dir()
+231
View File
@@ -0,0 +1,231 @@
"""Where a scan writes (contributor-scan Requirement 5.3): the run goes to the user's cache, and the analysed
tree is left as it was unless the scan has a false positive to remember."""
import errno
import hashlib
import json
import re
import shutil
import subprocess
from pathlib import Path
import pytest
from openultrasast import cli
from openultrasast.cli import main
from openultrasast.config import ResolvedConfig
LEDGER = ".openultrasast/calibration/false_positive_learnings.json"
LEDGER_DIRECTORIES = {".openultrasast", ".openultrasast/calibration"}
LEDGER_UNWRITTEN = {"stage": "record_calibration", "reason": "ledger_not_written"}
def _user_cache(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
"""The default run root for this test, with the user's cache pointed away from the real one."""
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache"))
monkeypatch.delenv("OPENULTRASAST_RUNS_DIR", raising=False)
return tmp_path / "cache" / "openultrasast" / "runs"
def _target(root: Path, *, repository: bool = False, learns: bool = False) -> Path:
repo = root / "repo"
(repo / "pkg").mkdir(parents=True)
(repo / "app.py").write_text("@app.route('/admin')\ndef admin():\n return eval(request.data)\n")
# An eval no route reaches is rejected as unreachable, and a rejected finding is a false-positive learning.
helper = "def helper(x):\n return eval(x)\n" if learns else "def helper():\n return 1\n"
(repo / "pkg" / "lib.py").write_text(helper)
(repo / ".gitignore").write_text("__pycache__/\n")
if repository:
git = ["git", "-C", str(repo), "-c", "user.name=tests", "-c", "[email protected]", "-c", "commit.gpgsign=false"]
subprocess.run([*git, "init", "-q"], check=True)
subprocess.run([*git, "add", "-A"], check=True)
subprocess.run([*git, "commit", "-q", "-m", "fixture"], check=True)
return repo
def _tree(root: Path) -> tuple[dict[str, str], set[str]]:
"""Every file with its size and digest, and every directory, hidden entries included."""
files: dict[str, str] = {}
directories: set[str] = set()
for path in root.rglob("*"):
relative = path.relative_to(root).as_posix()
if path.is_dir():
directories.add(relative)
else:
data = path.read_bytes()
files[relative] = f"{len(data)} {hashlib.sha256(data).hexdigest()}"
return files, directories
def _scan(repo: Path, mode: str = "quick") -> int:
return main(["scan", str(repo), "--mode", mode])
@pytest.mark.parametrize("repository", [False, True])
@pytest.mark.parametrize("mode", ["quick", "standard"])
def test_a_scan_that_learns_nothing_leaves_the_target_as_it_was(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], mode: str, repository: bool
) -> None:
if repository and shutil.which("git") is None:
pytest.skip("git is needed to prepare a repository target")
runs = _user_cache(tmp_path, monkeypatch)
repo = _target(tmp_path, repository=repository)
before = _tree(repo)
assert _scan(repo, mode) == 0
(run,) = runs.iterdir()
assert (run / "manifest.json").is_file()
assert _tree(repo) == before
def test_a_scan_that_learns_writes_the_ledger_into_the_tree_and_nothing_else(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
runs = _user_cache(tmp_path, monkeypatch)
repo = _target(tmp_path, learns=True)
files_before, directories_before = _tree(repo)
assert _scan(repo) == 0
(run,) = runs.iterdir()
learnings = json.loads((repo / LEDGER).read_text())["learnings"]
assert [learning["path"] for learning in learnings] == ["pkg/lib.py"]
kept = json.loads((run / "calibration" / "false_positive_learnings.json").read_text())["learnings"]
assert kept == learnings
files_after, directories_after = _tree(repo)
assert {name: files_after[name] for name in files_before} == files_before
assert set(files_after) - set(files_before) == {LEDGER}
assert directories_after - directories_before == LEDGER_DIRECTORIES
@pytest.mark.parametrize("mode", ["quick", "standard"])
def test_a_scan_that_cannot_write_the_ledger_records_it_and_goes_on(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], mode: str
) -> None:
runs = _user_cache(tmp_path, monkeypatch)
repo = _target(tmp_path, learns=True)
# A file where the ledger's directory has to be created. Permission bits do not stop root, and CI runs as
# root; this stops every user the way a read-only mount does.
(repo / ".openultrasast").write_text("not a directory\n")
before = _tree(repo)
assert _scan(repo, mode) == 0
(run,) = runs.iterdir()
degradations = json.loads((run / "manifest.json").read_text())["degradations"]
recorded = [{key: item.get(key) for key in LEDGER_UNWRITTEN} for item in degradations]
assert LEDGER_UNWRITTEN in recorded
detail = next(item["detail"] for item in degradations if item["reason"] == "ledger_not_written")
assert str(repo) in detail
assert _tree(repo) == before
assert json.loads((run / "calibration" / "false_positive_learnings.json").read_text())["learnings"]
def _learning_scan(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Path, Path]:
"""A target with one rejected finding, scanned once: the store in the tree now holds that learning."""
runs = _user_cache(tmp_path, monkeypatch)
repo = _target(tmp_path, learns=True)
assert _scan(repo) == 0
assert (repo / LEDGER).is_file()
return runs, repo
def _learned_again(run: Path) -> bool:
"""The scan rejected the same false positive once more, so it had a learning in hand."""
learnings = json.loads((run / "calibration" / "false_positive_learnings.json").read_text())["learnings"]
return [learning["path"] for learning in learnings] == ["pkg/lib.py"]
def test_a_rescan_that_rejects_a_stored_false_positive_leaves_the_store_as_it_was(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
runs, repo = _learning_scan(tmp_path, monkeypatch)
ledger = repo / LEDGER
tree_before = _tree(repo)
stamp_before = (ledger.stat().st_mtime_ns, ledger.read_bytes())
earlier = set(runs.iterdir())
assert _scan(repo) == 0
(run,) = set(runs.iterdir()) - earlier
assert _learned_again(run)
assert (ledger.stat().st_mtime_ns, ledger.read_bytes()) == stamp_before
assert _tree(repo) == tree_before
def test_a_rescan_on_a_read_only_tree_records_nothing_because_nothing_needed_writing(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
runs, repo = _learning_scan(tmp_path, monkeypatch)
ledger = repo / LEDGER
tree_before = _tree(repo)
write = cli.write_false_positive_learnings
def refuse_the_store(learnings, path):
# The tree is read-only from here on, so the one write into it fails as on a `:ro` mount. Permission
# bits cannot arrange that for a store that has to stay readable, because root ignores them.
if path == ledger.resolve():
raise PermissionError(errno.EACCES, "Permission denied", str(path))
write(learnings, path)
monkeypatch.setattr(cli, "write_false_positive_learnings", refuse_the_store)
earlier = set(runs.iterdir())
assert _scan(repo) == 0
(run,) = set(runs.iterdir()) - earlier
assert _learned_again(run)
degradations = json.loads((run / "manifest.json").read_text()).get("degradations") or []
assert "ledger_not_written" not in [item["reason"] for item in degradations]
assert _tree(repo) == tree_before
def test_the_scan_prints_the_run_directory_once(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
runs = _user_cache(tmp_path, monkeypatch)
repo = _target(tmp_path)
assert _scan(repo) == 0
(run,) = runs.iterdir()
out = capsys.readouterr().out
assert re.findall(r"^run_dir=(.+)$", out, flags=re.MULTILINE) == [str(run)]
assert out.count(str(run)) == 1
def test_an_absolute_runs_dir_override_replaces_the_default(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache"))
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(tmp_path / "elsewhere" / "runs"))
repo = _target(tmp_path)
assert _scan(repo) == 0
(run,) = (tmp_path / "elsewhere" / "runs").iterdir()
assert (run / "report.md").is_file()
assert not (tmp_path / "cache").exists()
def test_a_relative_runs_dir_override_is_taken_from_the_working_directory_not_the_target(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
working = tmp_path / "working"
working.mkdir()
monkeypatch.chdir(working)
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", ".runs")
repo = _target(tmp_path)
assert _scan(repo) == 0
(run,) = (working / ".runs").iterdir()
assert (run / "report.md").is_file()
assert not (repo / ".runs").exists()
def test_no_test_can_write_a_scan_run_into_the_developers_cache(tmp_path_factory: pytest.TempPathFactory) -> None:
"""tests/conftest.py redirects the override for every test, so one that forgets to name a location cannot
write into the real `~/.cache/openultrasast/runs`."""
assert Path(ResolvedConfig().runs_dir).is_relative_to(tmp_path_factory.getbasetemp())
+1 -1
View File
@@ -31,7 +31,7 @@ def _scan(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, *, mode: str, config_
repo = tmp_path / "repo"
repo.mkdir(parents=True)
(repo / "app.py").write_text(_VULN)
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", ".runs")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
monkeypatch.delenv("OPENROUTER_API_KEY", raising=False)
monkeypatch.delenv("OPENULTRASAST_HUNTER_CLIENT", raising=False)
argv = ["scan", str(repo), "--mode", mode]
+2 -2
View File
@@ -15,7 +15,7 @@ def test_scan_writes_score_artifact_and_manifest_block(tmp_path: Path, monkeypat
repo = tmp_path / "repo"
repo.mkdir()
(repo / "app.py").write_text("@app.route('/x')\ndef view():\n return eval(request.data)\n")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", ".runs")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
assert main(["scan", str(repo), "--mode", "quick"]) == 0
@@ -33,7 +33,7 @@ def test_scan_fails_loud_when_an_enabled_rule_cwe_is_unmapped(tmp_path: Path, mo
repo = tmp_path / "repo"
repo.mkdir()
(repo / "app.py").write_text("x = 1\n")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", ".runs")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
unmapped = SimpleNamespace(rule_id="bogus", cwe="CWE-99999", status="enabled")
real_loader = cli.load_ruleset
monkeypatch.setattr(cli, "load_ruleset", lambda *a, **k: (*real_loader(*a, **k), unmapped))
+2 -2
View File
@@ -47,9 +47,9 @@ def test_probe_off_yields_no_javascript_grammar(monkeypatch: pytest.MonkeyPatch)
def test_standard_javascript_is_unadjudicated_without_extra(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("OPENULTRASAST_TREE_SITTER_PROBE", "0")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", ".runs")
repo = tmp_path / "repo"
repo.mkdir()
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
(repo / "app.js").write_text("eval(req.query.x)\n")
assert main(["scan", str(repo), "--mode", "standard"]) == 0
run_dir = sorted((repo / ".runs").iterdir())[-1]
@@ -61,9 +61,9 @@ def test_standard_javascript_is_unadjudicated_without_extra(tmp_path: Path, monk
def test_quick_scan_without_extra_still_inventories(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("OPENULTRASAST_TREE_SITTER_PROBE", "0")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", ".runs")
repo = tmp_path / "repo"
repo.mkdir()
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
(repo / "app.py").write_text("def run():\n return eval(request.args)\n")
assert main(["scan", str(repo), "--mode", "quick"]) == 0
run_dir = sorted((repo / ".runs").iterdir())[-1]
+3 -3
View File
@@ -78,7 +78,7 @@ def test_quick_scan_writes_no_overlay(tmp_path: Path, monkeypatch: pytest.Monkey
repo = tmp_path / "repo"
repo.mkdir()
(repo / "app.py").write_text("def run():\n return eval(request.args)\n")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", ".runs")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
assert main(["scan", str(repo), "--mode", "quick"]) == 0
run_dir = _latest_run(repo)
assert not (run_dir / "overlay.json").exists()
@@ -90,7 +90,7 @@ def test_standard_scan_writes_overlay_without_executing_target(tmp_path: Path, m
repo = tmp_path / "repo"
repo.mkdir()
(repo / "app.py").write_text("def run():\n return eval(request.args)\n")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", ".runs")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
monkeypatch.setenv("OPENULTRASAST_SANDBOX_PROBE", "0")
assert main(["scan", str(repo), "--mode", "standard"]) == 0
run_dir = _latest_run(repo)
@@ -130,7 +130,7 @@ def test_unlabeled_messy_tree_has_both_dispositions(tmp_path: Path, monkeypatch:
repo.mkdir()
(repo / "broken.py").write_text("eval(request.args)\ndef oops(\n")
(repo / "app.py").write_text("def run():\n return eval(request.args)\n")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", ".runs")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
assert main(["scan", str(repo), "--mode", "standard"]) == 0
overlay = json.loads((_latest_run(repo) / "overlay.json").read_text())["records"]
by_path = {}
+2 -2
View File
@@ -218,7 +218,7 @@ def test_standard_scripted_hunter_emits_tool_hunter_suspicion(tmp_path: Path, mo
repo = _standard_repo(tmp_path)
config = _write_hunter_config(tmp_path)
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", ".runs")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
monkeypatch.setenv("OPENULTRASAST_HUNTER_CLIENT", "scripted")
docker_argv = _guard_docker(monkeypatch)
hunter_calls: list[int] = []
@@ -254,7 +254,7 @@ def test_dump_only_hunter_client_emits_no_hunter_findings(tmp_path: Path, monkey
repo = _standard_repo(tmp_path)
config = _write_hunter_config(tmp_path)
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", ".runs")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
monkeypatch.setenv("OPENULTRASAST_HUNTER_CLIENT", "dump-only")
docker_argv = _guard_docker(monkeypatch)
hunter_calls: list[int] = []
+1 -1
View File
@@ -84,7 +84,7 @@ def test_cli_scan_writes_accepted_and_rejected_verifications(tmp_path: Path, mon
(repo / "app.py").write_text(
"@app.route('/admin')\ndef admin():\n return eval(request.data)\n\ndef helper(value):\n return exec(value)\n"
)
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", ".runs")
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(repo / ".runs"))
assert main(["scan", str(repo), "--mode", "quick"]) == 0