From 4fa63dd1fbfa02d23836a0f047e2a843bd92743b Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 1 Nov 2026 17:48:08 +0100 Subject: [PATCH] feat(security): keep one vulnerability issue per image and comment its unresolved CVEs The dry-run mirror scan (run 41286420589) reported 10,179 CVE/image pairs across 135 red digests; one issue per pair would flood the tracker. The sync now keeps exactly one open issue per pinned image: - The body lists every CVE row (id, severity, engine, role, service, package, installed, fixed), CRITICAL first, and stops below 60,000 characters with the number of rows left out and a pointer to the vulnerability-findings artifact. On the dry-run data: 135 issues, 8 capped, the largest body 59,872 characters. - A further open issue with the same title closes as a duplicate of the oldest one. - When an image's CVE table changed, the issue gets a "Still unresolved" comment with the table and an updated body; an unchanged table leaves the issue alone, so a daily run does not add 135 identical comments. Part of #1324 Co-Authored-By: Claude Opus 5.5 --- cli/contributing/security/issues/__main__.py | 173 ++++++++++++------ .../cli/contributing/security/test_issues.py | 76 ++++++-- 2 files changed, 179 insertions(+), 70 deletions(-) diff --git a/cli/contributing/security/issues/__main__.py b/cli/contributing/security/issues/__main__.py index f0b301f83c..d96b9d7a06 100755 --- a/cli/contributing/security/issues/__main__.py +++ b/cli/contributing/security/issues/__main__.py @@ -17,12 +17,22 @@ LABEL_DESCRIPTION = "A pinned image carries a CVE at the scan threshold" ISSUE_LIMIT = "1000" GH_TIMEOUT_SECONDS = 120 GH_FAILURES = (subprocess.CalledProcessError, subprocess.TimeoutExpired) -COLUMNS = ("engine", "role", "service", "package", "installed", "fixed", "severity") +COLUMNS = ( + "id", + "severity", + "engine", + "role", + "service", + "package", + "installed", + "fixed", +) +BODY_LIMIT = 60000 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']}" + """Return the stable issue title of one image.""" + return f"🛡️ {row['image']}" def grouped(rows: Iterable[Mapping[str, Any]]) -> dict[str, list[Mapping[str, Any]]]: @@ -34,35 +44,56 @@ def grouped(rows: Iterable[Mapping[str, Any]]) -> dict[str, list[Mapping[str, An def body(rows: Sequence[Mapping[str, Any]]) -> str: - """Render the issue body of one CVE in one image.""" + """Render the issue body of one image, CRITICAL rows first. + + The table stops before the body would exceed ``BODY_LIMIT`` and names + how many rows it left out. + """ first = rows[0] - lines = [ - f"`{first['id']}` ({', '.join(first['ids'])}) in `{first['image']}`.", + cves = {row["id"] for row in rows} + head = [ + f"`{first['image']}` carries {len(cves)} CVE(s) at the scan threshold.", "", 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 += [ + tail = [ "", ( - "Suppress it in the owning role's `meta/services.yml` under " + "Suppress a CVE in the owning role's `meta/services.yml` under " "`.security.suppressions`, see " "`docs/contributing/actions/testing/suppression.md`." ), ] - return "\n".join(lines) + table = [ + "| " + " | ".join(str(row[column]) or "-" for column in COLUMNS) + " |" + for row in sorted( + rows, + key=lambda r: (r["severity"] != "CRITICAL", *(str(r[c]) for c in COLUMNS)), + ) + ] + budget = BODY_LIMIT - len("\n".join(head + tail)) - 200 + shown = [] + for line in table: + budget -= len(line) + 1 + if budget < 0: + break + shown.append(line) + hidden = len(table) - len(shown) + if hidden: + shown += [ + "", + f"{hidden} more row(s) are in the `vulnerability-findings` artifact of the scan run.", + ] + return "\n".join(head + shown + tail) 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. + """Open, update and close one issue per image. Args: report: the ``make test-security`` report. @@ -70,10 +101,13 @@ def sync( gh: runs ``gh`` with the given arguments and returns its stdout. Returns: - What was done, one line per issue; a ``failed`` line for an issue - whose ``gh`` call failed, while the other issues still run. An issue - is only closed when the scan reported no error, so an image that - failed to scan keeps its issues open. + What was done, one line per issue action; a ``failed`` line for a + ``gh`` call that failed, while the other issues still run. At most + 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. """ gh( [ @@ -89,42 +123,48 @@ def sync( "--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: - args = [ + issues = json.loads( + gh( + [ "issue", - "edit", - str(existing[name]), + "list", "--repo", repo, - "--body", - body(rows), + "--label", + LABEL, + "--state", + "open", + "--json", + "number,title,body", + "--limit", + ISSUE_LIMIT, ] - actions.append(attempt(gh, args, f"updated #{existing[name]} {name}")) - else: + ) + ) + actions = [] + existing: dict[str, Mapping[str, Any]] = {} + for issue in sorted(issues, key=lambda issue: issue["number"]): + kept = existing.setdefault(issue["title"], issue) + if kept is not issue: + args = [ + "issue", + "close", + str(issue["number"]), + "--repo", + repo, + "--comment", + f"Duplicate of #{kept['number']}: one issue per image.", + ] + actions.append( + attempt( + gh, args, f"closed duplicate #{issue['number']} {issue['title']}" + ) + ) + groups = grouped(report["findings"]) + for name, rows in sorted(groups.items()): + text = body(rows) + issue = existing.get(name) + if issue is None: args = [ "issue", "create", @@ -135,26 +175,49 @@ def sync( "--label", LABEL, "--body", - body(rows), + text, ] actions.append(attempt(gh, args, f"opened {name}")) + continue + number = str(issue["number"]) + if normalized(issue.get("body") or "") == normalized(text): + actions.append(f"unchanged #{number} {name}") + continue + comment = [ + "issue", + "comment", + number, + "--repo", + repo, + "--body", + f"Still unresolved:\n\n{text}", + ] + 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, number in sorted(existing.items()): + for name, issue in sorted(existing.items()): if name not in groups: args = [ "issue", "close", - str(number), + str(issue["number"]), "--repo", repo, "--comment", - "No engine reports it at the threshold any more.", + "No engine reports a CVE at the threshold for this image any more.", ] - actions.append(attempt(gh, args, f"closed #{number} {name}")) + actions.append(attempt(gh, args, f"closed #{issue['number']} {name}")) return actions +def normalized(text: str) -> str: + return "\n".join( + line.rstrip() for line in text.replace("\r\n", "\n").strip().splitlines() + ) + + def attempt(gh: Callable[[Sequence[str]], str], args: Sequence[str], done: str) -> str: try: gh(args) diff --git a/tests/unit/python/cli/contributing/security/test_issues.py b/tests/unit/python/cli/contributing/security/test_issues.py index e2b7308a2a..31cbf2fd39 100644 --- a/tests/unit/python/cli/contributing/security/test_issues.py +++ b/tests/unit/python/cli/contributing/security/test_issues.py @@ -20,7 +20,8 @@ ROW = { "installed": "8.4.26", "fixed": "8.4.27", } -TITLE = "🛡️ CVE-2026-109618 in docker.io/roundcube/roundcubemail:1.7.5-apache" +TITLE = "🛡️ docker.io/roundcube/roundcubemail:1.7.5-apache" +OTHER_IMAGE = "docker.io/library/nginx:1.31.8-alpine" class FakeGh: @@ -51,10 +52,32 @@ class TestSync(TestCase): ) self.assertEqual(gh.verbs(), [["issue", "create"]]) - def test_a_known_finding_updates_its_issue(self): - gh = FakeGh([{"number": 7, "title": TITLE}]) + 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) - self.assertEqual(gh.calls[-1][:3], ["issue", "edit", "7"]) + 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]) + gh = FakeGh([{"number": 7, "title": TITLE, "body": current + "\r\n"}]) + actions = issues_main.sync({"findings": [ROW], "errors": []}, "o/r", gh) + 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]) + gh = FakeGh( + [ + {"number": 9, "title": TITLE, "body": current}, + {"number": 7, "title": TITLE, "body": current}, + ] + ) + actions = issues_main.sync({"findings": [ROW], "errors": []}, "o/r", gh) + 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}]) @@ -69,11 +92,25 @@ class TestSync(TestCase): self.assertEqual(gh.verbs(), []) def test_a_failed_issue_call_is_reported_and_the_others_still_run(self): - other = {**ROW, "id": "CVE-2026-109619"} + 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) - self.assertTrue(actions[0].startswith(f"failed updated #7 {TITLE}")) - self.assertEqual(gh.verbs(), [["issue", "create"]]) + 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}")) + self.assertEqual(gh.verbs(), [["issue", "create"], ["issue", "comment"]]) + + def test_every_cve_of_one_image_shares_one_issue(self): + gh = FakeGh([]) + actions = issues_main.sync( + { + "findings": [ROW, {**ROW, "id": "CVE-2026-109619"}], + "errors": [], + }, + "o/r", + gh, + ) + self.assertEqual(actions, [f"opened {TITLE}"]) def test_the_issue_is_labelled(self): gh = FakeGh([]) @@ -83,16 +120,25 @@ class TestSync(TestCase): class TestBody(TestCase): + def _table(self, text): + 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"}]) - self.assertEqual( - sum( - 1 - for line in text.splitlines() - if line.startswith(("| grype", "| trivy")) - ), - 2, - ) + 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])) + self.assertIn("| CRITICAL |", table[0]) + + 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) + self.assertLessEqual(len(text), issues_main.BODY_LIMIT) + hidden = 2000 - len(self._table(text)) + self.assertGreater(hidden, 0) + self.assertIn(f"{hidden} more row(s)", text) if __name__ == "__main__":