~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
ci: verify Checkov analyses and retry processing errors once (#8003)
LearningCircuit641d48a444ba
diff --git a/.github/scripts/check_checkov_upload.py b/.github/scripts/check_checkov_upload.pynew file mode 100644index 0000000000..a24e7fd7bb--- /dev/null+++ b/.github/scripts/check_checkov_upload.py@@ -0,0 +1,187 @@+"""Verify Checkov's uploaded analysis, including after a bounded re-upload.++A completed SARIF upload can still produce an analysis with ``Unknown Error``.+Only that processing error may request one re-upload by the workflow; missing,+malformed, mismatched, and persistently failed evidence remains a failure.+"""++import argparse+import json+import os+import re+import subprocess+import sys+import time+from pathlib import Path+from urllib.parse import urlencode+from uuid import UUID+++class VerificationError(ValueError):+ """An error with a fixed, credential-free diagnostic."""+++def api(endpoint):+ response = subprocess.run(+ [+ "gh",+ "api",+ "--method",+ "GET",+ "-H",+ "Accept: application/vnd.github+json",+ "-H",+ "X-GitHub-Api-Version: 2022-11-28",+ endpoint,+ ],+ capture_output=True,+ text=True,+ check=True,+ timeout=30,+ )+ return json.loads(response.stdout)+++def check_upload(+ upload_id,+ repository,+ sha,+ ref,+ analysis_key,+ *,+ fetch=api,+ sleep=time.sleep,+ monotonic=time.monotonic,+):+ """Return whether this exact upload needs the workflow's single retry."""+ try:+ canonical_id = str(UUID(upload_id))+ except (ValueError, AttributeError, TypeError) as error:+ raise VerificationError("missing or invalid SARIF upload ID") from error+ if canonical_id != upload_id:+ raise VerificationError("non-canonical SARIF upload ID")+ if not re.fullmatch(r"[\w.-]+/[\w.-]+", repository, flags=re.ASCII) or any(+ part in {".", ".."} for part in repository.split("/")+ ):+ raise VerificationError("invalid repository context")+ if not re.fullmatch(r"[0-9a-f]{40}", sha) or not ref.startswith("refs/"):+ raise VerificationError("invalid commit or ref context")++ root = f"repos/{repository}/code-scanning"+ deadline = monotonic() + 90+ while True:+ status = fetch(f"{root}/sarifs/{upload_id}")+ state = (+ status.get("processing_status")+ if isinstance(status, dict)+ else None+ )+ if not isinstance(state, str) or state not in {+ "pending",+ "complete",+ "failed",+ }:+ raise VerificationError("invalid SARIF processing status")+ if status.get("errors") not in (None, []):+ raise VerificationError("SARIF upload reported processing errors")+ if status["processing_status"] == "failed":+ raise VerificationError("SARIF processing failed")+ if status["processing_status"] == "complete":+ records = fetch(+ f"{root}/analyses?"+ + urlencode({"sarif_id": upload_id, "per_page": 100})+ )+ if not isinstance(records, list) or len(records) > 1:+ raise VerificationError("expected one Checkov analysis")+ if records:+ row = records[0]+ if not isinstance(row, dict) or any(+ row.get(key) != value+ for key, value in {+ "sarif_id": upload_id,+ "commit_sha": sha,+ "ref": ref,+ "analysis_key": analysis_key,+ "category": "checkov-workflows",+ }.items()+ ):+ raise VerificationError(+ "analysis does not match this upload and job"+ )+ tool = row.get("tool")+ if (+ not isinstance(tool, dict)+ or str(tool.get("name")).lower() != "checkov"+ ):+ raise VerificationError("unexpected analysis tool")+ if (+ type(row.get("results_count")) is not int+ or row["results_count"] < 0+ ):+ raise VerificationError("invalid analysis result count")+ if row.get("error") == "Unknown Error":+ return True+ if row.get("error") != "":+ raise VerificationError(+ "analysis failed or has no error status"+ )+ return False+ if monotonic() >= deadline:+ raise VerificationError("timed out waiting for Checkov analysis")+ sleep(5)+++def verify(allow_retry):+ repository = os.environ["GITHUB_REPOSITORY"]+ workflow_ref = os.environ["GITHUB_WORKFLOW_REF"]+ prefix = repository + "/"+ if not workflow_ref.startswith(prefix) or "@" not in workflow_ref:+ raise VerificationError("invalid workflow context")+ workflow = workflow_ref[len(prefix) :].split("@", 1)[0]+ if not re.fullmatch(r"\.github/workflows/[\w.-]+\.ya?ml", workflow):+ raise VerificationError("invalid workflow path")+ if os.environ["GITHUB_JOB"] != "checkov":+ raise VerificationError("unexpected job context")+ retry = check_upload(+ os.environ["SARIF_ID"],+ repository,+ os.environ["GITHUB_SHA"],+ os.environ["GITHUB_REF"],+ f"{workflow}:checkov",+ )+ if retry and not allow_retry:+ raise VerificationError(+ "Checkov analysis still reports Unknown Error after retry"+ )+ if allow_retry:+ with Path(os.environ["GITHUB_OUTPUT"]).open(+ "a", encoding="utf-8"+ ) as output:+ output.write(f"retry={str(retry).lower()}\n")+ print(+ "Checkov analysis needs one re-upload after a processing error."+ if retry+ else "Checkov analysis verified for this upload and commit."+ )+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--allow-retry", action="store_true")+ args = parser.parse_args()+ try:+ verify(args.allow_retry)+ return 0+ except VerificationError as error:+ print(f"Checkov upload verification failed: {error}", file=sys.stderr)+ except (KeyError, OSError, ValueError, subprocess.SubprocessError):+ # API output and diagnostics can contain credentials; do not echo them.+ print(+ "Checkov upload verification failed: API or context unavailable",+ file=sys.stderr,+ )+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/.github/workflows/checkov-scan.yml b/.github/workflows/checkov-scan.ymlnew file mode 100644index 0000000000..3985d2bf96--- /dev/null+++ b/.github/workflows/checkov-scan.yml@@ -0,0 +1,137 @@+name: Checkov scan and upload++on:+ workflow_call:+ inputs:+ allow-analysis-retry:+ description: Allow the caller to retry one failed analysis in a fresh job+ type: boolean+ default: false+ outputs:+ retry:+ description: The workflow analysis needs one new scan and upload+ value: ${{ jobs.checkov.outputs.retry }}++permissions: {} # Minimal top-level for OSSF Scorecard Token-Permissions++jobs:+ checkov:+ runs-on: ubuntu-latest+ timeout-minutes: 10+ outputs:+ retry: ${{ steps.workflow-analysis.outputs.retry }}+ permissions:+ contents: read+ security-events: write++ steps:+ - name: Harden the runner (Audit all outbound calls)+ uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2+ with:+ egress-policy: audit++ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false++ - name: Set up Python+ uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0+ with:+ python-version: '3.12'++ - name: Install Checkov+ run: pip install checkov==3.2.499++ # Reverted to CLI approach due to known bug in bridgecrewio/checkov-action+ # when running multiple consecutive action calls (heredoc delimiter overflow)+ # See: https://github.com/bridgecrewio/checkov-action/issues/170+ # See: https://github.com/bridgecrewio/checkov/issues/5866+ - name: Run Checkov on Dockerfile+ run: |+ checkov -f Dockerfile \+ --framework dockerfile \+ --skip-check CKV_DOCKER_3 \+ -o cli -o sarif \+ --output-file-path console,checkov-docker.sarif++ - name: Run Checkov on docker-compose files+ run: |+ checkov \+ -f docker-compose.yml \+ -f docker-compose.gpu.override.yml \+ -f docker-compose.tts.yml \+ -f docker-compose.unraid.yml \+ --framework yaml \+ -o cli -o sarif \+ --output-file-path console,checkov-compose.sarif++ # Checkov 3.2.499's workflow schema rejects `concurrency.queue` and+ # silently skips any workflow that fails it, so release-gate.yml would go+ # unscanned. Blank the key in this CI checkout only (line numbers are+ # preserved) so the queue key no longer causes a skip. Checkov still+ # skips workflows that fail its schema for other reasons (for example+ # release.yml's `attestations` key and an expression in docker-tests.yml's+ # `cancel-in-progress`).+ - name: Blank concurrency.queue for Checkov+ run: python3 .github/scripts/strip-concurrency-queue.py .github/workflows/*.yml++ - name: Run Checkov on GitHub Actions workflows+ run: |+ checkov -d .github/workflows \+ --framework github_actions \+ --skip-check CKV_GHA_7 \+ -o cli -o sarif \+ --output-file-path console,checkov-workflows.sarif++ - name: Check SARIF files exist+ id: check-sarif+ if: always()+ run: |+ [ -f checkov-docker.sarif ] && echo "docker=true" >> "$GITHUB_OUTPUT"+ [ -f checkov-compose.sarif ] && echo "compose=true" >> "$GITHUB_OUTPUT"+ [ -f checkov-workflows.sarif ] && echo "workflows=true" >> "$GITHUB_OUTPUT"++ - name: Upload Dockerfile SARIF results+ if: always() && steps.check-sarif.outputs.docker == 'true'+ uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1+ with:+ sarif_file: checkov-docker.sarif+ category: checkov-dockerfile++ - name: Upload docker-compose SARIF results+ if: always() && steps.check-sarif.outputs.compose == 'true'+ uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1+ with:+ sarif_file: checkov-compose.sarif+ category: checkov-compose++ - name: Upload GitHub Actions SARIF results+ id: upload-workflows+ if: always() && steps.check-sarif.outputs.workflows == 'true'+ uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1+ with:+ sarif_file: checkov-workflows.sarif+ category: checkov-workflows++ # Processing can be marked complete even when the resulting analysis+ # failed. Inspect the exact upload; retry only Unknown Error once.+ - name: Inspect GitHub Actions analysis+ id: workflow-analysis+ if: always() && steps.check-sarif.outputs.workflows == 'true'+ env:+ GH_TOKEN: ${{ github.token }}+ SARIF_ID: ${{ steps.upload-workflows.outputs.sarif-id }}+ ALLOW_ANALYSIS_RETRY: ${{ inputs.allow-analysis-retry }}+ run: |+ if [ "$ALLOW_ANALYSIS_RETRY" = "true" ]; then+ python3 .github/scripts/check_checkov_upload.py --allow-retry+ else+ python3 .github/scripts/check_checkov_upload.py+ fi++ - name: Summary+ if: always()+ run: |+ echo "=== Checkov IaC Security Scan Summary ==="+ echo "SARIF results uploaded to GitHub Security tab"+ echo "Scan completed (strict mode - failures block CI)"diff --git a/.github/workflows/checkov.yml b/.github/workflows/checkov.ymlindex ddf737053f..8a50730bff 100644--- a/.github/workflows/checkov.yml+++ b/.github/workflows/checkov.yml@@ -4,107 +4,25 @@ on:workflow_dispatch:workflow_call: # Called by release-gate.yml-permissions: {} # Minimal top-level for OSSF Scorecard Token-Permissions+permissions: {}jobs:- checkov:- runs-on: ubuntu-latest- timeout-minutes: 10+ scan:+ uses: $/.github/workflows/checkov-scan.ymlpermissions:contents: readsecurity-events: write-- steps:- - name: Harden the runner (Audit all outbound calls)- uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2- with:- egress-policy: audit-- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- with:- persist-credentials: false-- - name: Set up Python- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0- with:- python-version: '3.12'-- - name: Install Checkov- run: pip install checkov==3.2.499-- # Reverted to CLI approach due to known bug in bridgecrewio/checkov-action- # when running multiple consecutive action calls (heredoc delimiter overflow)- # See: https://github.com/bridgecrewio/checkov-action/issues/170- # See: https://github.com/bridgecrewio/checkov/issues/5866- - name: Run Checkov on Dockerfile- run: |- checkov -f Dockerfile \- --framework dockerfile \- --skip-check CKV_DOCKER_3 \- -o cli -o sarif \- --output-file-path console,checkov-docker.sarif-- - name: Run Checkov on docker-compose files- run: |- checkov \- -f docker-compose.yml \- -f docker-compose.gpu.override.yml \- -f docker-compose.tts.yml \- -f docker-compose.unraid.yml \- --framework yaml \- -o cli -o sarif \- --output-file-path console,checkov-compose.sarif-- # Checkov 3.2.499's workflow schema rejects `concurrency.queue` and- # silently skips any workflow that fails it, so release-gate.yml would go- # unscanned. Blank the key in this CI checkout only (line numbers are- # preserved) so the queue key no longer causes a skip. Checkov still- # skips workflows that fail its schema for other reasons (for example- # release.yml's `attestations` key and an expression in docker-tests.yml's- # `cancel-in-progress`).- - name: Blank concurrency.queue for Checkov- run: python3 .github/scripts/strip-concurrency-queue.py .github/workflows/*.yml-- - name: Run Checkov on GitHub Actions workflows- run: |- checkov -d .github/workflows \- --framework github_actions \- --skip-check CKV_GHA_7 \- -o cli -o sarif \- --output-file-path console,checkov-workflows.sarif-- - name: Check SARIF files exist- id: check-sarif- if: always()- run: |- [ -f checkov-docker.sarif ] && echo "docker=true" >> "$GITHUB_OUTPUT"- [ -f checkov-compose.sarif ] && echo "compose=true" >> "$GITHUB_OUTPUT"- [ -f checkov-workflows.sarif ] && echo "workflows=true" >> "$GITHUB_OUTPUT"-- - name: Upload Dockerfile SARIF results- if: always() && steps.check-sarif.outputs.docker == 'true'- uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1- with:- sarif_file: checkov-docker.sarif- category: checkov-dockerfile-- - name: Upload docker-compose SARIF results- if: always() && steps.check-sarif.outputs.compose == 'true'- uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1- with:- sarif_file: checkov-compose.sarif- category: checkov-compose-- - name: Upload GitHub Actions SARIF results- if: always() && steps.check-sarif.outputs.workflows == 'true'- uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1- with:- sarif_file: checkov-workflows.sarif- category: checkov-workflows-- - name: Summary- if: always()- run: |- echo "=== Checkov IaC Security Scan Summary ==="- echo "SARIF results uploaded to GitHub Security tab"- echo "Scan completed (strict mode - failures block CI)"+ with:+ allow-analysis-retry: true++ # The official uploader permits one upload per tool/category per job.+ # A fresh job retains that protection and gives a failed analysis one retry.+ retry:+ needs: scan+ if: needs.scan.result == 'success' && needs.scan.outputs.retry == 'true'+ uses: $/.github/workflows/checkov-scan.yml+ permissions:+ contents: read+ security-events: write+ with:+ allow-analysis-retry: falsediff --git a/.github/workflows/ci-policy-tests.yml b/.github/workflows/ci-policy-tests.ymlindex 10df00f291..fb7d24f04a 100644--- a/.github/workflows/ci-policy-tests.yml+++ b/.github/workflows/ci-policy-tests.yml@@ -6,6 +6,7 @@ on:- ".github/workflows/**"- ".github/actions/request-dependency-ci/**"- ".github/scripts/check_release_scan_evidence.py"+ - ".github/scripts/check_checkov_upload.py"# The release-scan suite loads both release-exception checkers.- ".github/scripts/check_code_scanning_alerts.py"- ".github/scripts/check_release_deadline.py"diff --git a/docs/ci/workflow-status.md b/docs/ci/workflow-status.mdindex 7fadca34fc..dc0578472b 100644--- a/docs/ci/workflow-status.md+++ b/docs/ci/workflow-status.md@@ -57,6 +57,7 @@| `backwards-compatibility.yml` | last 30 days | workflow_call, PR, push:main, release, schedule(0 2 * * 0), manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/backwards-compatibility.yml) || `bandit.yml` | long ago | PR, workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/bandit.yml) || `bearer.yml` | last 30 days | PR, manual, workflow_call, schedule(0 4 * * *) | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/bearer.yml) |+| `checkov-scan.yml` | new | workflow_call | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/checkov-scan.yml) || `checkov.yml` | last 30 days | manual, workflow_call | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/checkov.yml) || `codeql.yml` | last 30 days | push:main, PR, schedule(45 5 * * 0), workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/codeql.yml) || `container-security.yml` | last 30 days | workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/container-security.yml) |diff --git a/tests/ci/standalone/test_release_scan_checkov_upload.py b/tests/ci/standalone/test_release_scan_checkov_upload.pynew file mode 100644index 0000000000..58c9509144--- /dev/null+++ b/tests/ci/standalone/test_release_scan_checkov_upload.py@@ -0,0 +1,359 @@+"""Verify Checkov upload recovery without accepting failed scan evidence."""++import importlib.util+import io+import json+import os+import subprocess+import sys+import tempfile+import unittest+from contextlib import redirect_stderr, redirect_stdout+from pathlib import Path+from unittest.mock import patch+from urllib.parse import parse_qs, urlsplit+++ROOT = Path(__file__).resolve().parents[3]+SCRIPT = ROOT / ".github/scripts/check_checkov_upload.py"+SPEC = importlib.util.spec_from_file_location("check_checkov_upload", SCRIPT)+UPLOAD = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(UPLOAD)++REPOSITORY = "example/project"+SHA = "a" * 40+REF = "refs/heads/main"+KEY = ".github/workflows/release.yml:checkov"+FIRST = "11111111-1111-4111-8111-111111111111"+SECOND = "22222222-2222-4222-8222-222222222222"+++def analysis(upload_id=FIRST, **changes):+ return {+ "sarif_id": upload_id,+ "commit_sha": SHA,+ "ref": REF,+ "analysis_key": KEY,+ "category": "checkov-workflows",+ "tool": {"name": "checkov", "version": "3.2.499"},+ "error": "",+ "results_count": 0,+ **changes,+ }+++class UploadTests(unittest.TestCase):+ def setUp(self):+ self.status = {"processing_status": "complete"}+ self.records = [analysis()]+ self.calls = []+ self.clock = 0++ def fetch(self, endpoint):+ self.calls.append(endpoint)+ path, query = (+ urlsplit(endpoint).path,+ parse_qs(urlsplit(endpoint).query),+ )+ prefix = f"repos/{REPOSITORY}/code-scanning"+ if path == f"{prefix}/sarifs/{FIRST}":+ self.assertFalse(query)+ return self.status+ self.assertEqual(path, f"{prefix}/analyses")+ self.assertEqual(query, {"sarif_id": [FIRST], "per_page": ["100"]})+ return self.records++ def sleep(self, seconds):+ self.clock += seconds++ def check(self, **overrides):+ return UPLOAD.check_upload(+ overrides.get("upload_id", FIRST),+ overrides.get("repository", REPOSITORY),+ overrides.get("sha", SHA),+ overrides.get("ref", REF),+ KEY,+ fetch=self.fetch,+ sleep=self.sleep,+ monotonic=lambda: self.clock,+ )++ def test_successful_analysis_requires_no_retry(self):+ self.assertIs(self.check(), False)+ self.assertEqual(len(self.calls), 2)++ def test_complete_upload_with_unknown_error_requires_retry(self):+ # This is the release failure: the upload endpoint said complete.+ self.records[0]["error"] = "Unknown Error"+ self.assertIs(self.check(), True)++ def test_findings_are_not_mistaken_for_an_ingestion_failure(self):+ self.records[0]["results_count"] = 3+ self.assertIs(self.check(), False)+ self.assertEqual(self.records[0]["results_count"], 3)++ def test_incomplete_upload_waits_for_its_actual_analysis(self):+ self.status = {"processing_status": "pending"}++ def ready(seconds):+ self.clock += seconds+ self.status = {"processing_status": "complete"}++ with patch.object(self, "sleep", ready):+ self.assertIs(self.check(), False)+ self.assertEqual(self.clock, 5)++ def test_missing_analysis_is_polled_but_not_accepted(self):+ self.records = []+ with self.assertRaisesRegex(UPLOAD.VerificationError, "timed out"):+ self.check()+ self.assertEqual(self.clock, 90)++ def test_pending_processing_has_a_deadline(self):+ self.status = {"processing_status": "pending"}+ with self.assertRaisesRegex(UPLOAD.VerificationError, "timed out"):+ self.check()+ self.assertEqual(self.clock, 90)++ def test_failed_or_malformed_status_cannot_request_retry(self):+ for status in (+ None,+ {},+ [],+ {"processing_status": "failed"},+ {"processing_status": "other"},+ {"processing_status": []},+ {"processing_status": {}},+ {"processing_status": "complete", "errors": ["rejected"]},+ ):+ with self.subTest(status=status):+ self.status = status+ with self.assertRaises(UPLOAD.VerificationError):+ self.check()++ def test_wrong_upload_scope_or_missing_error_never_requests_retry(self):+ changes = (+ {"sarif_id": SECOND},+ {"commit_sha": "b" * 40},+ {"ref": "refs/heads/other"},+ {"analysis_key": "other:checkov"},+ {"category": "checkov-compose"},+ {"tool": None},+ {"tool": {"name": "another-tool"}},+ {"error": None},+ {"error": "permission denied"},+ {"results_count": None},+ {"results_count": True},+ {"results_count": -1},+ )+ for change in changes:+ with self.subTest(change=change):+ self.records = [analysis(**change)]+ with self.assertRaises(UPLOAD.VerificationError):+ self.check()+ self.records = [analysis()]+ del self.records[0]["error"]+ with self.assertRaises(UPLOAD.VerificationError):+ self.check()++ def test_unknown_error_does_not_hide_a_scope_mismatch(self):+ self.records = [analysis(error="Unknown Error", sarif_id=SECOND)]+ with self.assertRaises(UPLOAD.VerificationError):+ self.check()++ def test_malformed_or_multiple_analyses_fail(self):+ for records in ({}, None, [None], [analysis(), analysis()]):+ with self.subTest(records=records):+ self.records = records+ with self.assertRaises(UPLOAD.VerificationError):+ self.check()++ def test_invalid_context_is_rejected_before_any_api_call(self):+ for changes in (+ {"upload_id": ""},+ {"upload_id": "../other"},+ {"repository": "../other/project"},+ {"repository": "../project"},+ {"repository": "example/.."},+ {"sha": ""},+ {"ref": "main"},+ ):+ with self.subTest(changes=changes):+ with self.assertRaises(UPLOAD.VerificationError):+ self.check(**changes)+ self.assertEqual(self.calls, [])+++class CommandTests(unittest.TestCase):+ def setUp(self):+ directory = tempfile.TemporaryDirectory()+ self.addCleanup(directory.cleanup)+ self.output = Path(directory.name) / "github-output"+ self.environment = {+ "GITHUB_REPOSITORY": REPOSITORY,+ "GITHUB_SHA": SHA,+ "GITHUB_REF": REF,+ "GITHUB_WORKFLOW_REF": f"{REPOSITORY}/.github/workflows/release.yml@{REF}",+ "GITHUB_JOB": "checkov",+ "SARIF_ID": FIRST,+ "GITHUB_OUTPUT": str(self.output),+ }+ self.record = analysis()+ self.calls = []++ def run_api(self, command, **kwargs):+ self.calls.append(command)+ self.assertEqual(command[:4], ["gh", "api", "--method", "GET"])+ self.assertTrue(kwargs["capture_output"])+ self.assertTrue(kwargs["check"])+ self.assertEqual(kwargs["timeout"], 30)+ data = (+ [self.record]+ if "/analyses?" in command[-1]+ else {"processing_status": "complete"}+ )+ return subprocess.CompletedProcess(command, 0, json.dumps(data), "")++ def invoke(self, allow_retry=False, run_api=None):+ stdout, stderr = io.StringIO(), io.StringIO()+ argv = [str(SCRIPT)] + (["--allow-retry"] if allow_retry else [])+ with (+ patch.dict(os.environ, self.environment, clear=True),+ patch.object(sys, "argv", argv),+ patch.object(+ UPLOAD.subprocess, "run", side_effect=run_api or self.run_api+ ),+ redirect_stdout(stdout),+ redirect_stderr(stderr),+ ):+ code = UPLOAD.main()+ return code, stdout.getvalue() + stderr.getvalue()++ def test_success_does_not_request_an_unnecessary_reupload(self):+ code, log = self.invoke(allow_retry=True)+ self.assertEqual(code, 0, log)+ self.assertEqual(self.output.read_text(), "retry=false\n")++ def test_only_first_pass_can_request_recovery_and_retry_must_succeed(self):+ self.record["error"] = "Unknown Error"+ code, log = self.invoke(allow_retry=True)+ self.assertEqual(code, 0, log)+ self.assertEqual(self.output.read_text(), "retry=true\n")++ self.environment["SARIF_ID"] = SECOND+ self.record = analysis(SECOND)+ code, log = self.invoke()+ self.assertEqual(code, 0, log)+ self.assertTrue(all(SECOND in call[-1] for call in self.calls[-2:]))++ def test_persistent_unknown_error_fails_final_validation(self):+ self.record["error"] = "Unknown Error"+ code, log = self.invoke()+ self.assertEqual(code, 1, log)+ self.assertIn("after retry", log)+ self.assertFalse(self.output.exists())++ def test_api_failures_do_not_expose_raw_diagnostics(self):+ def failing_api(*args, **kwargs):+ raise subprocess.CalledProcessError(+ 1, ["gh", "api"], output="private-value", stderr="private-value"+ )++ code, log = self.invoke(allow_retry=True, run_api=failing_api)+ self.assertEqual(code, 1)+ self.assertNotIn("private-value", log)+ self.assertFalse(self.output.exists())++ def test_wrong_or_missing_workflow_context_fails_before_network(self):+ for changes in (+ {+ "GITHUB_WORKFLOW_REF": "other/project/.github/workflows/release.yml@main"+ },+ {"GITHUB_WORKFLOW_REF": f"{REPOSITORY}/../other.yml@main"},+ {"GITHUB_WORKFLOW_REF": ""},+ {"GITHUB_JOB": "other"},+ ):+ with self.subTest(changes=changes):+ original = self.environment.copy()+ self.environment.update(changes)+ code, log = self.invoke(allow_retry=True)+ self.assertEqual(code, 1, log)+ self.assertEqual(self.calls, [])+ self.environment = original+ del self.environment["GITHUB_SHA"]+ code, log = self.invoke(allow_retry=True)+ self.assertEqual(code, 1, log)+ self.assertEqual(self.calls, [])++ def test_standalone_dispatch_uses_its_own_workflow_analysis_key(self):+ self.environment["GITHUB_WORKFLOW_REF"] = (+ f"{REPOSITORY}/.github/workflows/checkov.yml@{REF}"+ )+ self.record["analysis_key"] = ".github/workflows/checkov.yml:checkov"+ code, log = self.invoke(allow_retry=True)+ self.assertEqual(code, 0, log)+++class WorkflowContractTests(unittest.TestCase):+ def setUp(self):+ self.wrapper = (ROOT / ".github/workflows/checkov.yml").read_text()+ text = (ROOT / ".github/workflows/checkov-scan.yml").read_text()+ self.steps = {}+ for block in text.split(" - name: ")[1:]:+ name, _, body = block.partition("\n")+ self.steps[name] = body+ self.text = text++ def test_original_upload_is_inspected_before_requesting_a_retry(self):+ original = self.steps["Upload GitHub Actions SARIF results"]+ inspect = self.steps["Inspect GitHub Actions analysis"]+ self.assertIn("id: upload-workflows", original)+ self.assertIn("steps.upload-workflows.outputs.sarif-id", inspect)+ self.assertIn("check_checkov_upload.py --allow-retry", inspect)+ self.assertIn('if [ "$ALLOW_ANALYSIS_RETRY" = "true" ]; then', inspect)+ self.assertIn(+ "ALLOW_ANALYSIS_RETRY: ${{ inputs.allow-analysis-retry }}", inspect+ )+ self.assertIn(+ " python3 .github/scripts/check_checkov_upload.py\n",+ inspect,+ )+ self.assertEqual(self.text.count("category: checkov-workflows"), 1)+ self.assertIn("sarif_file: checkov-workflows.sarif", original)+ self.assertIn(+ "upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370", original+ )+ self.assertNotIn("continue-on-error", self.text)++ def test_retry_is_a_fresh_job_and_cannot_repeat(self):+ self.assertEqual(+ self.wrapper.count("uses: $/.github/workflows/checkov-scan.yml"), 2+ )+ self.assertIn("allow-analysis-retry: true", self.wrapper)+ retry = self.wrapper.split(" retry:\n", 1)[1]+ self.assertIn("needs: scan", retry)+ self.assertIn(+ "needs.scan.result == 'success' && needs.scan.outputs.retry == 'true'",+ retry,+ )+ self.assertIn("allow-analysis-retry: false", retry)+ self.assertNotIn("allow-analysis-retry: true", retry)+ self.assertNotIn("continue-on-error", self.wrapper)+ self.assertIn("value: ${{ jobs.checkov.outputs.retry }}", self.text)+ self.assertIn(+ "retry: ${{ steps.workflow-analysis.outputs.retry }}", self.text+ )++ def test_existing_scanner_strictness_and_release_policy_are_unchanged(self):+ scan = self.steps["Run Checkov on GitHub Actions workflows"]+ self.assertNotIn("--soft-fail", scan)+ self.assertIn("--framework github_actions", scan)+ self.assertIn("--skip-check CKV_GHA_7", scan)+ policy = json.loads(+ (ROOT / ".github/release-scan-policy.json").read_text()+ )+ self.assertEqual(policy["checkov-workflows"], "checkov")+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/ci/test_release_queue_contract.py b/tests/ci/test_release_queue_contract.pyindex ac0154da66..82a2743f2b 100644--- a/tests/ci/test_release_queue_contract.py+++ b/tests/ci/test_release_queue_contract.py@@ -29,7 +29,7 @@ def test_checkov_scans_workflows_with_queue_after_blanking_it() -> None:"""Checkov 3.2.499's schema rejects concurrency.queue and then silentlyskips the whole workflow, so the gate must blank it before scanning."""root = WORKFLOWS.parents[1]- checkov = yaml.safe_load((WORKFLOWS / "checkov.yml").read_text())+ checkov = yaml.safe_load((WORKFLOWS / "checkov-scan.yml").read_text())steps = checkov["jobs"]["checkov"]["steps"]commands = [step.get("run", "") for step in steps]blank = next(