Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 0 additions & 7 deletions scripts/check-image-vulnerabilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
133 changes: 132 additions & 1 deletion scripts/tests/fakeregistry.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,37 @@
"""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
client that drifted from them fails against this fake instead of agreeing with
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

Expand Down Expand Up @@ -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
81 changes: 81 additions & 0 deletions scripts/tests/reverify-tests.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -2256,6 +2301,30 @@ 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

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

Expand Down Expand Up @@ -2360,6 +2429,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.
Expand Down
19 changes: 10 additions & 9 deletions scripts/tests/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -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": (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.
"scripts/check-directory-manifest-size.py": (68, 71),
Expand Down
4 changes: 2 additions & 2 deletions scripts/tests/test_corpus_floors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading