feat(cve-gate): no image goes out with a new fixable critical or high CVE #2

Merged
christianmanivong merged 1 commits from feat/cve-gate into main 2026-11-08 05:50:32 +00:00
10 changed files with 640 additions and 10 deletions

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
# Changelog
All notable changes to image-tools are documented here. The format follows
[Keep a Changelog](https://keepachangelog.com/). Image repositories pin a commit, not a
version, so a section names the commit it describes once it is merged.
## [Unreleased]
### Added
- `actions/cve-gate` and `image_tools/cve_gate.py`: the release gate (NetOrk/netork#1390).
A candidate image fails when netOrk's matcher finds a critical or high CVE in it that the
last release of the same image does not have and that has a fixed version. A new one
without a fix is listed and does not block; what the release already had is no
regression. Without a verdict, an empty `NETORK_LICENSE_KEY` included, the step fails.
- `trivy_sbom` reads one platform of a multi-platform index (`--platform`).
### Changed
- The matcher's 401 and 403 now say what they mean: a licence key (`nlk_…`) where a kb API
key (`nak_kb_…`) belongs, an unknown key, or a plan without `feature_match`. An empty
`NETORK_LICENSE_KEY` is a clear error before anything is sent, also for the verdict, where
it used to end in a `KeyError`.
+20
View File
@@ -22,6 +22,7 @@ with its CIS result and SBOM attached (NetOrk/netork#1390).
| **Signature** (`bin/sign.sh`) | A cosign signature on the reference and on every platform image behind it, with the CIS result and the SBOM as in-toto attestations. Nothing goes to a public transparency log. | | **Signature** (`bin/sign.sh`) | A cosign signature on the reference and on every platform image behind it, with the CIS result and the SBOM as in-toto attestations. Nothing goes to a public transparency log. |
| **Verification** (`bin/verify-base.sh`, `bin/verify-signature.sh`) | Every `FROM` image of a Dockerfile is pinned by digest and signed with the key in `cosign.pub`. | | **Verification** (`bin/verify-base.sh`, `bin/verify-signature.sh`) | Every `FROM` image of a Dockerfile is pinned by digest and signed with the key in `cosign.pub`. |
| **Verdict** (`image_tools/verify.py`) | Whether a rebuild improves on the pinned image, by netOrk's matcher (kb-server), for a base's nightly. | | **Verdict** (`image_tools/verify.py`) | Whether a rebuild improves on the pinned image, by netOrk's matcher (kb-server), for a base's nightly. |
| **CVE gate** (`image_tools/cve_gate.py`) | Whether a candidate brings a critical or high CVE that the last release of the same image does not have **and** that has a fix, by the same matcher in one call. Only that blocks; a new one without a fix is listed. No verdict (an empty key, a matcher that cannot be asked) never passes. |
| **Bump** (`image_tools/bump.py`) | One pull request in every repository of a `dependents.toml` that moves only the pin, and that repository's workflow started. | | **Bump** (`image_tools/bump.py`) | One pull request in every repository of a `dependents.toml` that moves only the pin, and that repository's workflow started. |
## Using it in a workflow ## Using it in a workflow
@@ -49,6 +50,18 @@ with its CIS result and SBOM attached (NetOrk/netork#1390).
current: registry.netork.io/netork/base-os:pinned current: registry.netork.io/netork/base-os:pinned
candidate: registry.netork.io/netork/base-os:13-20261022.3-amd64 candidate: registry.netork.io/netork/base-os:13-20261022.3-amd64
# a release's image, before the push: nothing new and fixable against the last release
- name: No new fixable critical or high CVE
uses: https://git.netork.io/NetOrk/image-tools/actions/cve-gate@<commit>
env:
NETORK_LICENSE_KEY: ${{ secrets.NETORK_LICENSE_KEY }}
TRIVY_USERNAME: ${{ secrets.REGISTRY_USER }}
TRIVY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
with:
release: registry.netork.io/netork/engine:0.49.0
candidate: registry.netork.io/netork/engine:main-abc1234
arch: amd64
# push it, then: # push it, then:
- name: Sign it - name: Sign it
uses: https://git.netork.io/NetOrk/image-tools/actions/sign@<commit> uses: https://git.netork.io/NetOrk/image-tools/actions/sign@<commit>
@@ -59,6 +72,13 @@ with its CIS result and SBOM attached (NetOrk/netork#1390).
ref: registry.netork.io/netork/engine@sha256:… ref: registry.netork.io/netork/engine@sha256:…
``` ```
**The key.** The verdict and the CVE gate ask kb.netork.io's `POST /api/v1/match`, which
sits behind the licence server's forward-auth. `NETORK_LICENSE_KEY` must therefore hold a
**kb API key** (`nak_kb_…`) of an instance whose plan grants kb's `feature_match`, not a
licence key (`nlk_…`): the forward-auth answers a licence key with 401, a plan without the
entitlement with 403. The gate says which in its report. It exits 0 when it passes, 1 when it
is blocked and 2 without a verdict, and the step fails on both of the last two.
The judge action reads `cis.toml` and `packages.allow` from the working directory by default. The judge action reads `cis.toml` and `packages.allow` from the working directory by default.
The runner needs Docker, Python 3.12 or newer, and `curl`; cosign is installed by the actions, The runner needs Docker, Python 3.12 or newer, and `curl`; cosign is installed by the actions,
pinned and checked against its release checksum (`bin/install-cosign.sh`). pinned and checked against its release checksum (`bin/install-cosign.sh`).
+44
View File
@@ -0,0 +1,44 @@
name: No new fixable critical or high CVE
description: >-
The release gate (image_tools/cve_gate.py): fails when the candidate has a
critical or high CVE that the last release of the same image does not have
and that has a fix, by netOrk's matcher in kb-server. A new one without a fix
is listed and passes. Writes cve-gate.json and cve-gate.md, prints the report,
and fails as well when no verdict could be reached, an empty key included.
The caller passes NETORK_LICENSE_KEY (a kb API key whose plan grants
feature_match), and TRIVY_USERNAME/TRIVY_PASSWORD for the registry, as env.
inputs:
release:
description: The last release of the image, as a registry reference
required: true
candidate:
description: The image to push, as Docker can run it (local tag or reference)
required: true
arch:
description: The platform both are read for, amd64 or arm64
required: true
outputs:
passed:
description: '"true" when the candidate brings no new fixable critical or high CVE'
value: ${{ steps.gate.outputs.passed }}
runs:
using: composite
steps:
- id: gate
shell: bash
env:
RELEASE: ${{ inputs.release }}
CANDIDATE: ${{ inputs.candidate }}
ARCH: ${{ inputs.arch }}
PYTHONPATH: ${{ github.action_path }}/../..
run: |
status=0
python3 -m image_tools.cve_gate "$RELEASE" "$CANDIDATE" --platform "linux/$ARCH" \
--json cve-gate.json --report cve-gate.md || status=$?
# Into the log: Gitea shows no step summary.
cat cve-gate.md
cat cve-gate.md >> "$GITHUB_STEP_SUMMARY"
if [ "$status" -eq 0 ]; then passed=true; else passed=false; fi
echo "passed=$passed" >> "$GITHUB_OUTPUT"
# 1: blocked, 2: no verdict. Either way nothing is pushed.
exit "$status"
+162
View File
@@ -0,0 +1,162 @@
"""Does a candidate image bring a new fixable critical or high CVE? (NetOrk/netork#1390)
The release gate: an image is pushed only when it has no critical or high CVE
that the last release of the same image does not have **and** that has a fixed
version. Trivy lists the packages of both, netOrk's matcher in kb-server judges
both in one call, so against one state of its data (kb-server#155); its ``new``
are the critical and high (CVE, package) pairs only the candidate has.
- **blocked** when one of them has a fix: the image brings a hole that can be
closed, so it is closed before the image goes out;
- **passes** otherwise. A new one without a fix is listed and does not block:
nobody can close it yet, and blocking would stop every build until upstream
does. What the release already had is no regression and is not listed;
- **no verdict** when the matcher cannot be asked, an empty
``NETORK_LICENSE_KEY`` included. That never passes: no image on a guess.
python -m image_tools.cve_gate <release-ref> <candidate-ref> [--platform linux/amd64] \
--json cve-gate.json --report cve-gate.md
Exits 0 when it passes, 1 when it is blocked, 2 without a verdict.
Standard library only; Trivy runs as a pinned container (image_tools/verify.py).
"""
from __future__ import annotations
import argparse
import json
import subprocess
from collections.abc import Callable
from dataclasses import asdict, dataclass, field
from image_tools.verify import SEVERE, kb_key, kb_match, trivy_sbom
@dataclass
class Gate:
passed: bool
#: New critical or high with a fix: what blocks.
blocking: list[dict] = field(default_factory=list)
#: New critical or high without a fix: listed, never blocking.
unfixable: list[dict] = field(default_factory=list)
counts: dict = field(default_factory=dict)
corpus_revision: int | None = None
error: str | None = None
@property
def exit_code(self) -> int:
if self.error:
return 2
return 0 if self.passed else 1
def to_json(self) -> str:
return json.dumps(asdict(self), indent=2)
def _severe(finding: dict) -> bool:
return (finding.get("severity") or "").lower() in SEVERE
def gate(answer: dict) -> Gate:
"""The gate on the matcher's *answer* for the release (``current``) and the candidate."""
new = [f for f in answer.get("new") or [] if _severe(f)]
blocking = [f for f in new if f.get("fixed")]
unfixable = [f for f in new if not f.get("fixed")]
counts = {"release": answer.get("current", {}), "candidate": answer.get("candidate", {})}
return Gate(not blocking, blocking, unfixable, counts, answer.get("corpus_revision"))
def check(
release: str,
candidate: str,
*,
platform: str | None = None,
sbom: Callable[..., dict] | None = None,
match: Callable[[dict, dict], dict] | None = None,
) -> Gate:
"""Gate *candidate* against *release*, both read for *platform*; never raises."""
sbom = sbom or trivy_sbom
try:
if match is None:
# Before Trivy runs: without a key there is nobody to ask.
key = kb_key()
def match(current: dict, cand: dict) -> dict:
return kb_match(current, cand, key)
return gate(match(sbom(release, platform), sbom(candidate, platform)))
except subprocess.CalledProcessError as exc:
# Trivy's last words say why (an unknown tag, a refused pull), not the exit status.
detail = (exc.stderr or "").strip()[-500:] if isinstance(exc.stderr, str) else ""
return Gate(False, error=f"{type(exc).__name__}: {exc} {detail}".strip())
except (OSError, ValueError, subprocess.SubprocessError) as exc:
return Gate(False, error=f"{type(exc).__name__}: {exc}")
def _row(f: dict) -> str:
fixed = f.get("fixed") or "–"
return f"| {f.get('cve')} | {f.get('package')} | {f.get('severity')} | {f.get('installed')} | {fixed} |"
def render(result: Gate, release: str, candidate: str) -> str:
"""The report: what blocks, what is new without a fix, against what."""
if result.error:
head = "**No verdict** (nothing is pushed)"
elif result.passed:
head = "**Passes**: no new fixable critical or high CVE"
else:
head = f"**Blocked**: {len(result.blocking)} new fixable critical or high CVE"
lines = [f"{head}: `{candidate}` against the last release `{release}`.", ""]
if result.error:
lines += [f"The matcher could not be asked: {result.error}", ""]
table = ["| CVE | Package | Severity | Installed | Fixed in |", "|---|---|---|---|---|"]
if result.blocking:
lines += ["### New and fixable (blocking)", "", *table, *map(_row, result.blocking), ""]
if result.unfixable:
lines += [
"### New without a fix (listed, not blocking)",
"",
*table,
*map(_row, result.unfixable),
"",
]
if result.counts:
lines += [
f"Findings by severity: release {result.counts.get('release')}, "
f"candidate {result.counts.get('candidate')}; corpus revision {result.corpus_revision}."
]
return "\n".join(lines).rstrip() + "\n"
def _annotation(result: Gate, release: str, candidate: str) -> str | None:
"""One ``::error::`` line, so the run's summary names the reason."""
if result.error:
return f"::error::No CVE verdict for {candidate}: {result.error}"
if not result.passed:
cves = ", ".join(f"{f.get('cve')} ({f.get('package')})" for f in result.blocking)
return (
f"::error::{candidate} brings new fixable critical/high CVEs against {release}: {cves}"
)
return None
def main() -> int: # pragma: no cover - CLI seam
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("release")
parser.add_argument("candidate")
parser.add_argument("--platform", default=None)
parser.add_argument("--json", required=True)
parser.add_argument("--report", required=True)
args = parser.parse_args()
result = check(args.release, args.candidate, platform=args.platform or None)
with open(args.json, "w") as fh:
fh.write(result.to_json())
with open(args.report, "w") as fh:
fh.write(render(result, args.release, args.candidate))
annotation = _annotation(result, args.release, args.candidate)
print(annotation or "passes")
return result.exit_code
if __name__ == "__main__": # pragma: no cover
raise SystemExit(main())
+47 -9
View File
@@ -24,6 +24,7 @@ import argparse
import json import json
import os import os
import subprocess import subprocess
import urllib.error
import urllib.request import urllib.request
from collections.abc import Callable, Iterable from collections.abc import Callable, Iterable
from dataclasses import asdict, dataclass, field from dataclasses import asdict, dataclass, field
@@ -127,8 +128,9 @@ def render(verdict: Verdict, current: str, candidate: str) -> str:
return "\n".join(lines).rstrip() + "\n" return "\n".join(lines).rstrip() + "\n"
def trivy_sbom(ref: str) -> dict: # pragma: no cover - container seam def trivy_sbom(ref: str, platform: str | None = None) -> dict: # pragma: no cover - container seam
"""Trivy's package inventory of *ref* (no vulnerability DB).""" """Trivy's package inventory of *ref* (no vulnerability DB); of the *platform*
variant (``linux/arm64``) when *ref* is an index of several."""
proc = subprocess.run( proc = subprocess.run(
[ [
"docker", "docker",
@@ -150,6 +152,7 @@ def trivy_sbom(ref: str) -> dict: # pragma: no cover - container seam
"--list-all-pkgs", "--list-all-pkgs",
"--scanners", "--scanners",
"license", "license",
*(["--platform", platform] if platform else []),
ref, ref,
], ],
capture_output=True, capture_output=True,
@@ -160,20 +163,55 @@ def trivy_sbom(ref: str) -> dict: # pragma: no cover - container seam
return json.loads(proc.stdout) return json.loads(proc.stdout)
def kb_match(current: dict, candidate: dict) -> dict: # pragma: no cover - network seam def kb_key() -> str:
"""The key kb.netork.io's matcher is asked with; a PermissionError when there is none."""
key = os.environ.get("NETORK_LICENSE_KEY", "").strip()
if not key:
raise PermissionError(
"NETORK_LICENSE_KEY is empty: the matcher cannot be asked. "
"Set the secret to a kb API key (nak_kb_…) whose plan grants feature_match."
)
return key
def refusal(status: int, key: str) -> str:
"""What kb.netork.io's 401 or 403 means, for the log; never the key itself.
The licence server's forward-auth answers before kb-server does: 401 is a key
it does not know (a licence key always is one, it takes per-service API keys
only), 403 a known key without the plan for it. kb-server's own 403 is a plan
without ``feature_match``, which no sold plan grants.
"""
if status == 401:
kind = (
"NETORK_LICENSE_KEY holds a licence key (nlk_…), which kb.netork.io never accepts"
if key.startswith("nlk_")
else "kb.netork.io does not know the key in NETORK_LICENSE_KEY"
)
return f"401: {kind}. It must be a kb API key (nak_kb_…) of an instance with feature_match."
return (
f"{status}: the key in NETORK_LICENSE_KEY is known, but its plan does not grant "
"kb's feature_match (or kb at all)."
)
def kb_match(current: dict, candidate: dict, key: str | None = None) -> dict: # pragma: no cover
"""kb-server's verdict on both inventories, in one call (kb-server#155).""" """kb-server's verdict on both inventories, in one call (kb-server#155)."""
key = key or kb_key()
body = json.dumps({"current": current, "candidate": candidate}).encode() body = json.dumps({"current": current, "candidate": candidate}).encode()
request = urllib.request.Request( request = urllib.request.Request(
f"{KB_URL}/api/v1/match", f"{KB_URL}/api/v1/match",
data=body, data=body,
method="POST", method="POST",
headers={ headers={"Content-Type": "application/json", "Authorization": f"Bearer {key}"},
"Content-Type": "application/json",
"Authorization": f"Bearer {os.environ['NETORK_LICENSE_KEY']}",
},
) )
with urllib.request.urlopen(request, timeout=TIMEOUT) as response: # noqa: S310 - https try:
return json.load(response) with urllib.request.urlopen(request, timeout=TIMEOUT) as response: # noqa: S310 - https
return json.load(response)
except urllib.error.HTTPError as exc:
if exc.code in (401, 403):
raise PermissionError(refusal(exc.code, key)) from exc
raise
def debian_version_of(ref: str) -> str: # pragma: no cover - container seam def debian_version_of(ref: str) -> str: # pragma: no cover - container seam
+29
View File
@@ -0,0 +1,29 @@
{
"SchemaVersion": 2,
"ArtifactName": "registry.netork.io/netork/engine:main-abc1234",
"ArtifactType": "container_image",
"Metadata": {
"OS": {"Family": "debian", "Name": "13.1"},
"ImageID": "sha256:2222222222222222222222222222222222222222222222222222222222222222"
},
"Results": [
{
"Target": "registry.netork.io/netork/engine:main-abc1234 (debian 13.1)",
"Class": "os-pkgs",
"Type": "debian",
"Packages": [
{"ID": "openssl@3.5.1-1", "Name": "openssl", "Version": "3.5.1-1", "SrcName": "openssl", "SrcVersion": "3.5.1-1"},
{"ID": "zlib1g@1:1.3.dfsg+really1.3.1-2", "Name": "zlib1g", "Version": "1:1.3.dfsg+really1.3.1-2", "SrcName": "zlib", "SrcVersion": "1:1.3.dfsg+really1.3.1-2"}
]
},
{
"Target": "Python",
"Class": "lang-pkgs",
"Type": "python-pkg",
"Packages": [
{"ID": "jinja2@3.1.5", "Name": "jinja2", "Version": "3.1.5"},
{"ID": "urllib3@2.4.0", "Name": "urllib3", "Version": "2.4.0"}
]
}
]
}
+24
View File
@@ -0,0 +1,24 @@
{
"src": "netork-kb",
"corpus_revision": 48213,
"current": {"high": 2},
"candidate": {"critical": 1, "high": 3},
"findings": {
"current": [
{"cve": "CVE-2026-1111", "package": "openssl", "installed": "3.5.1-1", "severity": "high", "fixed": "3.5.1-1+deb13u1", "fix_available": true, "ecosystem": "Debian:13"},
{"cve": "CVE-2026-2222", "package": "jinja2", "installed": "3.1.5", "severity": "high", "fixed": "3.1.6", "fix_available": true, "ecosystem": "PyPI"}
],
"candidate": [
{"cve": "CVE-2026-1111", "package": "openssl", "installed": "3.5.1-1", "severity": "high", "fixed": "3.5.1-1+deb13u1", "fix_available": true, "ecosystem": "Debian:13"},
{"cve": "CVE-2026-2222", "package": "jinja2", "installed": "3.1.5", "severity": "high", "fixed": "3.1.6", "fix_available": true, "ecosystem": "PyPI"},
{"cve": "CVE-2026-3333", "package": "urllib3", "installed": "2.4.0", "severity": "high", "fixed": "2.5.0", "fix_available": true, "ecosystem": "PyPI"},
{"cve": "CVE-2026-4444", "package": "zlib1g", "installed": "1:1.3.dfsg+really1.3.1-2", "severity": "critical", "fixed": null, "fix_available": false, "ecosystem": "Debian:13"}
]
},
"closed": [],
"new": [
{"cve": "CVE-2026-3333", "package": "urllib3", "installed": "2.4.0", "severity": "high", "fixed": "2.5.0"},
{"cve": "CVE-2026-4444", "package": "zlib1g", "installed": "1:1.3.dfsg+really1.3.1-2", "severity": "critical", "fixed": null}
],
"point_release": null
}
+29
View File
@@ -0,0 +1,29 @@
{
"SchemaVersion": 2,
"ArtifactName": "registry.netork.io/netork/engine:0.49.0",
"ArtifactType": "container_image",
"Metadata": {
"OS": {"Family": "debian", "Name": "13.1"},
"ImageID": "sha256:1111111111111111111111111111111111111111111111111111111111111111"
},
"Results": [
{
"Target": "registry.netork.io/netork/engine:0.49.0 (debian 13.1)",
"Class": "os-pkgs",
"Type": "debian",
"Packages": [
{"ID": "openssl@3.5.1-1", "Name": "openssl", "Version": "3.5.1-1", "SrcName": "openssl", "SrcVersion": "3.5.1-1"},
{"ID": "zlib1g@1:1.3.dfsg+really1.3.1-1", "Name": "zlib1g", "Version": "1:1.3.dfsg+really1.3.1-1", "SrcName": "zlib", "SrcVersion": "1:1.3.dfsg+really1.3.1-1"}
]
},
{
"Target": "Python",
"Class": "lang-pkgs",
"Type": "python-pkg",
"Packages": [
{"ID": "jinja2@3.1.5", "Name": "jinja2", "Version": "3.1.5"},
{"ID": "urllib3@2.3.0", "Name": "urllib3", "Version": "2.3.0"}
]
}
]
}
+16 -1
View File
@@ -20,7 +20,7 @@ ACTIONS = sorted((ROOT / "actions").glob("*/action.yml"))
def test_the_actions(): def test_the_actions():
names = [a.parent.name for a in ACTIONS] names = [a.parent.name for a in ACTIONS]
assert names == ["bump", "judge", "sign", "verdict", "verify-base"] assert names == ["bump", "cve-gate", "judge", "sign", "verdict", "verify-base"]
@pytest.mark.parametrize("action", ACTIONS, ids=lambda a: a.parent.name) @pytest.mark.parametrize("action", ACTIONS, ids=lambda a: a.parent.name)
@@ -50,6 +50,21 @@ def test_a_verdict_that_could_not_be_reached_fails_the_step():
assert "cat report.md" in step["run"].splitlines() assert "cat report.md" in step["run"].splitlines()
def test_the_cve_gate_fails_the_step_when_it_blocks_or_cannot_judge():
"""The gate's exit code is the step's: 1 for a new fixable CVE, 2 for no verdict
(an empty NETORK_LICENSE_KEY included). The report reaches the log either way."""
spec = yaml.safe_load((ROOT / "actions/cve-gate/action.yml").read_text())
[step] = spec["runs"]["steps"]
lines = step["run"].splitlines()
assert {"release", "candidate", "arch"} <= set(spec["inputs"])
assert spec["outputs"]["passed"]["value"] == "${{ steps.gate.outputs.passed }}"
assert "python3 -m image_tools.cve_gate" in step["run"]
assert "cat cve-gate.md" in lines
assert lines[-1] == 'exit "$status"'
assert "NETORK_LICENSE_KEY" in spec["description"] and "secrets." not in step["run"]
def test_bumping_needs_its_token_from_the_caller(): def test_bumping_needs_its_token_from_the_caller():
text = (ROOT / "actions/bump/action.yml").read_text() text = (ROOT / "actions/bump/action.yml").read_text()
+248
View File
@@ -0,0 +1,248 @@
"""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",
}