homek8s/docs/secrets-sops.md
Lance Walters eea80f475e 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.
2026-11-27 00:57:31 -05:00

13 KiB

Cluster Secrets in Git (SOPS + age)

Decision (2026-11-27): every hand-made Secret consumed by a workload in this repo is committed as a SOPS/age-encrypted plain Secret manifest — not a SealedSecret, not secretGenerator from a plaintext file. One mechanism, no mixing.

Rationale: Flux already ships the sops decryptor (kustomize-controller), so there is no extra controller, CRD or admission webhook to run; the age private key never leaves the two places listed below. SealedSecrets would need a controller in the cluster and a sealing key escrowed somewhere anyway — the same single point of failure with more moving parts.

Where the key lives (this is the whole disaster-recovery story)

# Location Notes
1 Secret flux-system/sops-age, key age.agekey What Flux reads at reconcile time. Created out of band (kubectl create secret generic), never in git.
2 /root/sops/homek8s-age.key on the Linode VPS (0600, root) Off-workstation escrow. Reachable only over the mesh: laptop → rpi → ssh [email protected]. sha256 2d1b9d82e07ea126… (full hash in the 2026-11-27 card/handoff).
3 ~/.config/sops/age/keys.txt on the admin workstation (0600) Convenience only; sops' default lookup path. Losing this is survivable, losing #1 and #2 is not.

The key is not in the Obsidian vault (that tree is pushed nightly to Forgejo — a key there would publish itself) and not on any cluster node's disk other than as the Secret above.

Restore after losing both: nothing on the cluster can be decrypted and every encrypted file must be re-encrypted to a new recipient. That means re-entering the values from the upstream providers (Telegram bot tokens, Forgejo tokens, S3 keys, DB passwords). Treat #2 as the authoritative copy and copy it into a password manager as a third location.

Reading the key from escrow, if the workstation copy is gone:

ssh -i ~/.ssh/lancelot_priv [email protected] \
  'ssh -i ~/.ssh/linode_admin [email protected] cat /root/sops/homek8s-age.key' \
  > ~/.config/sops/age/keys.txt && chmod 600 ~/.config/sops/age/keys.txt

Working with the encrypted files

encrypted_regex: ^(data|stringData)$ — only the values are encrypted; metadata.name, namespace and type stay readable so git grep and code review still work.

# edit one (opens $EDITOR, re-encrypts on save)
sops apps/base/siriusdevops/secret-siriusdevops-contact.sops.yaml

# read key NAMES without decrypting values
sops decrypt --output-type json apps/base/siriusdevops/secret-siriusdevops-contact.sops.yaml \
  | jq -r '.data | keys[]'

# add a new secret: capture the live object, strip server metadata, encrypt through a pipe
kubectl -n <ns> get secret <name> -o json \
  | jq -S '{apiVersion:"v1",kind:"Secret",
            metadata:{name:.metadata.name,namespace:.metadata.namespace},
            type:.type,data:.data}' \
  | sops encrypt --filename-override secret-<name>.sops.yaml \
      --input-type yaml --output-type yaml /dev/stdin > apps/base/<ns>/secret-<name>.sops.yaml

Then list the file in that app's kustomization.yaml (they all end with a "Secrets, SOPS/age-encrypted in git" block).

Never commit a plaintext Secret, and never "encrypt it in a follow-up commit" — the plaintext commit is recoverable from the object database forever, even if force-pushed.

sops and age are packaged (pacman -S sops age); the recipient lives in .sops.yaml at the repo root, so sops picks it up with no flags as long as the filename matches secret-*.sops.yaml.

How Flux applies them

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:

  decryption:
    provider: sops
    secretRef:
      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.
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):

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.

Inventory — in git (35 Secrets, 8 namespaces)

Namespace Secrets
forgejo forgejo-pg-app, forgejo-runner-amd64-token, forgejo-runner-deploy-arm64-token, cluster-backup-ssh
siriusdevops siriusdevops-contact, garage-media-s3, forgejo-pull
piedmont piedmont-contact, forgejo-pull
sirius-growth sirius-growth-contact, sirius-growth-blog-app, sirius-growth-blog-s3, sirius-growth-portal-app, sirius-growth-portal-db, sirius-growth-portal-s3, portal-wal-s3, forgejo-pull, cluster-backup-ssh
osint osint-admin, osint-db, forgejo-pull
metabase pg-app, metabase-admin, metabase-data-source-creds
customer1 pg-app, pg-users, odoo-config, odoo-admin, metabase-admin, metabase-data-source-creds, metabase-secret-key
monitoring grafana-admin, grafana-secret-key, alertmanager-telegram, cluster-backup-ssh

cluster-backup-ssh is the same ed25519 key in three namespaces — a Secret cannot be referenced across namespaces and each backup CronJob mounts its own namespace's copy, so there are three files with identical plaintext (distinct ciphertext; age uses a random nonce). Rotating it means updating all three.

*-pg-app / pg-app / sirius-growth-portal-db deserve a note: these look like CNPG output but are ours — each Cluster's bootstrap.initdb.secret.name points at one of them, so CNPG reads the password from the Secret we create rather than minting it. Without them in git a rebuild's initdb has no application password and the Cluster never bootstraps. They are static (no password-rotation policy is configured), so re-applying the same bytes is a no-op.

forgejo-pull is committed even though docs/registry-pull-auth.md (F11) describes it as "out of band (never in git)". That wording predates this card: once every Deployment carries imagePullSecrets: [forgejo-pull], that Secret is the thing whose absence stops the cluster from starting, which is exactly what this card exists to prevent. It is a Forgejo read:package token — ciphertext in git is the correct home for it.

Excluded on purpose (not in git, by design)

Secret(s) Namespace Why
pg-server, pg-replication, pg-ca forgejo, metabase Issued and rotated by the CNPG instance manager (ownerRef Cluster/pg). Committing them pins stale certs the operator immediately overwrites → permanent drift.
portal-server, portal-replication, portal-ca sirius-growth Same, ownerRef Cluster/portal.
cnpg-ca-secret, cnpg-webhook-cert cnpg-system Operator's own CA + webhook serving cert, ownerRef Deployment/cnpg-controller-manager; regenerated on install.
barman-cloud-server-tls, barman-cloud-client-tls, plugin-barman-cloud-<hash> cnpg-system Generated by the vendored plugin-barman-cloud manifest (the <hash> is a content checksum in the object name).
cert-manager-webhook-ca cert-manager Helm-generated webhook CA.
cilium-ca, hubble-server-certs, hubble-relay-client-certs kube-system Cilium Helm chart mints these (lookup-reused); a stale copy wedges an upgrade — the documented failure is HelmRelease stalled on a cert that does not match the current cluster.name.
sh.helm.release.v1.* kube-system, cert-manager, monitoring Helm release records (release state, not configuration).
kube-prometheus-stack-admission monitoring Helm-generated webhook cert.
prometheus-kube-prometheus-stack-prometheus, alertmanager-kube-prometheus-stack-alertmanager, *-generated, *-tls-assets-*, *-web-config, *-cluster-tls-config monitoring Rendered by the prometheus-operator from the CRs on every reconcile — writing them into git creates a second, losing writer. Their inputs (alertmanager-telegram, grafana-admin, grafana-secret-key) are ours and are committed separately.
kube-prometheus-stack-prometheus-token monitoring kubernetes.io/service-account-token, minted by the token controller.
flux-system flux-system Git credential created by flux bootstrap; it authenticates the very pull that would apply it (chicken-and-egg), and rotating it is a bootstrap operation.
sops-age flux-system The age private key. It cannot encrypt itself and must exist before any file here can be decrypted — it is the one Secret that is by definition out of git. See "Where the key lives" above for the two escrow copies.

Every other live Secret is either in git as ciphertext or in the table above. Re-prove that with a clean checkout of master (needs the age key in ~/.config/sops/age/keys.txt):

kubectl get secret -A -o json \
  | jq -r '.items[] | "\(.metadata.namespace)/\(.metadata.name)"' | sort > /tmp/live.txt
for f in apps/base/*/secret-*.sops.yaml monitoring/controllers/home/secret-*.sops.yaml; do
  sops decrypt --output-type json "$f" | jq -r '"\(.metadata.namespace)/\(.metadata.name)"'
done | sort > /tmp/git.txt
comm -23 /tmp/live.txt /tmp/git.txt   # live but not restorable from git: must be the table above
comm -13 /tmp/live.txt /tmp/git.txt   # in git but absent live: must be empty

At the 2026-11-27 audit that printed 77 live = 35 in git + 42 excluded, all 42 accounted for above, and nothing in git that was missing from the cluster.

Now covered (added after the drill in the section below proved the recovery path): cluster-backup-ssh (3 namespaces), grafana-admin, grafana-secret-key, alertmanager-telegram.

Delete-and-reconcile drill (2026-11-27T05:29Z)

Target: siriusdevops/siriusdevops-contact (Telegram token for the contact form — losing it for a couple of minutes degrades one form, breaks nothing else).

05:28:59Z  pre:  pod Ready, /health {"ok":true}, keys TG_CHAT,TG_TOKEN, data sha256 1f17a3ac…
05:29:03Z  kubectl -n siriusdevops delete secret siriusdevops-contact
05:29:05Z  recreated by Flux (~2s, forced reconcile) — same keys, same data sha256 1f17a3ac…
05:29:11Z  kubectl rollout restart deploy/siriusdevops-contact   (prove env resolves from the
                                                                recovered Secret, not pod memory)
05:29:23Z  rollout complete; new pod Ready, env TG_CHAT/TG_TOKEN present, /health {"ok":true}
           both via localhost:8090 and via svc DNS + ClusterIP

Same key names before and after, byte-identical data, Secret back in the apps Kustomization inventory. Only key names are recorded here.