Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(ci): reject incomplete OSV scans (#7318)

LearningCircuit0134d7b24bbb
diff --git a/.github/scripts/run_osv_scan.py b/.github/scripts/run_osv_scan.py
new file mode 100644
index 0000000000..6aff5a6579
--- /dev/null
+++ b/.github/scripts/run_osv_scan.py
@@ -0,0 +1,151 @@
+#!/usr/bin/env python3
+"""Publish OSV evidence only after a complete native scanner invocation.
+
+The action's entrypoint maps exit 128 (no package sources) to success, and a
+recursive extraction error can leave a nonempty partial report. Neither is
+valid evidence for this repository, which always has dependency lockfiles.
+Run the hash-verified binary directly, accepting only its documented 0/1
+statuses with no error-level diagnostics. OSV prioritizes exit 1 over logged
+extraction errors when both occur. A completed vulnerable scan still fails
+the job, but its validated findings are uploaded.
+"""
+
+import argparse
+import json
+import os
+from pathlib import Path
+import secrets
+import shutil
+import subprocess
+import sys
+import tempfile
+
+
+class ScanError(ValueError):
+ """The scanner did not produce complete, usable evidence."""
+
+
+def validate_report(path: Path, exit_code: int) -> int:
+ """Check the native SARIF envelope and preserve clean empty results."""
+ try:
+ report = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, UnicodeError, ValueError) as exc:
+ raise ScanError(
+ "OSV-Scanner did not write a readable SARIF report"
+ ) from exc
+ if not isinstance(report, dict) or report.get("version") != "2.1.0":
+ raise ScanError("OSV-Scanner wrote an invalid SARIF envelope")
+ runs = report.get("runs")
+ if not isinstance(runs, list) or not runs:
+ raise ScanError("OSV-Scanner wrote no SARIF runs")
+ findings = 0
+ for run in runs:
+ if not isinstance(run, dict):
+ raise ScanError("OSV-Scanner wrote an invalid SARIF run")
+ tool = run.get("tool")
+ driver = tool.get("driver") if isinstance(tool, dict) else None
+ if not isinstance(driver, dict) or driver.get("name") != "osv-scanner":
+ raise ScanError("SARIF does not identify the OSV scanner")
+ results = run.get("results")
+ if not isinstance(results, list):
+ raise ScanError("OSV-Scanner wrote invalid SARIF results")
+ for result in results:
+ message = (
+ result.get("message") if isinstance(result, dict) else None
+ )
+ if (
+ not isinstance(message, dict)
+ or not isinstance(message.get("text"), str)
+ or not isinstance(result.get("ruleId"), str)
+ or not result["ruleId"]
+ ):
+ raise ScanError("OSV-Scanner wrote an invalid SARIF finding")
+ invocations = run.get("invocations", [])
+ if not isinstance(invocations, list) or any(
+ not isinstance(invocation, dict)
+ or invocation.get("executionSuccessful") is False
+ for invocation in invocations
+ ):
+ raise ScanError("SARIF records an unsuccessful scanner invocation")
+ findings += len(results)
+ if exit_code == 1 and not findings:
+ raise ScanError("OSV-Scanner reported vulnerabilities without findings")
+ return findings
+
+
+def scan(scanner: Path, root: Path, output: Path) -> int:
+ # An earlier invocation or a checked-in file must never qualify this scan.
+ output.unlink(missing_ok=True)
+ with tempfile.TemporaryDirectory(
+ prefix=".osv-scan-", dir=output.parent
+ ) as tmp:
+ pending = Path(tmp) / "results.sarif"
+ command = [
+ str(scanner),
+ "scan",
+ "source",
+ "--format=sarif",
+ "--verbosity=error",
+ f"--output-file={pending}",
+ "-r",
+ "./",
+ ]
+ # Scanner logs include repository-controlled package names and paths.
+ token = secrets.token_hex(16)
+ print(f"::stop-commands::{token}", flush=True)
+ with tempfile.TemporaryFile(
+ mode="w+", encoding="utf-8", errors="replace"
+ ) as diagnostics:
+ try:
+ completed = subprocess.run(
+ command,
+ cwd=root,
+ timeout=600,
+ check=False,
+ stdout=diagnostics,
+ stderr=subprocess.STDOUT,
+ )
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ raise ScanError(
+ "OSV-Scanner could not complete its invocation"
+ ) from exc
+ finally:
+ has_errors = bool(diagnostics.seek(0, os.SEEK_END))
+ diagnostics.seek(0)
+ shutil.copyfileobj(diagnostics, sys.stdout)
+ print(f"\n::{token}::", flush=True)
+ if completed.returncode not in (0, 1):
+ raise ScanError(
+ f"OSV-Scanner exited {completed.returncode}; refusing partial evidence"
+ )
+ if has_errors:
+ raise ScanError(
+ "OSV-Scanner logged errors; refusing partial evidence"
+ )
+ findings = validate_report(pending, completed.returncode)
+ pending.replace(output)
+ github_output = os.environ.get("GITHUB_OUTPUT")
+ if github_output:
+ with open(github_output, "a", encoding="utf-8") as stream:
+ stream.write("scan_complete=true\n")
+ print(f"OSV scan completed: {findings} SARIF findings", flush=True)
+ return completed.returncode
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--scanner", type=Path, required=True)
+ parser.add_argument("--root", type=Path, default=Path.cwd())
+ parser.add_argument("--output", type=Path, default=Path("results.sarif"))
+ args = parser.parse_args()
+ try:
+ return scan(
+ args.scanner.resolve(), args.root.resolve(), args.output.absolute()
+ )
+ except (OSError, ScanError) as exc:
+ print(f"::error::{exc}", flush=True)
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/.github/workflows/ci-policy-tests.yml b/.github/workflows/ci-policy-tests.yml
index 8de82be073..47d8097df5 100644
--- a/.github/workflows/ci-policy-tests.yml
+++ b/.github/workflows/ci-policy-tests.yml
@@ -6,9 +6,11 @@ on:
- ".github/workflows/**"
- ".github/scripts/check_release_scan_evidence.py"
- ".github/scripts/retire_json_to_sarif.py"
+ - ".github/scripts/run_osv_scan.py"
- ".github/release-scan-policy.json"
- "tests/ci/standalone/test_release_scan_*.py"
- "tests/ci/standalone/test_pytest_scheduling.py"
+ - "tests/ci/standalone/test_osv_scan.py"
workflow_dispatch:
permissions:
@@ -35,3 +37,5 @@ jobs:
run: python -m unittest discover -s tests/ci/standalone -p 'test_release_scan*.py' -v
- name: Test pytest scheduling and required-check behavior
run: python -m unittest discover -s tests/ci/standalone -p 'test_pytest_scheduling.py' -v
+ - name: Test OSV scan completion and reporting
+ run: python -m unittest discover -s tests/ci/standalone -p 'test_osv_scan.py' -v
diff --git a/.github/workflows/osv-scan-reusable.yml b/.github/workflows/osv-scan-reusable.yml
new file mode 100644
index 0000000000..0adee4a85d
--- /dev/null
+++ b/.github/workflows/osv-scan-reusable.yml
@@ -0,0 +1,71 @@
+# Keep the native scanner exit status: its Docker action rewrites exit 128,
+# and the upstream reporter accepts partial or missing scan results.
+name: OSV complete dependency scan
+
+on:
+ workflow_call:
+ inputs:
+ ref:
+ description: Exact commit to scan
+ type: string
+ default: ''
+
+permissions: {}
+
+jobs:
+ # Preserve the existing required "scan / osv-scan" check and the default
+ # caller-dependent SARIF category. Category alignment is tracked in #7220.
+ osv-scan:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ permissions:
+ contents: read
+ actions: read
+ security-events: write
+ steps:
+ - name: Harden the runner
+ uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1
+ with:
+ egress-policy: audit
+
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ ref: ${{ inputs.ref || github.sha }}
+
+ - name: Install verified OSV-Scanner
+ env:
+ OSV_VERSION: '2.6.0'
+ # Official v2.6.0 osv-scanner_SHA256SUMS, Linux amd64 binary.
+ OSV_SHA256: ca69b3d3cd08f889a49dc0a383122f71cc528b83803671df5fd874d97485b108
+ run: |
+ curl --fail --silent --show-error --location --retry 3 --proto '=https' \
+ --output "$RUNNER_TEMP/osv-scanner" \
+ "https://github.com/google/osv-scanner/releases/download/v${OSV_VERSION}/osv-scanner_linux_amd64"
+ printf '%s %s\n' "$OSV_SHA256" "$RUNNER_TEMP/osv-scanner" | sha256sum --check --strict
+ chmod +x "$RUNNER_TEMP/osv-scanner"
+
+ - name: Scan and validate completion
+ id: scan
+ env:
+ GOTOOLCHAIN: auto
+ run: |
+ python3 .github/scripts/run_osv_scan.py \
+ --scanner "$RUNNER_TEMP/osv-scanner" --output results.sarif
+
+ # Completed vulnerable scans exit 1 and fail the job, while their findings
+ # remain uploadable. Failed/partial scans never set scan_complete.
+ - name: Upload artifact
+ if: ${{ !cancelled() && steps.scan.outputs.scan_complete == 'true' }}
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: OSV Scanner SARIF file
+ path: results.sarif
+ if-no-files-found: error
+ retention-days: 5
+
+ - name: Upload to code-scanning
+ if: ${{ !cancelled() && steps.scan.outputs.scan_complete == 'true' }}
+ uses: github/codeql-action/upload-sarif@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
+ with:
+ sarif_file: results.sarif
diff --git a/.github/workflows/osv-scanner-scheduled.yml b/.github/workflows/osv-scanner-scheduled.yml
index 5db0fac744..0c7003b370 100644
--- a/.github/workflows/osv-scanner-scheduled.yml
+++ b/.github/workflows/osv-scanner-scheduled.yml
@@ -27,8 +27,6 @@ jobs:
security-events: write
contents: read
actions: read
- uses: "google/osv-scanner-action/.github/workflows/osv-scanner-reusable.yml@a345acffa64b0eaede81a3d9aae6141214d9c8fc" # v2.6.0
+ uses: $/.github/workflows/osv-scan-reusable.yml
with:
- scan-args: |-
- -r
- ./
+ ref: ${{ github.sha }}
diff --git a/.github/workflows/osv-scanner.yml b/.github/workflows/osv-scanner.yml
index c988363ac4..652c3bddc5 100644
--- a/.github/workflows/osv-scanner.yml
+++ b/.github/workflows/osv-scanner.yml
@@ -37,9 +37,6 @@ jobs:
security-events: write
contents: read
actions: read
- uses: "google/osv-scanner-action/.github/workflows/osv-scanner-reusable.yml@a345acffa64b0eaede81a3d9aae6141214d9c8fc" # v2.6.0
+ uses: $/.github/workflows/osv-scan-reusable.yml
with:
ref: ${{ github.sha }}
- scan-args: |-
- -r
- ./
diff --git a/changelog.d/+osv-scan-completeness.bugfix.md b/changelog.d/+osv-scan-completeness.bugfix.md
new file mode 100644
index 0000000000..821d23a006
--- /dev/null
+++ b/changelog.d/+osv-scan-completeness.bugfix.md
@@ -0,0 +1 @@
+Dependency scanning now rejects incomplete scans and invalid reports before uploading Code Scanning evidence, while preserving completed vulnerability findings and their failing CI status.
diff --git a/docs/ci/workflow-status.md b/docs/ci/workflow-status.md
index e459cd42dc..594047d2ce 100644
--- a/docs/ci/workflow-status.md
+++ b/docs/ci/workflow-status.md
@@ -185,3 +185,8 @@ the table above.
tests on Python 3.12 and 3.14; PR to main, push:main, manual.
Path-filtered to database/settings sources, config paths, locked
dependencies, the native test modules, runner, and workflow.
+
+- `osv-scan-reusable.yml` — shared `workflow_call` scanner used by
+ `osv-scanner.yml` and `osv-scanner-scheduled.yml`. Verifies the native
+ scanner binary and complete scan results before artifact and SARIF uploads.
+ Its status is reported in the calling workflows.
diff --git a/tests/ci/standalone/test_osv_scan.py b/tests/ci/standalone/test_osv_scan.py
new file mode 100644
index 0000000000..fe9186029e
--- /dev/null
+++ b/tests/ci/standalone/test_osv_scan.py
@@ -0,0 +1,320 @@
+"""Exercise OSV's exit/report boundary without network or application imports."""
+
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import sys
+import tempfile
+import unittest
+
+
+ROOT = Path(__file__).resolve().parents[3]
+SCRIPT = ROOT / ".github/scripts/run_osv_scan.py"
+WORKFLOW = ROOT / ".github/workflows/osv-scan-reusable.yml"
+
+
+def report(findings=False):
+ return {
+ "version": "2.1.0",
+ "runs": [
+ {
+ "tool": {"driver": {"name": "osv-scanner", "version": "2.6.0"}},
+ "results": (
+ [
+ {
+ "ruleId": "TEST-OSV-1",
+ "message": {"text": "Test finding"},
+ }
+ ]
+ if findings
+ else []
+ ),
+ }
+ ],
+ }
+
+
+def run_block(name):
+ """Read a workflow step's real shell script, including all its lines."""
+ text = WORKFLOW.read_text(encoding="utf-8")
+ step = text.split(f" - name: {name}\n", 1)[1].split("\n - ", 1)[0]
+ lines = step.split(" run: |\n", 1)[1].splitlines()
+ script = []
+ for line in lines:
+ if line.strip() and not line.startswith(" "):
+ break
+ script.append(line[10:])
+ return "\n".join(script) + "\n"
+
+
+class ScanBoundaryTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory(prefix="osv test ")
+ self.addCleanup(self.temp.cleanup)
+ self.directory = Path(self.temp.name)
+ self.root = self.directory / "repository with spaces"
+ self.root.mkdir()
+ self.scanner = self.directory / "osv-scanner"
+ self.scanner.write_text(
+ f"#!{sys.executable}\n"
+ "import json, os, pathlib, sys\n"
+ "pathlib.Path(os.environ['FAKE_ARGS']).write_text(json.dumps(\n"
+ " {'args': sys.argv[1:], 'cwd': os.getcwd()}))\n"
+ "out = next(x.split('=', 1)[1] for x in sys.argv if x.startswith('--output-file='))\n"
+ "if os.environ['FAKE_WRITE'] == '1':\n"
+ " pathlib.Path(out).write_text(os.environ['FAKE_REPORT'])\n"
+ "if os.environ.get('FAKE_LOG'):\n"
+ " print(os.environ['FAKE_LOG'], flush=True)\n"
+ "sys.exit(int(os.environ['FAKE_EXIT']))\n",
+ encoding="utf-8",
+ )
+ self.scanner.chmod(0o700)
+ self.output = self.directory / "results.sarif"
+ self.github_output = self.directory / "github-output"
+ self.args = self.directory / "scanner-args.json"
+
+ def invoke(
+ self, status=0, payload=None, write=True, workflow=False, log=""
+ ):
+ self.github_output.unlink(missing_ok=True)
+ env = dict(
+ os.environ,
+ GITHUB_OUTPUT=str(self.github_output),
+ FAKE_ARGS=str(self.args),
+ FAKE_EXIT=str(status),
+ FAKE_REPORT=json.dumps(report()) if payload is None else payload,
+ FAKE_WRITE="1" if write else "0",
+ FAKE_LOG=log,
+ RUNNER_TEMP=str(self.directory),
+ )
+ if workflow:
+ scripts = self.root / ".github/scripts"
+ scripts.mkdir(parents=True, exist_ok=True)
+ (scripts / "run_osv_scan.py").write_bytes(SCRIPT.read_bytes())
+ self.output = self.root / "results.sarif"
+ command = [
+ "bash",
+ "-e",
+ "-o",
+ "pipefail",
+ "-c",
+ run_block("Scan and validate completion"),
+ ]
+ else:
+ command = [
+ sys.executable,
+ str(SCRIPT),
+ "--scanner",
+ str(self.scanner),
+ "--root",
+ str(self.root),
+ "--output",
+ str(self.output),
+ ]
+ result = subprocess.run(
+ command,
+ cwd=self.root,
+ env=env,
+ text=True,
+ capture_output=True,
+ timeout=10,
+ check=False,
+ )
+ flags = (
+ self.github_output.read_text()
+ if self.github_output.exists()
+ else ""
+ )
+ return result, flags
+
+ def assert_rejected(self, status=0, payload=None, write=True, log=""):
+ # A report from an earlier invocation must not be uploaded on failure.
+ self.output.write_text(json.dumps(report(findings=True)))
+ result, flags = self.invoke(status, payload, write, log=log)
+ self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr)
+ self.assertNotIn("scan_complete=true", flags)
+ self.assertFalse(self.output.exists())
+
+ def test_clean_scan_publishes_fresh_empty_results(self):
+ self.output.write_text(json.dumps(report(findings=True)))
+ result, flags = self.invoke()
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ self.assertEqual(flags, "scan_complete=true\n")
+ self.assertEqual(json.loads(self.output.read_text()), report())
+ args = json.loads(self.args.read_text())
+ self.assertEqual(args["cwd"], str(self.root))
+ self.assertEqual(args["args"][:3], ["scan", "source", "--format=sarif"])
+ self.assertEqual(args["args"][3], "--verbosity=error")
+ self.assertTrue(args["args"][4].startswith("--output-file="))
+ self.assertEqual(args["args"][5:], ["-r", "./"])
+
+ def test_vulnerabilities_fail_but_preserve_uploadable_findings(self):
+ expected = json.dumps(report(findings=True))
+ result, flags = self.invoke(1, expected)
+ self.assertEqual(result.returncode, 1)
+ self.assertEqual(flags, "scan_complete=true\n")
+ self.assertEqual(self.output.read_text(), expected)
+
+ def test_partial_report_is_rejected_for_every_error_status(self):
+ for status in [2, 124, 127, 128, 137, 255]:
+ with self.subTest(status=status):
+ self.assert_rejected(status, json.dumps(report()))
+
+ def test_missing_report_is_rejected_even_after_success(self):
+ self.assert_rejected(write=False)
+
+ def test_vulnerability_exit_requires_findings(self):
+ self.assert_rejected(1, json.dumps(report()))
+
+ def test_error_diagnostics_reject_both_clean_and_vulnerable_reports(self):
+ # OSV 2.6.0 returns 1 before checking HasErrored when it has findings.
+ # The SARIF is still partial and must not resolve unrelated old alerts.
+ for status in [0, 1]:
+ with self.subTest(status=status):
+ self.assert_rejected(
+ status,
+ json.dumps(report(findings=status == 1)),
+ log="Error during extraction: unreadable dependency file",
+ )
+
+ def test_invalid_reports_are_rejected(self):
+ invalid = [
+ "",
+ " ",
+ "{",
+ "{}",
+ "null",
+ "[]",
+ '{"version":"2.1.0","runs":[]}',
+ ]
+ for payload in invalid:
+ with self.subTest(payload=payload):
+ self.assert_rejected(payload=payload)
+
+ def test_invalid_run_or_tool_or_result_is_rejected(self):
+ cases = []
+ for key, value in [
+ ("tool", {}),
+ ("results", None),
+ ("results", [None]),
+ ("results", [{}]),
+ ("invocations", [{"executionSuccessful": False}]),
+ ]:
+ item = report()
+ item["runs"][0][key] = value
+ cases.append(item)
+ item = report()
+ item["runs"] = [None]
+ cases.append(item)
+ item = report()
+ item["runs"][0]["tool"]["driver"]["name"] = "another-scanner"
+ cases.append(item)
+ for item in cases:
+ with self.subTest(item=item):
+ self.assert_rejected(payload=json.dumps(item))
+
+ def test_cannot_launch_scanner(self):
+ self.scanner.unlink()
+ self.assert_rejected()
+
+ def test_repository_output_cannot_become_workflow_commands(self):
+ result, _ = self.invoke(
+ log="::error::repository-controlled scanner output"
+ )
+ match = re.search(r"::stop-commands::([0-9a-f]{32})\n", result.stdout)
+ self.assertIsNotNone(match)
+ start = match.end()
+ end = result.stdout.index(f"::{match.group(1)}::", start)
+ self.assertIn(
+ "::error::repository-controlled", result.stdout[start:end]
+ )
+
+ def test_real_workflow_scan_step_preserves_all_three_outcomes(self):
+ for status, findings, accepted in [
+ (0, False, True),
+ (1, True, True),
+ (127, False, False),
+ (128, False, False),
+ ]:
+ with self.subTest(status=status):
+ result, flags = self.invoke(
+ status, json.dumps(report(findings)), workflow=True
+ )
+ self.assertEqual(result.returncode == 0, status == 0)
+ self.assertEqual("scan_complete=true" in flags, accepted)
+ self.assertEqual(self.output.exists(), accepted)
+
+
+class WorkflowTests(unittest.TestCase):
+ def test_checksum_mismatch_never_makes_download_executable(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ fake_bin = root / "bin"
+ fake_bin.mkdir()
+ curl = fake_bin / "curl"
+ curl.write_text(
+ f"#!{sys.executable}\n"
+ "import pathlib, sys\n"
+ "pathlib.Path(sys.argv[sys.argv.index('--output') + 1]).write_bytes(b'test binary')\n"
+ )
+ curl.chmod(0o700)
+ for digest, good in [
+ ("0" * 64, False),
+ (hashlib.sha256(b"test binary").hexdigest(), True),
+ ]:
+ with self.subTest(valid_hash=good):
+ target = root / "osv-scanner"
+ target.unlink(missing_ok=True)
+ env = dict(
+ os.environ,
+ PATH=str(fake_bin) + os.pathsep + os.environ["PATH"],
+ RUNNER_TEMP=directory,
+ OSV_VERSION="2.6.0",
+ OSV_SHA256=digest,
+ )
+ result = subprocess.run(
+ [
+ "bash",
+ "-e",
+ "-o",
+ "pipefail",
+ "-c",
+ run_block("Install verified OSV-Scanner"),
+ ],
+ env=env,
+ text=True,
+ capture_output=True,
+ check=False,
+ timeout=10,
+ )
+ self.assertEqual(result.returncode == 0, good)
+ self.assertEqual(os.access(target, os.X_OK), good)
+
+ def test_uploads_require_complete_evidence_and_failure_is_not_masked(self):
+ text = WORKFLOW.read_text()
+ self.assertNotIn("continue-on-error", text)
+ self.assertNotIn("|| true", text)
+ self.assertEqual(
+ text.count("steps.scan.outputs.scan_complete == 'true'"), 2
+ )
+ for name in ["Upload artifact", "Upload to code-scanning"]:
+ step = text.split(f" - name: {name}\n", 1)[1].split(
+ "\n - ", 1
+ )[0]
+ self.assertIn(
+ "!cancelled() && steps.scan.outputs.scan_complete == 'true'",
+ step,
+ )
+ self.assertIn("if-no-files-found: error", text)
+ self.assertIn(" osv-scan:\n", text)
+ self.assertIn(
+ "uses: $/.github/workflows/osv-scan-reusable.yml",
+ (ROOT / ".github/workflows/osv-scanner.yml").read_text(),
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/ci/standalone/test_release_scan_evidence.py b/tests/ci/standalone/test_release_scan_evidence.py
index a0a2d239cb..4bb2f05b5c 100644
--- a/tests/ci/standalone/test_release_scan_evidence.py
+++ b/tests/ci/standalone/test_release_scan_evidence.py
@@ -56,7 +56,7 @@ def alert(**changes):
# suite runs in ci-policy-tests.yml on a bare `actions/setup-python` with no
# dependency install step, so a `yaml` import here would break that job.
_JOB_ID_RE = re.compile(r"^ ([A-Za-z0-9_-]+):\s*$")
-_LOCAL_USES_RE = re.compile(r"^\s+uses:\s*(\$/\S+|\./\S+)\s*$")
+_LOCAL_USES_RE = re.compile(r"^ uses:\s*(\$/\S+|\./\S+)\s*$")
_UPLOAD_MARKERS = ("upload-sarif", "codeql-action/analyze")
_CATEGORY_RE = re.compile(r"^\s*category:\s*(.+?)\s*(#.*)?$")
@@ -87,6 +87,15 @@ _REMOTE_REUSABLE_SARIF_UPLOADERS = {
),
}
+# The local OSV workflow preserves the same terminal job id and implicit
+# category as its former upstream reusable workflow. Do not generalize this
+# exception to other uploads: #7220 tracks the caller/category alignment.
+_LOCAL_DEFAULT_SARIF_UPLOADERS = {
+ (".github/workflows/osv-scan-reusable.yml", "osv-scan"): (
+ "{workflow}:osv-scan"
+ ),
+}
+
# Categories the gate uploads but release-scan-policy.json deliberately does
# not require, each with the reason.
_UPLOADED_BUT_NOT_IN_POLICY = {
@@ -134,7 +143,11 @@ def _sarif_categories_in(text, source="workflow"):
"""
lines = text.splitlines()
found = []
+ current_job = None
for i, line in enumerate(lines):
+ job_match = _JOB_ID_RE.match(line)
+ if job_match:
+ current_job = job_match.group(1)
remote = _REMOTE_REUSABLE_RE.match(line)
if remote:
found.append(
@@ -159,7 +172,12 @@ def _sarif_categories_in(text, source="workflow"):
else:
match = None
if not match:
- found.append(f"<uncategorized upload in {source} line {i + 1}>")
+ found.append(
+ _LOCAL_DEFAULT_SARIF_UPLOADERS.get(
+ (source, current_job),
+ f"<uncategorized upload in {source} line {i + 1}>",
+ )
+ )
return found
@@ -188,8 +206,15 @@ def _release_gate_sarif_categories():
encoding="utf-8"
)
categories = set()
- for job_id, rel_path in _local_reusable_workflow_jobs(gate_text).items():
+ pending = list(_local_reusable_workflow_jobs(gate_text).items())
+ visited = set()
+ while pending:
+ job_id, rel_path = pending.pop()
+ if rel_path in visited:
+ continue
+ visited.add(rel_path)
workflow_text = (ROOT / rel_path).read_text(encoding="utf-8")
+ pending.extend(_local_reusable_workflow_jobs(workflow_text).items())
expanded = set()
for raw_category in _sarif_categories_in(workflow_text, rel_path):
expanded.update(
@@ -1047,66 +1072,63 @@ class RetireScanStepTests(unittest.TestCase):
self.assertEqual(len(re.findall(r"\bnpx\s+retire", workflow)), 1)
-# osv-scanner flags vetted against the binary the pinned reusable workflow
-# runs (osv-scanner-action v2.6.0). An unknown flag makes osv-scanner exit
-# 127 ("flag provided but not defined") without writing results.json. Under
-# the v2.5.1 reusable workflow the reporter then printed "No issues found"
-# and the required osv-scan check PASSED without scanning anything; that is
-# how `--skip-git` (not defined in osv-scanner v2) silently disabled the scan.
-# v2.6.0 fails the job when no results were written, but a rejected flag
-# still means no scan, so check any new flag against the pinned version's
-# `osv-scanner scan source --help` before adding it here.
-OSV_SCAN_ARGS_VETTED = frozenset({"-r", "./"})
+# The native invocation and exit/report contracts are exercised by
+# test_osv_scan.py. Both event wrappers must use that guarded implementation.
OSV_SCAN_WORKFLOWS = (
".github/workflows/osv-scanner.yml",
".github/workflows/osv-scanner-scheduled.yml",
)
-def _osv_scan_args(workflow_text):
- """Tokens of every ``scan-args: |-`` block in ``workflow_text``."""
- blocks = []
- lines = workflow_text.splitlines()
- for index, line in enumerate(lines):
- match = re.match(r"^(\s*)scan-args:\s*\|-?\s*$", line)
- if not match:
- continue
- indent = len(match.group(1))
- tokens = []
- for body in lines[index + 1 :]:
- if body.strip() and len(body) - len(body.lstrip()) <= indent:
- break
- tokens.extend(body.split())
- blocks.append(tokens)
- return blocks
-
-
class OsvScanArgsTests(unittest.TestCase):
- def test_osv_scan_args_are_vetted_for_the_pinned_scanner(self):
+ def test_workflow_walk_does_not_treat_local_actions_as_workflows(self):
+ text = (
+ "jobs:\n"
+ " scan:\n"
+ " uses: ./.github/workflows/osv-scan-reusable.yml\n"
+ " other:\n"
+ " steps:\n"
+ " - name: Install\n"
+ " uses: ./.github/actions/install-gitleaks\n"
+ )
+ self.assertEqual(
+ _local_reusable_workflow_jobs(text),
+ {"scan": ".github/workflows/osv-scan-reusable.yml"},
+ )
+
+ def test_both_callers_use_the_complete_scan_workflow(self):
for rel_path in OSV_SCAN_WORKFLOWS:
with self.subTest(workflow=rel_path):
text = (ROOT / rel_path).read_text(encoding="utf-8")
- self.assertIn("osv-scanner-reusable.yml@", text)
- blocks = _osv_scan_args(text)
- self.assertEqual(len(blocks), 1, blocks)
- self.assertTrue(blocks[0], "empty osv scan-args")
- unvetted = set(blocks[0]) - OSV_SCAN_ARGS_VETTED
- self.assertFalse(
- unvetted,
- f"{rel_path} passes osv-scanner flags not vetted for "
- f"the pinned version: {sorted(unvetted)}",
+ self.assertEqual(
+ list(_local_reusable_workflow_jobs(text).values()),
+ [".github/workflows/osv-scan-reusable.yml"],
)
+ self.assertNotIn("scan-args:", text)
+ self.assertIn("ref: ${{ github.sha }}", text)
- def test_scan_args_parser_reads_the_whole_block(self):
+ def test_default_category_is_limited_to_the_known_osv_job(self):
text = (
- " with:\n"
- " scan-args: |-\n"
- " -r\n"
- " --skip-git\n"
- " ./\n"
- " other: value\n"
+ "jobs:\n"
+ " osv-scan:\n"
+ " steps:\n"
+ " - uses: github/codeql-action/upload-sarif@abc\n"
+ " with:\n"
+ " sarif_file: results.sarif\n"
+ )
+ source = ".github/workflows/osv-scan-reusable.yml"
+ self.assertEqual(
+ _sarif_categories_in(text, source), ["{workflow}:osv-scan"]
+ )
+ self.assertIn(
+ "<uncategorized", _sarif_categories_in(text, "other.yml")[0]
+ )
+ self.assertIn(
+ "<uncategorized",
+ _sarif_categories_in(text.replace("osv-scan:", "other:"), source)[
+ 0
+ ],
)
- self.assertEqual(_osv_scan_args(text), [["-r", "--skip-git", "./"]])
if __name__ == "__main__":