diff --git a/cli/contributing/security/issues/__main__.py b/cli/contributing/security/issues/__main__.py index c835c4e5a4..f0b301f83c 100755 --- a/cli/contributing/security/issues/__main__.py +++ b/cli/contributing/security/issues/__main__.py @@ -15,6 +15,8 @@ LABEL = "vulnerability" LABEL_COLOR = "B60205" 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") @@ -68,9 +70,10 @@ def sync( 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. + 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. """ gh( [ @@ -111,56 +114,62 @@ def sync( 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}") + args = [ + "issue", + "edit", + str(existing[name]), + "--repo", + repo, + "--body", + body(rows), + ] + actions.append(attempt(gh, args, f"updated #{existing[name]} {name}")) else: - gh( - [ - "issue", - "create", - "--repo", - repo, - "--title", - name, - "--label", - LABEL, - "--body", - body(rows), - ] - ) - actions.append(f"opened {name}") + args = [ + "issue", + "create", + "--repo", + repo, + "--title", + name, + "--label", + LABEL, + "--body", + body(rows), + ] + actions.append(attempt(gh, args, 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}") + args = [ + "issue", + "close", + str(number), + "--repo", + repo, + "--comment", + "No engine reports it at the threshold any more.", + ] + actions.append(attempt(gh, args, f"closed #{number} {name}")) return actions +def attempt(gh: Callable[[Sequence[str]], str], args: Sequence[str], done: str) -> str: + try: + gh(args) + except GH_FAILURES as exc: + return f"failed {done}: {exc}" + return done + + def run_gh(args: Sequence[str]) -> str: return subprocess.run( - ["gh", *args], capture_output=True, text=True, check=True + ["gh", *args], + capture_output=True, + text=True, + check=True, + timeout=GH_TIMEOUT_SECONDS, ).stdout @@ -172,9 +181,10 @@ 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)) - for line in sync(report, args.repo, run_gh): + lines = sync(report, args.repo, run_gh) + for line in lines: print(line) - return 0 + return 1 if any(line.startswith("failed ") for line in lines) else 0 if __name__ == "__main__": diff --git a/tests/lint/ansible/services/test_cve_suppressions.py b/tests/lint/ansible/services/test_cve_suppressions.py index fc8c59962d..523edd83a7 100644 --- a/tests/lint/ansible/services/test_cve_suppressions.py +++ b/tests/lint/ansible/services/test_cve_suppressions.py @@ -27,12 +27,12 @@ from . import PROJECT_ROOT MARKER = re.compile(rf"^\s*#\s*nocheck:\s*{RULE}\b(?P.*)$", re.IGNORECASE) BLOCK = re.compile(r"^(?P\s*)suppressions:\s*$") -ENTRY = re.compile(r"^(?P\s*)-\s+id:") +ENTRY = re.compile(r"^(?P\s*)-\s+\S") REASON_SEPARATORS = " \t-:" def _entry_lines(lines: list[str]) -> list[int]: - """Return the index of every ``- id:`` line inside a ``suppressions:`` block.""" + """Return the index of every list item inside a ``suppressions:`` block.""" found = [] block_indent = None for index, line in enumerate(lines): @@ -155,6 +155,15 @@ class TestCheckerCases(unittest.TestCase): text = VALID.replace("2026-12-31", "2026-10-30") self.assertIn("expired on 2026-10-30", self._problems(text)[0]) + def test_an_unmarked_entry_that_starts_with_until_fails(self) -> None: + text = VALID.replace( + " # nocheck: cve the module is not built into the image\n" + " - id: CVE-2026-1234\n" + " until: 2026-12-31\n", + " - until: 2026-12-31\n id: CVE-2026-1234\n", + ) + self.assertIn("has no # nocheck: cve marker", self._problems(text)[0]) + def test_a_marker_for_another_rule_does_not_count(self) -> None: text = VALID.replace("nocheck: cve", "nocheck: url") self.assertIn("has no # nocheck: cve marker", self._problems(text)[0]) diff --git a/tests/unit/python/cli/contributing/security/test_issues.py b/tests/unit/python/cli/contributing/security/test_issues.py index 630bb168ee..fd544ee64d 100644 --- a/tests/unit/python/cli/contributing/security/test_issues.py +++ b/tests/unit/python/cli/contributing/security/test_issues.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import subprocess from unittest import TestCase, main import cli.contributing.security.issues.__main__ as issues_main @@ -64,6 +65,19 @@ class TestSync(TestCase): ) self.assertEqual(gh.verbs(), []) + def test_a_failed_issue_call_is_reported_and_the_others_still_run(self): + class HangingEdit(FakeGh): + def __call__(self, args): + if args[:2] == ["issue", "edit"]: + raise subprocess.TimeoutExpired(["gh", *args], 120) + return super().__call__(args) + + other = {**ROW, "id": "CVE-2026-109619"} + gh = HangingEdit([{"number": 7, "title": TITLE}]) + 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"]]) + def test_the_issue_is_labelled(self): gh = FakeGh([]) issues_main.sync({"findings": [ROW], "errors": []}, "o/r", gh) diff --git a/tests/unit/python/utils/security/test_database.py b/tests/unit/python/utils/security/test_database.py index 547cc19252..0c0af335c9 100644 --- a/tests/unit/python/utils/security/test_database.py +++ b/tests/unit/python/utils/security/test_database.py @@ -72,6 +72,16 @@ class TestFetchDatabases(_Root): errors, _calls, _downloads = self._fetch(["trivy"], 0) self.assertTrue(any("provided database" in error for error in errors)) + def test_an_interrupted_osv_download_leaves_no_zip_and_is_reported(self): + def fetch(url, destination): + destination.write_bytes(b"trunc") + raise TimeoutError("timed out") + + errors = database.fetch_databases(P, self.root, ["osv"], None, fetch) + ubuntu = self.root / "osv" / "osv-scalibr" / "Ubuntu" + self.assertIn("osv Ubuntu: timed out", errors) + self.assertEqual(list(ubuntu.iterdir()), []) + class TestStale(_Root): def test_a_missing_database_is_stale(self): diff --git a/utils/security/database.py b/utils/security/database.py index d5b09a6c27..b41aa35946 100644 --- a/utils/security/database.py +++ b/utils/security/database.py @@ -77,7 +77,14 @@ def fetch_databases( if "osv" in engines: for zip_file in osv_zips(p, root): zip_file.parent.mkdir(parents=True, exist_ok=True) - fetch(osv_url(zip_file.parent.name), zip_file) + partial = zip_file.with_name(f"{zip_file.name}.part") + try: + fetch(osv_url(zip_file.parent.name), partial) + except OSError as exc: + partial.unlink(missing_ok=True) + errors.append(f"osv {zip_file.parent.name}: {exc}") + continue + partial.replace(zip_file) for engine in engines: errors += p.missing_databases(engine, root) return errors