From eea80f475e03168064f601ab2039b6da68d4fd9b Mon Sep 17 00:00:00 2001 From: Lance Walters Date: Fri, 27 Nov 2026 00:57:31 -0500 Subject: [PATCH] sops: decrypt on every Flux Kustomization + static guard `spec.decryption` is opt-in per Flux Kustomization, and a secret-*.sops.yaml under a tree without it is still valid YAML: Flux applies the Secret with literal ENC[AES256_GCM,...] values and reports success. The Secret is green and wrong, and the first symptom is an auth failure days later that looks nothing like a git problem. Only `apps` and `monitoring` had the block; the other six trees were a trap for the next person to add a Secret there. - add decryption: {provider: sops, secretRef: sops-age} to cert-manager, databases, gateway-api-crds, infrastructure, logging and flux-system (8/8 Kustomizations now decrypt; harmless where no encrypted files exist) - scripts/check-sops-decryption.py + `make check-sops`: static guard that reads the live sync path from gotk-sync.yaml, walks each Kustomization's kustomize resource graph, and fails when a *.sops.yaml file is under a tree whose owner cannot decrypt, is under no reconciled tree, or is not actually encrypted (also catches `flux bootstrap` regenerating gotk-sync.yaml without the block) - .gitattributes marks *.sops.yaml with diff=sopsdiffer; docs/secrets-sops.md explains the opt-in trap, the eight Kustomizations and the guard No secret contents, recipients or keys touched. --- .gitattributes | 6 + Makefile | 7 +- clusters/homek8s/cert-manager.yaml | 7 + clusters/homek8s/databases.yaml | 6 + clusters/homek8s/flux-system/gotk-sync.yaml | 9 + clusters/homek8s/gateway-api-crds.yaml | 8 +- clusters/homek8s/infrastructure.yaml | 6 + clusters/homek8s/logging.yaml | 6 + docs/secrets-sops.md | 48 +++- scripts/check-sops-decryption.py | 238 ++++++++++++++++++++ 10 files changed, 338 insertions(+), 3 deletions(-) create mode 100644 .gitattributes create mode 100755 scripts/check-sops-decryption.py diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..aac45f0 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +# `git diff` on an encrypted Secret is otherwise a wall of ciphertext. +# Enable the driver once per workstation (needs the age key in ~/.config/sops/age/keys.txt): +# git config --global diff.sopsdiffer.textconv 'sops decrypt --output-type yaml' +# Without that config the attribute is inert and git diffs the file as plain text. +*.sops.yaml diff=sopsdiffer +*.sops.yml diff=sopsdiffer diff --git a/Makefile b/Makefile index 0889404..1336725 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,13 @@ -.PHONY: apply diff storage gateway +.PHONY: apply diff storage gateway check-sops apply: kubectl apply -k infrastructure/home +# Static guard: no secret-*.sops.yaml may sit in a tree whose Flux Kustomization +# cannot decrypt it (see docs/secrets-sops.md). No cluster or age key needed. +check-sops: + ./scripts/check-sops-decryption.py + diff: kubectl diff -k infrastructure/home diff --git a/clusters/homek8s/cert-manager.yaml b/clusters/homek8s/cert-manager.yaml index e32ba2a..8db3b3d 100644 --- a/clusters/homek8s/cert-manager.yaml +++ b/clusters/homek8s/cert-manager.yaml @@ -15,4 +15,11 @@ spec: # release object, and the chart's CRDs carry `helm.sh/resource-policy: keep` # so they survive. Nothing here is a bare CRD in git, hence prune: true. prune: true + # Uniform SOPS policy for every Flux Kustomization: a tree with no encrypted + # files today is exactly where a stray secret-*.sops.yaml would otherwise be + # applied as literal ENC[...] ciphertext — silently. See docs/secrets-sops.md. + decryption: + provider: sops + secretRef: + name: sops-age wait: true diff --git a/clusters/homek8s/databases.yaml b/clusters/homek8s/databases.yaml index 108270d..e73e1f5 100644 --- a/clusters/homek8s/databases.yaml +++ b/clusters/homek8s/databases.yaml @@ -18,6 +18,12 @@ spec: # reasoning as gateway-api-crds. Reverting the operator Deployment args is a # git change, not a prune. prune: false + # Uniform SOPS policy; harmless with no encrypted files in this tree, and it + # removes the "which tree am I in" trap — see docs/secrets-sops.md. + decryption: + provider: sops + secretRef: + name: sops-age # The plugin's operator<->plugin mTLS pair is issued by cert-manager # (Issuer/Certificate in the vendored plugin manifest). Applying those before # the cert-manager CRDs and webhook exist just churns; wait for it. diff --git a/clusters/homek8s/flux-system/gotk-sync.yaml b/clusters/homek8s/flux-system/gotk-sync.yaml index b46b999..52f7f48 100644 --- a/clusters/homek8s/flux-system/gotk-sync.yaml +++ b/clusters/homek8s/flux-system/gotk-sync.yaml @@ -22,6 +22,15 @@ spec: interval: 10m0s path: ./clusters/homek8s prune: true + # Added by hand on top of the generated manifest: uniform SOPS policy for every + # Flux Kustomization (see docs/secrets-sops.md). This tree holds only Flux + # manifests today; the field means a secret-*.sops.yaml dropped here fails + # loudly instead of applying as literal ENC[...] ciphertext. `flux bootstrap` + # regenerates this file and would drop the block — `make check-sops` catches that. + decryption: + provider: sops + secretRef: + name: sops-age sourceRef: kind: GitRepository name: flux-system diff --git a/clusters/homek8s/gateway-api-crds.yaml b/clusters/homek8s/gateway-api-crds.yaml index 6e55b6b..f1dfcbd 100644 --- a/clusters/homek8s/gateway-api-crds.yaml +++ b/clusters/homek8s/gateway-api-crds.yaml @@ -13,4 +13,10 @@ spec: path: ./infrastructure/networking/gateway-api # CRDs must never be pruned automatically: dropping them would delete # every Gateway/HTTPRoute object in the cluster. - prune: false \ No newline at end of file + prune: false + # Uniform SOPS policy; harmless with no encrypted files in this tree, and it + # removes the "which tree am I in" trap — see docs/secrets-sops.md. + decryption: + provider: sops + secretRef: + name: sops-age diff --git a/clusters/homek8s/infrastructure.yaml b/clusters/homek8s/infrastructure.yaml index d01d48d..7cd2b2b 100644 --- a/clusters/homek8s/infrastructure.yaml +++ b/clusters/homek8s/infrastructure.yaml @@ -12,3 +12,9 @@ spec: name: flux-system path: ./infrastructure/home prune: true + # Uniform SOPS policy; harmless with no encrypted files in this tree, and it + # removes the "which tree am I in" trap — see docs/secrets-sops.md. + decryption: + provider: sops + secretRef: + name: sops-age diff --git a/clusters/homek8s/logging.yaml b/clusters/homek8s/logging.yaml index 3ba94e4..cf4ed16 100644 --- a/clusters/homek8s/logging.yaml +++ b/clusters/homek8s/logging.yaml @@ -12,6 +12,12 @@ spec: name: flux-system path: ./infrastructure/logging prune: true + # Uniform SOPS policy; harmless with no encrypted files in this tree, and it + # removes the "which tree am I in" trap — see docs/secrets-sops.md. + decryption: + provider: sops + secretRef: + name: sops-age # Namespace + local-path PVC provisioning come from infrastructure; the # ServiceMonitor/PrometheusRule CRDs come from kube-prometheus-stack via # monitoring, so nothing here is applied before its CRDs exist. diff --git a/docs/secrets-sops.md b/docs/secrets-sops.md index acc9125..f20af1a 100644 --- a/docs/secrets-sops.md +++ b/docs/secrets-sops.md @@ -67,7 +67,16 @@ at the repo root, so `sops` picks it up with no flags as long as the filename ma ## How Flux applies them -`clusters/homek8s/apps.yaml` — the `apps` Kustomization — carries: +**`decryption` is opt-in per Flux Kustomization, and the failure mode is silent.** A +`secret-*.sops.yaml` under a tree whose Kustomization lacks the block is still valid YAML: +kustomize-controller applies the Secret with the literal strings `ENC[AES256_GCM,data:…]` as its +values. The Secret exists, `kubectl get secret` is green, and the first symptom is an application +failing to authenticate — possibly days later, on a pod restart, looking nothing like a git +problem. (Same class as the registry-secret trap in `docs/registry-pull-auth.md`.) + +So **every** Flux Kustomization in `clusters/homek8s/` carries the block, not just the two that +need it today — harmless where a tree has no encrypted files, and it removes the "which tree am +I in" question entirely: ```yaml decryption: @@ -76,10 +85,47 @@ at the repo root, so `sops` picks it up with no flags as long as the filename ma name: sops-age ``` +The eight: `apps`, `monitoring`, `infrastructure`, `logging`, `databases`, `cert-manager`, +`gateway-api-crds` and `flux-system`. Today only `apps` (`apps/base/*/`) and `monitoring` +(`monitoring/controllers/home/`) actually contain encrypted files. + +`clusters/homek8s/flux-system/gotk-sync.yaml` is generated by `flux bootstrap` and says +"DO NOT EDIT"; the `decryption` block there was added by hand and a future bootstrap would drop +it. The guard below catches that. + Flux decrypts server-side *before* kustomize builds, so what lands in the cluster is an ordinary Secret. `prune: true`, so deleting the file deletes the Secret — that is the intended lifecycle. +### Guard — `make check-sops` + +`scripts/check-sops-decryption.py` (static: no cluster, no age key, no network) reads the live +sync path out of `clusters/*/flux-system/gotk-sync.yaml`, walks each Kustomization's kustomize +resource graph, and fails when: + +1. any Flux Kustomization lacks `decryption.provider: sops` (or its `secretRef.name`); +2. a `*.sops.yaml` / `*.sops.yml` file sits under no reconciled tree, or under a tree whose + owner cannot decrypt; +3. a `*.sops.yaml` file contains no `sops:` block / `ENC[AES256_GCM…` — i.e. plaintext wearing + an encrypted file's name. + +```bash +make check-sops # exit 0 = clean, 1 = violations, 2 = could not run (never a pass) +./scripts/check-sops-decryption.py -v # same, plus each Kustomization and file→owner mapping +``` + +Run it before pushing a change that adds or moves a Secret. A violation is a config error, not a +warning: in the un-guarded case Flux applies ciphertext and reports success. + +### Reading a diff + +`.gitattributes` marks `*.sops.yaml` with `diff=sopsdiffer`. To make `git diff` show decrypted +values instead of ciphertext, enable the driver once per workstation (it needs the age key): + +```bash +git config --global diff.sopsdiffer.textconv 'sops decrypt --output-type yaml' +``` + Ordering note: a Secret must exist before its consumer starts (CNPG `bootstrap.initdb.secret`, `imagePullSecrets`, env refs). Kustomize sorts `Secret` before `Deployment`/`Cluster`, and all of these live in the same app directory, so one reconcile creates both. diff --git a/scripts/check-sops-decryption.py b/scripts/check-sops-decryption.py new file mode 100755 index 0000000..cf32e70 --- /dev/null +++ b/scripts/check-sops-decryption.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +"""Fail if a SOPS-encrypted manifest sits in a tree its Flux Kustomization cannot decrypt. + +Why this exists +--------------- +`spec.decryption` is opt-in per Flux Kustomization. A `secret-*.sops.yaml` dropped under a +tree that lacks the block is still valid YAML, so kustomize-controller applies the Secret with +literal `ENC[AES256_GCM,...]` values: the object exists, is wrong, and the first symptom is an +application failing to authenticate — possibly days later, looking nothing like a git problem. +See `docs/secrets-sops.md`. + +What it checks (static: no cluster, no age key, no network) +---------------------------------------------------------- +1. Every Flux `Kustomization` under the live sync path (discovered from + `clusters/*/flux-system/gotk-sync.yaml`) carries `decryption.provider: sops` and a + `secretRef.name`. +2. Every `*.sops.yaml` / `*.sops.yml` file in the repo lives inside the kustomize resource + graph of at least one such Kustomization, and *all* of its owning Kustomizations decrypt. +3. Every such file actually contains SOPS ciphertext (`sops:` metadata + `ENC[AES256_GCM`). + +Usage +----- + scripts/check-sops-decryption.py [-v] # or: make check-sops + +Exit codes: 0 clean, 1 violations found, 2 the check could not run (never treat as a pass). +""" + +from __future__ import annotations + +import os +import sys +from pathlib import Path + +try: + import yaml +except ImportError: # pragma: no cover - environment problem, not a repo problem + sys.stderr.write( + "check-sops-decryption: PyYAML is required (pacman -S python-yaml / pip install pyyaml)\n" + ) + raise SystemExit(2) + +REPO = Path(__file__).resolve().parents[1] +SKIP_DIRS = {".git", ".worktrees", "node_modules"} +SOPS_SECRET = "sops-age" +KUSTOMIZATION_FILES = ("kustomization.yaml", "kustomization.yml", "Kustomization") + +violations: list[str] = [] +notes: list[str] = [] + + +def fail(msg: str) -> None: + violations.append(msg) + + +def load_docs(path: Path): + try: + with path.open("r", encoding="utf-8") as fh: + return [d for d in yaml.safe_load_all(fh) if isinstance(d, dict)] + except (OSError, yaml.YAMLError) as exc: + fail(f"{path.relative_to(REPO)}: cannot parse YAML: {exc}") + return [] + + +def is_flux_kustomization(doc) -> bool: + return ( + doc.get("kind") == "Kustomization" + and str(doc.get("apiVersion", "")).startswith("kustomize.toolkit.fluxcd.io/") + ) + + +def live_manifest_dirs() -> list[Path]: + """Directories Flux actually reconciles, read from the bootstrapped sync manifests.""" + dirs: list[Path] = [] + for gotk in sorted(REPO.glob("clusters/*/flux-system/gotk-sync.yaml")): + for doc in load_docs(gotk): + if is_flux_kustomization(doc) and doc.get("metadata", {}).get("name") == "flux-system": + rel = (doc.get("spec") or {}).get("path", "./") + dirs.append((REPO / rel).resolve()) + return [d for d in dirs if d.is_dir()] + + +def kustomize_build_dirs(start: Path) -> set[Path]: + """Every directory reachable from `start` through kustomize `resources`/`bases`/`components`.""" + seen: dict[Path, None] = {} + stack = [start] + while stack: + current = stack.pop() + if current in seen or not current.is_dir() or current.name in SKIP_DIRS: + continue + seen[current] = None + kfile = next((current / n for n in KUSTOMIZATION_FILES if (current / n).is_file()), None) + if kfile is None: + continue + for doc in load_docs(kfile): + entries = [] + for key in ("resources", "bases", "components"): + value = doc.get(key) or [] + if isinstance(value, list): + entries.extend(v for v in value if isinstance(v, str)) + for entry in entries: + target = Path(os.path.normpath(current / entry)) + if target.is_dir(): + stack.append(target) + return set(seen) + + +class FluxKustomization: + def __init__(self, source: Path, doc) -> None: + self.source = source + self.name = doc.get("metadata", {}).get("name") or source.stem + spec = doc.get("spec") or {} + self.path = (REPO / str(spec.get("path", "./"))).resolve() + decryption = spec.get("decryption") or {} + self.provider = decryption.get("provider") + self.secret = (decryption.get("secretRef") or {}).get("name") + self.dirs = kustomize_build_dirs(self.path) if self.path.is_dir() else set() + + @property + def decrypts(self) -> bool: + return self.provider == "sops" and bool(self.secret) + + def describe(self) -> str: + return f"{self.source.relative_to(REPO)}: {self.name}" + + +def main() -> int: + verbose = "-v" in sys.argv[1:] or "--verbose" in sys.argv[1:] + + manifest_dirs = live_manifest_dirs() + if not manifest_dirs: + sys.stderr.write( + "check-sops-decryption: no clusters/*/flux-system/gotk-sync.yaml with a flux-system\n" + "Kustomization found — refusing to report a pass I cannot prove.\n" + ) + return 2 + + flux_ks: list[FluxKustomization] = [] + for directory in manifest_dirs: + for path in sorted(directory.rglob("*")): + if path.suffix not in (".yaml", ".yml") or not path.is_file(): + continue + if any(part in SKIP_DIRS for part in path.relative_to(REPO).parts): + continue + for doc in load_docs(path): + if is_flux_kustomization(doc): + flux_ks.append(FluxKustomization(path, doc)) + + if not flux_ks: + sys.stderr.write("check-sops-decryption: no Flux Kustomizations found — refusing a pass.\n") + return 2 + + # 1. Every reconciling Kustomization must be able to decrypt. + for k in flux_ks: + if k.provider != "sops": + fail( + f"{k.describe()}: decryption.provider is {k.provider!r}, expected 'sops'\n" + f" any *.sops.yaml under {k.path.relative_to(REPO)}/ would apply as ENC[...] ciphertext" + ) + elif not k.secret: + fail(f"{k.describe()}: decryption.provider is sops but secretRef.name is missing") + + secrets_used = sorted({k.secret for k in flux_ks if k.secret}) + for name in secrets_used: + if name != SOPS_SECRET: + notes.append( + f"note: {name!r} is used as the SOPS key instead of {SOPS_SECRET!r} — make sure it exists" + ) + + # 2./3. Every encrypted file must sit in a tree that decrypts, and be encrypted. + sops_files: list[Path] = [] + for pattern in ("*.sops.yaml", "*.sops.yml"): + for path in sorted(REPO.rglob(pattern)): + rel = path.relative_to(REPO) + if any(part in SKIP_DIRS for part in rel.parts): + continue + if path.name in (".sops.yaml", ".sops.yml"): + continue # the sops creation_rules config, not a manifest + sops_files.append(path) + + for path in sops_files: + rel = path.relative_to(REPO) + owners = [k for k in flux_ks if path.parent in k.dirs] + if not owners: + fail( + f"{rel}: not under any live Flux Kustomization tree\n" + " it is never applied (dead file) — move it into a reconciled tree or delete it" + ) + continue + for owner in owners: + if not owner.decrypts: + fail( + f"{rel}: owned by {owner.describe()} which does not decrypt\n" + f" add decryption: {{provider: sops, secretRef: {{name: {SOPS_SECRET}}}}} to that Kustomization" + ) + try: + text = path.read_text(encoding="utf-8") + except OSError as exc: + fail(f"{rel}: cannot read: {exc}") + continue + if "ENC[AES256_GCM" not in text: + fail(f"{rel}: no SOPS ciphertext (ENC[AES256_GCM...) — is the value plaintext?") + if not any("sops:" in line for line in text.splitlines()): + fail(f"{rel}: missing the `sops:` metadata block — not a SOPS file") + + if verbose: + for k in flux_ks: + print( + f" {k.name:<20} path={k.path.relative_to(REPO)}/" + f" decryption={'sops:' + (k.secret or '') if k.decrypts else 'NONE'}" + ) + for path in sops_files: + owners = ",".join(k.name for k in flux_ks if path.parent in k.dirs) or "-" + print(f" {path.relative_to(REPO)} owner={owners}") + + for note in notes: + print(note, file=sys.stderr) + + decrypting = sum(1 for k in flux_ks if k.provider == "sops") + if violations: + for violation in violations: + print(f"FAIL {violation}", file=sys.stderr) + print( + f"FAIL: {len(violations)} problem(s) across {len(flux_ks)} Flux Kustomizations " + f"({decrypting} decrypt with sops) and {len(sops_files)} SOPS file(s).", + file=sys.stderr, + ) + return 1 + + print( + f"OK: {len(flux_ks)} Flux Kustomizations, {decrypting}/{len(flux_ks)} decrypt with " + f"provider=sops (secret {', '.join(secrets_used) or 'none'}); " + f"{len(sops_files)} SOPS file(s), all inside decrypting trees and genuinely encrypted." + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())