Merge pull request #1706 from infinito-nexus/fix/sys-ctl-hlth-runtime/runtime-vulnerability-issues

feat(ci): file hlth-runtime findings of every main run as vulnerability-runtime issues
This commit is contained in:
kevinveenbirkenbach authored and GitHub committed 2026-11-12 15:16:22 +01:00
commit 9e8c47cc82
7 files changed
+798 -42

No files matched your search

+11 -2
View File
@@ -375,13 +375,13 @@ jobs:
secrets: inherit
report-main-failures:
name: 🐞 Report main role failures
name: 🐞 Report main role failures and runtime vulnerabilities
needs:
- test-deploy-chunk-0
- test-deploy-chunk-1
- test-deploy-chunk-2
- test-deploy-chunk-3
if: ${{ always() && github.ref == 'refs/heads/main' && (contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled')) }}
if: ${{ always() && github.ref == 'refs/heads/main' }}
runs-on: ubuntu-26.04
permissions:
issues: write
@@ -390,9 +390,18 @@ jobs:
steps:
- uses: actions/checkout@v7.0.0
- name: 🐞 Open or append issues for failed roles
if: ${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') }}
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: python3 -m cli.meta.ci.report_failures --run-id "${{ github.run_id }}" --repo "${{ github.repository }}"
- name: "📥 Load the GHCR mirror prefix SPOT into job env"
if: ${{ !cancelled() }}
run: grep '^INFINITO_GHCR_MIRROR_PREFIX=' default.env >> "$GITHUB_ENV"
- name: 🛡️ Open, update and close the runtime vulnerability issues
if: ${{ !cancelled() }}
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: python3 -m cli.meta.ci.runtime_vulnerabilities --run-id "${{ github.run_id }}" --repo "${{ github.repository }}" --ref "${GITHUB_REF}" --dir "${RUNNER_TEMP}/rescue-diagnostics"
done:
name: 🏁 Finish pipeline
+2 -1
View File
@@ -7,4 +7,5 @@ Repository-side vulnerability tooling over the pinned role images, built on the
| `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. Every finding at the threshold goes to `build/test-reports/security.json`, a suppressed one with its `suppressed_until` day; the scan fails only on the unsuppressed ones. |
| `python -m cli.contributing.security.database --dir <dir> --engines <engine>...` | Downloads the Trivy, Grype and OSV databases a CI deploy reads. |
| `python -m cli.contributing.security.summary --report <file> --counts <file> --summary <file>` | Counts the failing findings of the report per image and per CVE, plus the suppressed total, into a JSON file and appends the tables to a Markdown summary. |
| `python -m cli.contributing.security.issues --report <file> --repo <owner/name>` | Opens one `vulnerability` issue per image of the report that lists its CVEs, suppressed ones with their `suppressed_until` day, updates it while it stays, and closes it once no engine reports a CVE for the image. |
| `python -m cli.contributing.security.issues --report <file> --repo <owner/name>` | Opens one `vulnerability` issue per image of the report that lists its CVEs, suppressed ones with their `suppressed_until` day, updates it while it stays, and closes it once no engine reports a CVE for the image. The head line counts the CVEs per severity. |
| `python -m cli.meta.ci.runtime_vulnerabilities --run-id <id> --repo <owner/name> --ref <ref> --dir <dir>` | Run by the `report-main-failures` job of every `main` run, never for another ref: reads the hlth-runtime lines of the deploys' `rescue-diagnostics-*` journals into the same issue format under its own `vulnerability-runtime` label, one issue per image and one `host <distro>` issue per distro. It closes an issue only when a deploy of the run scanned that target without an engine error and reported nothing, so neither sync ever touches the other's issues. |
+75 -22
View File
@@ -4,16 +4,51 @@ from __future__ import annotations
import argparse
import json
import subprocess
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, NamedTuple
from utils.cache.files import read_text
from utils.security.pipeline import pipeline
if TYPE_CHECKING:
from collections.abc import Callable, Iterable, Mapping, Sequence
class Tracker(NamedTuple):
"""One family of vulnerability issues, owned by one label.
Args:
label: the label every issue of the family carries; a sync lists,
updates and closes only issues of this label.
color: the label colour.
description: the label description.
source: renders the line under the head line from the first row.
artifact: where the rows the body leaves out are kept.
gone: the comment an issue closes with.
covers: ``(report, title) -> bool``, whether the report speaks for
the issue of that title, so its absence may close it.
"""
label: str
color: str
description: str
source: Callable[[Mapping[str, Any]], str]
artifact: str
gone: str
covers: Callable[[Mapping[str, Any], str], bool]
LABEL = "vulnerability"
LABEL_COLOR = "B60205"
LABEL_DESCRIPTION = "A pinned image carries a CVE at the scan threshold"
MIRROR = Tracker(
label=LABEL,
color=LABEL_COLOR,
description=LABEL_DESCRIPTION,
source=lambda row: f"Mirror: `{row['mirror']}@{row['digest']}`",
artifact="the `vulnerability-findings` artifact of the scan run",
gone="No engine reports a CVE at the threshold for this image any more.",
covers=lambda report, _title: not report["errors"],
)
ISSUE_LIMIT = "1000"
GH_TIMEOUT_SECONDS = 120
GH_FAILURES = (subprocess.CalledProcessError, subprocess.TimeoutExpired)
@@ -44,12 +79,26 @@ def grouped(rows: Iterable[Mapping[str, Any]]) -> dict[str, list[Mapping[str, An
return groups
def body(rows: Sequence[Mapping[str, Any]]) -> str:
def severity_counts(rows: Iterable[Mapping[str, Any]]) -> str:
"""Return the distinct CVE count per severity, e.g. ``CRITICAL 7, HIGH 42``."""
cves: dict[str, set[str]] = {}
for row in rows:
cves.setdefault(row["severity"], set()).add(row["id"])
order = pipeline().SEVERITIES
ranked = sorted(
cves,
key=lambda s: (order.index(s) if s in order else len(order), s),
)
return ", ".join(f"{severity} {len(cves[severity])}" for severity in ranked)
def body(rows: Sequence[Mapping[str, Any]], tracker: Tracker) -> str:
"""Render the issue body of one image, unsuppressed and CRITICAL rows first.
A suppressed CVE stays listed with its ``suppressed_until`` day, so the
issue remains open while the suppression runs. The table stops before
the body would exceed ``BODY_LIMIT`` and names how many rows it left out.
issue remains open while the suppression runs. The head line ends in
:func:`severity_counts`. The table stops before the body would exceed
``BODY_LIMIT`` and names how many rows it left out.
"""
first = rows[0]
cves = {row["id"] for row in rows}
@@ -57,10 +106,10 @@ def body(rows: Sequence[Mapping[str, Any]]) -> str:
head = [
(
f"`{first['image']}` carries {len(cves)} CVE(s) at the scan threshold, "
f"{len(suppressed)} of them suppressed."
f"{len(suppressed)} of them suppressed: {severity_counts(rows)}."
),
"",
f"Mirror: `{first['mirror']}@{first['digest']}`",
tracker.source(first),
"",
"| " + " | ".join(COLUMNS) + " |",
"|" + "---|" * len(COLUMNS),
@@ -95,20 +144,25 @@ def body(rows: Sequence[Mapping[str, Any]]) -> str:
if hidden:
shown += [
"",
f"{hidden} more row(s) are in the `vulnerability-findings` artifact of the scan run.",
f"{hidden} more row(s) are in {tracker.artifact}.",
]
return "\n".join(head + shown + tail)
def sync(
report: Mapping[str, Any], repo: str, gh: Callable[[Sequence[str]], str]
report: Mapping[str, Any],
repo: str,
gh: Callable[[Sequence[str]], str],
tracker: Tracker,
) -> list[str]:
"""Open, update and close one issue per image.
Args:
report: the ``make test-security`` report.
report: ``findings`` (the rows) and ``errors``, plus whatever
``tracker.covers`` reads.
repo: ``owner/name``.
gh: runs ``gh`` with the given arguments and returns its stdout.
tracker: the issue family; only issues of its label are touched.
Returns:
What was done, one line per issue action; a ``failed`` line for a
@@ -116,20 +170,21 @@ def sync(
one open issue per image survives, the others close as duplicates.
An image whose CVE table changed gets a comment listing its
unresolved CVEs and an updated body; an unchanged table leaves the
issue alone. An issue is only closed when the scan reported no
error, so an image that failed to scan keeps its issue open.
issue alone. An issue without rows is only closed when
``tracker.covers`` says the report speaks for it, so an image that
failed to scan or was not scanned keeps its issue open.
"""
gh(
[
"label",
"create",
LABEL,
tracker.label,
"--repo",
repo,
"--color",
LABEL_COLOR,
tracker.color,
"--description",
LABEL_DESCRIPTION,
tracker.description,
"--force",
]
)
@@ -141,7 +196,7 @@ def sync(
"--repo",
repo,
"--label",
LABEL,
tracker.label,
"--state",
"open",
"--json",
@@ -172,7 +227,7 @@ def sync(
)
groups = grouped(report["findings"])
for name, rows in sorted(groups.items()):
text = body(rows)
text = body(rows, tracker)
issue = existing.get(name)
if issue is None:
args = [
@@ -183,7 +238,7 @@ def sync(
"--title",
name,
"--label",
LABEL,
tracker.label,
"--body",
text,
]
@@ -205,10 +260,8 @@ def sync(
actions.append(attempt(gh, comment, f"commented #{number} {name}"))
edit = ["issue", "edit", number, "--repo", repo, "--body", text]
actions.append(attempt(gh, edit, f"updated #{number} {name}"))
if report["errors"]:
return actions
for name, issue in sorted(existing.items()):
if name not in groups:
if name not in groups and tracker.covers(report, name):
args = [
"issue",
"close",
@@ -216,7 +269,7 @@ def sync(
"--repo",
repo,
"--comment",
"No engine reports a CVE at the threshold for this image any more.",
tracker.gone,
]
actions.append(attempt(gh, args, f"closed #{issue['number']} {name}"))
return actions
@@ -254,7 +307,7 @@ def main(argv=None) -> int:
parser.add_argument("--repo", required=True, help="owner/name")
args = parser.parse_args(argv)
report = json.loads(read_text(args.report))
lines = sync(report, args.repo, run_gh)
lines = sync(report, args.repo, run_gh, MIRROR)
for line in lines:
print(line)
return 1 if any(line.startswith("failed ") for line in lines) else 0
+272
View File
@@ -0,0 +1,272 @@
"""Mirror the hlth-runtime findings of a main run's deploys into GitHub issues."""
from __future__ import annotations
import argparse
import functools
import json
import os
import re
import sys
from pathlib import Path
from typing import TYPE_CHECKING, Any
from cli.contributing.security.issues.__main__ import (
GH_FAILURES,
Tracker,
run_gh,
sync,
title,
)
from utils import PROJECT_ROOT
from utils.docker.image.discovery import image_source
from utils.roles.entity.apps import apps_for_entity
from utils.security.engine import ROLE
if TYPE_CHECKING:
from collections.abc import Callable, Iterator, Sequence
MAIN_REF = "refs/heads/main"
ARTIFACTS = "rescue-diagnostics-*"
MIRROR_PREFIX_ENV = "INFINITO_GHCR_MIRROR_PREFIX"
UNMANAGED = "unmanaged container "
FINDING = re.compile(
r"(?:❌|⚠️?|ℹ️?) (?P<engine>\S+) (?P<kind>container|host) (?P<scope>.+?): "
r"(?P<id>\S+) (?P<severity>[A-Z]+) (?P<package>.+) (?P<installed>\S+) "
r"\((?:fixed in (?P<fixed>.+)|no fix)\)"
r"(?: suppressed until (?P<until>\d{4}-\d{2}-\d{2}))?$"
)
EVENT_MARK = '{"event": "hlth_runtime.'
EVENT = re.compile(r"\{\"event\": \"hlth_runtime\.(?:target|summary)\".*$")
RUNTIME = Tracker(
label="vulnerability-runtime",
color="D93F0B",
description="hlth-runtime reports a CVE at the threshold on a main deploy",
source=lambda row: f"Runtime: `{row['runtime']}`",
artifact="the `rescue-diagnostics-*` artifacts of the main run",
gone="No main deploy that scanned this target reports a CVE at the threshold any more.",
covers=lambda report, title: title in report["scanned"],
)
def host_image(distro: str) -> str:
"""Return the stable image field of the host scan of one distro's deploy node."""
return f"host {distro}"
def upstream(label: str, prefix: str) -> str:
"""Return the image reference an issue title names for a running image.
Args:
label: the image name the container runs,
``[registry/]repository[:tag][@digest]``.
prefix: the GHCR mirror prefix, see ``INFINITO_GHCR_MIRROR_PREFIX``.
Returns:
A mirror copy as the upstream pull reference the mirror scan titles
its issue with, any other image, such as a local build, as it runs.
"""
name = label.split("@", 1)[0]
mirrored = re.fullmatch(
rf"ghcr\.io/[^/]+/[^/]+/{re.escape(prefix)}/(?P<upstream>.+)", name
)
if mirrored is None:
return name
repository, separator, tag = mirrored["upstream"].rpartition(":")
if not separator or "/" in tag:
return mirrored["upstream"]
return image_source(repository, tag)
@functools.cache
def roles_of(stack: str) -> str | None:
"""Return the roles of a compose project or swarm stack, comma-joined."""
return ",".join(apps_for_entity(stack, roles_dir=PROJECT_ROOT / "roles")) or None
def row(found: re.Match, distro: str, prefix: str) -> dict[str, Any]:
"""Return one finding line as an issue row."""
engine = found["engine"]
if found["kind"] == "host":
image = runtime = host_image(distro)
role, service = ROLE, engine
else:
scope = found["scope"]
if scope.startswith(UNMANAGED):
role, service, label = None, None, scope.removeprefix(UNMANAGED)
else:
owner, label = scope.split(" ", 1)
stack, service = owner.split("/", 1)
role = roles_of(stack)
image, runtime = upstream(label, prefix), label.split("@", 1)[0]
return {
"engine": engine,
"role": role,
"service": service,
"image": image,
"runtime": runtime,
"id": found["id"],
"severity": found["severity"],
"package": found["package"],
"installed": found["installed"],
"fixed": found["fixed"] or "",
"suppressed_until": found["until"],
}
def target_image(event: dict[str, Any], distro: str, prefix: str) -> str:
"""Return the image field of the target one ``hlth_runtime.target`` event names."""
if event["kind"] == "host":
return host_image(distro)
return upstream(event["image"].rsplit("@", 1)[0], prefix)
def journals(artifact: Path) -> Iterator[tuple[str, Path]]:
"""Yield ``(distro, journal)`` for every journal one artifact holds."""
for path in sorted(artifact.rglob("*journal.txt")):
parts = path.relative_to(artifact).parts
if len(parts) > 1 and (
path.name == "journal.txt" or path.name.endswith(".journal.txt")
):
yield parts[0], path
def read_journal(
path: Path, distro: str, prefix: str
) -> tuple[list[dict[str, Any]], set[str], int]:
"""Read the hlth-runtime lines of one journal.
Returns:
``(rows, titles, errors)``: one row per finding line, the issue
title of every target an event names, and the engine errors the
summary events count plus every event line that does not parse.
"""
rows: list[dict[str, Any]] = []
seen: set[str] = set()
failed = 0
with path.open(encoding="utf-8", errors="replace") as handle:
for line in handle:
text = line.rstrip("\n")
if "(fixed in " in text or "(no fix)" in text:
found = FINDING.search(text)
if found is not None:
rows.append(row(found, distro, prefix))
continue
event = EVENT.search(text) if EVENT_MARK in text else None
if event is None:
continue
try:
data = json.loads(event.group(0))
except json.JSONDecodeError:
failed += 1
continue
if data["event"] == "hlth_runtime.summary":
failed += data["errors"]
else:
seen.add(title({"image": target_image(data, distro, prefix)}))
return rows, seen, failed
def collect(root: Path, prefix: str) -> dict[str, Any]:
"""Read every rescue artifact below *root* into one issue report.
Args:
root: holds one directory per downloaded artifact.
prefix: the GHCR mirror prefix.
Returns:
``findings``: one row per distinct finding; ``errors``: one line per
journal whose check runs reported engine errors or an unreadable
event; ``scanned``: the issue titles of every target a journal
without such an error scanned, the only issues an absent finding
may close.
"""
rows: dict[tuple, dict[str, Any]] = {}
scanned: set[str] = set()
blocked: set[str] = set()
errors: list[str] = []
for artifact in sorted(path for path in root.iterdir() if path.is_dir()):
for distro, path in journals(artifact):
found, seen, failed = read_journal(path, distro, prefix)
rows.update((tuple(sorted(item.items())), item) for item in found)
(blocked if failed else scanned).update(seen)
if failed:
errors.append(f"{path.relative_to(root)}: {failed} engine error(s)")
return {
"findings": [rows[key] for key in sorted(rows, key=str)],
"errors": errors,
"scanned": sorted(scanned - blocked),
}
def report(
*,
run_id: str,
repo: str,
ref: str,
dest: Path,
prefix: str,
gh: Callable[[Sequence[str]], str],
) -> list[str]:
"""Sync the runtime vulnerability issues of one main run.
Args:
run_id: the workflow run whose deploys are reported.
repo: ``owner/name``.
ref: the ref the run built; anything but ``refs/heads/main`` files
nothing.
dest: where the rescue artifacts are downloaded.
prefix: the GHCR mirror prefix.
gh: runs ``gh`` with the given arguments and returns its stdout.
Returns:
What was done, one line per action; a ``failed`` line when the
download failed, which then syncs nothing.
"""
if ref != MAIN_REF:
return [f"skipped: {ref} is not {MAIN_REF}, no issue is filed"]
try:
gh(
[
"run",
"download",
run_id,
"--repo",
repo,
"--pattern",
ARTIFACTS,
"-D",
str(dest),
]
)
except GH_FAILURES as exc:
return [f"failed downloading the {ARTIFACTS} artifacts of {run_id}: {exc}"]
found = collect(dest, prefix)
errors = [f"error {line}" for line in found["errors"]]
return [*errors, *sync(found, repo, gh, RUNTIME)]
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description="Mirror the hlth-runtime findings of a main run into GitHub issues."
)
parser.add_argument("--run-id", required=True)
parser.add_argument("--repo", required=True, help="owner/name")
parser.add_argument("--ref", required=True, help="The ref the run built")
parser.add_argument("--dir", required=True, help="Download directory")
args = parser.parse_args(argv)
lines = report(
run_id=args.run_id,
repo=args.repo,
ref=args.ref,
dest=Path(args.dir),
prefix=os.environ[MIRROR_PREFIX_ENV],
gh=run_gh,
)
for line in lines:
print(line)
return 1 if any(line.startswith("failed ") for line in lines) else 0
if __name__ == "__main__":
sys.exit(main())
+1 -1
View File
@@ -6,7 +6,7 @@ This role scans the node it runs on for known vulnerabilities with [Trivy](https
## Overview
The role installs a check script with a `systemd` service and a timer at 00:00 UTC, and the deploy runs it once at its end. `severity` maps each reported severity to `fail` or `warn`: an unsuppressed finding mapped to `fail` fails the check, one mapped to `warn` is a `⚠️` line, a suppressed one an `ℹ️` line. The check also fails, and the failure notifier from [`sys-ctl-alm-compose`](../sys-ctl-alm-compose/README.md) alerts, when an engine or its database fails, or when a service that declares `php_hardening` in its `meta/volumes.yml` still reports `expose_php` or `session.upload_progress.enabled` as on. The daily mirror scan of `cron-images-mirror-all.yml` fails on every mapped finding, `fail` and `warn` alike, and tracks them as issues. The scan configuration and the engine pins live in [services.yml](./meta/services.yml).
The role installs a check script with a `systemd` service and a timer at 00:00 UTC, and the deploy runs it once at its end. `severity` maps each reported severity to `fail` or `warn`: an unsuppressed finding mapped to `fail` fails the check, one mapped to `warn` is a `⚠️` line, a suppressed one an `ℹ️` line. The check also fails, and the failure notifier from [`sys-ctl-alm-compose`](../sys-ctl-alm-compose/README.md) alerts, when an engine or its database fails, or when a service that declares `php_hardening` in its `meta/volumes.yml` still reports `expose_php` or `session.upload_progress.enabled` as on. The daily mirror scan of `cron-images-mirror-all.yml` fails on every mapped finding, `fail` and `warn` alike, and tracks them as issues; the findings of every `main` deploy become `vulnerability-runtime` issues, see [README.md](../../cli/contributing/security/README.md). The scan configuration and the engine pins live in [services.yml](./meta/services.yml).
## Cosmos
@@ -6,6 +6,7 @@ from unittest import TestCase, main
import cli.contributing.security.issues.__main__ as issues_main
MIRROR = issues_main.MIRROR
ROW = {
"engine": "grype",
"role": "web-app-roundcube",
@@ -26,6 +27,10 @@ TITLE = "🛡️ docker.io/roundcube/roundcubemail:1.7.5-apache"
OTHER_IMAGE = "docker.io/library/nginx:1.31.8-alpine"
def body(rows):
return issues_main.body(rows, MIRROR)
class FakeGh:
def __init__(self, open_issues, hang=()):
self.open_issues = open_issues
@@ -50,59 +55,69 @@ 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
{"findings": [ROW, {**ROW, "engine": "trivy"}], "errors": []},
"o/r",
gh,
MIRROR,
)
self.assertEqual(gh.verbs(), [["issue", "create"]])
def test_a_changed_image_gets_a_comment_and_an_updated_body(self):
gh = FakeGh([{"number": 7, "title": TITLE, "body": "old table"}])
issues_main.sync({"findings": [ROW], "errors": []}, "o/r", gh)
issues_main.sync({"findings": [ROW], "errors": []}, "o/r", gh, MIRROR)
self.assertEqual(gh.verbs(), [["issue", "comment"], ["issue", "edit"]])
comment = gh.calls[-2]
self.assertIn("Still unresolved:", comment[comment.index("--body") + 1])
self.assertIn(ROW["id"], comment[comment.index("--body") + 1])
def test_an_unchanged_image_leaves_its_issue_alone(self):
current = issues_main.body([ROW])
current = body([ROW])
gh = FakeGh([{"number": 7, "title": TITLE, "body": current + "\r\n"}])
actions = issues_main.sync({"findings": [ROW], "errors": []}, "o/r", gh)
actions = issues_main.sync({"findings": [ROW], "errors": []}, "o/r", gh, MIRROR)
self.assertEqual((gh.verbs(), actions), ([], [f"unchanged #7 {TITLE}"]))
def test_a_second_open_issue_of_one_image_closes_as_duplicate(self):
current = issues_main.body([ROW])
current = body([ROW])
gh = FakeGh(
[
{"number": 9, "title": TITLE, "body": current},
{"number": 7, "title": TITLE, "body": current},
]
)
actions = issues_main.sync({"findings": [ROW], "errors": []}, "o/r", gh)
actions = issues_main.sync({"findings": [ROW], "errors": []}, "o/r", gh, MIRROR)
self.assertEqual(gh.verbs(), [["issue", "close"]])
self.assertEqual(gh.calls[-1][2], "9")
self.assertIn(f"unchanged #7 {TITLE}", actions)
def test_a_fixed_finding_closes_its_issue(self):
gh = FakeGh([{"number": 7, "title": TITLE}])
actions = issues_main.sync({"findings": [], "errors": []}, "o/r", gh)
actions = issues_main.sync({"findings": [], "errors": []}, "o/r", gh, MIRROR)
self.assertEqual(actions, [f"closed #7 {TITLE}"])
def test_a_suppressed_finding_keeps_its_issue_open(self):
gh = FakeGh([{"number": 7, "title": TITLE, "body": "old table"}])
actions = issues_main.sync({"findings": [SUPPRESSED], "errors": []}, "o/r", gh)
actions = issues_main.sync(
{"findings": [SUPPRESSED], "errors": []}, "o/r", gh, MIRROR
)
self.assertEqual(gh.verbs(), [["issue", "comment"], ["issue", "edit"]])
self.assertNotIn(f"closed #7 {TITLE}", actions)
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
{"findings": [], "errors": ["x: the mirror served no digest"]},
"o/r",
gh,
MIRROR,
)
self.assertEqual(gh.verbs(), [])
def test_a_failed_issue_call_is_reported_and_the_others_still_run(self):
other = {**ROW, "image": OTHER_IMAGE}
gh = FakeGh([{"number": 7, "title": TITLE}], hang=[("issue", "edit")])
actions = issues_main.sync({"findings": [ROW, other], "errors": []}, "o/r", gh)
actions = issues_main.sync(
{"findings": [ROW, other], "errors": []}, "o/r", gh, MIRROR
)
failed = [action for action in actions if action.startswith("failed ")]
self.assertEqual(len(failed), 1)
self.assertTrue(failed[0].startswith(f"failed updated #7 {TITLE}"))
@@ -117,12 +132,13 @@ class TestSync(TestCase):
},
"o/r",
gh,
MIRROR,
)
self.assertEqual(actions, [f"opened {TITLE}"])
def test_the_issue_is_labelled(self):
gh = FakeGh([])
issues_main.sync({"findings": [ROW], "errors": []}, "o/r", gh)
issues_main.sync({"findings": [ROW], "errors": []}, "o/r", gh, MIRROR)
create = gh.calls[-1]
self.assertEqual(create[create.index("--label") + 1], issues_main.LABEL)
@@ -132,28 +148,41 @@ class TestBody(TestCase):
return [line for line in text.splitlines() if line.startswith("| CVE-")]
def test_every_engine_gets_a_row(self):
text = issues_main.body([ROW, {**ROW, "engine": "trivy"}])
text = body([ROW, {**ROW, "engine": "trivy"}])
self.assertEqual(len(self._table(text)), 2)
def test_critical_rows_come_first(self):
high = {**ROW, "id": "CVE-2026-000001", "severity": "HIGH"}
table = self._table(issues_main.body([high, ROW]))
table = self._table(body([high, ROW]))
self.assertIn("| CRITICAL |", table[0])
def test_a_suppressed_cve_is_listed_after_the_failing_ones_with_its_until(self):
text = issues_main.body([SUPPRESSED, ROW])
text = body([SUPPRESSED, ROW])
table = self._table(text)
self.assertEqual(
(table[0].endswith("| - |"), table[1].endswith("| 2026-12-03 |")),
(True, True),
)
self.assertIn(
"carries 2 CVE(s) at the scan threshold, 1 of them suppressed.", text
"carries 2 CVE(s) at the scan threshold, 1 of them suppressed: CRITICAL 2.",
text,
)
def test_the_head_line_counts_each_severity_most_severe_first(self):
rows = [
{**ROW, "id": "CVE-2026-000001", "severity": "HIGH"},
{**ROW, "id": "CVE-2026-000002", "severity": "HIGH"},
{**ROW, "engine": "trivy"},
]
head = body(rows).splitlines()[0]
self.assertTrue(head.endswith(": CRITICAL 1, HIGH 2."), head)
def test_the_mirror_body_names_its_mirror_copy(self):
self.assertIn(f"Mirror: `{ROW['mirror']}@{ROW['digest']}`", body([ROW]))
def test_a_large_image_stays_under_the_body_limit(self):
rows = [{**ROW, "id": f"CVE-2026-{index:06d}"} for index in range(2000)]
text = issues_main.body(rows)
text = body(rows)
self.assertLessEqual(len(text), issues_main.BODY_LIMIT)
hidden = 2000 - len(self._table(text))
self.assertGreater(hidden, 0)
@@ -0,0 +1,392 @@
from __future__ import annotations
import datetime as dt
import json
import tempfile
import unittest
from pathlib import Path
import cli.contributing.security.issues.__main__ as issues_main
from cli.meta.ci import runtime_vulnerabilities as rv
from utils import PROJECT_ROOT
from utils.cache.yaml import load_yaml
from utils.security.pipeline import pipeline
P = pipeline()
PREFIX = "mirror"
TODAY = dt.date(2026, 11, 12)
UNTIL = dt.date(2026, 12, 31)
NGINX = "ghcr.io/infinito-nexus/core/mirror/docker.io/nginx:1.31-alpine"
CADVISOR = "ghcr.io/infinito-nexus/core/mirror/ghcr.io/google/cadvisor:v0.60.6"
LOCAL = "openresty_custom:1.31.8.1-alpine"
CLEAN = "ghcr.io/infinito-nexus/core/mirror/docker.io/library/redis:8.4-alpine"
OWNER = ("openresty", "openresty")
PROMETHEUS = ("prometheus", "cadvisor")
NGINX_TITLE = "🛡️ docker.io/library/nginx:1.31-alpine"
CADVISOR_TITLE = "🛡️ ghcr.io/google/cadvisor:v0.60.6"
LOCAL_TITLE = f"🛡️ {LOCAL}"
CLEAN_TITLE = "🛡️ docker.io/library/redis:8.4-alpine"
HOST_TITLE = "🛡️ host debian"
PREFIX_LINE = "Nov 12 05:10:34 node hlth-runtime.17.0.0.infinito.nexus[42]: "
MARKS = ("❌", "⚠️", "ℹ️")
CI_LINE = (
"❌ grype container prometheus/blackbox-exporter "
"ghcr.io/infinito-nexus/core/mirror/docker.io/prom/blackbox-exporter:v0.29.1: "
"CVE-2026-111497 CRITICAL github.com/andybalholm/brotli v1.2.6 (fixed in 1.2.7)"
)
ENGINE_ERROR = "❌ osv sbom: no OSV database for Wolfi"
def target(key, label, owner):
return P.Target(
key=key,
kind="container",
ref=f"sha256:{key}",
label=label,
owners=(owner,),
owner_tags=((owner, P.image_tag(label)),),
)
def finding(key, cve, severity, fixed, package="zlib"):
return P.Finding(
engine="grype",
target=key,
package=package,
installed="1.3.2-r1",
fixed=fixed,
ids=(cve,),
severity=severity,
)
def journal(engine_errors=0):
nginx = target("n", NGINX, OWNER)
cadvisor = target("c", CADVISOR, PROMETHEUS)
local = target("l", LOCAL, OWNER)
clean = target("r", CLEAN, ("baserow", "redis"))
host = P.host_target("node")
tag = P.Suppression(id=None, image_tag="v0.60.6", until=UNTIL)
judged = [
P.Verdict(
finding("n", "CVE-2026-4738", "CRITICAL", "1.4-r0"),
nginx,
OWNER,
None,
False,
"warn",
),
P.Verdict(
finding("n", "CVE-2026-0001", "HIGH", ""), nginx, OWNER, None, False, "warn"
),
P.Verdict(
finding("c", "CVE-2026-0002", "CRITICAL", "1.4-r0"),
cadvisor,
PROMETHEUS,
tag,
True,
"warn",
),
P.Verdict(
finding("c", "CVE-2026-0003", "HIGH", ""),
cadvisor,
PROMETHEUS,
tag,
True,
"warn",
),
P.Verdict(
finding("l", "CVE-2026-0004", "CRITICAL", "2.0"),
local,
OWNER,
None,
False,
"fail",
),
P.Verdict(
finding("host", "CVE-2025-22871", "CRITICAL", "1.24.2", "stdlib"),
host,
(None, None),
None,
False,
"warn",
),
]
failures, warnings, infos = P.report_lines(judged)
run = P.Run(
id="r",
started=dt.datetime(2026, 11, 12, tzinfo=dt.UTC),
host="node",
environment="development",
)
outcome = P.Outcome(
run=run,
targets=(nginx, cadvisor, local, clean, host),
records=tuple(P.record(verdict, run) for verdict in judged),
errors=tuple(f"osv: broken {index}" for index in range(engine_errors)),
engines=("grype",),
failed=bool(failures),
finished=0.0,
)
lines = [
*(f"{MARKS[2]} {line}" for line in infos),
*(f"{MARKS[1]} {line}" for line in warnings),
*(f"{MARKS[0]} {line}" for line in failures),
CI_LINE,
ENGINE_ERROR,
*(
json.dumps(event)
for event in [*outcome.target_events(), outcome.summary_event()]
),
]
return "".join(f"{PREFIX_LINE}{line}\n" for line in lines)
def write_bundle(
root, name="rescue-diagnostics-compose-svc-x-0-debian-ext4-amd64", engine_errors=0
):
text = journal(engine_errors)
base = Path(root) / name / "debian" / "svc-x"
for relative in (
"svc-x-20261112051034Z-1/journal.txt",
"ci-host/svc-x-20261112051203Z-2/containers/infinito_nexus_debian.journal.txt",
):
path = base / relative
path.parent.mkdir(parents=True)
path.write_text(text, encoding="utf-8")
def collected(engine_errors=0):
with tempfile.TemporaryDirectory() as root:
write_bundle(root, engine_errors=engine_errors)
return rv.collect(Path(root), PREFIX)
def rows_of(report, title):
return [row for row in report["findings"] if issues_main.title(row) == title]
class FakeGh:
def __init__(self, issues=(), bundle=None):
self.issues = list(issues)
self.bundle = bundle
self.calls = []
def __call__(self, args):
args = list(args)
self.calls.append(args)
if args[:2] == ["run", "download"]:
self.bundle(args[args.index("-D") + 1])
if args[:2] == ["issue", "list"]:
label = args[args.index("--label") + 1]
return json.dumps(
[issue for issue in self.issues if label in issue["labels"]]
)
return ""
def writes(self):
return [call for call in self.calls if call[0] == "issue" and call[1] != "list"]
def touched(self, number):
return [call for call in self.writes() if call[2] == str(number)]
class TestParse(unittest.TestCase):
def test_a_mirror_finding_becomes_a_row_with_every_column(self):
rows = rows_of(collected(), NGINX_TITLE)
critical = next(row for row in rows if row["severity"] == "CRITICAL")
self.assertEqual(
{key: critical[key] for key in issues_main.COLUMNS},
{
"id": "CVE-2026-4738",
"severity": "CRITICAL",
"engine": "grype",
"role": "svc-prx-openresty",
"service": "openresty",
"package": "zlib",
"installed": "1.3.2-r1",
"fixed": "1.4-r0",
"suppressed_until": None,
},
)
def test_a_real_ci_line_parses_and_an_engine_error_line_does_not(self):
report = collected()
self.assertEqual(
[
row["package"]
for row in rows_of(report, "🛡️ docker.io/prom/blackbox-exporter:v0.29.1")
],
["github.com/andybalholm/brotli"],
)
self.assertFalse(
[row for row in report["findings"] if "Wolfi" in json.dumps(row)]
)
def test_the_two_journals_of_one_bundle_yield_each_finding_once(self):
self.assertEqual(len(rows_of(collected(), NGINX_TITLE)), 2)
def test_an_image_tag_suppression_fills_every_row_it_covers(self):
report = collected()
covered = rows_of(report, CADVISOR_TITLE)
self.assertEqual(
[row["suppressed_until"] for row in covered], ["2026-12-31"] * 2
)
uncovered = rows_of(report, NGINX_TITLE)
self.assertEqual({row["suppressed_until"] for row in uncovered}, {None})
def test_a_local_build_keeps_its_name_and_the_host_one_title_per_distro(self):
report = collected()
self.assertEqual(len(rows_of(report, LOCAL_TITLE)), 1)
host = rows_of(report, HOST_TITLE)
self.assertEqual(
[(row["role"], row["service"]) for row in host], [(rv.ROLE, "grype")]
)
class TestBody(unittest.TestCase):
def _cells(self, text, cve):
line = next(line for line in text.splitlines() if line.startswith(f"| {cve} "))
return dict(
zip(
issues_main.COLUMNS,
(cell.strip() for cell in line.strip("|").split("|")),
strict=True,
)
)
def test_the_head_line_counts_each_severity(self):
text = issues_main.body(rows_of(collected(), NGINX_TITLE), rv.RUNTIME)
self.assertTrue(text.splitlines()[0].endswith(": CRITICAL 1, HIGH 1."), text)
self.assertIn(
"Runtime: `ghcr.io/infinito-nexus/core/mirror/docker.io/nginx:1.31-alpine`",
text,
)
def test_fixed_is_a_dash_without_a_fix_and_the_version_with_one(self):
text = issues_main.body(rows_of(collected(), NGINX_TITLE), rv.RUNTIME)
self.assertEqual(self._cells(text, "CVE-2026-0001")["fixed"], "-")
self.assertEqual(self._cells(text, "CVE-2026-4738")["fixed"], "1.4-r0")
def test_a_suppressed_row_shows_its_day_and_an_open_one_a_dash(self):
report = collected()
suppressed = issues_main.body(rows_of(report, CADVISOR_TITLE), rv.RUNTIME)
self.assertEqual(
self._cells(suppressed, "CVE-2026-0003")["suppressed_until"], "2026-12-31"
)
open_body = issues_main.body(rows_of(report, NGINX_TITLE), rv.RUNTIME)
self.assertEqual(
self._cells(open_body, "CVE-2026-0001")["suppressed_until"], "-"
)
class TestLabels(unittest.TestCase):
def mirror_issue(self):
return {
"number": 1,
"title": NGINX_TITLE,
"body": "mirror table",
"labels": [issues_main.LABEL],
}
def test_a_runtime_sync_never_touches_a_mirror_issue(self):
gh = FakeGh(
[
self.mirror_issue(),
{**self.mirror_issue(), "number": 2, "title": CLEAN_TITLE},
]
)
actions = issues_main.sync(collected(), "o/r", gh, rv.RUNTIME)
self.assertEqual((gh.touched(1), gh.touched(2)), ([], []))
labels = {
call[call.index("--label") + 1] for call in gh.calls if "--label" in call
}
self.assertEqual(labels, {rv.RUNTIME.label})
self.assertIn(f"opened {NGINX_TITLE}", actions)
def test_negative_control_the_mirror_sync_does_close_its_own_issue(self):
gh = FakeGh([self.mirror_issue()])
issues_main.sync({"findings": [], "errors": []}, "o/r", gh, issues_main.MIRROR)
self.assertEqual([call[1] for call in gh.touched(1)], ["close"])
def test_a_mirror_sync_never_touches_a_runtime_issue(self):
runtime = {
"number": 3,
"title": NGINX_TITLE,
"body": "x",
"labels": [rv.RUNTIME.label],
}
gh = FakeGh([runtime])
issues_main.sync({"findings": [], "errors": []}, "o/r", gh, issues_main.MIRROR)
self.assertEqual(gh.touched(3), [])
class TestClose(unittest.TestCase):
def issue(self, number, title):
return {
"number": number,
"title": title,
"body": "old",
"labels": [rv.RUNTIME.label],
}
def test_a_scanned_image_without_findings_closes_its_issue(self):
gh = FakeGh([self.issue(5, CLEAN_TITLE)])
actions = issues_main.sync(collected(), "o/r", gh, rv.RUNTIME)
self.assertIn(f"closed #5 {CLEAN_TITLE}", actions)
close = gh.touched(5)[0]
self.assertEqual(close[close.index("--comment") + 1], rv.RUNTIME.gone)
def test_negative_control_an_image_this_run_did_not_scan_stays_open(self):
title = "🛡️ docker.io/library/postgres:16-alpine"
gh = FakeGh([self.issue(6, title)])
issues_main.sync(collected(), "o/r", gh, rv.RUNTIME)
self.assertEqual(gh.touched(6), [])
def test_negative_control_a_scan_with_engine_errors_closes_nothing(self):
report = collected(engine_errors=1)
gh = FakeGh([self.issue(5, CLEAN_TITLE)])
issues_main.sync(report, "o/r", gh, rv.RUNTIME)
self.assertEqual((gh.touched(5), report["scanned"]), ([], []))
self.assertTrue(report["errors"])
class TestMainGuard(unittest.TestCase):
def run_report(self, ref):
gh = FakeGh(bundle=write_bundle)
with tempfile.TemporaryDirectory() as dest:
actions = rv.report(
run_id="9", repo="o/r", ref=ref, dest=Path(dest), prefix=PREFIX, gh=gh
)
return gh, actions
def test_a_pull_request_run_files_nothing(self):
gh, actions = self.run_report("refs/pull/7/merge")
self.assertEqual(gh.calls, [])
self.assertTrue(actions[0].startswith("skipped: refs/pull/7/merge"))
def test_negative_control_a_main_run_downloads_and_files(self):
gh, actions = self.run_report(rv.MAIN_REF)
self.assertEqual(gh.calls[0][:2], ["run", "download"])
self.assertIn(f"opened {NGINX_TITLE}", actions)
def guarded(self, job):
step = next(
step
for step in job["steps"]
if "runtime_vulnerabilities" in step.get("run", "")
)
return (
"github.ref == 'refs/heads/main'" in job["if"]
and '--ref "${GITHUB_REF}"' in step["run"]
)
def test_the_workflow_job_runs_only_on_main_and_hands_the_ref_on(self):
workflow = PROJECT_ROOT / ".github" / "workflows" / "call-orchestrator.yml"
job = load_yaml(str(workflow))["jobs"]["report-main-failures"]
self.assertTrue(self.guarded(job))
self.assertFalse(self.guarded({**job, "if": "${{ always() }}"}))
if __name__ == "__main__":
unittest.main()