CI / Tests, lint (pull_request) Successful in 13s
The release gate of NetOrk/netork#1390. The verdict answers "does a rebuild improve on the pin?"; a release needs the other question: does the candidate bring a critical or high CVE that the last release of the same image does not have and that has a fix? Both inventories go to netOrk's matcher in one call (kb-server's POST /api/v1/match, one state of its data), and only new and fixable blocks. A new one without a fix is listed: nobody can close it yet. No verdict never passes, and an empty NETORK_LICENSE_KEY is said so before Trivy runs. kb.netork.io's 401 and 403 come from the licence server's forward-auth and now say what they mean: a licence key where a kb API key belongs, an unknown key, or a plan without feature_match.
163 lines
6.4 KiB
Python
163 lines
6.4 KiB
Python
"""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())
|