From 39efaaa27adc43ca6dd787173765a4d884836b83 Mon Sep 17 00:00:00 2001 From: stxkxs <139715017+stxkxs@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:55:56 +0000 Subject: [PATCH 1/4] test(gates): serve a gate run whole from fakeregistry fakeregistry answered registry.py's own tests at the urlopen level. A gate run whole needs more than that: a chart helm can render, an HTTPS repository that indexes it, and every request routed to the fake serving its host. - chart_archive() builds a chart archive laid out as helm package writes one, with fixed modes and times, so the same files give the same digest. - ChartRepository serves an index.yaml carrying each archive's digest, and the archives. Its `answer` stands in for a repository that is down. - Hosts routes each request to a fake by URL prefix and records it. A URL no fake serves fails the test rather than reading as a registry's answer. - serve() points registry.py at those fakes for the length of one test, with the chart cache under the test's own directory and the index cache emptied. Co-authored-by: stxkxsbot <275011021+stxkxsbot@users.noreply.github.com> --- scripts/tests/fakeregistry.py | 133 +++++++++++++++++++++++++++++++++- 1 file changed, 132 insertions(+), 1 deletion(-) diff --git a/scripts/tests/fakeregistry.py b/scripts/tests/fakeregistry.py index 3774b72..d3599f4 100644 --- a/scripts/tests/fakeregistry.py +++ b/scripts/tests/fakeregistry.py @@ -1,4 +1,5 @@ -"""A registry served at the urlopen level, for tests of scripts/registry.py. +"""A registry served at the urlopen level, for tests of scripts/registry.py and +of the gates that read charts through it. What a registry serves is stated here rather than read from the client under test: the media types are the ones the OCI and Helm specifications name, so a @@ -6,18 +7,31 @@ itself. A 200 is the http.client.HTTPResponse urlopen hands back, parsed from the bytes a server would send, so the client reads a body, Content-Length or chunked, through the same code it reads one through in CI. + +A gate is run whole against these with serve(): the real client, its real +cache under a test's own directory, and every request routed to a fake by URL. +The charts they serve are real archives (chart_archive()), so the gate renders +them with the real helm. """ from __future__ import annotations import email.message import functools +import gzip import hashlib import http.client import io import json +import pathlib +import tarfile +import unittest import urllib.error from collections.abc import Callable +from types import ModuleType +from unittest import mock + +import yaml NOW = 1_800_000_000.0 @@ -263,3 +277,120 @@ def __call__(self, req): def transport(self, *overrides): """A transport answering from this registry, with scripted steps first.""" return self.transport_class(*overrides, *([self] * 20)) + + +def chart_archive( + name: str, + version: str, + templates: dict[str, str], + *, + values: str = "", + crds: dict[str, str] | None = None, +) -> bytes: + """An archive `helm template` renders, laid out as `helm package` writes one. + + `name/` holds Chart.yaml, values.yaml, each of `templates` under templates/ + and each of `crds` under crds/. Modes and times are fixed, so the same files + give the same bytes, and so the digest an index publishes for them. + """ + files = { + "Chart.yaml": f"apiVersion: v2\nname: {name}\nversion: {version}\n", + "values.yaml": values, + **{f"templates/{path}": text for path, text in templates.items()}, + **{f"crds/{path}": text for path, text in (crds or {}).items()}, + } + raw = io.BytesIO() + with ( + gzip.GzipFile(fileobj=raw, mode="wb", mtime=0) as gz, + tarfile.open(fileobj=gz, mode="w") as tar, + ): + for path, text in files.items(): + data = text.encode() + info = tarfile.TarInfo(f"{name}/{path}") + info.size, info.mode, info.mtime = len(data), 0o644, 0 + tar.addfile(info, io.BytesIO(data)) + return raw.getvalue() + + +class ChartRepository: + """An HTTPS chart repository: an index.yaml listing each archive with the + digest Helm's index carries for it, and each archive at the URL it names. + + `answer`, when set, answers every request in its place, which is how a + repository that is down or refusing is written. + """ + + def __init__(self, base: str, charts: dict[tuple[str, str], bytes]) -> None: + self.base = base.rstrip("/") + self.charts = dict(charts) + self.answer: Callable | None = None + + def index(self) -> bytes: + entries: dict[str, list[dict]] = {} + for (name, version), data in sorted(self.charts.items()): + entries.setdefault(name, []).append( + { + "version": version, + "urls": [f"{name}-{version}.tgz"], + "digest": hashlib.sha256(data).hexdigest(), + } + ) + return yaml.safe_dump({"apiVersion": "v1", "entries": entries}).encode() + + def __call__(self, req): + url = req.full_url + if self.answer is not None: + return self.answer(req) + if url == f"{self.base}/index.yaml": + return self.index() + for (name, version), data in self.charts.items(): + if url == f"{self.base}/{name}-{version}.tgz": + return data + return http_error(url, 404) + + +class Hosts: + """urlopen for registry.http_get over several fakes, each serving the URLs + under its prefix, with every URL asked for and every wait recorded. + + A URL no fake serves raises AssertionError, which no registry read handles, + so a request the test did not expect fails it rather than reading as a + registry's answer. + """ + + def __init__(self, routes: dict[str, Callable]) -> None: + self.routes = routes + self.urls: list[str] = [] + self.waits: list[float] = [] + + def urlopen(self, req, timeout=None): + url = req.full_url + self.urls.append(url) + server = next((s for prefix, s in self.routes.items() if url.startswith(prefix)), None) + if server is None: + raise AssertionError(f"no fake serves {url}") + answer = server(req) + if isinstance(answer, BaseException): + raise answer + return served(answer) if isinstance(answer, bytes) else answer + + def sleep(self, seconds: float) -> None: + self.waits.append(seconds) + + +def serve( + case: unittest.TestCase, client: ModuleType, routes: dict[str, Callable], cache: pathlib.Path +) -> Hosts: + """Point `client`, the registry module the gates import, at `routes` for the + length of `case`, keeping its charts in `cache` and its indexes fresh.""" + hosts = Hosts(routes) + for patch in ( + mock.patch.object(client, "CHART_CACHE", cache), + mock.patch.dict(client._INDEXES, clear=True), + mock.patch.dict( + client.http_get.__kwdefaults__, {"urlopen": hosts.urlopen, "sleep": hosts.sleep} + ), + ): + patch.start() + case.addCleanup(patch.stop) + return hosts From 3c2bdb006d4b48dd92a9b8ba693e17322890e2fe Mon Sep 17 00:00:00 2001 From: stxkxs <139715017+stxkxs@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:57:18 +0000 Subject: [PATCH 2/4] test(gates): run each network gate's orchestrator offline, end to end Six gates read a registry or grafana.com, so controls.py exempts them, and their stages were tested only apart. check-image-vulnerabilities main, check-falco-rule-floor main, check-log-volume-budget main, validate-dashboards main, check-platform-crs check and render-addons main each ran no further than its def line in the default run. Each one's test module now has a TheGateRunWhole class that runs it whole, with no network: - the chart gates read a fixture tree, fetch through registry.py's own client and cache from fakeregistry, and render with the real helm; - the falco gate also reads its rule sets through that client, from OCI fakes standing in for ghcr.io; - validate-dashboards reads the shipped tree, with grafana.com answered at urlopen and each retry's wait recorded rather than slept; - check-image-vulnerabilities scans through a trivy stand-in on PATH that answers each image from scripted reports. Each class holds the clean run, a finding the run names, and each way a stage fails, with the status that failure earns: a pin the registry rules out is 1; a registry that stays down, or a render that fails, is 2. run.py raises the six floors to what the suite now reaches, and that of check-image-pins.py, whose inventory the image gate's run covers. The new floors are platform-crs (96, 91), dashboards (98, 97), render-addons (98, 95), log-volume (100, 97), falco (97, 91), image-vulnerabilities (98, 97) and image-pins (93, 88). reverify-tests.sh reverts one composition step in each orchestrator and requires the end-to-end test that holds it to fail. Co-authored-by: stxkxsbot <275011021+stxkxsbot@users.noreply.github.com> --- scripts/tests/reverify-tests.sh | 70 +++++ scripts/tests/run.py | 19 +- scripts/tests/test_dashboards.py | 239 ++++++++++++++ scripts/tests/test_falco_rule_floor.py | 253 ++++++++++++++- scripts/tests/test_image_vulnerabilities.py | 331 ++++++++++++++++++++ scripts/tests/test_log_volume_budget.py | 204 ++++++++++++ scripts/tests/test_platform_crs.py | 262 ++++++++++++++++ scripts/tests/test_render_addons.py | 290 ++++++++++++++++- 8 files changed, 1657 insertions(+), 11 deletions(-) diff --git a/scripts/tests/reverify-tests.sh b/scripts/tests/reverify-tests.sh index 56d5c21..0af3b35 100755 --- a/scripts/tests/reverify-tests.sh +++ b/scripts/tests/reverify-tests.sh @@ -306,6 +306,17 @@ rejects "pin: keep the quotes a YAML scalar carries" test_platform_crs \ test_a_quoted_revision_is_unquoted res $F +edit $F <<'PY' +import pathlib, sys +p = pathlib.Path(sys.argv[1]); s = p.read_text() +m = s.replace(" missed = sorted(candidates - reached)\n", " missed: list[str] = []\n", 1) +assert m != s, "mutation did not land" +p.write_text(m) +PY +rejects "platform-crs run: pass a CR no schema reached as walked" test_platform_crs \ + test_a_cr_of_a_kind_the_chart_ships_no_schema_for_fails +res $F + F=scripts/validate-dashboards.py edit $F <<'PY' import pathlib, sys @@ -371,6 +382,17 @@ rejects "offline verdict: report nothing, whatever the tree holds" test_dashboar test_every_detection_is_reported_from_one_pass res $F +edit $F <<'PY' +import pathlib, sys +p = pathlib.Path(sys.argv[1]); s = p.read_text() +m = s.replace(" if json.loads(f'\"{expected}\"') != name:\n", " if False:\n", 1) +assert m != s, "mutation did not land" +p.write_text(m) +PY +rejects "dashboards run: compare no pinned title with the board's" test_dashboards \ + test_an_id_resolving_to_another_board_fails_naming_both_titles +res $F + F=scripts/render-addons.py edit $F <<'PY' import pathlib, sys @@ -519,6 +541,18 @@ rejects "stale skips: take an archive the chart cache holds for a fetch" test_re test_an_archive_left_in_the_chart_cache_is_no_stale_skip res $F +edit $F <<'PY' +import pathlib, sys +p = pathlib.Path(sys.argv[1]); s = p.read_text() +m = s.replace(" ok, msg = render(u, env, objects)\n", " ok, msg = render(u, env, None)\n", 1) +assert m != s, "mutation did not land" +p.write_text(m) +PY +rejects "render-addons run: pool no render's cluster-scoped objects" test_render_addons \ + test_an_object_two_applications_install_fails_naming_both \ + test_a_catalog_rendering_one_owner_per_object_passes +res $F + F=scripts/check-policy-admission.py edit $F <<'PY' import pathlib, sys @@ -1966,6 +2000,17 @@ rejects "rulesfile: unpack a layer that is not an archive" test_falco_rule_floor test_a_layer_that_is_not_a_rule_set_archive_cannot_run res $F +edit $F <<'PY' +import pathlib, sys +p = pathlib.Path(sys.argv[1]); s = p.read_text() +m = s.replace(" is_read = reachable(path, files, dirs)\n", " is_read = True\n", 1) +assert m != s, "mutation did not land" +p.write_text(m) +PY +rejects "falco run: count a rule set read wherever it is written" test_falco_rule_floor \ + test_a_rule_set_installed_where_falco_does_not_read_fails +res $F + # A chart repository that could not be read says nothing about the controller # this catalog pins. Exiting 1 for it hands a network failure to whoever reads @@ -2256,6 +2301,19 @@ rejects "trivy: drop what a scan past its timeout had written" test_image_vulner test_a_scan_past_its_timeout_is_reported_with_what_trivy_had_said res $F +edit $F <<'PY' +import pathlib, sys +p = pathlib.Path(sys.argv[1]); s = p.read_text() +m = s.replace(" run_canary()\n if args.self_test:\n", " if args.self_test:\n", 1) +assert m != s, "mutation did not land" +p.write_text(m) +PY +rejects "image-vulnerabilities run: scan without the canary first" test_image_vulnerabilities \ + test_a_canary_reporting_nothing_cannot_run \ + test_the_self_test_scans_the_canary_alone +res $F + + F=scripts/check-renovate-coverage.py @@ -2360,6 +2418,18 @@ rejects "alert: accept a rule keyed on the edge counter" test_log_volume_budget test_a_rule_querying_both_still_fails_on_the_edge_counter res $F +edit $F <<'PY' +import pathlib, sys +p = pathlib.Path(sys.argv[1]); s = p.read_text() +m = s.replace(" for problem in problems:\n fail(problem)\n", " del problems\n", 1) +assert m != s, "mutation did not land" +p.write_text(m) +PY +rejects "log-volume run: drop each environment's problems" test_log_volume_budget \ + test_an_environment_whose_cutoff_falls_to_the_alert_fails_naming_it \ + test_retention_the_render_turns_off_fails +res $F + # The harness layer. controls.py excuses four executables from a positive # control on the grounds that each asserts its own outcome when it runs, and # these revert the reader that decides whether anything runs them. diff --git a/scripts/tests/run.py b/scripts/tests/run.py index e9d042b..b1fcf27 100755 --- a/scripts/tests/run.py +++ b/scripts/tests/run.py @@ -253,16 +253,17 @@ # Every gate that reads a catalog chart reads what this renders, so a # branch no test reaches here is a render nothing proves. "scripts/catalog.py": (100, 100), - # The control-exempt gates. Their floors are what keeps the verdict half - # covered after the module that covers it is edited. - "scripts/check-platform-crs.py": (51, 51), - "scripts/validate-dashboards.py": (52, 49), - "scripts/render-addons.py": (67, 56), - "scripts/check-log-volume-budget.py": (65, 59), - "scripts/check-falco-rule-floor.py": (58, 33), + # The control-exempt gates. Six of them read a registry or grafana.com, and + # each one's test module runs its orchestrator end to end against fakes + # (TheGateRunWhole), so these floors hold the run as well as the verdict. + "scripts/check-platform-crs.py": (96, 91), + "scripts/validate-dashboards.py": (98, 97), + "scripts/render-addons.py": (98, 95), + "scripts/check-log-volume-budget.py": (100, 97), + "scripts/check-falco-rule-floor.py": (97, 91), "scripts/check-alert-severity-routes.py": (96, 90), - "scripts/check-image-vulnerabilities.py": (76, 70), - "scripts/check-image-pins.py": (91, 85), + "scripts/check-image-vulnerabilities.py": (98, 97), + "scripts/check-image-pins.py": (93, 88), # The half of the directory-size gate that decides the verdict. The rest is # `--sync`, `--live` and `--self-test`, which run against a clone. "scripts/check-directory-manifest-size.py": (68, 71), diff --git a/scripts/tests/test_dashboards.py b/scripts/tests/test_dashboards.py index 993ad1c..45897b6 100644 --- a/scripts/tests/test_dashboards.py +++ b/scripts/tests/test_dashboards.py @@ -12,6 +12,10 @@ writes `$name`. TEMPLATE_VAR carries all four of Grafana's spellings and each is exercised here; check_local_dashboards carries a floor that fails when the whole corpus declares variables and references none. + +TheGateRunWhole runs the gate end to end over the shipped tree with grafana.com +answered by a fake at urlopen, so every pinned id is resolved, its board's title +compared and its revision read without the network. """ from __future__ import annotations @@ -20,11 +24,14 @@ import io import json import pathlib +import re import tempfile import textwrap import unittest +from collections.abc import Mapping from unittest import mock +import fakeregistry as fake from gateloader import load gate = load("validate-dashboards") @@ -454,5 +461,237 @@ def test_a_run_that_reads_everything_returns_its_own_status(self): self.assertEqual(gate.entry(), 1) +class GrafanaCom: + """grafana.com's dashboard API as the gate reads it, for the boards given. + + Each board answers its revisions, its metadata naming it and its latest + revision, and that revision's download carrying its panels. An id with no + board, a revision that is not the board's, and the metadata or download of + a board marking it False, answer 404 as grafana.com does; `down` answers + every request 503. + """ + + PATH = re.compile(rf"{re.escape(gate.API)}/(\d+)(/revisions(?:/(\d+)/download)?)?") + + def __init__(self, boards: dict[int, dict]) -> None: + self.boards = boards + self.down = False + self.urls: list[str] = [] + + def urlopen(self, req, timeout=None): + url = req.full_url + self.urls.append(url) + if self.down: + raise fake.http_error(url, 503) + match = self.PATH.fullmatch(url) + board = self.boards.get(int(match.group(1))) if match else None + if match is None or board is None: + raise fake.http_error(url, 404) + if match.group(2) is None and board.get("metadata", True): + body = {"name": board["name"], "revision": board["revision"]} + elif match.group(2) is None: + raise fake.http_error(url, 404) + elif match.group(3) is None: + body = {"items": [{"revision": board["revision"]}]} + elif int(match.group(3)) == board["revision"] and board.get("downloadable", True): + body = {"panels": board["panels"]} + else: + raise fake.http_error(url, 404) + return fake.served(json.dumps(body).encode()) + + +class TheGateRunWhole(unittest.TestCase): + """entry() over the shipped tree, with grafana.com answered by GrafanaCom. + + The extractors above hold the offline half. These hold the run: every + pinned id is asked for its revisions, its metadata and its latest revision, + each answer reaches the check it decides, and a grafana.com that never + answers is could-not-run after every retry rather than a dead catalog. + """ + + def setUp(self): + self.refs = gate.discover(ROOT) + self.grafana = GrafanaCom( + { + gnet_id: { + "name": json.loads(f'"{expected}"'), + "revision": 7, + "panels": [{"title": "Requests", "type": "timeseries"}], + } + for gnet_id, _, expected in self.refs + } + ) + self.waits: list[float] = [] + for patch in ( + mock.patch.object(gate.urllib.request, "urlopen", self.grafana.urlopen), + mock.patch.object(gate.time, "sleep", self.waits.append), + mock.patch.object(gate.sys, "argv", ["validate-dashboards.py"]), + ): + patch.start() + self.addCleanup(patch.stop) + + def run_gate(self): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + status = gate.entry() + return status, out.getvalue(), err.getvalue() + + def first(self): + gnet_id, path, _ = self.refs[0] + return gnet_id, path.relative_to(ROOT) + + def test_every_pin_resolving_to_its_own_board_passes(self): + status, out, err = self.run_gate() + self.assertEqual(status, 0, out + err) + self.assertGreaterEqual(len(self.refs), gate.MIN_DASHBOARD_REFS) + self.assertIn(f"all {len(self.refs)} grafana.com dashboards exist", out) + self.assertEqual( + len(self.grafana.urls), + 3 * len(self.refs), + "an id was not asked for its revisions, its metadata and its download", + ) + self.assertEqual(self.waits, []) + + def test_an_id_grafana_com_no_longer_has_fails_naming_it(self): + gnet_id, rel = self.first() + del self.grafana.boards[gnet_id] + status, out, _ = self.run_gate() + self.assertEqual(status, 1, out) + self.assertIn("FAIL — dead grafana.com dashboard id(s):", out) + self.assertIn(f"{gnet_id} ({rel}) /revisions -> HTTP 404", out) + + def test_an_id_resolving_to_another_board_fails_naming_both_titles(self): + gnet_id, rel = self.first() + self.grafana.boards[gnet_id]["name"] = "AKA SNMP Network" + status, out, _ = self.run_gate() + self.assertEqual(status, 1, out) + self.assertIn("FAIL — grafana.com id(s) that resolve to a different dashboard:", out) + self.assertIn(f"{gnet_id} ({rel}) annotation says", out) + self.assertIn('grafana.com says "AKA SNMP Network"', out) + + def test_a_board_carrying_legacy_alert_panels_fails(self): + gnet_id, rel = self.first() + self.grafana.boards[gnet_id]["panels"] = [ + {"title": "Requests", "type": "timeseries"}, + {"title": "Errors", "type": "graph", "alert": {"name": "errors high"}}, + ] + status, out, _ = self.run_gate() + self.assertEqual(status, 1, out) + self.assertIn("FAIL — dashboard(s) carrying legacy panel `alert` blocks:", out) + self.assertIn(f"{gnet_id} ({rel})", out) + self.assertIn("1 alert panel(s): Errors", out) + + def test_a_revision_that_cannot_be_downloaded_is_dead(self): + gnet_id, rel = self.first() + self.grafana.boards[gnet_id]["downloadable"] = False + status, out, _ = self.run_gate() + self.assertEqual(status, 1, out) + self.assertIn(f"{gnet_id} ({rel}) rev 7 download -> HTTP 404", out) + + def test_a_grafana_com_that_stays_down_cannot_run_after_every_retry(self): + self.grafana.down = True + gnet_id, _ = self.first() + status, out, err = self.run_gate() + self.assertEqual(status, gate.gatelib.CANNOT_RUN, out + err) + self.assertIn( + f"Cannot run: {gate.API}/{gnet_id}/revisions: unreachable after {gate.RETRIES} " + f"attempts (HTTP 503)", + err, + ) + self.assertEqual(self.waits, [gate.BACKOFF * n for n in range(1, gate.RETRIES)]) + self.assertNotIn("FAIL", out) + + def test_metadata_grafana_com_will_not_serve_is_dead(self): + gnet_id, rel = self.first() + self.grafana.boards[gnet_id]["metadata"] = False + status, out, _ = self.run_gate() + self.assertEqual(status, 1, out) + self.assertIn(f"{gnet_id} ({rel}) metadata -> HTTP 404", out) + + def test_a_dead_id_and_a_legacy_board_are_each_reported(self): + (dead, dead_path, _), (old, old_path, _) = self.refs[:2] + del self.grafana.boards[dead] + self.grafana.boards[old]["panels"] = [{"title": "Errors", "alert": {"name": "x"}}] + status, out, _ = self.run_gate() + self.assertEqual(status, 1, out) + self.assertIn(f"{dead} ({dead_path.relative_to(ROOT)}) /revisions -> HTTP 404", out) + self.assertIn(f"{old} ({old_path.relative_to(ROOT)})", out) + self.assertLess(out.index("FAIL — dead"), out.index("FAIL — dashboard(s) carrying legacy")) + + def tree(self, pins: Mapping[int, str | None], *, local=None): + """A root wiring one datasource, a GrafanaDashboard pinning each of `pins` + ({id: the title its annotation records, or None for no annotation}), and, + when given, a locally-authored board carrying `local` as its JSON.""" + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + root = pathlib.Path(tmp.name) + base = root / "dashboards" / "base" + (base / "datasources").mkdir(parents=True) + (base / "kustomization.yaml").write_text("resources:\n - datasources/managed-loki.yaml\n") + (base / "datasources" / "managed-loki.yaml").write_text( + "spec:\n datasource:\n uid: managed-loki\n" + ) + for gnet_id, title in pins.items(): + note = ( + f' annotations:\n nanohype.dev/grafana-com-title: "{title}"\n' if title else "" + ) + (base / f"board-{gnet_id}.yaml").write_text( + f"kind: GrafanaDashboard\nmetadata:\n name: board-{gnet_id}\n{note}" + f"spec:\n grafanaCom:\n id: {gnet_id}\n" + ) + if local is not None: + payload = "\n".join(" " + line for line in json.dumps(local, indent=1).splitlines()) + (base / "local.yaml").write_text( + f"kind: GrafanaDashboard\nspec:\n json: |\n{payload}\n" + ) + self.grafana.boards = { + gnet_id: {"name": title or "Untitled", "revision": 7, "panels": []} + for gnet_id, title in pins.items() + } + return root + + def run_tree(self, root): + with mock.patch.object(gate.sys, "argv", ["validate-dashboards.py", "--root", str(root)]): + return self.run_gate() + + def test_a_tree_pinning_fewer_ids_than_the_floor_cannot_run(self): + root = self.tree({1001: "One", 1002: "Two", 1003: "Three"}) + status, out, _ = self.run_tree(root) + self.assertEqual(status, gate.gatelib.CANNOT_RUN, out) + self.assertIn( + f"found 3 grafanaCom.id reference(s), below the floor of {gate.MIN_DASHBOARD_REFS}", out + ) + self.assertEqual(self.grafana.urls, []) + + def test_a_tree_pinning_no_id_cannot_run(self): + status, out, _ = self.run_tree(self.tree({})) + self.assertEqual(status, gate.gatelib.CANNOT_RUN, out) + self.assertIn("no grafanaCom.id references found", out) + + def test_a_pin_recording_no_title_fails(self): + pins: dict[int, str | None] = { + 1000 + n: f"Board {n}" for n in range(gate.MIN_DASHBOARD_REFS) + } + pins[1000] = None + status, out, _ = self.run_tree(self.tree(pins)) + self.assertEqual(status, 1, out) + self.assertIn( + "1000 (dashboards/base/board-1000.yaml) has no nanohype.dev/grafana-com-title annotation", + out, + ) + + def test_a_local_board_naming_an_unwired_datasource_fails(self): + pins = {1000 + n: f"Board {n}" for n in range(gate.MIN_DASHBOARD_REFS)} + root = self.tree(pins, local={"panels": [{"datasource": "athena-cur"}]}) + status, out, _ = self.run_tree(root) + self.assertEqual(status, 1, out) + self.assertIn("Locally-authored dashboard problems:", out) + self.assertIn("panel datasource 'athena-cur' is not wired", out) + self.assertIn( + f"Validating {gate.MIN_DASHBOARD_REFS} grafana.com dashboard reference(s)", out + ) + self.assertNotIn("✓", out) + + if __name__ == "__main__": unittest.main() diff --git a/scripts/tests/test_falco_rule_floor.py b/scripts/tests/test_falco_rule_floor.py index 923e5bb..e4ce1a8 100644 --- a/scripts/tests/test_falco_rule_floor.py +++ b/scripts/tests/test_falco_rule_floor.py @@ -8,7 +8,9 @@ Everything here is offline. The rule-set reader is exercised against a scripted registry (scripts/tests/fakeregistry.py) through registry.py's client, the same -path a run against ghcr.io takes. +path a run against ghcr.io takes. TheGateRunWhole runs main() the same way end +to end: a fixture tree, a chart and rule sets served through that client, and the +real helm rendering the chart. """ import contextlib @@ -16,14 +18,22 @@ import http.client import io import json +import pathlib +import shutil import tarfile +import tempfile import unittest +from unittest import mock import fakeregistry as fake +import registry +import yaml from gateloader import load gate = load("check-falco-rule-floor") +HAS_HELM = shutil.which("helm") is not None + class PathIsRead(unittest.TestCase): """falcoctl writes to the root of the shared dir; Falco reads a listed set. @@ -317,5 +327,246 @@ def test_an_artifact_that_is_not_a_rulesfile_installs_no_rules(self): self.assertNotIn(f"{self.BASE}/blobs/{self.digest}", self.transport.urls()) +# A chart that renders what the upstream one renders for this gate: Falco's +# ConfigMap and falcoctl's, each built here from the values that configure it. +FALCO_CONFIGMAPS = """\ +apiVersion: v1 +kind: ConfigMap +metadata: + name: falco +data: + falco.yaml: | +{{ toYaml .Values.falco | indent 4 }} +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: falco-falcoctl +data: + falcoctl.yaml: | +{{ toYaml .Values.falcoctl.config | indent 4 }} +""" + +PLUGIN_CONFIG = "application/vnd.cncf.falco.plugin.config.v1+json" + + +def rules(count: int, priority: str = "INFO") -> str: + return yaml.safe_dump( + [ + {"rule": f"rule {i}", "priority": priority, "condition": "evt.num > 0"} + for i in range(count) + ] + ) + + +@unittest.skipUnless(HAS_HELM, "helm is not on PATH") +class TheGateRunWhole(unittest.TestCase): + """main() over a fixture tree, its chart and rule sets read by the real client. + + The tests above hold each decision apart. These hold the run: every + environment's render is read, each installed ref is resolved on the registry + and counted against what that environment's rules_files reads, and each way + a stage fails ends the run with the status that failure earns. + """ + + CHARTS = "https://charts.example/falcosecurity" + VERSION = "7.0.0" + RULES = "falcosecurity/rules/falco-rules" + SANDBOX = "falcosecurity/rules/falco-sandbox-rules" + PLUGIN = "falcosecurity/plugins/plugin/k8smeta" + + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = pathlib.Path(tmp.name) + self.addon = self.root / "addons" / "security" / "falco" + self.addon.mkdir(parents=True) + self.appset = self.root / "applicationsets" / "addons-security.yaml" + self.appset.parent.mkdir() + self.appset.write_text( + yaml.safe_dump( + { + "kind": "ApplicationSet", + "spec": { + "generators": [ + { + "matrix": { + "generators": [ + {"clusters": {}}, + { + "list": { + "elements": [ + { + "appName": "falco", + "chart": "falco", + "chartRepo": self.CHARTS, + "chartVersion": self.VERSION, + } + ] + } + }, + ] + } + } + ] + }, + } + ) + ) + self.values( + "values.yaml", + priority="info", + rules_files=["/etc/falco/falco_rules.yaml", "/etc/falco/rules.d"], + refs=["falco-rules:4", f"ghcr.io/{self.PLUGIN}:0.3"], + ) + (self.addon / "values-development.yaml").write_text("{}\n") + (self.addon / "values-production.yaml").write_text("{}\n") + + chart = fake.chart_archive( + "falco", + self.VERSION, + {"configmaps.yaml": FALCO_CONFIGMAPS}, + values="falco: {}\nfalcoctl:\n config: {}\n", + ) + self.charts = fake.ChartRepository(self.CHARTS, {("falco", self.VERSION): chart}) + self.rule_sets = { + self.RULES: self.oci(self.RULES, "4", {"falco_rules.yaml": rules(90)}), + self.SANDBOX: self.oci(self.SANDBOX, "4", {"falco-sandbox_rules.yaml": rules(40)}), + self.PLUGIN: fake.OciRegistry( + "ghcr.io", self.PLUGIN, "0.3", {}, content=b"plugin", media_type=PLUGIN_CONFIG + ), + } + routes = {self.CHARTS: self.charts, fake.OciRegistry.REALM: self.rule_sets[self.RULES]} + routes.update({f"https://ghcr.io/v2/{repo}/": reg for repo, reg in self.rule_sets.items()}) + self.hosts = fake.serve(self, registry, routes, self.root / "cache") + self.failures: list[str] = [] + for patch in ( + mock.patch.object(gate, "ROOT", self.root), + mock.patch.object(gate, "APPSET", self.appset), + mock.patch.object(gate, "ADDON", self.addon), + mock.patch.object(gate, "failures", self.failures), + ): + patch.start() + self.addCleanup(patch.stop) + + @staticmethod + def oci(repo, tag, files): + return fake.OciRegistry( + "ghcr.io", repo, tag, {}, content=_rules_layer(files), media_type=gate.RULESFILE_CONFIG + ) + + def values(self, name, *, priority=None, rules_files=None, refs=None): + falco = {} + if priority is not None: + falco["priority"] = priority + if rules_files is not None: + falco["rules_files"] = rules_files + doc = {"falco": falco} + if refs is not None: + doc["falcoctl"] = {"config": {"artifact": {"install": {"refs": refs}}}} + (self.addon / name).write_text(yaml.safe_dump(doc)) + + def run_gate(self): + out = io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(out): + try: + rc = gate.main() + except SystemExit as exc: + rc = exc.code + return rc, out.getvalue() + + def test_a_tree_that_loads_every_rule_set_it_installs_passes(self): + rc, out = self.run_gate() + self.assertEqual(rc, 0, out) + self.assertIn("falco rule floor OK", out) + self.assertIn("loaded/installed development 90/90, production 90/90", out) + self.assertIn(f"{self.CHARTS}/falco-{self.VERSION}.tgz", self.hosts.urls) + self.assertNotIn( + f"https://ghcr.io/v2/{self.PLUGIN}/blobs/{self.rule_sets[self.PLUGIN].content_digest}", + self.hosts.urls, + "the plugin's layer was read as though it carried rules", + ) + + def test_a_rule_set_installed_where_falco_does_not_read_fails(self): + self.values("values-production.yaml", refs=["falco-rules:4", "falco-sandbox-rules:4"]) + rc, out = self.run_gate() + self.assertEqual(rc, 1, out) + self.assertIn( + "addons/security/falco/values-production.yaml: ref 'falco-sandbox-rules:4' installs " + "/etc/falco/falco-sandbox_rules.yaml, which falco.rules_files does not name", + out, + ) + self.assertNotIn("values-development.yaml", out) + + def test_a_priority_floor_that_drops_rules_below_the_floor_fails(self): + self.values("values-development.yaml", priority="warning") + rc, out = self.run_gate() + self.assertEqual(rc, 1, out) + self.assertIn( + "values-development.yaml: falco.priority is 'warning', stricter than 'info'", out + ) + self.assertIn( + "values-development.yaml: 0 rule(s) load at priority 'warning', below the floor of 85. " + "90 are installed on disk.", + out, + ) + + def test_a_ref_the_registry_does_not_have_is_a_finding(self): + self.values("values-production.yaml", refs=["falco-rules:99"]) + rc, out = self.run_gate() + self.assertEqual(rc, 1, out) + self.assertIn("ref 'falco-rules:99' does not resolve", out) + self.assertIn("values-production.yaml: none of the 1 installed ref(s) is a rule set", out) + + def test_a_registry_that_stays_down_cannot_run(self): + reg = self.rule_sets[self.RULES] + reg_call = reg.__call__ + + def down(req): + if req.full_url.startswith(f"{reg.base}/manifests/"): + return fake.http_error(req.full_url, 503) + return reg_call(req) + + self.hosts.routes[f"https://ghcr.io/v2/{self.RULES}/"] = down + rc, out = self.run_gate() + self.assertEqual(rc, gate.gatelib.CANNOT_RUN, out) + self.assertIn(f"Cannot run: ghcr.io/{self.RULES}:4 could not be read", out) + self.assertNotIn("FAIL", out) + + def test_a_tree_with_no_environment_fails(self): + for env in ("development", "production"): + (self.addon / f"values-{env}.yaml").unlink() + rc, out = self.run_gate() + self.assertEqual(rc, 1, out) + self.assertIn( + "addons/security/falco carries no values-.yaml, so this gate examined no environment", + out, + ) + + def test_a_priority_falco_does_not_know_fails_and_counts_nothing(self): + self.values("values-development.yaml", priority="urgent") + rc, out = self.run_gate() + self.assertEqual(rc, 1, out) + self.assertIn("values-development.yaml: the render sets falco.priority to 'urgent'", out) + self.assertNotIn("values-development.yaml: 0 rule(s) load", out) + + def test_an_environment_installing_no_refs_fails(self): + self.values("values-production.yaml", refs=[]) + rc, out = self.run_gate() + self.assertEqual(rc, 1, out) + self.assertIn("values-production.yaml: the rendered falcoctl config installs no refs", out) + + def test_a_render_with_no_falcoctl_configmap_cannot_run(self): + self.charts.charts[("falco", self.VERSION)] = fake.chart_archive( + "falco", + self.VERSION, + {"configmaps.yaml": FALCO_CONFIGMAPS.split("---")[0]}, + values="falco: {}\n", + ) + rc, out = self.run_gate() + self.assertEqual(rc, gate.gatelib.CANNOT_RUN, out) + self.assertIn("the development render produced no ConfigMap carrying falcoctl.yaml", out) + + if __name__ == "__main__": unittest.main() diff --git a/scripts/tests/test_image_vulnerabilities.py b/scripts/tests/test_image_vulnerabilities.py index 59afe20..9774366 100644 --- a/scripts/tests/test_image_vulnerabilities.py +++ b/scripts/tests/test_image_vulnerabilities.py @@ -14,6 +14,9 @@ invocation with a status and what trivy writes, so what the gate does with a registry refusing it for now, with any other failure, and with what trivy said about either is decided here; a real scan is exercised by running the gate. +TheGateRunWhole runs main() end to end: a fixture catalog whose charts +fakeregistry serves through registry.py's own client, rendered by the real helm, +and a trivy stand-in on PATH answering each image it is asked to scan. """ from __future__ import annotations @@ -22,19 +25,26 @@ import datetime import io import json +import os import pathlib +import shutil import subprocess +import sys import tempfile import types import unittest from typing import Any from unittest import mock +import fakeregistry as fake +import registry import yaml from gateloader import load gate = load("check-image-vulnerabilities") +HAS_HELM = shutil.which("helm") is not None + ROOT = pathlib.Path(__file__).resolve().parent.parent.parent @@ -600,5 +610,326 @@ def test_only_the_end_of_a_long_stderr_is_quoted(self): self.assertEqual(lines[-1], f" line {gate.STDERR_LINES + 4}") +# trivy, answering `trivy image ... ` with the next of the answers scripted +# for in answers.json, or with the ones under "*", and recording each call. +TRIVY_STANDIN = """\ +#!PYTHON +import json, pathlib, sys +work = pathlib.Path(WORK) +ref = sys.argv[-1] +with (work / "calls").open("a") as calls: + calls.write(json.dumps(sys.argv[1:]) + "\\n") +asked = [json.loads(line)[-1] for line in (work / "calls").read_text().splitlines()] +answers = json.loads((work / "answers.json").read_text()) +steps = answers.get(ref) or answers["*"] +rc, out, err = steps[min(asked.count(ref), len(steps)) - 1] +sys.stdout.write(out) +sys.stderr.write(err) +sys.exit(rc) +""" + +DEPLOYMENT = """\ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ .Release.Name }} +spec: + template: + spec: + containers: + - name: main + image: {{ .Values.image }} +""" + + +def report(*vulns) -> str: + return json.dumps({"Results": [{"Vulnerabilities": list(vulns)}]}) + + +def vuln(cve, package, severity="CRITICAL"): + return { + "VulnerabilityID": cve, + "PkgName": package, + "InstalledVersion": "1.0", + "FixedVersion": "1.1", + "Severity": severity, + } + + +@unittest.skipUnless(HAS_HELM, "helm is not on PATH") +class TheGateRunWhole(unittest.TestCase): + """main() over a fixture catalog, every image it renders scanned by a trivy stand-in. + + The verdict and the scan are held above apart. These hold the run: the + canary is scanned before anything is believed, the population is every + image the catalog's charts render, each image's findings reach the verdict + against the advisories, and each way a stage falls short ends the run with + the status that shortfall earns. + """ + + WIDGETS = "https://charts.example/widgets" + GADGETS = ("registry.example", "charts/gadget") + WIDGET_IMAGE = "registry.example/widget:1.0.0" + GADGET_IMAGE = "registry.example/gadget@sha256:" + "b" * 64 + + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + base = pathlib.Path(tmp.name) + self.root = base / "tree" + self.appsets = self.root / "applicationsets" + self.appsets.mkdir(parents=True) + self.write_appset() + for name, image in (("widget", self.WIDGET_IMAGE), ("gadget", self.GADGET_IMAGE)): + addon = self.root / "addons" / "demo" / name + addon.mkdir(parents=True) + (addon / "values.yaml").write_text(yaml.safe_dump({"image": image})) + self.advisories = self.root / "image-advisories.yaml" + self.advise() + + self.widgets = fake.ChartRepository( + self.WIDGETS, + { + ("widget", "1.0.0"): fake.chart_archive( + "widget", "1.0.0", {"deployment.yaml": DEPLOYMENT} + ) + }, + ) + gadgets = fake.OciRegistry( + *self.GADGETS, + "2.0.0", + {"name": "gadget", "version": "2.0.0"}, + content=fake.chart_archive("gadget", "2.0.0", {"deployment.yaml": DEPLOYMENT}), + ) + fake.serve( + self, + registry, + { + self.WIDGETS: self.widgets, + f"https://{self.GADGETS[0]}/v2/{self.GADGETS[1]}/": gadgets, + fake.OciRegistry.REALM: gadgets, + }, + base / "cache", + ) + + self.work = base / "trivy" + (self.work / "bin").mkdir(parents=True) + standin = self.work / "bin" / "trivy" + standin.write_text( + TRIVY_STANDIN.replace("PYTHON", sys.executable).replace("WORK", repr(str(self.work))) + ) + standin.chmod(0o755) + (self.work / "calls").write_text("") + self.answer("*", (0, report(), "")) + self.answer(gate.CANARY, (0, report(vuln("CVE-2019-14697", "musl")), "")) + self.waits: list[float] = [] + self.failures: list[str] = [] + for patch in ( + mock.patch.dict( + os.environ, {"PATH": f"{self.work / 'bin'}{os.pathsep}{os.environ['PATH']}"} + ), + mock.patch.object(gate, "ROOT", self.root), + mock.patch.object(gate, "ADVISORIES", self.advisories), + mock.patch.object(gate, "failures", self.failures), + mock.patch.object(gate.image_pins, "ROOT", self.root), + mock.patch.object(gate.image_pins.render_addons, "APPSET_DIR", self.appsets), + mock.patch.dict(gate.image_pins.render_addons.SKIP_CHARTS, clear=True), + # The catalog's own declarations name images its charts start or carry, + # and are held to what the catalog renders; the fixture renders none. + mock.patch.dict(gate.image_pins.CONTROLLER_IMAGES, clear=True), + mock.patch.dict(gate.image_pins.NOT_A_CONTAINER, clear=True), + mock.patch.dict(gate.image_pins.IMAGELESS_CHARTS, clear=True), + mock.patch.dict( + gate.scan.__kwdefaults__, {"sleep": self.waits.append, "jitter": lambda: 0.0} + ), + ): + patch.start() + self.addCleanup(patch.stop) + + def write_appset(self): + elements = [ + { + "appName": "widget", + "chart": "widget", + "chartRepo": self.WIDGETS, + "chartVersion": "1.0.0", + "path": "addons/demo/widget", + }, + { + "appName": "gadget", + "chart": "gadget", + "chartRepo": f"oci://{self.GADGETS[0]}/charts", + "chartVersion": "2.0.0", + "path": "addons/demo/gadget", + }, + ] + (self.appsets / "addons-demo.yaml").write_text( + yaml.safe_dump( + { + "kind": "ApplicationSet", + "spec": { + "generators": [ + { + "matrix": { + "generators": [ + {"clusters": {}}, + {"list": {"elements": elements}}, + ] + } + } + ], + "template": { + "spec": { + "sources": [ + { + "repoURL": "{{ .chartRepo }}", + "chart": "{{ .chart }}", + "targetRevision": "{{ .chartVersion }}", + "helm": {"valueFiles": ["$values/{{ .path }}/values.yaml"]}, + }, + {"repoURL": "https://git.example/eks-gitops", "ref": "values"}, + ] + } + }, + }, + } + ) + ) + + def advise(self, *entries): + self.advisories.write_text(yaml.safe_dump({"advisories": list(entries)})) + + def answer(self, ref, *steps): + path = self.work / "answers.json" + answers = json.loads(path.read_text()) if path.exists() else {} + answers[ref] = [list(step) for step in steps] + path.write_text(json.dumps(answers)) + + def scanned(self): + return [json.loads(line)[-1] for line in (self.work / "calls").read_text().splitlines()] + + def run_gate(self, *argv): + out = io.StringIO() + with ( + mock.patch.object(gate.sys, "argv", ["check-image-vulnerabilities.py", *argv]), + contextlib.redirect_stdout(out), + contextlib.redirect_stderr(out), + ): + try: + rc = gate.main() + except SystemExit as exc: + rc = exc.code + return rc, out.getvalue() + + def test_a_catalog_whose_images_carry_nothing_unacknowledged_passes(self): + rc, out = self.run_gate() + self.assertEqual(rc, 0, out) + self.assertIn("canary OK: 1 fixed CRITICAL finding(s)", out) + self.assertIn("image vulnerabilities OK: 2 image(s) scanned across 2 chart(s).", out) + self.assertEqual(self.scanned(), [gate.CANARY, self.GADGET_IMAGE, self.WIDGET_IMAGE]) + + def test_an_unacknowledged_critical_fails_naming_its_image(self): + self.answer(self.WIDGET_IMAGE, (0, report(vuln("CVE-2026-1", "openssl")), "")) + rc, out = self.run_gate() + self.assertEqual(rc, 1, out) + self.assertIn("1 problem(s) across 2 scanned image(s):", out) + self.assertIn("CVE-2026-1", out) + self.assertIn("registry.example/widget", out) + + def test_an_acknowledged_critical_passes_and_is_counted(self): + self.answer(self.WIDGET_IMAGE, (0, report(vuln("CVE-2026-1", "openssl")), "")) + self.advise( + advisory(cve="CVE-2026-1", package="openssl", images=("registry.example/widget",)) + ) + rc, out = self.run_gate() + self.assertEqual(rc, 0, out) + self.assertIn("1 fixed CRITICAL finding(s), every one acknowledged", out) + + def test_an_acknowledgement_no_scanned_image_carries_fails(self): + self.advise(advisory(cve="CVE-2026-9", package="zlib", images=("registry.example/gadget",))) + rc, out = self.run_gate() + self.assertEqual(rc, 1, out) + self.assertIn("CVE-2026-9", out) + + def test_a_canary_reporting_nothing_cannot_run(self): + self.answer(gate.CANARY, (0, report(), "")) + rc, out = self.run_gate() + self.assertEqual(rc, gate.gatelib.CANNOT_RUN, out) + self.assertIn("the canary returned no fixed CRITICAL findings", out) + self.assertEqual( + self.scanned(), [gate.CANARY], "images were scanned by a scanner that reports nothing" + ) + + def test_an_image_refused_for_now_is_scanned_again(self): + self.answer(self.GADGET_IMAGE, (1, "", THROTTLED), (0, report(), "")) + rc, out = self.run_gate() + self.assertEqual(rc, 0, out) + self.assertEqual(self.waits, [gate.SCAN_BACKOFF_SECONDS]) + self.assertEqual(self.scanned().count(self.GADGET_IMAGE), 2) + + def test_an_image_that_does_not_scan_cannot_run_naming_its_chart(self): + self.answer( + self.WIDGET_IMAGE, + (1, "", "FATAL\tDENIED: requested access to the resource is denied\n"), + ) + rc, out = self.run_gate() + self.assertEqual(rc, gate.gatelib.CANNOT_RUN, out) + self.assertIn(f" {self.WIDGET_IMAGE} (via widget)", out) + self.assertIn("DENIED: requested access to the resource is denied", out) + + def test_a_chart_that_does_not_render_cannot_run(self): + self.widgets.charts[("widget", "1.0.0")] = fake.chart_archive( + "widget", "1.0.0", {"deployment.yaml": "{{ .Values.missing.key }}\n"} + ) + rc, out = self.run_gate() + self.assertEqual(rc, gate.gatelib.CANNOT_RUN, out) + self.assertIn("charts that did not render contributed no images", out) + self.assertIn("addons/demo/widget", out) + self.assertEqual(self.scanned(), [gate.CANARY]) + + def test_a_reference_reaching_no_pod_template_cannot_run(self): + sidecar = "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: injected\ndata:\n sidecar: registry.example/sidecar:2.0.0\n" + self.widgets.charts[("widget", "1.0.0")] = fake.chart_archive( + "widget", "1.0.0", {"deployment.yaml": DEPLOYMENT, "sidecar.yaml": sidecar} + ) + rc, out = self.run_gate() + self.assertEqual(rc, gate.gatelib.CANNOT_RUN, out) + self.assertIn( + "image-shaped references that reach no pod template and are on no declaration", out + ) + self.assertIn( + "widget: registry.example/sidecar:2.0.0 is image-shaped and reaches no pod template", + out, + ) + self.assertEqual(self.scanned(), [gate.CANARY]) + + def test_a_chart_that_renders_no_image_cannot_run(self): + self.widgets.charts[("widget", "1.0.0")] = fake.chart_archive( + "widget", + "1.0.0", + {"cm.yaml": "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: only\n"}, + ) + rc, out = self.run_gate() + self.assertEqual(rc, gate.gatelib.CANNOT_RUN, out) + self.assertIn("the image population is smaller than the charts that rendered it", out) + self.assertIn("widget rendered and contributed no image", out) + + def test_list_prints_every_finding_and_blocks_nothing(self): + self.answer( + self.WIDGET_IMAGE, + (0, report(vuln("CVE-2026-1", "openssl"), vuln("CVE-2026-2", "curl", "HIGH")), ""), + ) + rc, out = self.run_gate("--list") + self.assertEqual(rc, 0, out) + self.assertIn(f"CRITICAL {self.WIDGET_IMAGE} CVE-2026-1 openssl 1.0 -> 1.1", out) + self.assertIn(f"HIGH {self.WIDGET_IMAGE} CVE-2026-2 curl 1.0 -> 1.1", out) + self.assertIn("2 fixed finding(s) at CRITICAL/HIGH across 2 image(s)", out) + + def test_the_self_test_scans_the_canary_alone(self): + rc, out = self.run_gate("--self-test") + self.assertEqual(rc, 0, out) + self.assertEqual(self.scanned(), [gate.CANARY]) + + if __name__ == "__main__": unittest.main() diff --git a/scripts/tests/test_log_volume_budget.py b/scripts/tests/test_log_volume_budget.py index 11e4377..aaeeb9d 100644 --- a/scripts/tests/test_log_volume_budget.py +++ b/scripts/tests/test_log_volume_budget.py @@ -12,6 +12,10 @@ The alert-reading half is exercised against fixture files rather than the shipped one: the shipped rule is a single sample of a shape with several failure modes, and the ones that matter are the shapes it does not have. + +TheGateRunWhole runs main() end to end without the network: a fixture tree, a +chart served by fakeregistry through registry.py's own client and cache, and the +real helm rendering it, so the stages are proven composed and not only apart. """ from __future__ import annotations @@ -19,15 +23,20 @@ import contextlib import io import pathlib +import shutil import tempfile import unittest from unittest import mock +import fakeregistry as fake +import registry import yaml from gateloader import load gate = load("check-log-volume-budget") +HAS_HELM = shutil.which("helm") is not None + REL = "addons/observability/loki/values-production.yaml" @@ -261,5 +270,200 @@ def test_the_shipped_alert_names_the_gauge_the_ingester_sets_every_tick(self): self.assertIsNotNone(threshold) +# A chart that renders what the upstream one renders for this gate: the Loki +# ConfigMap carrying config.yaml, here built from `loki.config` in the values. +LOKI_CONFIGMAP = """\ +apiVersion: v1 +kind: ConfigMap +metadata: + name: loki +data: + config.yaml: | +{{ toYaml .Values.loki.config | indent 4 }} +""" + + +@unittest.skipUnless(HAS_HELM, "helm is not on PATH") +class TheGateRunWhole(unittest.TestCase): + """main() over a fixture tree, its chart fetched by the real client and rendered by helm. + + Each stage has its own tests above. These hold the composition: the pin read + off the ApplicationSet is the chart fetched, every environment's values reach + the render, the verdict is per environment, and each way a stage can fail + ends the run with the status that failure earns. + """ + + REPO = "https://charts.example/grafana" + VERSION = "6.29.0" + + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = pathlib.Path(tmp.name) + self.addon = self.root / "addons" / "observability" / "loki" + self.addon.mkdir(parents=True) + self.appset = self.root / "applicationsets" / "addons-loki.yaml" + self.appset.parent.mkdir() + self.alert = self.root / "dashboards" / "base" / "alerting" / "loki-disk.yaml" + self.alert.parent.mkdir(parents=True) + self.write_appset(self.VERSION) + self.alert.write_text( + yaml.safe_dump( + { + "apiVersion": "grafana.integreatly.org/v1beta1", + "kind": "GrafanaAlertRuleGroup", + "spec": {"rules": [fill_rule(threshold=0.8)]}, + } + ) + ) + self.values("values.yaml", config(cutoff=0.9, retention="720h")) + self.values("values-development.yaml", {}) + self.values("values-production.yaml", {"limits_config": {"retention_period": "2160h"}}) + + self.repo = fake.ChartRepository( + self.REPO, + { + ("loki", self.VERSION): fake.chart_archive( + "loki", + self.VERSION, + {"configmap.yaml": LOKI_CONFIGMAP}, + values="loki:\n config: {}\n", + ) + }, + ) + self.cache = self.root / "cache" + self.hosts = fake.serve(self, registry, {self.REPO: self.repo}, self.cache) + self.failures: list[str] = [] + for patch in ( + mock.patch.object(gate, "ROOT", self.root), + mock.patch.object(gate, "APPSET", self.appset), + mock.patch.object(gate, "ADDON", self.addon), + mock.patch.object(gate, "ALERT", self.alert), + mock.patch.object(gate, "failures", self.failures), + ): + patch.start() + self.addCleanup(patch.stop) + + def write_appset(self, version): + self.appset.write_text( + yaml.safe_dump( + { + "apiVersion": "argoproj.io/v1alpha1", + "kind": "ApplicationSet", + "metadata": {"name": "addons-loki"}, + "spec": { + "template": { + "spec": { + "sources": [ + { + "repoURL": self.REPO, + "chart": "loki", + "targetRevision": version, + }, + {"repoURL": "https://git.example/eks-gitops", "ref": "values"}, + ] + } + } + }, + } + ) + ) + + def values(self, name, loki_config): + (self.addon / name).write_text(yaml.safe_dump({"loki": {"config": loki_config}})) + + def run_gate(self): + out = io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(out): + try: + rc = gate.main() + except SystemExit as exc: + rc = exc.code + return rc, out.getvalue() + + def test_a_tree_whose_alert_leads_every_cutoff_passes(self): + rc, out = self.run_gate() + self.assertEqual(rc, 0, out) + self.assertIn("log-volume budget OK: 2 environment(s)", out) + self.assertIn("fires at 0.8", out) + self.assertIn("(2 checked)", out) + self.assertEqual( + self.hosts.urls, + [f"{self.REPO}/index.yaml", f"{self.REPO}/loki-{self.VERSION}.tgz"], + "the chart fetched is not the one the ApplicationSet pins", + ) + + def test_a_second_run_reads_the_chart_from_the_cache(self): + self.assertEqual(self.run_gate()[0], 0) + asked = list(self.hosts.urls) + rc, out = self.run_gate() + self.assertEqual(rc, 0, out) + self.assertEqual(self.hosts.urls, asked, "a cached, intact chart was fetched again") + + def test_an_environment_whose_cutoff_falls_to_the_alert_fails_naming_it(self): + self.values("values-production.yaml", {"ingester": {"wal": {"disk_full_threshold": 0.8}}}) + rc, out = self.run_gate() + self.assertEqual(rc, 1, out) + self.assertIn( + "FAIL addons/observability/loki/values-production.yaml: the fill alert fires at 0.8 " + "but ingestion stops at 0.8", + out, + ) + self.assertNotIn("values-development.yaml", out) + + def test_retention_the_render_turns_off_fails(self): + self.values("values-development.yaml", {"compactor": {"retention_enabled": False}}) + rc, out = self.run_gate() + self.assertEqual(rc, 1, out) + self.assertIn("values-development.yaml: compactor.retention_enabled is not true", out) + + def test_a_tree_with_no_environment_fails(self): + for env in ("development", "production"): + (self.addon / f"values-{env}.yaml").unlink() + rc, out = self.run_gate() + self.assertEqual(rc, 1, out) + self.assertIn( + "FAIL addons/observability/loki carries no values-.yaml, so this gate " + "examined no environment", + out, + ) + + def test_a_pin_the_repository_does_not_list_is_a_finding(self): + self.write_appset("6.30.0") + rc, out = self.run_gate() + self.assertEqual(rc, 1, out) + self.assertIn("answered, and its answer rules the pin out", out) + self.assertIn("lists no loki 6.30.0", out) + + def test_a_repository_that_stays_down_cannot_run(self): + self.repo.answer = lambda req: fake.http_error(req.full_url, 503) + rc, out = self.run_gate() + self.assertEqual(rc, gate.gatelib.CANNOT_RUN, out) + self.assertIn( + "Cannot run: loki 6.29.0 from https://charts.example/grafana could not be read", out + ) + self.assertTrue(self.hosts.waits, "a 503 was not retried") + self.assertNotIn("FAIL", out) + + def test_a_chart_helm_cannot_render_cannot_run(self): + self.repo.charts[("loki", self.VERSION)] = fake.chart_archive( + "loki", self.VERSION, {"configmap.yaml": "{{ .Values.missing.key }}\n"} + ) + rc, out = self.run_gate() + self.assertEqual(rc, gate.gatelib.CANNOT_RUN, out) + self.assertIn("Cannot run: helm could not render loki for development.", out) + + def test_a_render_without_the_loki_configmap_cannot_run(self): + self.repo.charts[("loki", self.VERSION)] = fake.chart_archive( + "loki", + self.VERSION, + {"configmap.yaml": LOKI_CONFIGMAP.replace("name: loki", "name: other")}, + values="loki:\n config: {}\n", + ) + rc, out = self.run_gate() + self.assertEqual(rc, gate.gatelib.CANNOT_RUN, out) + self.assertIn("the development render produced no loki ConfigMap carrying config.yaml", out) + + if __name__ == "__main__": unittest.main() diff --git a/scripts/tests/test_platform_crs.py b/scripts/tests/test_platform_crs.py index 12529bb..5f966fd 100644 --- a/scripts/tests/test_platform_crs.py +++ b/scripts/tests/test_platform_crs.py @@ -12,6 +12,8 @@ The schemas here are written inline rather than fetched, so the assertions are about the walk rather than about whatever the pinned chart currently ships. +TheGateRunWhole runs the gate end to end the same way: a fixture tree and a +fixture operator chart, served by fakeregistry through registry.py's own client. """ from __future__ import annotations @@ -21,7 +23,11 @@ import pathlib import tempfile import unittest +from unittest import mock +import fakeregistry as fake +import registry +import yaml from gateloader import load gate = load("check-platform-crs") @@ -401,5 +407,261 @@ def test_a_quoted_revision_is_unquoted(self): self.assertEqual(gate.pinned_chart_version(), "0.6.7") +GROUP = "agents.nanohype.dev" + + +def crd(kind: str, spec: dict) -> str: + """A CustomResourceDefinition for `kind` whose v1alpha1 spec schema is `spec`.""" + plural = f"{kind.lower()}s" + return yaml.safe_dump( + { + "apiVersion": "apiextensions.k8s.io/v1", + "kind": "CustomResourceDefinition", + "metadata": {"name": f"{plural}.{GROUP}"}, + "spec": { + "group": GROUP, + "names": {"kind": kind, "plural": plural}, + "scope": "Namespaced", + "versions": [ + { + "name": gate.CRD_VERSION, + "served": True, + "storage": True, + "schema": { + "openAPIV3Schema": {"type": "object", "properties": {"spec": spec}} + }, + } + ], + }, + } + ) + + +class TheGateRunWhole(unittest.TestCase): + """main() over a fixture tree, its CRDs read from a fixture chart by the real client. + + The walk is held above rule by rule. These hold the run: the version read + off the ApplicationSet is the chart fetched, its CRDs are the schemas every + CR in the tree is walked against, the corpus is complete, and each way the + chart can fail to arrive ends the run with the status that failure earns. + """ + + VERSION = "0.7.5" + PATH = "nanohype/eks-agent-platform/charts/operator" + + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = pathlib.Path(tmp.name) / "tree" + self.appset = self.root / "applicationsets" / "addons-agent-operator.yaml" + self.appset.parent.mkdir(parents=True) + self.pin(self.VERSION) + self.cr("platform.yaml", "Platform", {"datastores": [{"relational": {"minACU": "0.5"}}]}) + self.cr("gateway.yaml", "ModelGateway", {"model": "claude"}) + self.schemas = { + "Platform": { + "type": "object", + "properties": { + "datastores": { + "type": "array", + "items": { + "type": "object", + "properties": { + "relational": { + "type": "object", + "properties": {"minACU": {"type": "string"}}, + } + }, + }, + } + }, + }, + "ModelGateway": { + "type": "object", + "required": ["model"], + "properties": {"model": {"type": "string"}}, + }, + } + self.operator = self.chart(self.VERSION) + self.hosts = fake.serve( + self, + registry, + { + f"https://ghcr.io/v2/{self.PATH}/": self.route, + fake.OciRegistry.REALM: self.route, + }, + pathlib.Path(tmp.name) / "cache", + ) + for patch in ( + mock.patch.object(gate, "ROOT", self.root), + mock.patch.object(gate, "OPERATOR_APPSET", self.appset), + ): + patch.start() + self.addCleanup(patch.stop) + + def route(self, req): + return self.operator(req) + + def chart(self, version): + archive = fake.chart_archive( + "operator", + version, + {}, + crds={f"{kind.lower()}s.yaml": crd(kind, spec) for kind, spec in self.schemas.items()}, + ) + return fake.OciRegistry( + "ghcr.io", self.PATH, version, {"name": "operator", "version": version}, content=archive + ) + + def pin(self, version): + self.appset.write_text( + yaml.safe_dump( + { + "kind": "ApplicationSet", + "spec": { + "template": { + "spec": { + "sources": [ + { + "repoURL": "ghcr.io/nanohype/eks-agent-platform/charts", + "chart": "operator", + "targetRevision": version, + }, + { + "repoURL": "https://git.example/eks-gitops", + "targetRevision": "main", + }, + ] + } + } + }, + } + ) + ) + + def cr(self, name, kind, spec): + path = self.root / "addons" / "ai-platform" / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + yaml.safe_dump( + { + "apiVersion": f"{GROUP}/{gate.CRD_VERSION}", + "kind": kind, + "metadata": {"name": "main"}, + "spec": spec, + } + ) + ) + + def run_gate(self, *argv): + out = io.StringIO() + with ( + mock.patch.object(gate.sys, "argv", ["check-platform-crs.py", *argv]), + contextlib.redirect_stdout(out), + contextlib.redirect_stderr(out), + ): + try: + rc = gate.main() + except SystemExit as exc: + rc = exc.code + return rc, out.getvalue() + + def test_a_catalog_whose_crs_the_pinned_crds_admit_passes(self): + rc, out = self.run_gate("--list") + self.assertEqual(rc, 0, out) + self.assertIn(f"operator chart {self.VERSION} → ModelGateway, Platform", out) + self.assertIn("addons/ai-platform/gateway.yaml: ModelGateway/main", out) + self.assertIn(f"ok: 2 platform CR(s) admissible against operator chart {self.VERSION}", out) + self.assertIn(f"https://ghcr.io/v2/{self.PATH}/manifests/{self.VERSION}", self.hosts.urls) + + def test_a_field_the_crd_types_as_a_string_written_as_a_number_fails(self): + self.cr("platform.yaml", "Platform", {"datastores": [{"relational": {"minACU": 0.5}}]}) + rc, out = self.run_gate() + self.assertEqual(rc, 1, out) + self.assertIn( + "addons/ai-platform/platform.yaml (main): Platform spec.datastores[0].relational.minACU " + "is a number and the CRD declares string — quote it", + out, + ) + + def test_a_required_field_left_out_fails(self): + self.cr("gateway.yaml", "ModelGateway", {}) + rc, out = self.run_gate() + self.assertEqual(rc, 1, out) + self.assertIn("ModelGateway spec.model is REQUIRED by the CRD", out) + + def test_a_cr_of_a_kind_the_chart_ships_no_schema_for_fails(self): + self.cr("tenant.yaml", "Tenant", {"name": "acme"}) + rc, out = self.run_gate() + self.assertEqual(rc, 1, out) + self.assertIn("1 custom resource(s) carry an operator API group and were not walked", out) + self.assertIn("addons/ai-platform/tenant.yaml: Tenant/main", out) + + def test_a_corpus_under_the_floor_cannot_run(self): + (self.root / "addons" / "ai-platform" / "gateway.yaml").unlink() + rc, out = self.run_gate() + self.assertEqual(rc, gate.gatelib.CANNOT_RUN, out) + self.assertIn(f"below the floor of {gate.MIN_CRS}", out) + + def test_a_version_the_registry_does_not_have_is_a_finding(self): + self.pin("0.9.9") + rc, out = self.run_gate() + self.assertEqual(rc, 1, out) + self.assertIn( + "operator 0.9.9: oci://ghcr.io/nanohype/eks-agent-platform/charts/operator answered", + out, + ) + + def test_a_registry_that_stays_down_cannot_run(self): + self.operator = lambda req: fake.http_error(req.full_url, 503) + rc, out = self.run_gate() + self.assertEqual(rc, gate.gatelib.CANNOT_RUN, out) + self.assertIn( + f"Cannot run: operator {self.VERSION} from {gate.CHART} could not be read", out + ) + + def test_chart_source_and_other_documents_in_the_tree_are_passed_over(self): + templates = self.root / "catalog" / "x" / "chart" / "templates" + templates.mkdir(parents=True) + (templates.parent / "Chart.yaml").write_text("apiVersion: v2\nname: x\nversion: 0.1.0\n") + (templates / "cm.yaml").write_text( + "kind: ConfigMap\nmetadata:\n name: {{ .Release.Name }}\n" + ) + (self.root / "addons" / "list.yaml").write_text("- one\n- two\n") + path = self.root / "addons" / "ai-platform" / "older.yaml" + path.write_text( + yaml.safe_dump( + { + "apiVersion": f"{GROUP}/v1beta1", + "kind": "Platform", + "metadata": {"name": "old"}, + "spec": {"x": 1}, + } + ) + ) + rc, out = self.run_gate() + self.assertEqual(rc, 0, out) + self.assertIn("ok: 2 platform CR(s) admissible", out) + + def test_a_manifest_that_does_not_parse_cannot_run(self): + (self.root / "addons" / "broken.yaml").write_text("kind: Platform\nspec: [unclosed\n") + rc, out = self.run_gate() + self.assertEqual(rc, gate.gatelib.CANNOT_RUN, out) + self.assertIn("addons/broken.yaml is not parseable YAML", out) + + def test_offline_skips_without_reading_the_registry(self): + rc, out = self.run_gate("--offline") + self.assertEqual(rc, 0, out) + self.assertIn( + f"--offline: skipped (would validate against operator chart {self.VERSION})", out + ) + self.assertEqual(self.hosts.urls, []) + + def test_the_self_test_holds_the_walker(self): + rc, out = self.run_gate("--self-test") + self.assertEqual(rc, 0, out) + self.assertEqual(self.hosts.urls, []) + + if __name__ == "__main__": unittest.main() diff --git a/scripts/tests/test_render_addons.py b/scripts/tests/test_render_addons.py index ad8cae6..11cf77e 100644 --- a/scripts/tests/test_render_addons.py +++ b/scripts/tests/test_render_addons.py @@ -9,7 +9,9 @@ It fetches every chart from a registry, so the positive-control sweep exempts it. These exercise what decides the result without a network: which units exist, where each is fetched from, and what a render is handed. What an unavailable -chart means is registry.py's, and is held in test_registry. +chart means is registry.py's, and is held in test_registry. TheGateRunWhole runs +main() end to end over a fixture catalog whose charts fakeregistry serves through +registry.py's own client, rendered by the real helm. """ from __future__ import annotations @@ -20,6 +22,7 @@ import json import os import pathlib +import shutil import tempfile import unittest from typing import Any @@ -31,6 +34,8 @@ gate = load("render-addons") +HAS_HELM = shutil.which("helm") is not None + def appset(sources, generators=None, destination=None): doc: dict[str, Any] = { @@ -1032,5 +1037,288 @@ def test_every_skipped_chart_is_one_the_corpus_contains(self): self.assertIn(chart, charts) +# A chart template rendering one namespaced object and one cluster-scoped one, +# the ClusterRole's name taken from the values so two charts can collide on it. +ADDON_TEMPLATE = """\ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ .Release.Name }} + namespace: {{ .Release.Namespace }} +data: + replicas: {{ .Values.replicas | quote }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ .Values.clusterRole }} +rules: [] +""" + +GADGET_CRD = yaml.safe_dump( + { + "apiVersion": "apiextensions.k8s.io/v1", + "kind": "CustomResourceDefinition", + "metadata": {"name": "gadgets.fixture.example"}, + "spec": { + "group": "fixture.example", + "names": {"kind": "Gadget", "plural": "gadgets"}, + "scope": "Namespaced", + "versions": [ + { + "name": "v1", + "served": True, + "storage": True, + "schema": {"openAPIV3Schema": {"type": "object"}}, + } + ], + }, + } +) + + +@unittest.skipUnless(HAS_HELM, "helm is not on PATH") +class TheGateRunWhole(unittest.TestCase): + """main() over a fixture catalog: an HTTPS chart and an OCI one, each in its own env set. + + The tests above hold discovery, the render's arguments and the ownership + rules apart. These hold the run: every unit is rendered once per environment + it carries values for, through the chart the ApplicationSet pins, the + cluster-scoped objects of every render are pooled for ownership, and each + way a stage fails ends the run with the status that failure earns. The + catalog's directory-source ApplicationSets are copied in, so the ownership + records are checked against what they describe here too. + """ + + WIDGETS = "https://charts.example/widgets" + GADGETS = ("registry.example", "charts/gadget") + + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = pathlib.Path(tmp.name) / "tree" + self.appsets = self.root / "applicationsets" + self.appsets.mkdir(parents=True) + for owner in gate.DIRECTORY_OWNERS: + shutil.copy(gate.APPSET_DIR / owner.appset, self.appsets / owner.appset) + self.write_appset(gadget_path="addons/demo/gadget") + self.addon( + "widget", + { + "values.yaml": "replicas: 1\n", + "values-development.yaml": "replicas: 2\n", + "values-production.yaml": "replicas: 3\n", + }, + ) + self.addon( + "gadget", + { + "values.yaml": "{}\n", + "values-development.yaml": "{}\n", + "values-staging.yaml": "{}\n", + "values-hub.yaml": "{}\n", + }, + ) + + self.widgets = fake.ChartRepository( + self.WIDGETS, + { + ("widget", "1.0.0"): fake.chart_archive( + "widget", + "1.0.0", + {"addon.yaml": ADDON_TEMPLATE}, + values="replicas: 1\nclusterRole: widget\n", + ) + }, + ) + self.gadgets = fake.OciRegistry( + *self.GADGETS, + "2.0.0", + {"name": "gadget", "version": "2.0.0"}, + content=fake.chart_archive( + "gadget", + "2.0.0", + {"addon.yaml": ADDON_TEMPLATE}, + values="replicas: 1\nclusterRole: gadget\n", + crds={"gadgets.yaml": GADGET_CRD}, + ), + ) + self.cache = pathlib.Path(tmp.name) / "cache" + self.hosts = fake.serve( + self, + gate.registry, + { + self.WIDGETS: self.widgets, + f"https://{self.GADGETS[0]}/v2/{self.GADGETS[1]}/": self.gadgets, + fake.OciRegistry.REALM: self.gadgets, + }, + self.cache, + ) + for patch in ( + mock.patch.object(gate, "REPO_ROOT", self.root), + mock.patch.object(gate, "APPSET_DIR", self.appsets), + mock.patch.object(gate, "MIN_COMBINATIONS", 5), + mock.patch.dict(gate.SKIP_CHARTS, clear=True), + ): + patch.start() + self.addCleanup(patch.stop) + + def write_appset(self, *, gadget_path): + elements = [ + { + "appName": "widget", + "chart": "widget", + "chartRepo": self.WIDGETS, + "chartVersion": "1.0.0", + "path": "addons/demo/widget", + "namespace": "widget", + }, + { + "appName": "gadget", + "chart": "gadget", + "chartRepo": f"oci://{self.GADGETS[0]}/charts", + "chartVersion": "2.0.0", + "path": gadget_path, + "namespace": "gadget", + }, + ] + sources = [ + { + "repoURL": "{{ .chartRepo }}", + "chart": "{{ .chart }}", + "targetRevision": "{{ .chartVersion }}", + "helm": {"valueFiles": ["$values/{{ .path }}/values.yaml"]}, + }, + {"repoURL": "https://git.example/eks-gitops", "ref": "values"}, + ] + generators = [ + { + "matrix": { + "generators": [ + {"clusters": {"selector": {"matchLabels": {"fleet": "spoke"}}}}, + {"list": {"elements": elements}}, + ] + } + } + ] + (self.appsets / "addons-demo.yaml").write_text(yaml.safe_dump(appset(sources, generators))) + + def addon(self, name, files): + where = self.root / "addons" / "demo" / name + where.mkdir(parents=True, exist_ok=True) + for fname, text in files.items(): + (where / fname).write_text(text) + + def run_gate(self, *argv): + out = io.StringIO() + with ( + mock.patch.object(gate.sys, "argv", ["render-addons.py", *argv]), + contextlib.redirect_stdout(out), + contextlib.redirect_stderr(out), + ): + try: + rc = gate.main() + except SystemExit as exc: + rc = exc.code + return rc, out.getvalue() + + def test_a_catalog_rendering_one_owner_per_object_passes(self): + rc, out = self.run_gate() + self.assertEqual(rc, 0, out) + for line in ( + " ok widget@1.0.0 (development)", + " ok widget@1.0.0 (production)", + " ok gadget@2.0.0 (development)", + " ok gadget@2.0.0 (staging)", + " ok gadget@2.0.0 (hub)", + "Rendered 5 addon×env combinations, 0 failed.", + "Rendered 3 cluster-scoped object(s), 1 of them CustomResourceDefinitions; " + "0 with more than one owning Application.", + ): + self.assertIn(line, out) + self.assertNotIn( + "widget@1.0.0 (staging)", out, "an environment with no values was rendered" + ) + + def test_an_object_two_applications_install_fails_naming_both(self): + self.addon("gadget", {"values.yaml": "clusterRole: widget\n"}) + rc, out = self.run_gate() + self.assertEqual(rc, 1, out) + self.assertIn( + "ClusterRole/widget is installed by 2 Applications: addons-demo.yaml addons/demo/gadget, " + "addons-demo.yaml addons/demo/widget", + out, + ) + + def test_a_chart_that_does_not_render_fails_each_environment(self): + self.widgets.charts[("widget", "1.0.0")] = fake.chart_archive( + "widget", "1.0.0", {"addon.yaml": "{{ .Values.missing.key }}\n"} + ) + rc, out = self.run_gate() + self.assertEqual(rc, 1, out) + self.assertIn(" FAIL widget@1.0.0 (development)", out) + self.assertIn(" FAIL widget@1.0.0 (production)", out) + self.assertIn(" ok gadget@2.0.0 (hub)", out) + self.assertIn("Rendered 5 addon×env combinations, 2 failed.", out) + + def test_an_element_pointing_at_no_directory_fails(self): + self.write_appset(gadget_path="addons/demo/gizmo") + rc, out = self.run_gate() + self.assertEqual(rc, 1, out) + self.assertIn("path 'addons/demo/gizmo' does not exist", out) + + def test_a_run_under_the_floor_cannot_run(self): + with mock.patch.object(gate, "MIN_COMBINATIONS", 6): + rc, out = self.run_gate() + self.assertEqual(rc, gate.gatelib.CANNOT_RUN, out) + self.assertIn("rendered 5 combination(s), under the floor of 6", out) + + def test_a_skip_whose_chart_an_anonymous_client_can_fetch_is_stale(self): + with ( + mock.patch.dict(gate.SKIP_CHARTS, {"gadget": "needs a registry login"}), + mock.patch.object(gate, "MIN_COMBINATIONS", 2), + ): + rc, out = self.run_gate() + self.assertEqual(rc, 1, out) + self.assertIn(" skip gadget@2.0.0 — needs a registry login", out) + self.assertIn("These skips claim a chart cannot be fetched, but it can:", out) + self.assertIn("declared: needs a registry login", out) + + def test_a_directory_owner_that_reads_another_source_fails(self): + owner = gate.DIRECTORY_OWNERS[0] + path = self.appsets / owner.appset + doc = yaml.safe_load(path.read_text()) + doc["spec"]["template"]["spec"]["source"]["path"] = "elsewhere" + path.write_text(yaml.safe_dump(doc)) + rc, out = self.run_gate() + self.assertEqual(rc, 1, out) + self.assertIn("A directory-source ownership record no longer describes its source:", out) + self.assertIn(f"{owner.appset}: ownership recorded for {owner.source}", out) + + def test_a_repository_that_stays_down_cannot_run(self): + self.widgets.answer = lambda req: fake.http_error(req.full_url, 503) + rc, out = self.run_gate() + self.assertEqual(rc, gate.gatelib.CANNOT_RUN, out) + self.assertIn(f"Cannot run: widget 1.0.0 from {self.WIDGETS} could not be read", out) + + def test_list_prints_every_unit_and_fetches_nothing(self): + rc, out = self.run_gate("--list") + self.assertEqual(rc, 0, out) + self.assertIn("addons/demo/widget", out) + self.assertIn("addons/demo/gadget", out) + self.assertEqual(self.hosts.urls, []) + + def test_fetch_keeps_every_pinned_archive_and_renders_nothing(self): + rc, out = self.run_gate("--fetch") + self.assertEqual(rc, 0, out) + for source, chart, version in ( + (self.WIDGETS, "widget", "1.0.0"), + (f"oci://{self.GADGETS[0]}/charts/gadget", "gadget", "2.0.0"), + ): + archive = gate.registry.archive_path(source, chart, version, self.cache) + self.assertTrue(archive.is_file(), f"{chart} {version} was not kept") + self.assertNotIn(" ok ", out) + + if __name__ == "__main__": unittest.main() From 88265e0622a1eebc07d8880b7e4d7d953c5a0e40 Mon Sep 17 00:00:00 2001 From: stxkxs <139715017+stxkxs@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:57:30 +0000 Subject: [PATCH 3/4] fix(gates): drop the image total the per-chart floor already holds check-image-vulnerabilities refused to run whenever the render produced fewer distinct images than it had units, as a walk that "got smaller rather than the catalog". Every chart a unit renders is already held to contributing an image, per chart, by check-image-pins.chart_coverage, the floor the file's own comment names. What the total added was a refusal of catalogs with nothing wrong: two charts whose one image is the same, a chart pinned by more than one unit, or imageless charts outnumbering the images the rest render beyond one each. The end-to-end run met the first: two charts sharing their image exited 2. The total is gone. test_charts_sharing_their_one_image_scan_it_once holds that run, and reverify-tests.sh restores the total and requires that test to fail. test_corpus_floors held the total's text as part of the derived floor, and now holds the per-chart derivation alone. The gate's floor rises to (99, 98). Co-authored-by: stxkxsbot <275011021+stxkxsbot@users.noreply.github.com> --- scripts/check-image-vulnerabilities.py | 7 ------- scripts/tests/reverify-tests.sh | 11 +++++++++++ scripts/tests/run.py | 2 +- scripts/tests/test_corpus_floors.py | 4 ++-- scripts/tests/test_image_vulnerabilities.py | 12 ++++++++++++ 5 files changed, 26 insertions(+), 10 deletions(-) diff --git a/scripts/check-image-vulnerabilities.py b/scripts/check-image-vulnerabilities.py index 10a4dc2..338adc8 100755 --- a/scripts/check-image-vulnerabilities.py +++ b/scripts/check-image-vulnerabilities.py @@ -591,13 +591,6 @@ def main() -> int: "rendered it, so a scan over it says less than it appears to:", *(f" {problem}" for problem in coverage), ) - if len(images) < len(units): - cannot_run( - f"Cannot run: the render produced {len(images)} image(s) from " - f"{len(units)} chart(s). Every chart shipping a workload " - f"contributes at least one, so the walk got smaller rather than " - f"the catalog." - ) findings = scan_all(images) diff --git a/scripts/tests/reverify-tests.sh b/scripts/tests/reverify-tests.sh index 0af3b35..2970c5d 100755 --- a/scripts/tests/reverify-tests.sh +++ b/scripts/tests/reverify-tests.sh @@ -2313,6 +2313,17 @@ rejects "image-vulnerabilities run: scan without the canary first" test_image_vu test_the_self_test_scans_the_canary_alone res $F +edit $F <<'PY' +import pathlib, sys +p = pathlib.Path(sys.argv[1]); s = p.read_text() +anchor = " *(f\" {problem}\" for problem in coverage),\n )\n" +m = s.replace(anchor, anchor + " if len(images) < len(units):\n cannot_run(\"Cannot run: fewer images than charts.\")\n", 1) +assert m != s, "mutation did not land" +p.write_text(m) +PY +rejects "image-vulnerabilities run: refuse charts sharing an image" test_image_vulnerabilities \ + test_charts_sharing_their_one_image_scan_it_once +res $F F=scripts/check-renovate-coverage.py diff --git a/scripts/tests/run.py b/scripts/tests/run.py index b1fcf27..8111f05 100755 --- a/scripts/tests/run.py +++ b/scripts/tests/run.py @@ -262,7 +262,7 @@ "scripts/check-log-volume-budget.py": (100, 97), "scripts/check-falco-rule-floor.py": (97, 91), "scripts/check-alert-severity-routes.py": (96, 90), - "scripts/check-image-vulnerabilities.py": (98, 97), + "scripts/check-image-vulnerabilities.py": (99, 98), "scripts/check-image-pins.py": (93, 88), # The half of the directory-size gate that decides the verdict. The rest is # `--sync`, `--live` and `--self-test`, which run against a clone. diff --git a/scripts/tests/test_corpus_floors.py b/scripts/tests/test_corpus_floors.py index dbaae99..8a450c9 100644 --- a/scripts/tests/test_corpus_floors.py +++ b/scripts/tests/test_corpus_floors.py @@ -151,10 +151,10 @@ def test_each_floor_is_compared_against_a_count_of_what_was_read(self): def test_the_image_floor_is_derived_per_chart(self): """Not a constant, because here a second enumerator exists: every chart the render covers must contribute an image, which is the shape a total - cannot see.""" + cannot see. Nor a total of images against charts, which refuses a catalog + whose charts share an image; test_image_vulnerabilities runs one.""" source = (ROOT / "scripts" / "check-image-vulnerabilities.py").read_text() self.assertIn("coverage = image_pins.chart_coverage(images, units, seen)", source) - self.assertIn("if len(images) < len(units):", source) self.assertNotIn( "MIN_IMAGES", source, diff --git a/scripts/tests/test_image_vulnerabilities.py b/scripts/tests/test_image_vulnerabilities.py index 9774366..d7aed1f 100644 --- a/scripts/tests/test_image_vulnerabilities.py +++ b/scripts/tests/test_image_vulnerabilities.py @@ -914,6 +914,18 @@ def test_a_chart_that_renders_no_image_cannot_run(self): self.assertIn("the image population is smaller than the charts that rendered it", out) self.assertIn("widget rendered and contributed no image", out) + def test_charts_sharing_their_one_image_scan_it_once(self): + """Two charts rendering one image are one image to scan, not a walk that got + smaller: each chart contributed an image, which is what the floor asks.""" + shared = "registry.example/shared:1.0.0" + for name in ("widget", "gadget"): + values = self.root / "addons" / "demo" / name / "values.yaml" + values.write_text(yaml.safe_dump({"image": shared})) + rc, out = self.run_gate() + self.assertEqual(rc, 0, out) + self.assertIn("image vulnerabilities OK: 1 image(s) scanned across 2 chart(s).", out) + self.assertEqual(self.scanned(), [gate.CANARY, shared]) + def test_list_prints_every_finding_and_blocks_nothing(self): self.answer( self.WIDGET_IMAGE, From 980d0be27ccd22c7464b41321e4d15d9e10956e4 Mon Sep 17 00:00:00 2001 From: stxkxs <139715017+stxkxs@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:00:53 +0000 Subject: [PATCH 4/4] test(gates): load registry through gateloader in the end-to-end runs Four test modules imported registry by name, and the import sort put that ahead of the gateloader import, which is what puts scripts/ on sys.path. The suite passed because an earlier module had already imported gateloader. reverify-tests.sh runs one module at a time, and there each of the four failed to import, so every probe it planted against them read as a miss. Each module now takes registry from load(), as test_gatelib and test_registry do, and gets the instance the gates hold. Co-authored-by: stxkxsbot <275011021+stxkxsbot@users.noreply.github.com> --- scripts/tests/test_falco_rule_floor.py | 2 +- scripts/tests/test_image_vulnerabilities.py | 2 +- scripts/tests/test_log_volume_budget.py | 2 +- scripts/tests/test_platform_crs.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/scripts/tests/test_falco_rule_floor.py b/scripts/tests/test_falco_rule_floor.py index e4ce1a8..ef2ce60 100644 --- a/scripts/tests/test_falco_rule_floor.py +++ b/scripts/tests/test_falco_rule_floor.py @@ -26,11 +26,11 @@ from unittest import mock import fakeregistry as fake -import registry import yaml from gateloader import load gate = load("check-falco-rule-floor") +registry = load("registry") HAS_HELM = shutil.which("helm") is not None diff --git a/scripts/tests/test_image_vulnerabilities.py b/scripts/tests/test_image_vulnerabilities.py index d7aed1f..3c0fe1b 100644 --- a/scripts/tests/test_image_vulnerabilities.py +++ b/scripts/tests/test_image_vulnerabilities.py @@ -37,11 +37,11 @@ from unittest import mock import fakeregistry as fake -import registry import yaml from gateloader import load gate = load("check-image-vulnerabilities") +registry = load("registry") HAS_HELM = shutil.which("helm") is not None diff --git a/scripts/tests/test_log_volume_budget.py b/scripts/tests/test_log_volume_budget.py index aaeeb9d..befb19f 100644 --- a/scripts/tests/test_log_volume_budget.py +++ b/scripts/tests/test_log_volume_budget.py @@ -29,11 +29,11 @@ from unittest import mock import fakeregistry as fake -import registry import yaml from gateloader import load gate = load("check-log-volume-budget") +registry = load("registry") HAS_HELM = shutil.which("helm") is not None diff --git a/scripts/tests/test_platform_crs.py b/scripts/tests/test_platform_crs.py index 5f966fd..1dec7dd 100644 --- a/scripts/tests/test_platform_crs.py +++ b/scripts/tests/test_platform_crs.py @@ -26,11 +26,11 @@ from unittest import mock import fakeregistry as fake -import registry import yaml from gateloader import load gate = load("check-platform-crs") +registry = load("registry") KIND = "Platform" SOURCE = "addons/ai-platform/agent-platform/base/platform.yaml"