diff --git a/README.md b/README.md index d69b7c54..7e7d27ef 100644 --- a/README.md +++ b/README.md @@ -193,6 +193,11 @@ there older than 30 days are removed, and `ousast` prints one `notice:` line whe `OPENULTRASAST_RUNS_RETENTION_DAYS` sets the number of days (`0` keeps every run), and nothing is ever removed from a location chosen with `OPENULTRASAST_RUNS_DIR`. +`ousast benchmark` writes its run to the same runs directory, as +`//` beside the scan runs, and prints that path +(`benchmark_run_dir=`); run retention removes it like a scan run. The MCP tool +`openultrasast.benchmark` uses the same directory. + A scan that rejects or holds a finding writes one file into the scanned tree, `/.openultrasast/calibration/false_positive_learnings.json`, and only when that file's content would change; on a read-only tree the scan records `ledger_not_written` instead and keeps diff --git a/docs/examples.md b/docs/examples.md index 601ff481..aab24931 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -8,7 +8,9 @@ the current working directory, never against the target. Once a scan has written default location, with no `OPENULTRASAST_RUNS_DIR` set, the runs there that are older than 30 days are removed, and `ousast` prints one `notice:` line when it removes any; `OPENULTRASAST_RUNS_RETENTION_DAYS` sets the number of days (`0` keeps every run), and nothing is -ever removed from a location chosen with `OPENULTRASAST_RUNS_DIR`. +ever removed from a location chosen with `OPENULTRASAST_RUNS_DIR`. `ousast benchmark` writes its +run to the same directory, as `//` beside the scan runs, and prints +that path (`benchmark_run_dir=`); run retention removes it like a scan run. A scan that rejects or holds a finding writes one file into the scanned tree, and only when that file's content would change: diff --git a/src/openultrasast/benchmark.py b/src/openultrasast/benchmark.py index 528a4e63..ebbf3627 100644 --- a/src/openultrasast/benchmark.py +++ b/src/openultrasast/benchmark.py @@ -182,10 +182,15 @@ def resolve_benchmark_source(manifest_path: Path, manifest: BenchmarkManifest) - return source.resolve() -def create_benchmark_run(target: Path, manifest: BenchmarkManifest) -> BenchmarkRun: +def create_benchmark_run(runs_dir: Path, manifest: BenchmarkManifest) -> BenchmarkRun: + """A run beside the scan runs, named like one so that run retention removes it. + + Create it once its scan has returned: a run that exists while a scan prunes can be taken for an old + one when the scan outlasts the retention window. + """ timestamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ") benchmark_run_id = f"{timestamp}-{uuid4().hex[:8]}" - root = target.resolve() / ".openultrasast" / "benchmarks" / benchmark_run_id + root = runs_dir / benchmark_run_id root.mkdir(parents=True, exist_ok=False) return BenchmarkRun(benchmark_run_id=benchmark_run_id, root=root, manifest=manifest) diff --git a/src/openultrasast/cli.py b/src/openultrasast/cli.py index cf7f6c1d..16e619e5 100644 --- a/src/openultrasast/cli.py +++ b/src/openultrasast/cli.py @@ -1100,10 +1100,11 @@ def _benchmark(manifest_path: Path, config_path: Path, mode: str) -> int: raise SystemExit(f"benchmark manifest is not a file: {manifest_path}") manifest = load_benchmark_manifest(manifest_path) target = resolve_benchmark_source(manifest_path, manifest) - run = create_benchmark_run(target, manifest) + config = load_config(config_path if config_path.exists() else None) started_at = perf_counter() outcome = _run_scan(target, config_path, mode, "never") runtime_seconds = perf_counter() - started_at + run = create_benchmark_run(Path(config.runs_dir), manifest) findings = _load_scan_findings(outcome.run_dir) baseline_findings = load_baseline_findings(manifest_path, manifest) result = evaluate_benchmark( diff --git a/src/openultrasast/mcp.py b/src/openultrasast/mcp.py index dac9e800..e7abb68d 100644 --- a/src/openultrasast/mcp.py +++ b/src/openultrasast/mcp.py @@ -163,6 +163,7 @@ def _artifacts(args: dict[str, Any]) -> dict[str, Any]: def _benchmark(args: dict[str, Any]) -> dict[str, Any]: from .benchmark import create_benchmark_run, evaluate_benchmark, load_benchmark_manifest, load_findings, resolve_benchmark_source from .cli import _run_scan + from .config import load_config manifest_path = Path(_require(args, "manifest")) if not manifest_path.is_file(): @@ -170,8 +171,10 @@ def _benchmark(args: dict[str, Any]) -> dict[str, Any]: mode = str(args.get("mode", "quick")) manifest = load_benchmark_manifest(manifest_path) target = resolve_benchmark_source(manifest_path, manifest) - run = create_benchmark_run(target, manifest) - outcome = _run_scan(target, Path(str(args.get("config", "openultrasast.toml"))), mode, "never") + config_path = Path(str(args.get("config", "openultrasast.toml"))) + config = load_config(config_path if config_path.exists() else None) + outcome = _run_scan(target, config_path, mode, "never") + run = create_benchmark_run(Path(config.runs_dir), manifest) result = evaluate_benchmark( run=run, mode=mode, findings=load_findings(outcome.run_dir / "findings.json"), scan_id=outcome.scan_id, scan_run_dir=outcome.run_dir ) diff --git a/tests/test_benchmark.py b/tests/test_benchmark.py index 443b9675..5195ae37 100644 --- a/tests/test_benchmark.py +++ b/tests/test_benchmark.py @@ -1,6 +1,9 @@ import json +from datetime import UTC, datetime, timedelta, tzinfo from pathlib import Path +from test_run_pruning import _default_cache + from openultrasast.benchmark import ( create_benchmark_run, evaluate_benchmark, @@ -10,6 +13,7 @@ from openultrasast.benchmark import ( ) from openultrasast.cli import main from openultrasast.findings import StaticFinding +from openultrasast.run import prune_old_runs def test_benchmark_manifest_loads_expected_findings(tmp_path: Path) -> None: @@ -103,7 +107,7 @@ evidence = "memcpy copies attacker-controlled input" + "\n" ) manifest = load_benchmark_manifest(manifest_path) - run = create_benchmark_run(repo, manifest) + run = create_benchmark_run(repo / ".runs", manifest) result = evaluate_benchmark(run=run, mode="quick", findings=[], scan_id="scan-1", scan_run_dir=repo / ".runs" / "scan-1") write_benchmark_artifacts(run, manifest_path, result) @@ -146,8 +150,9 @@ evidence = "memcpy copies attacker-controlled input" assert main(["benchmark", str(manifest_path), "--mode", "quick"]) == 0 - benchmark_dir = sorted((repo / ".openultrasast" / "benchmarks").iterdir())[-1] - payload = json.loads((benchmark_dir / "benchmark_result.json").read_text()) + [scoreboard] = sorted((repo / ".runs").glob("*/benchmark_result.json")) + assert not (repo / ".openultrasast" / "benchmarks").exists() + payload = json.loads(scoreboard.read_text()) assert payload["benchmark_name"] == "cpp-smoke" assert payload["metrics"]["expected_findings_total"] == 1 @@ -157,6 +162,40 @@ evidence = "memcpy copies attacker-controlled input" assert payload["metrics"]["artifact_links"]["findings"].endswith("findings.json") +def test_run_retention_removes_a_benchmark_run_like_a_scan_run(tmp_path: Path) -> None: + manifest_path = tmp_path / "benchmark.toml" + manifest_path.write_text('name = "cpp-smoke"\nlanguage = "c_cpp"\n\n[source]\npath = "repo"\n') + runs = tmp_path / "runs" + + run = create_benchmark_run(runs, load_benchmark_manifest(manifest_path)) + + assert run.root.parent == runs + assert prune_old_runs(runs, retention_days=30, now=datetime.now(UTC) + timedelta(days=31)) == [run.root] + + +class _FortyDaysAgo(datetime): + """Stands in for the clock that names a benchmark run: that run then started forty days ago.""" + + @classmethod + def now(cls, tz: tzinfo | None = None) -> datetime: + return datetime.now(UTC) - timedelta(days=40) + + +def test_benchmark_keeps_its_run_when_its_scan_outlasts_the_retention(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") + manifest = tmp_path / "benchmark.toml" + manifest.write_text('name = "py-smoke"\nlanguage = "python"\n\n[source]\npath = "repo"\n') + runs = _default_cache(tmp_path, monkeypatch) + monkeypatch.setattr("openultrasast.benchmark.datetime", _FortyDaysAgo) + + assert main(["benchmark", str(manifest), "--mode", "quick"]) == 0 + + [scoreboard] = runs.glob("*/benchmark_result.json") + assert json.loads(scoreboard.read_text())["benchmark_name"] == "py-smoke" + + def test_benchmark_matching_uses_function_sink_and_evidence_text(tmp_path: Path) -> None: manifest_path = tmp_path / "benchmark.toml" repo = tmp_path / "repo" @@ -182,7 +221,7 @@ evidence = "attacker-controlled memcpy" + "\n" ) manifest = load_benchmark_manifest(manifest_path) - run = create_benchmark_run(repo, manifest) + run = create_benchmark_run(repo / ".runs", manifest) findings = [ _finding( finding_id="c-unsafe-memory-copy:src/vuln.cpp:9", @@ -226,7 +265,7 @@ evidence = "memcpy" + "\n" ) manifest = load_benchmark_manifest(manifest_path) - run = create_benchmark_run(repo, manifest) + run = create_benchmark_run(repo / ".runs", manifest) findings = [ _finding( finding_id="c-shell-exec:src/other.cpp:12", @@ -299,7 +338,7 @@ evidence = "memcpy copies attacker-controlled input" + "\n" ) manifest = load_benchmark_manifest(manifest_path) - run = create_benchmark_run(repo, manifest) + run = create_benchmark_run(repo / ".runs", manifest) baseline_findings = load_baseline_findings(manifest_path, manifest) unrelated_finding = _finding( finding_id="c-shell-exec:src/other.cpp:12", @@ -372,7 +411,7 @@ evidence = "system runs attacker input" + "\n" ) manifest = load_benchmark_manifest(manifest_path) - run = create_benchmark_run(repo, manifest) + run = create_benchmark_run(repo / ".runs", manifest) findings = [ _finding( finding_id="c-unsafe-memory-copy:src/vuln.cpp:9", diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 261723c8..48aba506 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -178,6 +178,21 @@ def test_benchmark_result_carries_the_notice_of_the_runs_the_scan_removed(tmp_pa assert result["notices"] == [f"removed 1 run older than 30 days from {runs}"] +def test_a_benchmark_run_sits_beside_the_scan_runs_not_in_the_scanned_tree(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + runs = _default_cache(tmp_path, monkeypatch) + repo = _repo(tmp_path) + manifest = tmp_path / "benchmark.toml" + manifest.write_text('name = "py-smoke"\nlanguage = "python"\n\n[source]\npath = "repo"\n') + + result = _call(McpServer(), "openultrasast.benchmark", {"manifest": str(manifest), "mode": "quick"}) + + assert not result["isError"] + benchmark_run = runs / result["benchmark_run_id"] + assert benchmark_run.is_dir() + assert any((path / "manifest.json").is_file() for path in runs.iterdir() if path != benchmark_run) + assert not (repo / ".openultrasast" / "benchmarks").exists() + + # ---- stdio loop -------------------------------------------------------------