"""No image is pushed with a new fixable critical or high CVE (NetOrk/netork#1390). Trivy lists the packages of the candidate and of the last release of the same image, netOrk's matcher in kb-server judges both in one call (one state of its data, kb-server#155), and the gate fails only on what is new **and** fixable: a critical or high (CVE, package) the release does not have and that has a fixed version. What the release already had is no regression, and a new one nobody can fix yet would only stop every build until upstream ships a fix; both are listed, neither blocks. A gate that cannot ask the matcher does not pass: no image goes out on a guess. The fixtures are two Trivy ``--list-all-pkgs`` reports and kb-server's answer on them, as ``POST /api/v1/match`` gives it. """ from __future__ import annotations import json import subprocess import urllib.error from pathlib import Path import pytest from image_tools import verify from image_tools.cve_gate import Gate, check, gate, render FIXTURES = Path(__file__).parent / "fixtures" / "cve_gate" RELEASE = "registry.netork.io/netork/engine:0.49.0" CANDIDATE = "registry.netork.io/netork/engine:main-abc1234" def _fixture(name: str) -> dict: return json.loads((FIXTURES / name).read_text()) def _answer(new=(), current=None, candidate=None): return { "corpus_revision": 7, "current": current or {"high": 1}, "candidate": candidate or {"high": 1}, "closed": [], "new": list(new), } def _new(cve="CVE-2026-9999", severity="high", fixed="1.2.4"): return { "cve": cve, "package": "libfoo", "installed": "1.2.3", "severity": severity, "fixed": fixed, } class TestGate: @pytest.mark.parametrize("severity", ["critical", "high", "HIGH"]) def test_a_new_fixable_critical_or_high_blocks(self, severity): result = gate(_answer(new=[_new(severity=severity)])) assert not result.passed assert [f["cve"] for f in result.blocking] == ["CVE-2026-9999"] def test_nothing_new_passes(self): result = gate(_answer()) assert result.passed assert result.blocking == [] and result.unfixable == [] @pytest.mark.parametrize("fixed", [None, ""]) def test_a_new_one_without_a_fix_is_listed_and_passes(self, fixed): result = gate(_answer(new=[_new(fixed=fixed)])) assert result.passed assert [f["cve"] for f in result.unfixable] == ["CVE-2026-9999"] @pytest.mark.parametrize("severity", ["medium", "low", "unknown", None]) def test_only_critical_and_high_count(self, severity): """kb-server lists only those as new; a weaker one slipping through blocks nothing.""" result = gate(_answer(new=[_new(severity=severity)])) assert result.passed assert result.blocking == [] and result.unfixable == [] def test_the_counts_and_the_corpus_state_are_kept(self): result = gate(_answer(current={"high": 2}, candidate={"high": 3})) assert result.counts == {"release": {"high": 2}, "candidate": {"high": 3}} assert result.corpus_revision == 7 class TestCheck: """Against the fixtures: the release and the candidate as Trivy lists them.""" def _seams(self, answer=None, error=None): inventories = {RELEASE: "release.trivy.json", CANDIDATE: "candidate.trivy.json"} calls = {"sbom": [], "match": []} def sbom(ref, platform=None): calls["sbom"].append((ref, platform)) return _fixture(inventories[ref]) def match(current, candidate): calls["match"].append((current, candidate)) if error: raise error return answer return calls, {"sbom": sbom, "match": match} def test_both_go_to_the_matcher_in_one_call_the_release_as_current(self): calls, seams = self._seams(answer=_fixture("match.json")) check(RELEASE, CANDIDATE, platform="linux/amd64", **seams) assert calls["sbom"] == [(RELEASE, "linux/amd64"), (CANDIDATE, "linux/amd64")] assert calls["match"] == [ (_fixture("release.trivy.json"), _fixture("candidate.trivy.json")) ] def test_only_the_new_fixable_one_blocks(self): """urllib3 moved to a version with a fixable high: blocked. zlib's new critical has no fix: listed. openssl's and jinja2's highs were in the release already: not new, so neither listed nor blocking.""" _, seams = self._seams(answer=_fixture("match.json")) result = check(RELEASE, CANDIDATE, **seams) assert not result.passed assert [(f["cve"], f["package"]) for f in result.blocking] == [("CVE-2026-3333", "urllib3")] assert [(f["cve"], f["package"]) for f in result.unfixable] == [("CVE-2026-4444", "zlib1g")] assert result.error is None def test_a_candidate_that_is_the_release_passes(self): _, seams = self._seams(answer=_answer()) assert check(RELEASE, CANDIDATE, **seams).passed @pytest.mark.parametrize( "error", [ OSError("connection refused"), ValueError("Expecting value: line 1 column 1"), subprocess.CalledProcessError(1, "docker"), urllib.error.URLError("timed out"), ], ) def test_a_matcher_that_cannot_be_asked_does_not_pass(self, error): _, seams = self._seams(error=error) result = check(RELEASE, CANDIDATE, **seams) assert not result.passed assert result.error def test_a_release_trivy_cannot_read_does_not_pass(self): def sbom(ref, platform=None): raise subprocess.CalledProcessError(1, "trivy", stderr="MANIFEST_UNKNOWN") result = check(RELEASE, CANDIDATE, sbom=sbom, match=lambda a, b: _answer()) assert not result.passed assert "MANIFEST_UNKNOWN" in result.error def test_without_the_key_it_fails_before_anything_is_sent(self, monkeypatch): monkeypatch.delenv("NETORK_LICENSE_KEY", raising=False) calls, seams = self._seams() result = check(RELEASE, CANDIDATE, sbom=seams["sbom"]) assert not result.passed assert "NETORK_LICENSE_KEY" in result.error assert calls["sbom"] == [], "Trivy runs only when there is someone to ask" class TestRefusal: """kb.netork.io is behind the licence server's forward-auth: what a 401 or a 403 means is not obvious from the status alone, so the gate says it.""" def test_401_names_the_kind_of_key_it_needs(self): text = verify.refusal(401, "nak_kb_ABCDEFGH") assert "nak_kb_" in text and "NETORK_LICENSE_KEY" in text def test_401_with_a_licence_key_says_so(self): text = verify.refusal(401, "nlk_ABCDEFGH") assert "licence key" in text assert "ABCDEFGH" not in text, "the key itself never reaches a log" def test_403_names_the_entitlement(self): assert "feature_match" in verify.refusal(403, "nak_kb_ABCDEFGH") def test_an_empty_key_is_refused_before_a_call(self, monkeypatch): monkeypatch.setenv("NETORK_LICENSE_KEY", " ") with pytest.raises(PermissionError, match="NETORK_LICENSE_KEY"): verify.kb_key() class TestReport: def test_a_blocked_candidate_names_what_blocks_it_and_what_does_not(self): result = gate(_fixture("match.json")) text = render(result, RELEASE, CANDIDATE) assert text.startswith("**Blocked**") assert RELEASE in text and CANDIDATE in text blocking, listed = text.split("### New without a fix") assert "CVE-2026-3333" in blocking and "2.5.0" in blocking assert "CVE-2026-4444" in listed assert "48213" in text def test_a_passing_candidate_says_so(self): assert render(gate(_answer()), RELEASE, CANDIDATE).startswith("**Passes**") def test_no_verdict_says_why(self): text = render(Gate(False, error="PermissionError: boom"), RELEASE, CANDIDATE) assert text.startswith("**No verdict**") assert "boom" in text @pytest.mark.parametrize( ("result", "code"), [ (Gate(True), 0), (Gate(False, blocking=[_new()]), 1), (Gate(False, error="down"), 2), ], ) def test_the_exit_code_tells_blocked_from_no_verdict(result, code): assert result.exit_code == code def test_the_result_is_json_for_the_workflow(): data = json.loads(gate(_fixture("match.json")).to_json()) assert data["passed"] is False assert data["blocking"][0]["cve"] == "CVE-2026-3333" assert set(data) == { "passed", "blocking", "unfixable", "counts", "corpus_revision", "error", }