diff --git a/.agents/skills/openultrasast-scan/SKILL.md b/.agents/skills/openultrasast-scan/SKILL.md index 11ede433..e0102a3a 100644 --- a/.agents/skills/openultrasast-scan/SKILL.md +++ b/.agents/skills/openultrasast-scan/SKILL.md @@ -16,7 +16,9 @@ it wrote. 3. Start with `--mode quick` unless the task needs the Joern model layer (`standard`) or sandboxed regression snippets (`deep`). Check the prerequisites below first; a mode whose engine is missing still exits 0 and records a degradation. -4. Read the printed `scan_id=` and `run_dir=` lines; the run directory is `.openultrasast/runs//`. +4. Read the printed `scan_id=` and `run_dir=` lines; the run directory is `~/.cache/openultrasast/runs//` + (`$XDG_CACHE_HOME/openultrasast/runs/` when that variable is set to an absolute path; `OPENULTRASAST_RUNS_DIR` + overrides it). 5. Report the finding count, how many the verifier accepted, and **every** recorded degradation (`manifest.json`, key `degradations`). No findings plus a degradation is not a clean scan: the scan answered a smaller question than it was asked. @@ -66,6 +68,10 @@ Each entry in `manifest.json` `degradations` is `{"stage": ..., "reason": ...}`. but has no line in `report.md`'s "What could not be analysed" section. - `hunter_model_unavailable` (stage `map`): `[models] hunter` is unset, so the tool hunter did not run. Recorded on every standard scan without that setting; it is expected, not an error. +- `ledger_not_written` (stage `record_calibration`): the scan rejected or held a finding and could not write the + false-positive ledger into the analysed tree, as on a read-only mount. Recorded whenever such a scan has a + learning the tree's ledger does not already hold; the learnings are in this run's + `calibration/false_positive_learnings.json`, and the next scan starts without them. - coverage facts from the graph, rendered in `report.md` under "What could not be analysed": `cpg_empty`, `cpg_build_failed`, `cpg_sharded`, `files_unparsed`, `query_failed`, `query_budget_reserved`, `query_too_expensive`, `budget_exhausted`, `regions_truncated`, @@ -97,7 +103,7 @@ above, and that is what `--fail-on verified` counts. There is no configurable re ## Run artifacts -Under `.openultrasast/runs//`: +Under `~/.cache/openultrasast/runs//`: - `report.md`, `report.sarif` (SARIF 2.1.0 for code hosts and IDEs), `manifest.json` (stages, degradations, model payload) - `findings.json`, `verification.json`, `score.json`, `shadow_findings.json` (rules shipped as `shadow`) @@ -105,6 +111,11 @@ Under `.openultrasast/runs//`: - standard: `fusion.json`, `complexity_map.json`, `overlay.json`; deep: `verdicts.json` - `calibration/false_positive_learnings.json`, `rank/ranking.json`, `mapping/`, `preprocess/`, `trace/events.jsonl` +The only write a scan makes into the scanned tree is the ledger +`/.openultrasast/calibration/false_positive_learnings.json`: a scan that rejects or holds a finding +writes it only when that file's content would change; on a read-only tree the scan records `ledger_not_written` +instead and keeps the learnings in this run directory's `calibration/false_positive_learnings.json`. + ## Changed code only `ousast pre-push --base --head --artifact ` replays a revision pair and diff --git a/.kiro/specs/contributor-scan/tasks.md b/.kiro/specs/contributor-scan/tasks.md index 06f2f8ba..ee8c1b13 100644 --- a/.kiro/specs/contributor-scan/tasks.md +++ b/.kiro/specs/contributor-scan/tasks.md @@ -370,6 +370,16 @@ — absent rather than zero when a slice is missing. - _Requirements: 5.1, 5.2, 5.3, 5.4, 8.1, 8.2_ - _Depends: 1.3_ + - _Part A landed 2026-11-24: where a scan writes._ A native scan creates its run under the user cache + (`~/.cache/openultrasast/runs//` by default; `OPENULTRASAST_RUNS_DIR` still wins), prints + `run_dir=` once, and leaves the analysed tree byte-identical unless it learns. The one write a scan + makes into the tree is the calibration ledger, + `/.openultrasast/calibration/false_positive_learnings.json`, by maintainer decision: written only + when its content would change; on a read-only tree the scan records `ledger_not_written` and completes with + the learnings in the run directory. Proven by tests and by runs of the real CLI; + `benchmarks/repos/measure.py` follows the printed run directory. Still open here: part B, the readable + summary; `ousast benchmark` and its MCP twin still write under `/.openultrasast/benchmarks/` and + no user doc names them; `_run_scan` stays over the complexity cap (18), touched by one line. - [ ] 3.2 Build and verify the image - `docker compose build`, then run a real scan through it and through the shell wrapper. The Dockerfile and diff --git a/README.md b/README.md index fdf89748..0384fa45 100644 --- a/README.md +++ b/README.md @@ -182,9 +182,17 @@ A missing engine is a recorded degradation (`cpg_unavailable`, `regress_retired` clean result. `--fail-on never|findings|verified|worth-fixing` sets the exit code. `--config openultrasast.toml` -loads settings. Every run writes these files under `/.openultrasast/runs//`: -`manifest.json`, `findings.json`, `verification.json`, `score.json`, `report.md`, `report.sarif` -and `trace/events.jsonl`. +loads settings. Every run writes `manifest.json`, `findings.json`, `verification.json`, +`score.json`, `report.md`, `report.sarif` and `trace/events.jsonl` under +`~/.cache/openultrasast/runs//`, or under `$XDG_CACHE_HOME/openultrasast/runs/` when that +variable is set to an absolute path. The scan prints that path (`run_dir=`). +`OPENULTRASAST_RUNS_DIR` moves the run directory: an absolute path is used as given, and a relative +one is resolved against the current working directory, never against the directory being scanned. + +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 +the learnings in the run directory. `ousast pre-push` (experimental) analyses the commits a push would publish against their base. First, the quick rules run on the changed lines. Then the engine compares head with base, and only diff --git a/benchmarks/repos/measure.py b/benchmarks/repos/measure.py index a9477244..48949d89 100644 --- a/benchmarks/repos/measure.py +++ b/benchmarks/repos/measure.py @@ -89,6 +89,14 @@ def main(argv: list[str] | None = None) -> int: return 0 +def _printed_run_dir(stdout: str) -> Path | None: + """The `run_dir=` line the scan prints: where the run went, wherever the default or the override puts it.""" + for line in stdout.splitlines(): + if line.startswith("run_dir="): + return Path(line.removeprefix("run_dir=")) + return None + + def _copy(root: Path, work: Path) -> None: if work.exists(): shutil.rmtree(work) @@ -107,8 +115,8 @@ def _scan(work: Path, mode: str, config: Path | None = None) -> dict[str, object wall = round(time.monotonic() - started, 2) peak_kb = max(resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss, before) - runs = sorted((work / ".openultrasast" / "runs").glob("*/")) - manifest = runs[-1] / "manifest.json" if runs else None + run_dir = _printed_run_dir(proc.stdout) + manifest = run_dir / "manifest.json" if run_dir is not None else None if proc.returncode not in (0, 1) or manifest is None or not manifest.is_file(): # Req 4.3: a repository that cannot be processed records the stage it failed at, not an opaque error. return { @@ -123,7 +131,7 @@ def _scan(work: Path, mode: str, config: Path | None = None) -> dict[str, object data = json.loads(manifest.read_text()) model = dict(data.get("model", {})) - findings = _findings(runs[-1]) + findings = _findings(run_dir) return { "completed": True, "exit_code": proc.returncode, diff --git a/docs/examples.md b/docs/examples.md index bea59f81..c7f16204 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -1,13 +1,23 @@ # End-to-end examples -Each example stands on its own. Artifacts land under `/.openultrasast/runs//`. -`.openultrasast/` is gitignored. +Each example stands on its own. A scan writes its run under +`~/.cache/openultrasast/runs//`, or under `$XDG_CACHE_HOME/openultrasast/runs/` when +that variable is set to an absolute path, and prints that path. `OPENULTRASAST_RUNS_DIR` +overrides the location: an absolute path is used as given, and a relative one is resolved against +the current working directory, never against the target. + +A scan that rejects or holds a finding writes one file into the scanned tree, and only when that +file's content would change: +`/.openultrasast/calibration/false_positive_learnings.json` (`.openultrasast/` is +gitignored in this repository, not in one of your own); on a read-only tree the scan records +`ledger_not_written` instead and keeps the learnings in the run directory. ## 1. Quick scan a local repo (deterministic, no keys) ```bash uv run ousast scan /path/to/code --mode quick -run=/path/to/code/.openultrasast/runs/ +# the scan prints: run_dir=/home/you/.cache/openultrasast/runs/ +run=/home/you/.cache/openultrasast/runs/ cat "$run/report.md" # findings + evidence (secrets redacted) jq . "$run/score.json" # 0–100 project score + gate verdict "$run/report.sarif" # SARIF for code-scanning / IDEs diff --git a/src/openultrasast/cli.py b/src/openultrasast/cli.py index 4db45508..e480a361 100644 --- a/src/openultrasast/cli.py +++ b/src/openultrasast/cli.py @@ -631,7 +631,7 @@ def _run_scan(path: Path, config_path: Path, mode: str, fail_on: str) -> ScanOut write_verification_results(verifications, verification_path) runtime.run_stage( "record_calibration", - lambda: _persist_calibration_feedback(run, ledger_path, prior_learnings, findings, verifications), + lambda: _persist_calibration_feedback(run, ledger_path, prior_learnings, findings, verifications, runtime), ) # Fusion: deterministic two-panel adjudication for triggered findings (standard mode). fusion_decisions: list[FusionDecision] = [] @@ -887,11 +887,19 @@ def _persist_calibration_feedback( prior_learnings: list[FalsePositiveLearning], findings: list[StaticFinding], verifications: list[VerificationResult], + runtime: HarnessRuntime, ) -> list[FalsePositiveLearning]: # Store rejected or held findings as scoped learnings for the next scan. new_learnings = learnings_from_verifications(findings, verifications) merged = merge_false_positive_learnings(prior_learnings, new_learnings) - write_false_positive_learnings(merged, ledger_path) + if merged != prior_learnings: + # The ledger is the one thing a scan still writes into the analysed tree, so it is written only when its + # content would change: a false positive already in the store is not a new learning. A tree that refuses + # the write (mounted read-only) is recorded, not fatal. + try: + write_false_positive_learnings(merged, ledger_path) + except OSError as exc: + runtime.state["degradations"].append({"stage": "record_calibration", "reason": "ledger_not_written", "detail": str(exc)}) write_false_positive_learnings(new_learnings, run.root / "calibration" / "false_positive_learnings.json") return merged diff --git a/src/openultrasast/config.py b/src/openultrasast/config.py index c2c4da5c..cb3a4799 100644 --- a/src/openultrasast/config.py +++ b/src/openultrasast/config.py @@ -4,7 +4,7 @@ import json import logging import os import tomllib -from dataclasses import asdict, dataclass +from dataclasses import asdict, dataclass, field from pathlib import Path from typing import Literal @@ -195,6 +195,27 @@ class PushConfig(Contract): raise ValueError("push deadlines, cancellation allowance and cache limit must be positive") +def _user_cache_dir() -> Path: + """`$XDG_CACHE_HOME` when it is set and absolute, otherwise `~/.cache` (the XDG base-directory rule).""" + override = os.environ.get("XDG_CACHE_HOME", "") + if override and Path(override).is_absolute(): + return Path(override) + return Path.home() / ".cache" + + +def _runs_dir() -> str: + """Where a scan creates its run: the user's cache, unless `OPENULTRASAST_RUNS_DIR` says otherwise. + + Always absolute, and taken from the working directory when the override is relative, never from the + target: a run inside the analysed tree is what this default exists to prevent. + """ + override = os.environ.get("OPENULTRASAST_RUNS_DIR") + if not override: + return str(_user_cache_dir() / "openultrasast" / "runs") + path = Path(override) + return str(path if path.is_absolute() else Path.cwd() / path) + + @dataclass(frozen=True) class ResolvedConfig: models: ModelConfig = ModelConfig() @@ -208,7 +229,9 @@ class ResolvedConfig: obligations: ObligationsConfig = ObligationsConfig() model: ModelLayerConfig = ModelLayerConfig() push: PushConfig = PushConfig() - runs_dir: str = ".openultrasast/runs" + # Read from the environment each time a config is built, so one made without `load_config` lands in the + # same place. + runs_dir: str = field(default_factory=_runs_dir) def load_config(config_path: Path | None = None, *, dotenv: bool = True) -> ResolvedConfig: @@ -232,7 +255,6 @@ def load_config(config_path: Path | None = None, *, dotenv: bool = True) -> Reso obligations=_load_obligations(data.get("obligations", {})), model=_load_model(data.get("model", {})), push=PushConfig.from_payload(data.get("push", {})), - runs_dir=os.environ.get("OPENULTRASAST_RUNS_DIR", ".openultrasast/runs"), ) diff --git a/src/openultrasast/reports.py b/src/openultrasast/reports.py index 7b3b6cb5..a501a502 100644 --- a/src/openultrasast/reports.py +++ b/src/openultrasast/reports.py @@ -440,6 +440,10 @@ _COVERAGE_DEGRADATIONS: dict[str, str] = { "language not covered: {language} ({count} files). No quick rules{engine} exist for it, so **silence about " "these files is not a clean result**." ), + "ledger_not_written": ( + "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. {detail}" + ), } diff --git a/src/openultrasast/run.py b/src/openultrasast/run.py index 5bc7d5ee..eba8313a 100644 --- a/src/openultrasast/run.py +++ b/src/openultrasast/run.py @@ -19,7 +19,7 @@ def create_scan_run(target: Path, config: ResolvedConfig) -> ScanRun: resolved_target = target.resolve() timestamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ") scan_id = f"{timestamp}-{uuid4().hex[:8]}" - root = resolved_target / config.runs_dir / scan_id + root = Path(config.runs_dir) / scan_id root.mkdir(parents=True, exist_ok=False) (root / "preprocess").mkdir() write_resolved_config(config, root / "resolved_config.json") diff --git a/tests/conftest.py b/tests/conftest.py index 08ea1165..93b52b53 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -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. diff --git a/tests/test_benchmark.py b/tests/test_benchmark.py index b2ec0e22..443b9675 100644 --- a/tests/test_benchmark.py +++ b/tests/test_benchmark.py @@ -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 diff --git a/tests/test_config.py b/tests/test_config.py index 3daa2ac8..abf0a8d8 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -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") diff --git a/tests/test_degradation_matrix.py b/tests/test_degradation_matrix.py index 2ab3b2a9..135a8136 100644 --- a/tests/test_degradation_matrix.py +++ b/tests/test_degradation_matrix.py @@ -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 diff --git a/tests/test_fusion.py b/tests/test_fusion.py index b29757cf..453318dd 100644 --- a/tests/test_fusion.py +++ b/tests/test_fusion.py @@ -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] diff --git a/tests/test_hardening_pipeline.py b/tests/test_hardening_pipeline.py index 4521acd3..e60cd6db 100644 --- a/tests/test_hardening_pipeline.py +++ b/tests/test_hardening_pipeline.py @@ -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" diff --git a/tests/test_hunter.py b/tests/test_hunter.py index 2de2b1e3..cbddba4a 100644 --- a/tests/test_hunter.py +++ b/tests/test_hunter.py @@ -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 diff --git a/tests/test_obligation_scan.py b/tests/test_obligation_scan.py index 793c55ff..d0c928a5 100644 --- a/tests/test_obligation_scan.py +++ b/tests/test_obligation_scan.py @@ -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 diff --git a/tests/test_pipeline_calibration.py b/tests/test_pipeline_calibration.py index 1c12a27d..6870a3eb 100644 --- a/tests/test_pipeline_calibration.py +++ b/tests/test_pipeline_calibration.py @@ -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 --------------- diff --git a/tests/test_repo_measure.py b/tests/test_repo_measure.py new file mode 100644 index 00000000..6e3550b8 --- /dev/null +++ b/tests/test_repo_measure.py @@ -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() diff --git a/tests/test_reports.py b/tests/test_reports.py index 17d02c8b..d556ae9b 100644 --- a/tests/test_reports.py +++ b/tests/test_reports.py @@ -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"] == { diff --git a/tests/test_ruleset.py b/tests/test_ruleset.py index 7de381ba..283c2f38 100644 --- a/tests/test_ruleset.py +++ b/tests/test_ruleset.py @@ -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 diff --git a/tests/test_run.py b/tests/test_run.py index 564bf685..c3645d53 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -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() diff --git a/tests/test_scan_output_location.py b/tests/test_scan_output_location.py new file mode 100644 index 00000000..47763fbc --- /dev/null +++ b/tests/test_scan_output_location.py @@ -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", "user.email=tests@example.invalid", "-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()) diff --git a/tests/test_scan_pipeline_integrity.py b/tests/test_scan_pipeline_integrity.py index 0b1281b7..9a3f508d 100644 --- a/tests/test_scan_pipeline_integrity.py +++ b/tests/test_scan_pipeline_integrity.py @@ -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] diff --git a/tests/test_score_pipeline.py b/tests/test_score_pipeline.py index 696c20a6..9f731794 100644 --- a/tests/test_score_pipeline.py +++ b/tests/test_score_pipeline.py @@ -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)) diff --git a/tests/test_semantic_extra.py b/tests/test_semantic_extra.py index dd0fa709..286a0d6f 100644 --- a/tests/test_semantic_extra.py +++ b/tests/test_semantic_extra.py @@ -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] diff --git a/tests/test_semantic_pipeline.py b/tests/test_semantic_pipeline.py index f85bd5b0..ca9524c4 100644 --- a/tests/test_semantic_pipeline.py +++ b/tests/test_semantic_pipeline.py @@ -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 = {} diff --git a/tests/test_tool_hunter.py b/tests/test_tool_hunter.py index e123b7b3..a4870d9a 100644 --- a/tests/test_tool_hunter.py +++ b/tests/test_tool_hunter.py @@ -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] = [] diff --git a/tests/test_verification.py b/tests/test_verification.py index 422740da..1e50d105 100644 --- a/tests/test_verification.py +++ b/tests/test_verification.py @@ -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