fix(verdict): a rebuild that regresses is never an improvement
CI / Tests, lint (pull_request) Successful in 18s

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
This commit is contained in:
Christian Manivong committed 2026-11-15 22:43:55 +01:00
1 parent 77b31ed835
commit 015c6e18cb
6 files changed
+397 -28

No files matched your search

+151 -20
View File
@@ -3,17 +3,21 @@
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:
- **improved** when a critical or high CVE that has a fixed version is closed,
Debian made a point release (``/etc/debian_version`` differs), or the
candidate passes a CIS control the pin fails (``image_tools/cis.py``, both measured
in the same run);
- **same** otherwise, and whenever the matcher cannot be asked: no pin moves on
a guess.
- **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 in the candidate never block; the report lists them.
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] \
--json verdict.json --report report.md
[--changes changes.txt] --json verdict.json --report report.md
Standard library only; Trivy runs as a pinned container.
"""
@@ -23,6 +27,7 @@ from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import urllib.error
import urllib.request
@@ -37,6 +42,8 @@ TRIVY_IMAGE = (
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
@@ -48,6 +55,12 @@ class Verdict:
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)
@@ -57,42 +70,112 @@ 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 and
the CIS controls the candidate passes and the pin fails."""
"""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]
point = None
if current_debian.strip() != candidate_debian.strip():
point = (current_debian.strip(), candidate_debian.strip())
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)
return Verdict(bool(closed) or point is not None or bool(cis), closed, new, point, cis, counts)
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*; never raises."""
"""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)
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}")
@@ -102,12 +185,24 @@ def _row(f: dict) -> str:
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 closed, what is new, against what."""
head = "**Improved**" if verdict.improved else "**Same** (the pin stays)"
lines = [f"{head}: `{candidate}` against the pinned `{current}`.", ""]
"""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}", ""]
@@ -128,6 +223,24 @@ def render(verdict: Verdict, current: str, candidate: str) -> str:
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."""
@@ -225,6 +338,18 @@ def debian_version_of(ref: str) -> str: # pragma: no cover - container seam
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."""
@@ -241,17 +366,23 @@ def main() -> int: # pragma: no cover - CLI seam
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("improved" if verdict.improved else "same")
print("regressed" if verdict.regressions else "improved" if verdict.improved else "same")
return 0