From e6c4c81d433f2ede5115bf6c79ecbc59248c66de Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 18:10:25 +0000 Subject: [PATCH 1/2] ci: check that every guarded SOPS value is in COMPOSE_VARS #1566 guarded WALL_HA_TOKEN in stacks/sensitive/compose.yaml and seeded it, #1563 put it in secrets/sensitive.sops.yaml, and nothing added it to render-config.sh's COMPOSE_VARS. CI validates with the seed's stand-ins and never runs render, so it passed; `make up STACK=sensitive` on trinity did not. scripts/check_compose_vars.py holds the three copies together: a guarded or seeded SOPS key must be in COMPOSE_VARS, a guarded SOPS key must have a stand-in, and a COMPOSE_VARS entry must be a SOPS key. It reads only key names, which SOPS leaves in plaintext. Wired into CI, validate.sh and `make check-compose-vars`; its fixtures run in self-tests.sh. It fails on main at #1566 and passes on #1570's head. Refs #1570. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L2Eweh7G6uK8cbuptGtxTR --- .github/workflows/ci.yml | 9 + Makefile | 4 + docs/changelog.md | 23 +++ scripts/README.md | 1 + scripts/check_compose_vars.py | 307 ++++++++++++++++++++++++++++++++++ scripts/render-config.sh | 2 + scripts/validate.sh | 13 ++ 7 files changed, 359 insertions(+) create mode 100755 scripts/check_compose_vars.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2573191b..a282fa7a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -527,6 +527,15 @@ jobs: - name: Verify every .sops.yaml rule matches the file it was written for run: python3 scripts/check_sops_rules.py + # A SOPS value a compose.yaml guards with ${NAME:?} has to be in + # render-config.sh's COMPOSE_VARS too, or render never writes it and + # `make up` dies on the unset variable. The jobs above validate against + # seed-validation-env.sh's stand-ins and never run render, so #1566 passed + # here with WALL_HA_TOKEN missing from the list and failed on trinity + # (#1570). Names only: no secret is decrypted. + - name: Verify every guarded SOPS value is rendered into .env + run: python3 scripts/check_compose_vars.py + - name: Verify the SNMP inventory agrees with itself run: ./scripts/snmp-targets.sh --check diff --git a/Makefile b/Makefile index 22156a4d..618a640a 100644 --- a/Makefile +++ b/Makefile @@ -596,6 +596,10 @@ check-dashboard-roundtrip: ## Boot the pinned Grafana and verify the dashboards check-image-pins: ## Verify every docker image comes from compose.yaml $(PYTHON) scripts/check_image_pins.py +.PHONY: check-compose-vars +check-compose-vars: ## Verify every guarded SOPS value is rendered into .env + $(PYTHON) scripts/check_compose_vars.py + .PHONY: check-timers check-timers: ## Verify the schedule and its staleness thresholds agree @# Under Validation rather than Maintenance, unlike `install-timers` below: diff --git a/docs/changelog.md b/docs/changelog.md index d42394c6..7e40ba29 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -19,6 +19,29 @@ docstring gives: it is a record, not a claim about now. ## 2026-11-18 +- **CI now checks that a guarded SOPS value is one render writes.** + [#1566](https://github.com/Gerrrt/HomeLab/issues/1566) added the + `${WALL_HA_TOKEN:?}` guard to `stacks/sensitive/compose.yaml` and a + stand-in to `scripts/seed-validation-env.sh`, and + [#1563](https://github.com/Gerrrt/HomeLab/issues/1563) added the key to + `secrets/sensitive.sops.yaml`, but nothing added it to `COMPOSE_VARS` in + `scripts/render-config.sh`. CI passed, because it validates against the + seed's stand-ins and never runs render, and `make up STACK=sensitive` on + `trinity` then stopped on "required variable WALL_HA_TOKEN is missing a + value". [#1570](https://github.com/Gerrrt/HomeLab/issues/1570) adds the + line. + - **The check:** `scripts/check_compose_vars.py` reads the guards from every + `stacks/*/compose.yaml`, the top-level key names from every + `secrets/*.sops.yaml` (plaintext in the encrypted file, so nothing is + decrypted), `COMPOSE_VARS` and the seed's stand-ins. It fails on a guarded + or seeded SOPS key missing from `COMPOSE_VARS`, a guarded SOPS key with no + stand-in, and a `COMPOSE_VARS` entry that is no SOPS key. It runs in CI, + `make validate` and `make check-compose-vars`, and its fixtures run in + `scripts/self-tests.sh`. + - **Proved on both sides of the fix:** on `main` at #1566 it fails and + names `WALL_HA_TOKEN`; on #1570's head it passes, with 51 guarded SOPS + values all rendered and seeded. + - **The wall page reads the house and the family calendar from Home Assistant.** Its header now shows the weather; a Today panel under the alerts lists today's and tomorrow's events; and its bottom row reads the diff --git a/scripts/README.md b/scripts/README.md index 20cd9d8f..0ff41b6f 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -49,6 +49,7 @@ and only its fixtures run in CI, through `self-tests.sh`. | `check_detection_config.sh` | — | Wazuh's rules, `ossec.conf` and `agent.conf` parse, and the rule ids are unique and in range; the indexer JSON parses; and in their pinned images, `wazuh-analysisd -t` and `zeek --parse-only` accept the configs odin and fenrir run | | `check_image_pins.py` | `check-image-pins` | Every image the repository runs comes from a `compose.yaml`, and an image that mounts another stack's config runs that stack's exact pin | | `check_shared_blocks.py` | — | Every copy of a `# shared-block:` (code copied because a collector installs as one file) matches the others, so a fix cannot land in one copy only | +| `check_compose_vars.py` | `check-compose-vars` | Every SOPS value a `compose.yaml` guards with `${VAR:?}` is in `render-config.sh`'s `COMPOSE_VARS` and has a stand-in in `seed-validation-env.sh`, and every `COMPOSE_VARS` entry is a SOPS key (#1570) | | `check_sops_rules.py`, `check-sops-encrypted.sh` | — | `.sops.yaml` matches its files, and every committed SOPS file is ciphertext, now and (`--history`) in every past revision | | `check-tracked-artefacts.sh` | — | Nothing rendered, decrypted or secret-bearing is tracked | | `gitleaks-history.sh` | — | The full-history secret scan CI and `validate.sh` both run, which fails a scan of zero commits because gitleaks exits 0 when git cannot read the repository; its fixtures run in `self-tests.sh` | diff --git a/scripts/check_compose_vars.py b/scripts/check_compose_vars.py new file mode 100755 index 00000000..91afff3d --- /dev/null +++ b/scripts/check_compose_vars.py @@ -0,0 +1,307 @@ +#!/usr/bin/env python3 +"""Every guarded SOPS value is one render-config.sh writes into .env. + +Usage: + scripts/check_compose_vars.py check the repository + scripts/check_compose_vars.py --self-test fixtures + +Why this exists +--------------- +A value a stack reads from SOPS reaches compose through three copies of one +fact, and the comment above COMPOSE_VARS in scripts/render-config.sh says so: + + - the `${NAME:?}` guard in stacks//compose.yaml, which makes a + missing value fail loudly at `make up`; + - the COMPOSE_VARS array in scripts/render-config.sh, the names it copies + out of the decrypted SOPS file into the stack's .env; + - scripts/seed-validation-env.sh, the throwaway .env that lets validation + get past the guard. + +On 2026-11-18 #1563 added WALL_HA_TOKEN to secrets/sensitive.sops.yaml and +#1566 added its guard to stacks/sensitive/compose.yaml and its stand-in to +seed-validation-env.sh. Nobody added it to COMPOSE_VARS. CI passed, because CI +validates against the seed's stand-ins and never runs render-config.sh, and +`make up STACK=sensitive` on trinity then died with "required variable +WALL_HA_TOKEN is missing a value". #1570 added the line. Nothing checked the +copies against each other; this does. + +What this asserts +----------------- +1. A guarded name that is a key in some secrets/*.sops.yaml is in + COMPOSE_VARS. This is the one that would have caught #1566. +2. A name seed-validation-env.sh stands in for that is a SOPS key is in + COMPOSE_VARS: the same bug, seen from the third copy. +3. A guarded name that is a SOPS key has a stand-in in seed-validation-env.sh. + That script checks this per stack when it runs; here it is checked for + every stack at once. +4. Every COMPOSE_VARS entry is a key in some SOPS file. One that is not + names nothing render can ever write, which is a typo or a leftover. + +A guard on a name that is not a SOPS key (RENDER_UID, a bind address in +.env.example) is not this check's business: render-config.sh writes those +another way, or the operator does. + +No secret is read. A SOPS file keeps its top-level key names in plaintext +(`NAME: ENC[...]`); only the names are taken, never the line's value. +""" + +from __future__ import annotations + +import argparse +import re +import sys +import tempfile +from pathlib import Path + +import yaml + +REPO = Path(__file__).resolve().parent.parent + +NAME = r"[A-Za-z_][A-Za-z0-9_]*" +# The same pattern scripts/compose-guards.sh walks the parsed YAML with, so a +# comment that mentions the guard syntax is not read as a guard (#107). +GUARD = re.compile(r"\$\{(" + NAME + r"):\?") +SOPS_KEY = re.compile(r"^(" + NAME + r"):", re.MULTILINE) +COMPOSE_VARS = re.compile(r"^COMPOSE_VARS=\((.*?)^\)", re.MULTILINE | re.DOTALL) +SEED = re.compile(r"""^\s*echo\s+['"](""" + NAME + r")=", re.MULTILINE) + + +class SourceError(Exception): + """A source could not be read, which must fail rather than pass empty.""" + + +def compose_guards(root: Path) -> dict[str, set[str]]: + """Guarded name -> the compose files that guard it.""" + found: dict[str, set[str]] = {} + + def walk(node: object, rel: str) -> None: + if isinstance(node, dict): + for key, value in node.items(): + walk(key, rel) + walk(value, rel) + elif isinstance(node, list): + for item in node: + walk(item, rel) + elif isinstance(node, str): + for name in GUARD.findall(node): + found.setdefault(name, set()).add(rel) + + files = sorted(root.glob("stacks/*/compose.yaml")) + if not files: + raise SourceError("no stacks/*/compose.yaml found") + for path in files: + walk(yaml.safe_load(path.read_text(encoding="utf-8")), path.relative_to(root).as_posix()) + return found + + +def sops_keys(root: Path) -> dict[str, set[str]]: + """Top-level key name -> the SOPS files that hold it. Names only.""" + found: dict[str, set[str]] = {} + files = sorted(root.glob("secrets/*.sops.yaml")) + if not files: + raise SourceError("no secrets/*.sops.yaml found") + for path in files: + for name in SOPS_KEY.findall(path.read_text(encoding="utf-8")): + if name != "sops": + found.setdefault(name, set()).add(path.relative_to(root).as_posix()) + return found + + +def compose_vars(root: Path) -> set[str]: + text = (root / "scripts/render-config.sh").read_text(encoding="utf-8") + match = COMPOSE_VARS.search(text) + if not match: + raise SourceError("scripts/render-config.sh: no COMPOSE_VARS=( ... ) array found") + names: set[str] = set() + for line in match.group(1).splitlines(): + line = line.split("#", 1)[0] + names.update(line.split()) + if not names: + raise SourceError("scripts/render-config.sh: COMPOSE_VARS is empty") + return names + + +def seed_names(root: Path) -> set[str]: + text = (root / "scripts/seed-validation-env.sh").read_text(encoding="utf-8") + names = set(SEED.findall(text)) + if not names: + raise SourceError("scripts/seed-validation-env.sh: no `echo NAME=` lines found") + return names + + +def where(files: set[str]) -> str: + return ", ".join(sorted(files)) + + +def check(root: Path) -> tuple[list[str], str]: + """Problems found, and a one-line summary for a clean run.""" + try: + guards = compose_guards(root) + keys = sops_keys(root) + listed = compose_vars(root) + seeded = seed_names(root) + except (OSError, SourceError, yaml.YAMLError) as err: + return [f"could not read a source: {err}"], "" + + problems = [] + for name in sorted((guards.keys() & keys.keys()) - listed): + problems.append( + f"{where(guards[name])} guards {name}, a key in {where(keys[name])}, but " + f"COMPOSE_VARS in scripts/render-config.sh does not list it: render would " + f"not write it and `make up` would fail on the unset variable. Add it there." + ) + for name in sorted((seeded & keys.keys()) - guards.keys() - listed): + problems.append( + f"scripts/seed-validation-env.sh stands in for {name}, a key in " + f"{where(keys[name])}, but COMPOSE_VARS in scripts/render-config.sh does " + f"not list it. Add it there, or drop the stand-in if nothing reads it." + ) + for name in sorted((guards.keys() & keys.keys()) - seeded): + problems.append( + f"{where(guards[name])} guards {name}, a key in {where(keys[name])}, but " + f"scripts/seed-validation-env.sh has no stand-in for it. Add one there." + ) + for name in sorted(listed - keys.keys()): + problems.append( + f"COMPOSE_VARS in scripts/render-config.sh lists {name}, which is a key in " + f"no secrets/*.sops.yaml, so render can never write it. Fix or remove it." + ) + + covered = len(guards.keys() & keys.keys()) + summary = ( + f"COMPOSE_VARS OK — all {covered} guarded SOPS values are rendered and seeded " + f"({len(listed)} listed, {len(keys)} SOPS keys, {len(guards)} guards)" + ) + return problems, summary + + +def self_test() -> int: + render = "COMPOSE_VARS=(\n {names}\n)\n" + seed = "{{\n{lines}}} >> out\n" + + def tree( + root: Path, + *, + guards: list[str], + keys: list[str], + listed: list[str] | None, + seeded: list[str], + compose_extra: str = "", + ) -> None: + for d in ("stacks/a", "secrets", "scripts"): + (root / d).mkdir(parents=True, exist_ok=True) + env = "".join(f" {g}: ${{{g}:?set it}}\n" for g in guards) + (root / "stacks/a/compose.yaml").write_text( + "services:\n x:\n image: x\n" + compose_extra + (" environment:\n" + env if env else "") + ) + (root / "secrets/a.sops.yaml").write_text( + "".join(f"{k}: ENC[AES256_GCM,data:xx,type:str]\n" for k in keys) + "sops:\n version: 3\n" + ) + (root / "scripts/render-config.sh").write_text( + render.format(names="\n ".join(listed)) if listed is not None else "echo no list\n" + ) + (root / "scripts/seed-validation-env.sh").write_text( + seed.format(lines="".join(f' echo "{s}=validation-only"\n' for s in seeded)) + ) + + cases = [ + ( + "a consistent tree passes", + {"guards": ["TOKEN"], "keys": ["TOKEN"], "listed": ["TOKEN"], "seeded": ["TOKEN"]}, + 0, + ), + ( + "the WALL_HA_TOKEN shape (guarded, in SOPS, seeded, not listed) fails", + { + "guards": ["TOKEN", "WALL_HA_TOKEN"], + "keys": ["TOKEN", "WALL_HA_TOKEN"], + "listed": ["TOKEN"], + "seeded": ["TOKEN", "WALL_HA_TOKEN"], + }, + 1, + ), + ( + "a seeded SOPS key that is not listed fails even unguarded", + {"guards": [], "keys": ["TOKEN", "OTHER"], "listed": ["TOKEN"], "seeded": ["OTHER"]}, + 1, + ), + ( + "a guarded SOPS key with no stand-in fails", + {"guards": ["TOKEN"], "keys": ["TOKEN"], "listed": ["TOKEN"], "seeded": ["SOMETHING"]}, + 1, + ), + ( + "a listed name in no SOPS file fails", + {"guards": ["TOKEN"], "keys": ["TOKEN"], "listed": ["TOKEN", "TYPO"], "seeded": ["TOKEN"]}, + 1, + ), + ( + "a guard on a non-SOPS name (RENDER_UID) is ignored", + { + "guards": ["TOKEN", "RENDER_UID"], + "keys": ["TOKEN"], + "listed": ["TOKEN"], + "seeded": ["TOKEN", "RENDER_UID"], + }, + 0, + ), + ( + "the `sops:` metadata key is not a value", + {"guards": ["TOKEN"], "keys": ["TOKEN"], "listed": ["TOKEN", "sops"], "seeded": ["TOKEN"]}, + 1, + ), + ( + "a guard in a YAML comment is not a guard", + { + "guards": ["TOKEN"], + "keys": ["TOKEN", "WALL_HA_TOKEN"], + "listed": ["TOKEN", "WALL_HA_TOKEN"], + "seeded": ["TOKEN"], + "compose_extra": " # ${NOT_A_GUARD:?} would be read by a grep\n", + }, + 0, + ), + ( + "a missing COMPOSE_VARS array fails rather than passing empty", + {"guards": ["TOKEN"], "keys": ["TOKEN"], "listed": None, "seeded": ["TOKEN"]}, + 1, + ), + ("an empty COMPOSE_VARS array fails", {"guards": [], "keys": ["TOKEN"], "listed": [], "seeded": ["TOKEN"]}, 1), + ( + "a seed script with no stand-ins fails rather than passing empty", + {"guards": ["TOKEN"], "keys": ["TOKEN"], "listed": ["TOKEN"], "seeded": []}, + 1, + ), + ] + failed = 0 + for desc, spec, want in cases: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + tree(root, **spec) + problems, _ = check(root) + got = 1 if problems else 0 + if got == want: + print(f"\033[0;32m PASS\033[0m {desc}") + else: + print(f"\033[0;31m FAIL\033[0m {desc} (got {got}, want {want}): {problems}") + failed = 1 + return failed + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--self-test", action="store_true", help="run the fixtures") + args = parser.parse_args() + if args.self_test: + return self_test() + problems, summary = check(REPO) + for problem in problems: + print(f" {problem}", file=sys.stderr) + if problems: + return 1 + print(summary) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/render-config.sh b/scripts/render-config.sh index a3c3a611..2f431ac3 100755 --- a/scripts/render-config.sh +++ b/scripts/render-config.sh @@ -555,6 +555,8 @@ fi # that names a SOPS value has to be added here, or render passes and `make up` # then dies on the unset variable — the guard and this list are two copies of # one fact, and scripts/seed-validation-env.sh is the third. +# scripts/check_compose_vars.py holds the three together in CI: #1566 added +# WALL_HA_TOKEN's guard and stand-in but not this line, and only trinity saw it. COMPOSE_VARS=( GRAFANA_ADMIN_USER GRAFANA_ADMIN_PASSWORD diff --git a/scripts/validate.sh b/scripts/validate.sh index 4682b01e..2d628f16 100755 --- a/scripts/validate.sh +++ b/scripts/validate.sh @@ -822,6 +822,19 @@ else skip "python3 not installed" fi +# A guarded SOPS value missing from render-config.sh's COMPOSE_VARS passes every +# compose validation here, which uses seed-validation-env.sh's stand-ins, and +# fails only at `make up` on the host (#1566, #1570). +if have python3; then + if python3 scripts/check_compose_vars.py; then + pass "every guarded SOPS value is in COMPOSE_VARS and seeded" + else + fail "a guarded SOPS value is missing from COMPOSE_VARS or the seed — see above" + fi +else + skip "python3 not installed" +fi + # Both scans, matching CI exactly. Running only the working-tree scan locally # would let `make validate` pass while CI fails on history, or vice versa. # The docker fallback is the same shape promtool, amtool and alloy have above, From c1501510dfae3772190e6d3dab450a7d9992e747 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 18:18:17 +0000 Subject: [PATCH 2/2] ci(check_compose_vars): load PyYAML via _deps; make the comment fixture bite Load PyYAML through scripts/_deps.require_yaml(), as every sibling check does, so the pinned bootstrap is used where bare python3 lacks it (#848). The YAML-comment fixture now comments out a guard on a SOPS key that is listed but unseeded, so a regression to scanning raw text fails it; with NOT_A_GUARD, a non-SOPS name, every assertion ignored it either way (#107). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L2Eweh7G6uK8cbuptGtxTR --- scripts/check_compose_vars.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/scripts/check_compose_vars.py b/scripts/check_compose_vars.py index 91afff3d..f4d918a3 100755 --- a/scripts/check_compose_vars.py +++ b/scripts/check_compose_vars.py @@ -53,7 +53,11 @@ import tempfile from pathlib import Path -import yaml +# PyYAML from the one pinned bootstrap, scripts/_deps.py (#848). +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from _deps import require_yaml + +yaml = require_yaml() REPO = Path(__file__).resolve().parent.parent @@ -257,7 +261,7 @@ def tree( "keys": ["TOKEN", "WALL_HA_TOKEN"], "listed": ["TOKEN", "WALL_HA_TOKEN"], "seeded": ["TOKEN"], - "compose_extra": " # ${NOT_A_GUARD:?} would be read by a grep\n", + "compose_extra": " # ${WALL_HA_TOKEN:?} would be read by a grep\n", }, 0, ),