From 5e5e61d255ac9293e03febae5e143b41e6ed37e8 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 1 Nov 2026 00:36:20 +0100 Subject: [PATCH] feat(ci): scan the mirrored images daily and track their CVEs as issues The daily mirror workflow gains a scan job after the sync. It runs make test-security against the GHCR mirror, writes the failing findings per image and per CVE into the job summary and uploads the report as the vulnerability-findings artifact. - One issue per CVE and image, labelled vulnerability, is opened, updated while the finding stays and closed once no engine reports it. Issues are only closed when the scan reported no error, so an image that failed to scan keeps its issues. - workflow_dispatch and workflow_call take an issues switch; false is a dry run that only produces the summary and the artifact. Scheduled runs always sync the issues. - Only the scan job holds issues: write. Part of #1324 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/cron-images-mirror-all.yml | 77 ++++++++ cli/contributing/security/README.md | 9 +- cli/contributing/security/issues/__init__.py | 0 cli/contributing/security/issues/__main__.py | 181 ++++++++++++++++++ cli/contributing/security/summary/__init__.py | 0 cli/contributing/security/summary/__main__.py | 103 ++++++++++ .../cli/contributing/security/test_issues.py | 88 +++++++++ .../cli/contributing/security/test_summary.py | 79 ++++++++ 8 files changed, 536 insertions(+), 1 deletion(-) create mode 100644 cli/contributing/security/issues/__init__.py create mode 100755 cli/contributing/security/issues/__main__.py create mode 100644 cli/contributing/security/summary/__init__.py create mode 100755 cli/contributing/security/summary/__main__.py create mode 100644 tests/unit/python/cli/contributing/security/test_issues.py create mode 100644 tests/unit/python/cli/contributing/security/test_summary.py diff --git a/.github/workflows/cron-images-mirror-all.yml b/.github/workflows/cron-images-mirror-all.yml index 3f1619f873..97199aada5 100644 --- a/.github/workflows/cron-images-mirror-all.yml +++ b/.github/workflows/cron-images-mirror-all.yml @@ -25,6 +25,11 @@ on: description: "โฑ๏ธ Optional throttle: max images mirrored per hour" required: false type: string + issues: + description: "๐Ÿ›ก๏ธ Sync the vulnerability issues; off is a dry run" + required: false + default: true + type: boolean workflow_call: inputs: @@ -46,6 +51,11 @@ on: description: "Optional throttle: max images mirrored per hour" required: false type: string + issues: + description: "Open, update and close the vulnerability issues; false is a dry run" + required: false + default: true + type: boolean secrets: DOCKERHUB_USERNAME: required: false @@ -117,3 +127,70 @@ jobs: GHCR_PREFIX: ${{ inputs.ghcr_prefix || 'mirror' }} REPO_ROOT: ${{ inputs.repo_root || '.' }} run: bash scripts/meta/mirror/sync/all.sh + + scan: + name: ๐Ÿ”ฌ Scan the mirror + needs: sync + runs-on: ubuntu-26.04 + timeout-minutes: 355 + permissions: + contents: read + issues: write + + env: + INFINITO_GHCR_MIRROR_PREFIX: ${{ inputs.ghcr_prefix || 'mirror' }} + + steps: + - name: ๐Ÿงน Free disk space + uses: jlumbroso/free-disk-space@54081f138730dfa15788a46383842cd2f914a1be # v1.3.1 + with: + tool-cache: true + android: true + dotnet: true + haskell: true + large-packages: true + docker-images: true + swap-storage: true + + - name: โฌ‡๏ธ Checkout + uses: actions/checkout@v7.0.0 + + - name: ๐Ÿ”ง Setup Python + uses: actions/setup-python@v6 + with: + python-version: "3.12" + cache: pip + cache-dependency-path: pyproject.toml + + - name: ๐Ÿ“ฆ Install Python deps + run: PYTHON=python bash scripts/install/python.sh + + - name: ๐Ÿ—‚๏ธ SBOM tree by digest + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: build/security/sbom + key: security-sbom-${{ github.run_id }} + restore-keys: security-sbom- + + - name: ๐Ÿ”ฌ Scan every pinned image + run: make test-security + + - name: ๐Ÿ“Š Count the findings per image and per CVE + if: ${{ !cancelled() }} + run: python -m cli.contributing.security.summary --report build/test-reports/security.json --counts build/test-reports/security-counts.json --summary "$GITHUB_STEP_SUMMARY" + + - name: โฌ†๏ธ Upload the findings + if: ${{ !cancelled() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v4.6.1 + with: + name: vulnerability-findings + path: | + build/test-reports/security.json + build/test-reports/security-counts.json + if-no-files-found: error + + - name: ๐Ÿ›ก๏ธ Open, update and close the vulnerability issues + if: ${{ !cancelled() && (github.event_name == 'schedule' || inputs.issues) }} + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: python -m cli.contributing.security.issues --report build/test-reports/security.json --repo "${{ github.repository }}" diff --git a/cli/contributing/security/README.md b/cli/contributing/security/README.md index 8c43a9dbaf..53d1205322 100644 --- a/cli/contributing/security/README.md +++ b/cli/contributing/security/README.md @@ -1,3 +1,10 @@ # Security ๐Ÿ›ก๏ธ -Repository-side security reports over the declared role artefacts, such as the language runtimes the pinned images ship, read from registry metadata without pulling. +Repository-side vulnerability tooling over the pinned role images, built on the engine pipeline of [sys-ctl-hlth-runtime](../../../roles/sys-ctl-hlth-runtime/README.md). + +| Command | What it does | +|---|---| +| `make test-security` | Runs `scan`: Syft builds an SBOM of every pinned image straight from the GHCR mirror, cached by digest under `build/security/sbom`, and Trivy, Grype and OSV scan that SBOM tree with the role's threshold and suppressions. The failing findings go to `build/test-reports/security.json`. | +| `python -m cli.contributing.security.database --dir --engines ...` | Downloads the Trivy, Grype and OSV databases a CI deploy reads. | +| `python -m cli.contributing.security.summary --report --counts --summary ` | Counts the failing findings of the report per image and per CVE into a JSON file and appends the tables to a Markdown summary. | +| `python -m cli.contributing.security.issues --report --repo ` | Opens one `vulnerability` issue per CVE and image of the report, updates it while it stays, and closes it once no engine reports it. | diff --git a/cli/contributing/security/issues/__init__.py b/cli/contributing/security/issues/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/cli/contributing/security/issues/__main__.py b/cli/contributing/security/issues/__main__.py new file mode 100755 index 0000000000..c835c4e5a4 --- /dev/null +++ b/cli/contributing/security/issues/__main__.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import subprocess +from typing import TYPE_CHECKING, Any + +from utils.cache.files import read_text + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Mapping, Sequence + +LABEL = "vulnerability" +LABEL_COLOR = "B60205" +LABEL_DESCRIPTION = "A pinned image carries a CVE at the scan threshold" +ISSUE_LIMIT = "1000" +COLUMNS = ("engine", "role", "service", "package", "installed", "fixed", "severity") + + +def title(row: Mapping[str, Any]) -> str: + """Return the stable issue title of one CVE in one image.""" + return f"๐Ÿ›ก๏ธ {row['id']} in {row['image']}" + + +def grouped(rows: Iterable[Mapping[str, Any]]) -> dict[str, list[Mapping[str, Any]]]: + """Group the report rows by issue title.""" + groups: dict[str, list[Mapping[str, Any]]] = {} + for row in rows: + groups.setdefault(title(row), []).append(row) + return groups + + +def body(rows: Sequence[Mapping[str, Any]]) -> str: + """Render the issue body of one CVE in one image.""" + first = rows[0] + lines = [ + f"`{first['id']}` ({', '.join(first['ids'])}) in `{first['image']}`.", + "", + f"Mirror: `{first['mirror']}@{first['digest']}`", + "", + "| " + " | ".join(COLUMNS) + " |", + "|" + "---|" * len(COLUMNS), + ] + lines.extend( + "| " + " | ".join(str(row[column]) or "-" for column in COLUMNS) + " |" + for row in sorted(rows, key=lambda r: tuple(str(r[c]) for c in COLUMNS)) + ) + lines += [ + "", + ( + "Suppress it in the owning role's `meta/services.yml` under " + "`.security.suppressions`, see " + "`docs/contributing/actions/testing/suppression.md`." + ), + ] + return "\n".join(lines) + + +def sync( + report: Mapping[str, Any], repo: str, gh: Callable[[Sequence[str]], str] +) -> list[str]: + """Open, update and close one issue per CVE and image. + + Args: + report: the ``make test-security`` report. + repo: ``owner/name``. + gh: runs ``gh`` with the given arguments and returns its stdout. + + Returns: + What was done, one line per issue. An issue is only closed when the + scan reported no error, so an image that failed to scan keeps its + issues open. + """ + gh( + [ + "label", + "create", + LABEL, + "--repo", + repo, + "--color", + LABEL_COLOR, + "--description", + LABEL_DESCRIPTION, + "--force", + ] + ) + existing = { + issue["title"]: issue["number"] + for issue in json.loads( + gh( + [ + "issue", + "list", + "--repo", + repo, + "--label", + LABEL, + "--state", + "open", + "--json", + "number,title", + "--limit", + ISSUE_LIMIT, + ] + ) + ) + } + actions = [] + groups = grouped(report["findings"]) + for name, rows in sorted(groups.items()): + if name in existing: + gh( + [ + "issue", + "edit", + str(existing[name]), + "--repo", + repo, + "--body", + body(rows), + ] + ) + actions.append(f"updated #{existing[name]} {name}") + else: + gh( + [ + "issue", + "create", + "--repo", + repo, + "--title", + name, + "--label", + LABEL, + "--body", + body(rows), + ] + ) + actions.append(f"opened {name}") + if report["errors"]: + return actions + for name, number in sorted(existing.items()): + if name not in groups: + gh( + [ + "issue", + "close", + str(number), + "--repo", + repo, + "--comment", + "No engine reports it at the threshold any more.", + ] + ) + actions.append(f"closed #{number} {name}") + return actions + + +def run_gh(args: Sequence[str]) -> str: + return subprocess.run( + ["gh", *args], capture_output=True, text=True, check=True + ).stdout + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser( + description="Mirror the make test-security report into GitHub issues." + ) + parser.add_argument("--report", required=True, help="The make test-security report") + parser.add_argument("--repo", required=True, help="owner/name") + args = parser.parse_args(argv) + report = json.loads(read_text(args.report)) + for line in sync(report, args.repo, run_gh): + print(line) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/cli/contributing/security/summary/__init__.py b/cli/contributing/security/summary/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/cli/contributing/security/summary/__main__.py b/cli/contributing/security/summary/__main__.py new file mode 100755 index 0000000000..f60ada6b01 --- /dev/null +++ b/cli/contributing/security/summary/__main__.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from utils.cache.files import read_text + +if TYPE_CHECKING: + from collections.abc import Iterable, Mapping + +TOP = 25 + + +def counts(report: Mapping[str, Any]) -> dict[str, Any]: + """Count the failing findings of a ``make test-security`` report. + + Returns: + ``findings`` and ``errors`` totals, plus per image and per CVE the + distinct CVEs or images and the finding rows behind them. + """ + images: dict[str, dict[str, set[str] | int]] = {} + cves: dict[str, dict[str, set[str] | int]] = {} + for row in report["findings"]: + image = images.setdefault(row["image"], {"cves": set(), "findings": 0}) + image["cves"].add(row["id"]) + image["findings"] += 1 + cve = cves.setdefault(row["id"], {"images": set(), "findings": 0}) + cve["images"].add(row["image"]) + cve["findings"] += 1 + return { + "findings": len(report["findings"]), + "errors": len(report["errors"]), + "per_image": { + name: {"cves": len(entry["cves"]), "findings": entry["findings"]} + for name, entry in sorted(images.items()) + }, + "per_cve": { + name: {"images": len(entry["images"]), "findings": entry["findings"]} + for name, entry in sorted(cves.items()) + }, + } + + +def _table( + title: str, rows: Iterable[tuple[str, int, int]], columns: tuple[str, str, str] +) -> list[str]: + lines = [f"### {title}", "", f"| {' | '.join(columns)} |", "|---|---|---|"] + lines.extend(f"| `{name}` | {first} | {second} |" for name, first, second in rows) + return [*lines, ""] + + +def markdown(summary: Mapping[str, Any]) -> str: + """Render :func:`counts` as a job summary, largest first.""" + per_image = sorted( + summary["per_image"].items(), key=lambda item: (-item[1]["cves"], item[0]) + ) + per_cve = sorted( + summary["per_cve"].items(), key=lambda item: (-item[1]["images"], item[0]) + ) + lines = [ + "## ๐Ÿ”ฌ Vulnerability scan of the mirror", + "", + ( + f"{summary['findings']} failing finding(s) in {len(per_image)} image(s), " + f"{len(per_cve)} CVE(s), {summary['errors']} scan error(s)." + ), + "", + ] + lines += _table( + f"Images (top {TOP})", + ((name, entry["cves"], entry["findings"]) for name, entry in per_image[:TOP]), + ("image", "CVEs", "findings"), + ) + lines += _table( + f"CVEs (top {TOP})", + ((name, entry["images"], entry["findings"]) for name, entry in per_cve[:TOP]), + ("CVE", "images", "findings"), + ) + return "\n".join(lines) + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser( + description="Count the findings of a make test-security report per image and per CVE." + ) + parser.add_argument("--report", required=True, help="The make test-security report") + parser.add_argument("--counts", required=True, help="JSON file the counts go to") + parser.add_argument( + "--summary", required=True, help="Markdown file the summary is appended to" + ) + args = parser.parse_args(argv) + summary = counts(json.loads(read_text(args.report))) + Path(args.counts).write_text(json.dumps(summary, indent=2), encoding="utf-8") + with Path(args.summary).open("a", encoding="utf-8") as handle: + handle.write(markdown(summary) + "\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/unit/python/cli/contributing/security/test_issues.py b/tests/unit/python/cli/contributing/security/test_issues.py new file mode 100644 index 0000000000..630bb168ee --- /dev/null +++ b/tests/unit/python/cli/contributing/security/test_issues.py @@ -0,0 +1,88 @@ +from __future__ import annotations + +import json +from unittest import TestCase, main + +import cli.contributing.security.issues.__main__ as issues_main + +ROW = { + "engine": "grype", + "role": "web-app-roundcube", + "service": "roundcube", + "image": "docker.io/roundcube/roundcubemail:1.7.5-apache", + "mirror": "ghcr.io/o/r/mirror/docker.io/roundcube/roundcubemail", + "digest": "sha256:abc", + "id": "CVE-2026-109618", + "ids": ["CVE-2026-109618"], + "severity": "CRITICAL", + "package": "php-cli", + "installed": "8.4.26", + "fixed": "8.4.27", +} +TITLE = "๐Ÿ›ก๏ธ CVE-2026-109618 in docker.io/roundcube/roundcubemail:1.7.5-apache" + + +class FakeGh: + def __init__(self, open_issues): + self.open_issues = open_issues + self.calls = [] + + def __call__(self, args): + self.calls.append(list(args)) + if args[:2] == ["issue", "list"]: + return json.dumps(self.open_issues) + return "" + + def verbs(self): + return [ + call[:2] for call in self.calls if call[0] == "issue" and call[1] != "list" + ] + + +class TestSync(TestCase): + def test_a_new_finding_opens_one_issue(self): + gh = FakeGh([]) + issues_main.sync( + {"findings": [ROW, {**ROW, "engine": "trivy"}], "errors": []}, "o/r", gh + ) + self.assertEqual(gh.verbs(), [["issue", "create"]]) + + def test_a_known_finding_updates_its_issue(self): + gh = FakeGh([{"number": 7, "title": TITLE}]) + issues_main.sync({"findings": [ROW], "errors": []}, "o/r", gh) + self.assertEqual(gh.calls[-1][:3], ["issue", "edit", "7"]) + + def test_a_fixed_finding_closes_its_issue(self): + gh = FakeGh([{"number": 7, "title": TITLE}]) + actions = issues_main.sync({"findings": [], "errors": []}, "o/r", gh) + self.assertEqual(actions, [f"closed #7 {TITLE}"]) + + def test_a_scan_error_closes_nothing(self): + gh = FakeGh([{"number": 7, "title": TITLE}]) + issues_main.sync( + {"findings": [], "errors": ["x: the mirror served no digest"]}, "o/r", gh + ) + self.assertEqual(gh.verbs(), []) + + def test_the_issue_is_labelled(self): + gh = FakeGh([]) + issues_main.sync({"findings": [ROW], "errors": []}, "o/r", gh) + create = gh.calls[-1] + self.assertEqual(create[create.index("--label") + 1], issues_main.LABEL) + + +class TestBody(TestCase): + def test_every_engine_gets_a_row(self): + text = issues_main.body([ROW, {**ROW, "engine": "trivy"}]) + self.assertEqual( + sum( + 1 + for line in text.splitlines() + if line.startswith(("| grype", "| trivy")) + ), + 2, + ) + + +if __name__ == "__main__": + main() diff --git a/tests/unit/python/cli/contributing/security/test_summary.py b/tests/unit/python/cli/contributing/security/test_summary.py new file mode 100644 index 0000000000..090e521578 --- /dev/null +++ b/tests/unit/python/cli/contributing/security/test_summary.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +import json +import tempfile +from pathlib import Path +from unittest import TestCase, main + +import cli.contributing.security.summary.__main__ as summary_main +from utils.cache.files import read_text + + +def _row(image, cve, engine="grype"): + return {"image": image, "id": cve, "engine": engine} + + +REPORT = { + "findings": [ + _row("docker.io/a:1", "CVE-2026-1001"), + _row("docker.io/a:1", "CVE-2026-1001", engine="trivy"), + _row("docker.io/a:1", "CVE-2026-1002"), + _row("docker.io/b:2", "CVE-2026-1001"), + ], + "errors": ["docker.io/c:3: the mirror served no digest"], +} + + +class TestCounts(TestCase): + def test_an_image_counts_its_distinct_cves(self): + self.assertEqual( + summary_main.counts(REPORT)["per_image"]["docker.io/a:1"], + {"cves": 2, "findings": 3}, + ) + + def test_a_cve_counts_its_distinct_images(self): + self.assertEqual( + summary_main.counts(REPORT)["per_cve"]["CVE-2026-1001"], + {"images": 2, "findings": 3}, + ) + + def test_totals_include_the_scan_errors(self): + counts = summary_main.counts(REPORT) + self.assertEqual((counts["findings"], counts["errors"]), (4, 1)) + + +class TestMarkdown(TestCase): + def test_the_most_affected_image_comes_first(self): + text = summary_main.markdown(summary_main.counts(REPORT)) + self.assertLess(text.index("docker.io/a:1"), text.index("docker.io/b:2")) + + def test_the_headline_names_the_totals(self): + text = summary_main.markdown(summary_main.counts(REPORT)) + self.assertIn( + "4 failing finding(s) in 2 image(s), 2 CVE(s), 1 scan error(s).", text + ) + + +class TestMain(TestCase): + def test_the_counts_artifact_and_the_summary_are_written(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / "report.json").write_text(json.dumps(REPORT), encoding="utf-8") + summary_main.main( + [ + "--report", + str(root / "report.json"), + "--counts", + str(root / "counts.json"), + "--summary", + str(root / "summary.md"), + ] + ) + counts = json.loads(read_text(str(root / "counts.json"))) + text = read_text(str(root / "summary.md")) + self.assertEqual(counts["findings"], 4) + self.assertIn("Vulnerability scan of the mirror", text) + + +if __name__ == "__main__": + main()