238 lines
9.2 KiB
Python
238 lines
9.2 KiB
Python
|
|
#!/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())
|