feat(cve-gate): no image goes out with a new fixable critical or high CVE
CI / Tests, lint (pull_request) Successful in 13s
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.
This commit is contained in:
1 parent
adf80a7131
commit
1a7319bac4
10 files changed
+640
-10
No files matched your search
@@ -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
@@ -24,6 +24,7 @@ import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from collections.abc import Callable, Iterable
|
||||
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"
|
||||
|
||||
|
||||
def trivy_sbom(ref: str) -> dict: # pragma: no cover - container seam
|
||||
"""Trivy's package inventory of *ref* (no vulnerability DB)."""
|
||||
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",
|
||||
@@ -150,6 +152,7 @@ def trivy_sbom(ref: str) -> dict: # pragma: no cover - container seam
|
||||
"--list-all-pkgs",
|
||||
"--scanners",
|
||||
"license",
|
||||
*(["--platform", platform] if platform else []),
|
||||
ref,
|
||||
],
|
||||
capture_output=True,
|
||||
@@ -160,20 +163,55 @@ def trivy_sbom(ref: str) -> dict: # pragma: no cover - container seam
|
||||
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)."""
|
||||
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 {os.environ['NETORK_LICENSE_KEY']}",
|
||||
},
|
||||
headers={"Content-Type": "application/json", "Authorization": f"Bearer {key}"},
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=TIMEOUT) as response: # noqa: S310 - https
|
||||
return json.load(response)
|
||||
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
|
||||
|
||||
Reference in new issue
Block a user