diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4ca01f0..c4d2d28 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1370,24 +1370,18 @@ jobs: done echo "All ${{ matrix.environment }} manifests rendered successfully." - # The druid catalog chart is a tenant-workload chart (not wired by a - # default ApplicationSet). Render it with synthetic tenant values so its - # templates still pass the same render-assert / schema / misconfiguration + # The catalog charts are tenant workloads, which no default ApplicationSet + # installs. scripts/catalog.py renders each one with the tenant inputs + # beside it, the render `task render` also makes, so + # its templates pass the same render-assert / schema / misconfiguration # gates as every kustomize root. - - name: Render druid catalog chart - run: | - helm template ci catalog/druid/chart -n druid-ci \ - -f catalog/druid/values.yaml \ - --set hostedId=ci \ - --set environment=${{ matrix.environment }} \ - --set secrets.metadata=ci/druid/metadata \ - --set secrets.admin=ci/druid/admin \ - --set secrets.system=ci/druid/system \ - --set secrets.keystore=ci/druid/keystore \ - --set s3.indexLogsBucket=ci-druid-indexlogs \ - --set s3.deepStorageBucket=ci-druid-deepstorage \ - --set s3.msqBucket=ci-druid-msq \ - > rendered/catalog_druid_chart.yaml + - name: Set up Python + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version-file: .python-version + + - name: Render the catalog charts + run: python3 scripts/catalog.py --env "${{ matrix.environment }}" --out 'rendered/catalog_{name}_chart.yaml' # Source files are gated by the zero-placeholder job; this asserts the # RENDERED output too — catching a zero account id, placeholder token, or diff --git a/CLAUDE.md b/CLAUDE.md index 57d0e7a..70773c7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -293,7 +293,7 @@ documents: `task validate` runs it report-only, CI runs it `--blocking`. ## CI - PR and push to main trigger `.github/workflows/ci.yml` (lint → validate per environment → PR summary) -- The validate job renders every kustomize root plus the druid catalog chart, then gates the rendered output: render-assert (no unfilled sentinels), kubeconform strict (native schemas + datreeio CRDs-catalog, each read at a commit the shared `scripts/kubeconform-scan.sh` pins, no ignore-missing-schemas), and `trivy config` (misconfiguration scan, MEDIUM+ hard-fails; scoped justified exceptions live in `.trivyignore.yaml`) +- The validate job renders every kustomize root plus the druid catalog chart, then gates the rendered output. A catalog chart is rendered through `scripts/catalog.py`, with the tenant inputs in `catalog//ci-values.yaml`; `task render` and `check-serviceaccount-bindings.py` render it the same way. The gates: render-assert (no unfilled sentinels), kubeconform strict (native schemas + datreeio CRDs-catalog, each read at a commit the shared `scripts/kubeconform-scan.sh` pins, no ignore-missing-schemas), and `trivy config` (misconfiguration scan, MEDIUM+ hard-fails; scoped justified exceptions live in `.trivyignore.yaml`) - Standalone jobs on every PR: `helm-render` (templates every addon against its appset-pinned chart with base + each env's values — an unknown key fails here, not fleet-wide at sync), `policy-admission` (renders the whole fleet into its real destination namespaces and runs `kyverno apply` against the Deny-tier best-practice/pod-security policies, so an addon landing in a namespace the policies don't exclude fails here instead of being denied at admission on a vended enforce cluster — also asserts all six exclusion lists stay identical, that every namespace the fleet lands a workload in is on that list, that each overlay carries its tier's `validationActions`, and that a deliberately non-compliant canary is denied by every validation, which is what proves the run evaluated anything), `appsets` (ApplicationSet schema + documented sync-wave ordering), `appset-render` (renders every template string an ApplicationSet carries the way the ArgoCD ApplicationSet controller does — Go text/template + sprig, `missingkey=error`: the Karpenter EC2NodeClass patch against fixture create/adopt/legacy cluster Secrets, the argo-workflows/loki/tempo bucket injection against with- and without-bucket fixtures, and the `addons-ai-platform.yaml` prune `templatePatch` against every element plus both `autoPrune` arms — so a control-flow edit that breaks a per-cluster render, or a prune nobody meant to change, fails here instead of at sync), `secrets` (gitleaks over the working tree), plus the dashboard, fork-safety, and Kyverno policy gates - `charts` (Pinned chart archives) runs `scripts/render-addons.py --fetch` and keeps every pinned chart archive, each beside a `.sha256` record of the digest it was verified against, in an Actions cache of `~/.cache/eks-gitops/charts` keyed on `applicationsets/*.yaml` and `scripts/registry.py`. The cache is restored and saved as separate steps, and the save runs whatever the fetch did: a complete set goes under that key, and a set a failed fetch left incomplete under a `charts-partial-` key carrying the same pins hash, the run and its attempt. No incomplete set's key begins with the key the rendering jobs restore, so the prefix match a restore falls back to cannot hand one a partial set; the `charts` job's own restore-keys take the newest partial set for the same pins first. Requests to `public.ecr.aws` are spaced by `REQUEST_SPACING_SECONDS` in `scripts/registry.py`, above ECR Public's one-pull-a-second anonymous quota. `charts` and `image-vulnerabilities`, the two jobs that read `public.ecr.aws` in bulk, first assume the role the `ECR_PUBLIC_PULL_ROLE_ARN` repository secret names over GitHub OIDC and log in to `public.ecr.aws`, so ECR Public meters their pulls by that role's AWS account rather than by the runner's shared address; a run for a pull request from a fork, or with the secret unset, skips the login and reads anonymously. The ARN carries an AWS account id and this repository's Actions logs are public, so it is a secret (a variable is printed unmasked), at repository level (the role trusts this repo's `pull_request` and `ref:refs/heads/main` OIDC subjects, and an environment would change the subject); the first step that receives it runs the vendored `scripts/mask-aws-ids.sh` as its first command, fails the job while the name still exists as a variable, and `configure-aws-credentials` runs with `mask-aws-account-id: true`. trivy reads the login from the docker config, and `scripts/registry.py` sends it to a token realm only when the realm and the registry being read are both the host it was stored for, and reads a registry that refuses it anonymously, saying so once on stderr. These two are the only jobs granted `id-token`, each at job level. Every job that renders a pinned chart waits on it (`needs: charts`) and restores that cache, so a registry is read once per pin set; `scripts/registry.py` hands out a cached archive only while it still hashes to its record. A chart read exits 1 when the registry answered and ruled the pin out, and 2 when the registry could not be read. Each of these jobs, and each scheduled job in `chart-provenance.yml` that reads upstream through the client, sets a `timeout-minutes` above `CALL_BOUND_SECONDS` in `scripts/registry.py`: the deadline one client call runs to, its token request included, plus the one socket read a body still arriving at that deadline can have under way. `docs/runbooks/render-gate-failures.md` covers a red run - `workflow-id-masking` runs `scripts/check-workflow-id-masking.py`, its `--self-test`, and `scripts/mask-aws-ids.sh --self-test`. The gate holds every workflow to reading an AWS account id or role ARN only as a secret, whole, masked by the mask script as the first command of the first step that receives it, never from a variable, an input, a matrix value or a literal, with `mask-aws-account-id: true` on every `configure-aws-credentials` step and a leftover-variable guard (`vars.NAME != ''`) beside every secret read. The gate, the mask script and the core that script runs (`scripts/mask-aws-ids.py`) are landing-zone's, vendored byte for byte: `scripts/vendored.json` records the repository, path, commit and SHA-256 of each, and the gate fails when the bytes stop matching, so a change lands there first and is re-vendored here with the record moved in the same commit. What is particular to this repository is its policy, `scripts/workflow-id-masking.toml`: the floor a scan must meet, the self-test's cases anchored in these workflows, and `ECR_PUBLIC_PULL_ROLE_ARN` as the one id allowed at repository level (`[repository_level_ids]`); any other id must be an environment secret with a refuse-inherited-config job, as landing-zone's are. ruff excludes the vendored Python, and `scripts/tests/test_workflow_id_masking.py` holds that exclusion to the record and runs both self-tests under the coverage run diff --git a/Taskfile.yaml b/Taskfile.yaml index c0af83a..e8d7016 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -346,21 +346,9 @@ tasks: echo "Rendering $dir ..." kustomize build --enable-helm "$dir" > "rendered/${name}.yaml" || exit 1 done - # Druid catalog chart with synthetic tenant values — same render CI - # gates (see .github/workflows/ci.yml). - echo "Rendering catalog/druid/chart ..." - helm template ci catalog/druid/chart -n druid-ci \ - -f catalog/druid/values.yaml \ - --set hostedId=ci \ - --set environment={{.ENVIRONMENT}} \ - --set secrets.metadata=ci/druid/metadata \ - --set secrets.admin=ci/druid/admin \ - --set secrets.system=ci/druid/system \ - --set secrets.keystore=ci/druid/keystore \ - --set s3.indexLogsBucket=ci-druid-indexlogs \ - --set s3.deepStorageBucket=ci-druid-deepstorage \ - --set s3.msqBucket=ci-druid-msq \ - > rendered/catalog-druid-chart.yaml + # The catalog charts, rendered with their tenant inputs: the same + # render CI's validate job makes (see .github/workflows/ci.yml). + python3 scripts/catalog.py --env {{.ENVIRONMENT}} --out 'rendered/catalog-{name}-chart.yaml' || exit 1 echo "All {{.ENVIRONMENT}} overlays rendered to rendered/" clean: diff --git a/catalog/druid/ci-values.yaml b/catalog/druid/ci-values.yaml new file mode 100644 index 0000000..9ea8d9d --- /dev/null +++ b/catalog/druid/ci-values.yaml @@ -0,0 +1,18 @@ +# The inputs a tenant's Application supplies when it installs this chart, as +# synthetic values. No ApplicationSet in this repository deploys the chart, so +# every render made here stands in for a tenant's, and this file is what it +# stands in with. scripts/catalog.py reads it beside values.yaml for every +# render: CI's validate job, `task render` and check-serviceaccount-bindings.py. +# `environment` is set per render. +hostedId: ci + +secrets: + metadata: ci/druid/metadata + admin: ci/druid/admin + system: ci/druid/system + keystore: ci/druid/keystore + +s3: + indexLogsBucket: ci-druid-indexlogs + deepStorageBucket: ci-druid-deepstorage + msqBucket: ci-druid-msq diff --git a/scripts/catalog.py b/scripts/catalog.py new file mode 100644 index 0000000..9fa9aca --- /dev/null +++ b/scripts/catalog.py @@ -0,0 +1,151 @@ +"""catalog.py — the catalog's own charts, and the one way this repository renders them. + +A chart under catalog//chart is a workload a tenant installs. No +ApplicationSet in this repository deploys one, so ArgoCD never renders it from +here, and every render made here stands in for a tenant's. What it stands in with +is catalog//ci-values.yaml, the inputs a tenant's Application supplies, +read beside the chart's own values.yaml. + +This module is the one place that turns those into a `helm template` command. +CI's validate job and `task render` write the render through main(); +check-serviceaccount-bindings.py reads it through render(). +Written out separately, the command drifted: three renderers each spelled it, +and one of them passed a single input of the nine. With one definition, what +one gate checks is what the others check. + +The population is every directory matching CHART_GLOB, derived rather than +listed, so a second catalog chart is rendered by everything that renders the +first. + +Exit status: 0 when every chart rendered, 1 when a chart failed to render or has +no tenant inputs, and 2 (CANNOT_RUN) when helm is missing, a render ran out of +time, or no chart matched CHART_GLOB. +""" + +from __future__ import annotations + +import argparse +import subprocess +import sys +from collections.abc import Sequence +from dataclasses import dataclass +from pathlib import Path + +import gatelib + +ROOT = Path(__file__).resolve().parent.parent +CHART_GLOB = "catalog/*/chart" + +# Beside each chart's values.yaml: the inputs a tenant's Application supplies. +TENANT_INPUTS = "ci-values.yaml" + +# The release every render uses. Each chart renders into -ci, a namespace +# no cluster this catalog reaches runs a tenant in. +RELEASE = "ci" + +# Seconds one `helm template` of a chart in this tree may take. It reads only the +# working tree, so running past this is a hang rather than a slow network. +RENDER_TIMEOUT = 120 + + +class RenderFailed(Exception): + """The chart, as this tree has it, does not render: a finding about the tree.""" + + +class CannotRender(Exception): + """helm did not finish, so nothing was decided about the chart.""" + + +@dataclass(frozen=True) +class CatalogChart: + root: Path + chart_dir: Path + + @property + def name(self) -> str: + return self.chart_dir.parent.name + + @property + def path(self) -> str: + return self.chart_dir.relative_to(self.root).as_posix() + + @property + def namespace(self) -> str: + return f"{self.name}-{RELEASE}" + + @property + def value_files(self) -> list[Path]: + return [self.chart_dir.parent / "values.yaml", self.chart_dir.parent / TENANT_INPUTS] + + +def discover(root: Path = ROOT) -> list[CatalogChart]: + return [CatalogChart(root, d) for d in sorted(root.glob(CHART_GLOB)) if d.is_dir()] + + +def template_command(chart: CatalogChart, env: str) -> list[str]: + cmd = ["helm", "template", RELEASE, str(chart.chart_dir), "--namespace", chart.namespace] + for values in chart.value_files: + cmd += ["-f", str(values)] + return cmd + ["--set", f"environment={env}"] + + +def render(chart: CatalogChart, env: str) -> str: + """The chart's manifests for `env`, rendered with its tenant inputs.""" + missing = [v.relative_to(chart.root).as_posix() for v in chart.value_files if not v.is_file()] + if missing: + raise RenderFailed( + f"{', '.join(missing)} does not exist. A catalog chart renders here with " + f"values.yaml and the tenant inputs in {TENANT_INPUTS}, both beside it." + ) + try: + proc = subprocess.run( + template_command(chart, env), capture_output=True, text=True, timeout=RENDER_TIMEOUT + ) + except subprocess.TimeoutExpired as exc: + raise CannotRender( + f"helm template ran past the {RENDER_TIMEOUT}s a render of {chart.path} is allowed" + ) from exc + if proc.returncode != 0: + raise RenderFailed((proc.stderr.strip() or proc.stdout.strip())[:1200]) + return proc.stdout + + +def main(argv: Sequence[str] | None = None) -> int: + ap = argparse.ArgumentParser(description="Render every catalog chart with its tenant inputs.") + ap.add_argument("--env", required=True, help="the environment value each render sets") + ap.add_argument( + "--out", + required=True, + help="where each render is written, with {name} for the chart, " + "e.g. rendered/catalog-{name}-chart.yaml", + ) + args = ap.parse_args(argv) + if "{name}" not in args.out: + ap.error("--out must contain {name}, or every chart would be written to one file") + + gatelib.require("helm") + charts = discover() + if not charts: + print(f"Cannot run: no chart matched {CHART_GLOB}, so nothing was rendered.") + return gatelib.CANNOT_RUN + + failed = 0 + for chart in charts: + try: + manifests = render(chart, args.env) + except CannotRender as exc: + print(f"Cannot run: {exc}.") + return gatelib.CANNOT_RUN + except RenderFailed as exc: + print(f"FAIL {chart.path} did not render for {args.env}:\n{exc}") + failed += 1 + continue + out = Path(args.out.format(name=chart.name)) + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text(manifests) + print(f"rendered {chart.path} for {args.env} to {out}") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/check-serviceaccount-bindings.py b/scripts/check-serviceaccount-bindings.py index 86cf9be..b88d42a 100755 --- a/scripts/check-serviceaccount-bindings.py +++ b/scripts/check-serviceaccount-bindings.py @@ -31,23 +31,12 @@ import gatelib import yaml -# Seconds a child process may run before the gate gives up on it. A subprocess -# with no deadline turns an unreachable registry into a job that hangs until the -# CI runner's own ceiling, with no diagnostic naming the command that stalled. -# NETWORK_TIMEOUT covers commands that resolve a remote chart or registry; -# LOCAL_TIMEOUT covers commands that only read the working tree. -LOCAL_TIMEOUT = 120 - -# Charts rendered from this repo. Upstream-charted addons are covered by -# render-addons.py, which templates them against their appset-pinned versions. -CHART_GLOB = "catalog/*/chart" - -# Minimal values needed to make a chart render at all. A chart that requires an input -# it cannot default is not a finding here — it is the chart's contract with its -# consumer, and render-addons.py documents the same pattern for --set parameters. -RENDER_VALUES = { - "druid": ["--set", "hostedId=ci"], -} +import catalog + +# The environment each chart renders for. The gate reads one render per chart, as +# it did when it set no environment at all, so a ServiceAccount that only some +# environment's values add or rename is outside what it sees. +ENVIRONMENT = "production" # ServiceAccounts a chart creates for something other than a pod in the same chart. # Each entry names what consumes it, so "unused" stays a finding rather than a @@ -61,18 +50,14 @@ } -def render(chart: Path) -> list[dict]: - name = chart.parent.name - values = chart.parent / "values.yaml" - cmd = ["helm", "template", name, str(chart)] - if values.exists(): - cmd += ["-f", str(values)] - cmd += RENDER_VALUES.get(name, []) - out = gatelib.run(cmd, timeout=LOCAL_TIMEOUT, what=f"helm template of {name}") - if out.returncode != 0: - print(f"::error file={chart}::helm template failed\n{out.stderr.strip()[:1200]}") +def render(chart: catalog.CatalogChart) -> list[dict]: + """The chart's documents, rendered the way scripts/catalog.py renders it.""" + try: + manifests = catalog.render(chart, ENVIRONMENT) + except catalog.RenderFailed as exc: + print(f"::error file={chart.path}::helm template failed\n{exc}") return [] - return [d for d in yaml.safe_load_all(out.stdout) if d] + return [d for d in yaml.safe_load_all(manifests) if d] def pod_specs(doc: dict): @@ -94,17 +79,21 @@ def pod_specs(doc: dict): def main() -> int: gatelib.require("helm") repo = Path(__file__).resolve().parent.parent - charts = sorted(repo.glob(CHART_GLOB)) + charts = catalog.discover(repo) if not charts: - print(f"::error::no charts matched {CHART_GLOB} — this gate verified nothing") - return 1 + print(f"::error::no charts matched {catalog.CHART_GLOB} — this gate verified nothing") + return gatelib.CANNOT_RUN failures = [] for chart in charts: - name = chart.parent.name - docs = render(chart) + name = chart.name + try: + docs = render(chart) + except catalog.CannotRender as exc: + print(f"Cannot run: {exc}. No chart after it was checked.") + return gatelib.CANNOT_RUN if not docs: - failures.append(f"::error file={chart}::rendered no documents") + failures.append(f"::error file={chart.path}::rendered no documents") continue created = {d["metadata"]["name"] for d in docs if d.get("kind") == "ServiceAccount"} @@ -116,7 +105,7 @@ def main() -> int: for sa in sorted(used - created): failures.append( - f"::error file={chart}::a pod runs as ServiceAccount {sa!r}, which this chart " + f"::error file={chart.path}::a pod runs as ServiceAccount {sa!r}, which this chart " f"does not create\n" f" It will not schedule, or it will silently run as `default` with none of\n" f" the AWS identity its Pod Identity association was meant to give it." @@ -125,7 +114,7 @@ def main() -> int: if (name, sa) in EXTERNAL_CONSUMERS: continue failures.append( - f"::error file={chart}::ServiceAccount {sa!r} is created and no pod in this " + f"::error file={chart.path}::ServiceAccount {sa!r} is created and no pod in this " f"chart runs as it\n" f" Either a pod should and does not — in which case its Pod Identity\n" f" association is attached to nothing and the real pods run on the node\n" diff --git a/scripts/tests/reverify-tests.sh b/scripts/tests/reverify-tests.sh index 1310a95..56d5c21 100755 --- a/scripts/tests/reverify-tests.sh +++ b/scripts/tests/reverify-tests.sh @@ -76,7 +76,7 @@ ALL_MODULES=(test_policy_admission test_platform_crs test_dashboards test_digest_rewrite_run test_workflows test_ai_config test_alert_coverage test_athena_panel_columns test_catalog_revision test_env_coverage test_externalsecret_keys test_serviceaccount_bindings test_workflow_id_masking - test_hardcoded_org) + test_hardcoded_org test_catalog) # Bytecode caching keys on (mtime, size). A restore and the next mutation inside # the same second can hand the run the PREVIOUS mutant's module, and the suite @@ -3994,6 +3994,94 @@ rejects "serviceaccount-bindings: let a pod name an account nothing creates" tes test_a_pod_naming_an_account_the_chart_does_not_create_fails res $F +edit $F <<'PY' +import pathlib, sys +p = pathlib.Path(sys.argv[1]); s = p.read_text() +m = s.replace(" except catalog.CannotRender as exc:\n" + " print(f\"Cannot run: {exc}. No chart after it was checked.\")\n" + " return gatelib.CANNOT_RUN\n", + " except catalog.CannotRender:\n continue\n", 1) +assert m != s, "mutation did not land" +p.write_text(m) +PY +rejects "serviceaccount-bindings: pass over a render that never finished" test_serviceaccount_bindings \ + test_a_render_that_runs_out_of_time_cannot_run +res $F + +edit $F <<'PY' +import pathlib, sys +p = pathlib.Path(sys.argv[1]); s = p.read_text() +m = s.replace("this gate verified nothing\")\n return gatelib.CANNOT_RUN\n", + "this gate verified nothing\")\n return 1\n", 1) +assert m != s, "mutation did not land" +p.write_text(m) +PY +rejects "serviceaccount-bindings: report an empty catalog as a finding" test_serviceaccount_bindings \ + test_no_chart_is_a_gate_that_verified_nothing +res $F + +F=scripts/catalog.py + +edit $F <<'PY' +import pathlib, sys +p = pathlib.Path(sys.argv[1]); s = p.read_text() +m = s.replace(' if missing:\n raise RenderFailed(', + ' if False:\n raise RenderFailed(', 1) +assert m != s, "mutation did not land" +p.write_text(m) +PY +rejects "catalog: render a chart without its tenant inputs" test_catalog \ + test_missing_inputs_are_named_and_helm_is_not_run +res $F + +edit $F <<'PY' +import pathlib, sys +p = pathlib.Path(sys.argv[1]); s = p.read_text() +m = s.replace(' for values in chart.value_files:\n cmd += ["-f", str(values)]\n', + ' for values in chart.value_files[:1]:\n cmd += ["-f", str(values)]\n', 1) +assert m != s, "mutation did not land" +p.write_text(m) +PY +rejects "catalog: leave the tenant inputs out of the command" test_catalog \ + test_it_renders_the_chart_with_its_values_then_its_inputs_then_the_environment +res $F + +edit $F <<'PY' +import pathlib, sys +p = pathlib.Path(sys.argv[1]); s = p.read_text() +m = s.replace(' raise CannotRender(\n', + ' raise RenderFailed(\n', 1) +assert m != s, "mutation did not land" +p.write_text(m) +PY +rejects "catalog: report a hung render as a finding" test_catalog \ + test_a_render_that_runs_out_of_time_decided_nothing +res $F + +edit $F <<'PY' +import pathlib, sys +p = pathlib.Path(sys.argv[1]); s = p.read_text() +m = s.replace(' return 1 if failed else 0\n', + ' return 0\n', 1) +assert m != s, "mutation did not land" +p.write_text(m) +PY +rejects "catalog: exit 0 over a chart that did not render" test_catalog \ + test_a_chart_that_fails_fails_the_run_and_the_rest_still_render +res $F + +edit $F <<'PY' +import pathlib, sys +p = pathlib.Path(sys.argv[1]); s = p.read_text() +m = s.replace(' ap.error("--out must contain {name}, or every chart would be written to one file")\n', + ' pass\n', 1) +assert m != s, "mutation did not land" +p.write_text(m) +PY +rejects "catalog: write every chart to one --out file" test_catalog \ + test_an_out_path_without_the_chart_name_is_refused +res $F + # scripts/check-workflow-id-masking.py and scripts/mask-aws-ids.py carry no # probe here. Both are vendored (scripts/vendored.json): an edit to either is # refused by the record check before any rule is reached, so a probe planted in diff --git a/scripts/tests/run.py b/scripts/tests/run.py index ffffa52..e9d042b 100755 --- a/scripts/tests/run.py +++ b/scripts/tests/run.py @@ -152,6 +152,9 @@ # The ServiceAccounts a chart's pods run as and the ones it creates, held to # one set in both directions. "test_serviceaccount_bindings", + # The one render of the catalog's own charts, which every renderer of them + # goes through. + "test_catalog", # Every AWS account id a workflow reads is a secret masked first, and the # vendored mask script is the copy its record names. "test_workflow_id_masking", @@ -247,6 +250,9 @@ "scripts/check-image-verification.py": (100, 100), "scripts/check-policy-validity.py": (100, 100), "scripts/verdicts.py": (100, 100), + # 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), diff --git a/scripts/tests/test_catalog.py b/scripts/tests/test_catalog.py new file mode 100644 index 0000000..6ffee9e --- /dev/null +++ b/scripts/tests/test_catalog.py @@ -0,0 +1,253 @@ +"""Unit tests for scripts/catalog.py, the one render of the catalog's own charts. + +Every renderer of a catalog chart goes through this module: CI's validate job, +`task render` and check-serviceaccount-bindings.py. These hold +which charts it finds, the command it builds, what a render that fails or hangs +is reported as, and what main() writes and exits with. helm is replaced by a +stub, so no case depends on helm or on the chart tree on disk, except the last +class, which reads the real tree without rendering it. +""" + +from __future__ import annotations + +import contextlib +import io +import pathlib +import subprocess +import tempfile +import unittest +from unittest import mock + +from gateloader import load + +catalog = load("catalog") + + +class ATree(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = pathlib.Path(tmp.name).resolve() + self.calls: list[tuple[list[str], dict]] = [] + self.answers: dict[str, subprocess.CompletedProcess | Exception] = {} + + def chart(self, name: str, values: bool = True, inputs: bool = True): + d = self.root / "catalog" / name / "chart" + d.mkdir(parents=True) + if values: + (d.parent / "values.yaml").write_text("{}\n") + if inputs: + (d.parent / catalog.TENANT_INPUTS).write_text("{}\n") + return catalog.CatalogChart(self.root, d) + + def helm(self, cmd, **kwargs): + self.calls.append((cmd, kwargs)) + answer = self.answers[pathlib.Path(cmd[3]).parent.name] + if isinstance(answer, Exception): + raise answer + return answer + + def stub_helm(self): + patch = mock.patch.object(catalog.subprocess, "run", self.helm) + patch.start() + self.addCleanup(patch.stop) + + def answer(self, name: str, rc: int = 0, out: str = "", err: str = "") -> None: + self.answers[name] = subprocess.CompletedProcess([], rc, out, err) + + +class Discovery(ATree): + def test_every_chart_directory_is_found_in_order(self): + self.chart("zeta") + self.chart("alpha") + self.assertEqual([c.name for c in catalog.discover(self.root)], ["alpha", "zeta"]) + + def test_a_file_named_chart_is_not_a_chart(self): + (self.root / "catalog" / "notes").mkdir(parents=True) + (self.root / "catalog" / "notes" / "chart").write_text("not a directory\n") + self.assertEqual(catalog.discover(self.root), []) + + def test_a_tree_with_no_catalog_finds_nothing(self): + self.assertEqual(catalog.discover(self.root), []) + + def test_a_chart_is_named_for_its_catalog_directory(self): + c = self.chart("druid") + self.assertEqual(c.name, "druid") + self.assertEqual(c.path, "catalog/druid/chart") + self.assertEqual(c.namespace, "druid-ci") + self.assertEqual( + c.value_files, + [ + self.root / "catalog" / "druid" / "values.yaml", + self.root / "catalog" / "druid" / catalog.TENANT_INPUTS, + ], + ) + + +class TheCommand(ATree): + def test_it_renders_the_chart_with_its_values_then_its_inputs_then_the_environment(self): + c = self.chart("druid") + self.assertEqual( + catalog.template_command(c, "staging"), + [ + "helm", + "template", + "ci", + str(c.chart_dir), + "--namespace", + "druid-ci", + "-f", + str(c.value_files[0]), + "-f", + str(c.value_files[1]), + "--set", + "environment=staging", + ], + ) + + +class Render(ATree): + def setUp(self): + super().setUp() + self.stub_helm() + + def test_a_chart_that_renders_returns_its_manifests(self): + c = self.chart("app") + self.answer("app", out="kind: Pod\n") + self.assertEqual(catalog.render(c, "development"), "kind: Pod\n") + ((cmd, kwargs),) = self.calls + self.assertEqual(cmd, catalog.template_command(c, "development")) + self.assertEqual(kwargs["timeout"], catalog.RENDER_TIMEOUT) + + def test_missing_inputs_are_named_and_helm_is_not_run(self): + c = self.chart("app", values=False, inputs=False) + with self.assertRaises(catalog.RenderFailed) as raised: + catalog.render(c, "development") + self.assertIn( + f"catalog/app/values.yaml, catalog/app/{catalog.TENANT_INPUTS} does not exist", + str(raised.exception), + ) + self.assertEqual(self.calls, []) + + def test_a_chart_helm_refuses_is_a_finding_with_helms_words(self): + c = self.chart("app") + self.answer("app", rc=1, err="Error: values don't meet the schema\n") + with self.assertRaises(catalog.RenderFailed) as raised: + catalog.render(c, "development") + self.assertEqual(str(raised.exception), "Error: values don't meet the schema") + + def test_a_refusal_on_stdout_alone_is_still_reported(self): + c = self.chart("app") + self.answer("app", rc=1, out="Error: on stdout\n") + with self.assertRaises(catalog.RenderFailed) as raised: + catalog.render(c, "development") + self.assertEqual(str(raised.exception), "Error: on stdout") + + def test_helms_words_are_bounded(self): + c = self.chart("app") + self.answer("app", rc=1, err="x" * 5000) + with self.assertRaises(catalog.RenderFailed) as raised: + catalog.render(c, "development") + self.assertEqual(len(str(raised.exception)), 1200) + + def test_a_render_that_runs_out_of_time_decided_nothing(self): + c = self.chart("app") + self.answers["app"] = subprocess.TimeoutExpired(["helm"], catalog.RENDER_TIMEOUT) + with self.assertRaises(catalog.CannotRender) as raised: + catalog.render(c, "development") + self.assertIn( + f"ran past the {catalog.RENDER_TIMEOUT}s a render of catalog/app/chart", + str(raised.exception), + ) + + +class Main(ATree): + def setUp(self): + super().setUp() + self.stub_helm() + self.required: list[tuple[str, ...]] = [] + for patch in ( + mock.patch.object(catalog, "ROOT", self.root), + mock.patch.object(catalog.gatelib, "require", lambda *t: self.required.append(t)), + ): + patch.start() + self.addCleanup(patch.stop) + # discover() binds ROOT as its default when the module loads, so main's + # call is pointed at the scratch tree here rather than through ROOT. + real = catalog.discover + rediscover = mock.patch.object(catalog, "discover", lambda root=None: real(self.root)) + rediscover.start() + self.addCleanup(rediscover.stop) + self.out = str(self.root / "rendered" / "catalog-{name}-chart.yaml") + + def run_main(self, *argv: str) -> tuple[int, str]: + said = io.StringIO() + with contextlib.redirect_stdout(said): + rc = catalog.main(list(argv)) + return rc, said.getvalue() + + def test_every_chart_is_written_where_out_names_it(self): + self.chart("app") + self.chart("db") + self.answer("app", out="kind: A\n") + self.answer("db", out="kind: B\n") + rc, said = self.run_main("--env", "hub", "--out", self.out) + self.assertEqual(rc, 0, said) + rendered = self.root / "rendered" + self.assertEqual((rendered / "catalog-app-chart.yaml").read_text(), "kind: A\n") + self.assertEqual((rendered / "catalog-db-chart.yaml").read_text(), "kind: B\n") + self.assertIn("rendered catalog/app/chart for hub to", said) + self.assertEqual(self.required, [("helm",)]) + self.assertTrue(all(cmd[-1] == "environment=hub" for cmd, _ in self.calls)) + + def test_a_chart_that_fails_fails_the_run_and_the_rest_still_render(self): + self.chart("app") + self.chart("db") + self.answer("app", rc=1, err="Error: broken\n") + self.answer("db", out="kind: B\n") + rc, said = self.run_main("--env", "development", "--out", self.out) + self.assertEqual(rc, 1, said) + self.assertIn( + "FAIL catalog/app/chart did not render for development:\nError: broken", said + ) + self.assertFalse((self.root / "rendered" / "catalog-app-chart.yaml").exists()) + self.assertTrue((self.root / "rendered" / "catalog-db-chart.yaml").exists()) + + def test_a_render_that_runs_out_of_time_cannot_run(self): + self.chart("app") + self.chart("db") + self.answers["app"] = subprocess.TimeoutExpired(["helm"], catalog.RENDER_TIMEOUT) + rc, said = self.run_main("--env", "development", "--out", self.out) + self.assertEqual(rc, catalog.gatelib.CANNOT_RUN, said) + self.assertIn("Cannot run: helm template ran past", said) + self.assertEqual(len(self.calls), 1, "a run that cannot decide stops there") + + def test_no_chart_cannot_run(self): + rc, said = self.run_main("--env", "development", "--out", self.out) + self.assertEqual(rc, catalog.gatelib.CANNOT_RUN, said) + self.assertIn(f"no chart matched {catalog.CHART_GLOB}", said) + + def test_an_out_path_without_the_chart_name_is_refused(self): + self.chart("app") + err = io.StringIO() + with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as raised: + catalog.main(["--env", "development", "--out", "rendered/all.yaml"]) + self.assertEqual(raised.exception.code, 2) + self.assertIn("--out must contain {name}", err.getvalue()) + self.assertEqual(self.calls, []) + + +class TheRealTree(unittest.TestCase): + """The catalog on disk carries what every render needs, without rendering it.""" + + def test_druid_is_in_the_catalog_with_its_values_and_tenant_inputs(self): + charts = {c.name: c for c in catalog.discover()} + self.assertIn("druid", charts) + for chart in charts.values(): + for values in chart.value_files: + with self.subTest(chart=chart.name, values=values.name): + self.assertTrue(values.is_file(), f"{values} does not exist") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_serviceaccount_bindings.py b/scripts/tests/test_serviceaccount_bindings.py index 787656e..4588d2d 100644 --- a/scripts/tests/test_serviceaccount_bindings.py +++ b/scripts/tests/test_serviceaccount_bindings.py @@ -5,9 +5,10 @@ renders each in-repo chart and requires the names its pods run as and the names it creates to be one set, in both directions, with an exemption that has to say what consumes a ServiceAccount no pod uses. These hold where it finds a PodSpec -in each workload kind, what it renders with, and the verdict over rendered -charts. helm is replaced by a stub that returns the documents a test hands it, -so no case depends on the chart tree on disk. +in each workload kind, that it renders each chart the way scripts/catalog.py +does, and the verdict over rendered charts. helm is replaced by a stub that +returns the documents a test hands it, so no case depends on the chart tree on +disk. """ from __future__ import annotations @@ -78,29 +79,32 @@ def setUp(self): self.addCleanup(tmp.cleanup) self.root = pathlib.Path(tmp.name).resolve() (self.root / "scripts").mkdir() - self.rendered: dict[str, list[dict] | None] = {} + self.rendered: dict[str, list[dict] | str | None] = {} self.commands: list[list[str]] = [] # The gate finds charts relative to its own file, so it is pointed at the tree. for patch in ( mock.patch.object(gate, "__file__", str(self.root / "scripts" / "gate.py")), mock.patch.object(gate.gatelib, "require", lambda *tools: None), - mock.patch.object(gate.gatelib.subprocess, "run", self.helm), + mock.patch.object(gate.catalog.subprocess, "run", self.helm), ): patch.start() self.addCleanup(patch.stop) def helm(self, cmd, **kwargs): self.commands.append(cmd) - docs = self.rendered[cmd[2]] + docs = self.rendered[pathlib.Path(cmd[3]).parent.name] + if docs == "hang": + raise subprocess.TimeoutExpired(cmd, kwargs["timeout"]) if docs is None: return subprocess.CompletedProcess(cmd, 1, "", "Error: values don't meet the schema") return subprocess.CompletedProcess(cmd, 0, yaml.safe_dump_all([*docs, None]), "") - def chart(self, name: str, *docs: dict, values: bool = True) -> None: + def chart(self, name: str, *docs: dict, inputs: bool = True) -> None: chart = self.root / "catalog" / name / "chart" chart.mkdir(parents=True) - if values: - (chart.parent / "values.yaml").write_text("{}\n") + (chart.parent / "values.yaml").write_text("{}\n") + if inputs: + (chart.parent / gate.catalog.TENANT_INPUTS).write_text("{}\n") self.rendered[name] = list(docs) def check(self) -> tuple[int, str]: @@ -152,26 +156,37 @@ def test_a_chart_that_renders_nothing_fails(self): self.assertIn("helm template failed\nError: values don't meet the schema", said) self.assertIn("broken/chart::rendered no documents", said) - def test_each_chart_renders_with_its_values_and_its_required_inputs(self): + def test_each_chart_renders_the_way_the_catalog_renders_it(self): self.chart("druid", account("druid-msk-client")) - self.chart("plain", account("app"), deployment("app"), values=False) + self.chart("plain", account("app"), deployment("app")) self.check() - druid, plain = self.commands - self.assertEqual(druid[:3], ["helm", "template", "druid"]) - self.assertEqual( - druid[4:], - [ - "-f", - str(self.root / "catalog" / "druid" / "values.yaml"), - *gate.RENDER_VALUES["druid"], - ], - ) - self.assertEqual(plain[3:], [str(self.root / "catalog" / "plain" / "chart")]) + expected = [ + gate.catalog.template_command(chart, gate.ENVIRONMENT) + for chart in gate.catalog.discover(self.root) + ] + self.assertEqual(self.commands, expected) + self.assertEqual(len(expected), 2) + + def test_a_chart_without_its_tenant_inputs_fails_unrendered(self): + self.chart("app", account("app"), deployment("app"), inputs=False) + rc, said = self.check() + self.assertEqual(rc, 1, said) + self.assertIn(f"catalog/app/{gate.catalog.TENANT_INPUTS} does not exist", said) + self.assertIn("app/chart::rendered no documents", said) + self.assertEqual(self.commands, [], "helm ran without the chart's inputs") + + def test_a_render_that_runs_out_of_time_cannot_run(self): + self.chart("app", account("app"), deployment("app")) + self.rendered["app"] = "hang" + rc, said = self.check() + self.assertEqual(rc, gate.gatelib.CANNOT_RUN, said) + self.assertIn("Cannot run: helm template ran past", said) + self.assertNotIn("every ServiceAccount has a consumer", said) def test_no_chart_is_a_gate_that_verified_nothing(self): rc, said = self.check() - self.assertEqual(rc, 1, said) - self.assertIn(f"no charts matched {gate.CHART_GLOB}", said) + self.assertEqual(rc, gate.gatelib.CANNOT_RUN, said) + self.assertIn(f"no charts matched {gate.catalog.CHART_GLOB}", said) class TheExemptions(unittest.TestCase):