Files
Christian Manivong 015c6e18cb
CI / Tests, lint (pull_request) Successful in 18s
fix(verdict): a rebuild that regresses is never an improvement
A candidate on an older base-os than the pin, with Debian's point release
going back, or with a critical or high CVE the pin does not have and that
has a fix (the CVE gate's rule) is now "regressed": the pin stays, whatever
else it closes, and the report names each regression first.

The verdict action takes the components a nightly says moved (changes);
each is an improvement on its own, but only through the verdict, so a new
PostgreSQL minor on an older base-os is judged instead of waved through
(NetOrk/netork#2523). verdict.json carries base_os, changes and regressions.
A base-os version that cannot be read is no verdict.

Closes #3
2026-11-15 22:43:55 +01:00

391 lines
15 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Does a candidate image improve on the pinned one? (#1308)
Trivy lists both images' packages; netOrk's matcher in kb-server judges both in
one call, so against one state of its data (kb-server#155). The verdict:
- **regressed** when the candidate is worse than the pin anywhere: built on an
older base-os (``/etc/netork/base-os``), Debian's point release going back, or
a critical or high CVE the pin does not have and that has a fixed version (the
CVE gate's rule). Nothing else outweighs it (image-tools#3, netork#2523);
- **improved** otherwise when a critical or high CVE that has a fixed version is
closed, Debian made a point release, the candidate passes a CIS control the
pin fails (``image_tools/cis.py``, both measured in the same run), or the
caller names a component that moved (``--changes``: a new PostgreSQL minor);
- **same** otherwise, and whenever the matcher cannot be asked or a base-os
version cannot be read: no pin moves on a guess.
New critical or high CVEs without a fix never block; the report lists them.
python -m image_tools.verify <current-ref> <candidate-ref> [--packages packages.allow] \
[--changes changes.txt] --json verdict.json --report report.md
Standard library only; Trivy runs as a pinned container.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import urllib.error
import urllib.request
from collections.abc import Callable, Iterable
from dataclasses import asdict, dataclass, field
from pathlib import Path
#: Trivy, pinned by its multi-platform index digest.
TRIVY_IMAGE = (
"aquasec/trivy:0.75.0@sha256:af6acf9a6b85dfe389a1941505c0ce9efef52a4719635e1a962f022a3d855daa"
)
SEVERE = frozenset({"critical", "high"})
KB_URL = os.environ.get("KB_URL", "https://kb.netork.io")
TIMEOUT = 300
#: base-os versions: ``<debian major>-<YYYYMMDD>.<n>`` (base-os ``tools/version.py``).
_BASE_OS = re.compile(r"^(\d+)-(\d{8})\.(\d+)$")
@dataclass
class Verdict:
improved: bool
closed: list[dict] = field(default_factory=list)
new: list[dict] = field(default_factory=list)
point_release: tuple[str, str] | None = None
cis_closed: list[str] = field(default_factory=list)
counts: dict = field(default_factory=dict)
error: str | None = None
#: (pinned, candidate) base-os versions, when they differ.
base_os: tuple[str, str] | None = None
#: The components the caller says moved, one line each.
changes: list[str] = field(default_factory=list)
#: Why the candidate is worse than the pin; any of them keeps the pin.
regressions: list[str] = field(default_factory=list)
def to_json(self) -> str:
return json.dumps(asdict(self), indent=2)
def _patched(finding: dict) -> bool:
return (finding.get("severity") or "").lower() in SEVERE and bool(finding.get("fixed"))
def _base_os_key(version: str) -> tuple[int, int, int]:
match = _BASE_OS.match(version.strip())
if not match:
raise ValueError(f"not a base-os version: {version!r}")
return int(match[1]), int(match[2]), int(match[3])
def _debian_key(version: str) -> tuple[int, ...] | None:
"""``13.7`` as numbers; None for a Debian version that is no number (``trixie/sid``)."""
parts = version.split(".")
return tuple(map(int, parts)) if all(p.isdigit() for p in parts) else None
def _base_os_move(base_os: tuple[str, str] | None) -> tuple[tuple[str, str] | None, list[str]]:
"""The base-os move between pin and candidate, and the regression it is, if any."""
if base_os is None:
return None, []
current, candidate = (v.strip() for v in base_os)
if _base_os_key(candidate) < _base_os_key(current):
return (current, candidate), [f"base-os goes back: {current} → {candidate}"]
return ((current, candidate) if current != candidate else None), []
def _debian_move(current: str, candidate: str) -> tuple[tuple[str, str] | None, list[str]]:
"""A point release forwards, or the regression of one backwards."""
current, candidate = current.strip(), candidate.strip()
if current == candidate:
return None, []
old, new = _debian_key(current), _debian_key(candidate)
if old is not None and new is not None and new < old:
return None, [f"Debian goes back: {current} → {candidate}"]
return (current, candidate), []
def _fixable_regression(finding: dict) -> str:
return (
f"{finding.get('cve')} ({finding.get('package')}, {finding.get('severity')}) "
f"is new and has a fix: {finding.get('fixed')}"
)
def judge(
answer: dict,
current_debian: str,
candidate_debian: str,
cis_closed: Iterable[str] = (),
*,
base_os: tuple[str, str] | None = None,
changes: Iterable[str] = (),
) -> Verdict:
"""The verdict on the matcher's *answer*, both images' Debian versions, the CIS
controls the candidate passes and the pin fails, both images' *base_os* versions
(pinned, candidate) and the components the caller says moved (*changes*).
A ValueError when a base-os version is no base-os version."""
closed = [f for f in answer.get("closed") or [] if _patched(f)]
new = [f for f in answer.get("new") or [] if (f.get("severity") or "").lower() in SEVERE]
base_move, regressions = _base_os_move(base_os)
point, debian_back = _debian_move(current_debian, candidate_debian)
regressions += debian_back + [_fixable_regression(f) for f in new if f.get("fixed")]
counts = {"current": answer.get("current", {}), "candidate": answer.get("candidate", {})}
cis = sorted(cis_closed)
changed = [c.strip() for c in changes if c.strip()]
better = bool(closed) or point is not None or bool(cis) or bool(changed)
return Verdict(
better and not regressions,
closed,
new,
point,
cis,
counts,
base_os=base_move,
changes=changed,
regressions=regressions,
)
def verify(
current: str,
candidate: str,
*,
changes: Iterable[str] = (),
sbom: Callable[[str], dict] | None = None,
match: Callable[[dict, dict], dict] | None = None,
debian_version: Callable[[str], str] | None = None,
cis_failing: Callable[[str], set[str]] | None = None,
base_os_version: Callable[[str], str] | None = None,
) -> Verdict:
"""Judge *candidate* against *current*, with the components the caller says
moved (*changes*); never raises."""
sbom = sbom or trivy_sbom
match = match or kb_match
debian_version = debian_version or debian_version_of
cis_failing = cis_failing or cis_failing_of
base_os_version = base_os_version or base_os_version_of
try:
answer = match(sbom(current), sbom(candidate))
cis_closed = cis_failing(current) - cis_failing(candidate)
return judge(
answer,
debian_version(current),
debian_version(candidate),
cis_closed,
base_os=(base_os_version(current), base_os_version(candidate)),
changes=changes,
)
except (OSError, ValueError, subprocess.SubprocessError) as exc:
return Verdict(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 _headline(verdict: Verdict) -> str:
if verdict.regressions:
return "**Regressed** (the pin stays)"
return "**Improved**" if verdict.improved else "**Same** (the pin stays)"
def render(verdict: Verdict, current: str, candidate: str) -> str:
"""The pull request body: what got worse, what moved, what closed, what is new."""
lines = [f"{_headline(verdict)}: `{candidate}` against the pinned `{current}`.", ""]
if verdict.error:
lines += [f"The matcher could not be asked: {verdict.error}", ""]
if verdict.regressions:
lines += ["### Regressions", "", *(f"- {r}" for r in verdict.regressions), ""]
if verdict.changes:
lines += ["Changed components:", "", *(f"- {c}" for c in verdict.changes), ""]
if verdict.base_os and not verdict.regressions:
old, new = verdict.base_os
lines += [f"base-os: {old} → {new}", ""]
if verdict.point_release:
old, new = verdict.point_release
lines += [f"Debian point release: {old} → {new}", ""]
if verdict.cis_closed:
lines += [
f"CIS controls the pin fails and the candidate passes: {', '.join(verdict.cis_closed)}",
"",
]
table = ["| CVE | Package | Severity | Installed | Fixed in |", "|---|---|---|---|---|"]
if verdict.closed:
lines += ["### Closed critical/high", "", *table, *map(_row, verdict.closed), ""]
if verdict.new:
lines += ["### New critical/high in the candidate", "", *table, *map(_row, verdict.new), ""]
if verdict.counts:
lines += [
f"Counts: current {verdict.counts.get('current')}, candidate {verdict.counts.get('candidate')}."
]
return "\n".join(lines).rstrip() + "\n"
def read_changes(path: str | Path) -> list[str]:
"""The change lines a nightly hands over, one component each; blanks and a
leading ``- `` dropped."""
lines = (
line.strip().removeprefix("- ").strip() for line in Path(path).read_text().splitlines()
)
return [line for line in lines if line]
def base_os_version(record: str) -> str:
"""The ``VERSION=`` of a base-os record (``/etc/netork/base-os``); a ValueError without one."""
for line in record.splitlines():
key, _, value = line.partition("=")
if key.strip() == "VERSION" and value.strip():
return value.strip()
raise ValueError("no VERSION in /etc/netork/base-os")
def trivy_sbom(ref: str, platform: str | None = None) -> dict: # pragma: no cover - container seam
"""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(
[
"docker",
"run",
"--rm",
"-v",
"/var/run/docker.sock:/var/run/docker.sock",
"-e",
"TRIVY_USERNAME",
"-e",
"TRIVY_PASSWORD",
TRIVY_IMAGE,
"image",
"--quiet",
"--disable-telemetry",
"--skip-version-check",
"--format",
"json",
"--list-all-pkgs",
"--scanners",
"license",
*(["--platform", platform] if platform else []),
ref,
],
capture_output=True,
text=True,
timeout=TIMEOUT,
check=True,
)
return json.loads(proc.stdout)
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)."""
key = key or kb_key()
body = json.dumps({"current": current, "candidate": candidate}).encode()
request = urllib.request.Request(
f"{KB_URL}/api/v1/match",
data=body,
method="POST",
headers={"Content-Type": "application/json", "Authorization": f"Bearer {key}"},
)
try:
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
proc = subprocess.run(
["docker", "run", "--rm", "--entrypoint", "cat", ref, "/etc/debian_version"],
capture_output=True,
text=True,
timeout=120,
check=True,
)
return proc.stdout.strip()
def base_os_version_of(ref: str) -> str: # pragma: no cover - container seam
"""The base-os *ref* was built on, from the record every image on base-os inherits."""
proc = subprocess.run(
["docker", "run", "--rm", "--entrypoint", "cat", ref, "/etc/netork/base-os"],
capture_output=True,
text=True,
timeout=120,
check=True,
)
return base_os_version(proc.stdout)
def cis_failing_of(ref: str, packages: str = "packages.allow") -> set[str]: # pragma: no cover
"""The CIS controls *ref* fails, measured as image_tools/cis.py measures a build;
*packages* is the image repository's allow list."""
from image_tools import cis
allowed = cis.load_packages(Path(packages).read_text())
return {c.id for c in cis.measure(ref, allowed) if c.result == cis.FAIL}
def main() -> int: # pragma: no cover - CLI seam
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("current")
parser.add_argument("candidate")
parser.add_argument("--json", required=True)
parser.add_argument("--report", required=True)
parser.add_argument("--packages", default="packages.allow")
parser.add_argument(
"--changes",
default="",
help="a file of the components that moved, one per line (an improvement on its own)",
)
args = parser.parse_args()
verdict = verify(
args.current,
args.candidate,
changes=read_changes(args.changes) if args.changes else (),
cis_failing=lambda ref: cis_failing_of(ref, args.packages),
)
with open(args.json, "w") as fh:
fh.write(verdict.to_json())
with open(args.report, "w") as fh:
fh.write(render(verdict, args.current, args.candidate))
print("regressed" if verdict.regressions else "improved" if verdict.improved else "same")
return 0
if __name__ == "__main__": # pragma: no cover
raise SystemExit(main())