feat(keycloak): own realm state passphrase and scheduled realm drift check #932

Sammanfogat
supernaut sammanfogade 3 incheckningar från feat/realm-state-passphrase in i main 2026-11-30 21:10:53 +00:00
Ägare

This PR carries the whole #576 stack. #934 merged into #933's branch and #933 into this one, so the
three changes land together:

  1. The realm state gets its own passphrase.
  2. The shared passphrase is dropped from the realm root (#933).
  3. A scheduled realm drift check with alerts (#934).

Both realm workspaces (staging, prod) were re-encrypted from this branch's first two commits, which
still had the fallback, before merge. Both now read key_provider.pbkdf2.realm. The vault keys are
in #935.

Own passphrase for the realm state

Each environment's realm state (opentofu/keycloak) is encrypted with its own
vault_keycloak_opentofu_state_passphrase instead of the main root's passphrase. The drift check
needs the realm state on the services host, and the host must never hold the main root's key.

  • encryption.tofu: only the pbkdf2.realm key and aes_gcm.realm method, for state and plans.
  • variables.tofu: realm_state_passphrase (sensitive, at least 16 characters).
    state_encryption_passphrase is gone from the realm root.
  • scripts/keycloak-tofu-env.py: exports TF_VAR_realm_state_passphrase from the environment's own
    vault and reads no other vault. The self-test checks that it never exports the main root's
    passphrase.
  • vault.example.yml and the runbook ("Keycloak realm", "Realm state passphrase") document the key.

The main root keeps vault_opentofu_state_encryption_passphrase unchanged.

Proof on a throwaway root with the fallback config, then the final config: the fallback read the old
state (No changes, exit 0), apply -refresh-only rewrote it to key_provider.pbkdf2.realm, and
the final config read it with only the realm passphrase. The old config could no longer read it.

Realm drift check

A timer on the prod services host runs tofu plan -detailed-exitcode for opentofu/keycloak every
6 hours and writes the exit code to the textfile collector. Three alerts read it:

Alert Fires when Severity
KeycloakRealmDrift the plan is not empty (exit 2) warning
KeycloakRealmDriftCheckFailed the plan did not complete warning
KeycloakRealmDriftCheckStale no completed plan for 14 hours, or none recorded warning

The plan covers everything the root declares. A changed flow, execution, required action, client,
scope or permission raises KeycloakRealmDrift, and so does a merged realm change that was never
applied.

  • Runs on the services host as bitborg-id, in the OpenTofu container
    (ghcr.io/opentofu/opentofu, through the registry mirror). The admin API listens only on that
    host's loopback.
  • Authenticates as opentofu. A read-only client cannot plan this root: the provider refreshes
    every keycloak_openid_client with GET /clients/<id>/client-secret, which needs manage rights.
    bitborg-id owns Keycloak's database, which already holds every client secret, so the job gives
    no account anything it lacked.
  • Inputs: --tags keycloak copies the .tofu files, lock file, env/prod.tfvars and the
    encrypted workspace state from the checkout that runs Ansible, and templates the TF_VAR_* inputs
    into a 0600 env file. The self-test fails if the role's inputs differ from the script's or include
    the main root's passphrase.
  • Prod only. The monitoring VM does not scrape staging. The role skips the check while the realm
    passphrase or the opentofu secret is unset.
  • Traceability. The role records the applying checkout's HEAD on the host, and each run's
    journal line names it. The role warns when that checkout is not at origin/main.
  • Failures. With no state copy, the run reports status 1. A failed run retries after 5 minutes,
    at most twice an hour.

Rejected: CI (needs the admin secret and an SSH path into prod), the monitoring VM (a second host
with the admin secret), a read-only client (cannot refresh clients), plan -refresh-only (misses
merged changes never applied).

Proof against a local Keycloak 26.8.2: clean realm gives status 0; an OTP execution set to
DISABLED gives status 2; Keycloak stopped gives status 1 and keeps the last success timestamp.

Operator steps after merge

  1. In a fresh shell, per environment with its tunnel open:
    eval "$(./scripts/keycloak-tofu-env.py <env>)", then tofu plan -detailed-exitcode must
    exit 0.
  2. Run the registry mirror once so bitborg/opentofu:1.13.9 exists in the registry.
  3. From the main checkout, run --tags keycloak on prod.
  4. Start bitborg-keycloak-realm-drift.service as bitborg-id. Expect status 0.
  5. Apply the monitoring role so the rules load.
  6. Prove it: change a client description in the admin console, start the check, expect status 2.
    Apply the realm to undo it, then run --tags keycloak again.

After every realm apply, run --tags keycloak from the same checkout, or the check plans stale
state and fires.

Checks

tofu fmt -check, tofu validate, keycloak-tofu-env.py --self-test, ruff, shellcheck,
test-alert-rules.py, check-alert-rules.py, check-metric-names.py,
check-renovate-annotations.py, lint-rendered-templates.py, check-podman-run-log-driver.py,
ansible-lint, site.yml --syntax-check, prettier, markdownlint.

Closes #576

This PR carries the whole #576 stack. #934 merged into #933's branch and #933 into this one, so the three changes land together: 1. The realm state gets its own passphrase. 2. The shared passphrase is dropped from the realm root (#933). 3. A scheduled realm drift check with alerts (#934). Both realm workspaces (staging, prod) were re-encrypted from this branch's first two commits, which still had the fallback, before merge. Both now read `key_provider.pbkdf2.realm`. The vault keys are in #935. ## Own passphrase for the realm state Each environment's realm state (`opentofu/keycloak`) is encrypted with its own `vault_keycloak_opentofu_state_passphrase` instead of the main root's passphrase. The drift check needs the realm state on the services host, and the host must never hold the main root's key. - `encryption.tofu`: only the `pbkdf2.realm` key and `aes_gcm.realm` method, for state and plans. - `variables.tofu`: `realm_state_passphrase` (sensitive, at least 16 characters). `state_encryption_passphrase` is gone from the realm root. - `scripts/keycloak-tofu-env.py`: exports `TF_VAR_realm_state_passphrase` from the environment's own vault and reads no other vault. The self-test checks that it never exports the main root's passphrase. - `vault.example.yml` and the runbook ("Keycloak realm", "Realm state passphrase") document the key. The main root keeps `vault_opentofu_state_encryption_passphrase` unchanged. Proof on a throwaway root with the fallback config, then the final config: the fallback read the old state (`No changes`, exit 0), `apply -refresh-only` rewrote it to `key_provider.pbkdf2.realm`, and the final config read it with only the realm passphrase. The old config could no longer read it. ## Realm drift check A timer on the prod services host runs `tofu plan -detailed-exitcode` for `opentofu/keycloak` every 6 hours and writes the exit code to the textfile collector. Three alerts read it: | Alert | Fires when | Severity | | ------------------------------- | ------------------------------------------------ | -------- | | `KeycloakRealmDrift` | the plan is not empty (exit 2) | warning | | `KeycloakRealmDriftCheckFailed` | the plan did not complete | warning | | `KeycloakRealmDriftCheckStale` | no completed plan for 14 hours, or none recorded | warning | The plan covers everything the root declares. A changed flow, execution, required action, client, scope or permission raises `KeycloakRealmDrift`, and so does a merged realm change that was never applied. - **Runs on the services host** as `bitborg-id`, in the OpenTofu container (`ghcr.io/opentofu/opentofu`, through the registry mirror). The admin API listens only on that host's loopback. - **Authenticates as `opentofu`.** A read-only client cannot plan this root: the provider refreshes every `keycloak_openid_client` with `GET /clients/<id>/client-secret`, which needs manage rights. `bitborg-id` owns Keycloak's database, which already holds every client secret, so the job gives no account anything it lacked. - **Inputs:** `--tags keycloak` copies the `.tofu` files, lock file, `env/prod.tfvars` and the encrypted workspace state from the checkout that runs Ansible, and templates the `TF_VAR_*` inputs into a 0600 env file. The self-test fails if the role's inputs differ from the script's or include the main root's passphrase. - **Prod only.** The monitoring VM does not scrape staging. The role skips the check while the realm passphrase or the `opentofu` secret is unset. - **Traceability.** The role records the applying checkout's `HEAD` on the host, and each run's journal line names it. The role warns when that checkout is not at `origin/main`. - **Failures.** With no state copy, the run reports status 1. A failed run retries after 5 minutes, at most twice an hour. Rejected: CI (needs the admin secret and an SSH path into prod), the monitoring VM (a second host with the admin secret), a read-only client (cannot refresh clients), `plan -refresh-only` (misses merged changes never applied). Proof against a local Keycloak 26.8.2: clean realm gives status 0; an OTP execution set to `DISABLED` gives status 2; Keycloak stopped gives status 1 and keeps the last success timestamp. ## Operator steps after merge 1. In a fresh shell, per environment with its tunnel open: `eval "$(./scripts/keycloak-tofu-env.py <env>)"`, then `tofu plan -detailed-exitcode` must exit 0. 2. Run the registry mirror once so `bitborg/opentofu:1.13.9` exists in the registry. 3. From the main checkout, run `--tags keycloak` on prod. 4. Start `bitborg-keycloak-realm-drift.service` as `bitborg-id`. Expect status 0. 5. Apply the monitoring role so the rules load. 6. Prove it: change a client description in the admin console, start the check, expect status 2. Apply the realm to undo it, then run `--tags keycloak` again. After every realm apply, run `--tags keycloak` from the same checkout, or the check plans stale state and fires. ## Checks `tofu fmt -check`, `tofu validate`, `keycloak-tofu-env.py --self-test`, ruff, shellcheck, `test-alert-rules.py`, `check-alert-rules.py`, `check-metric-names.py`, `check-renovate-annotations.py`, `lint-rendered-templates.py`, `check-podman-run-log-driver.py`, `ansible-lint`, `site.yml --syntax-check`, prettier, markdownlint. Closes #576
supernaut lade till 2 incheckningar 2026-11-30 09:06:10 +00:00
Each environment's realm state is now encrypted with
vault_keycloak_opentofu_state_passphrase instead of the main root's
passphrase, so a host that needs the realm state never holds the key to
the main root's. A fallback reads state still encrypted with the old
passphrase until a refresh-only apply rewrites it. The runbook has the
per-workspace steps.

Refs #576
docs(keycloak): tighten the realm passphrase migration steps
Alla kontroller lyckades
ci / ci (pull_request) Successful in 22m56s
54ff720a00
supernaut lade till 1 incheckning 2026-11-30 10:36:14 +00:00
refactor(keycloak): drop the shared passphrase from the realm root (#933)
Alla kontroller lyckades
ci / ci (pull_request) Successful in 22m25s
5d16a7ebe2
refactor(keycloak): drop the shared passphrase from the realm root

Stack: `feat/realm-state-passphrase`, then **this PR (2 of 3)**, then `feat/realm-drift-check`.
Merge it only after every realm workspace is rewritten with its own passphrase (the steps in the
previous PR). Otherwise the realm state cannot be read.

## What

- `encryption.tofu`: only the realm key. The shared key provider, its method and both `fallback`
  blocks are gone.
- `variables.tofu`: `state_encryption_passphrase` is gone from the realm root.
- `scripts/keycloak-tofu-env.py`: reads only the environment's own vault, so staging no longer
  needs the prod vault. It never exports the main root's passphrase, and the self-test checks that.
- Runbook "Realm state passphrase": the one-time rewrite steps are replaced by a short description.

The main root keeps `vault_opentofu_state_encryption_passphrase` unchanged.

## Proof

The rewrite proof in the previous PR used this commit's `encryption.tofu` and `variables.tofu`, byte
for byte. A rewritten state reads with only `TF_VAR_realm_state_passphrase` set, and a state not yet
rewritten fails with `decryption failed for all`.

## Operator steps

1. Before merging, check both workspaces read `key_provider.pbkdf2.realm`:
   `jq -r '.meta | keys[]' opentofu/keycloak/terraform.tfstate.d/<env>/terraform.tfstate`.
2. After merging, in a fresh shell: `eval "$(./scripts/keycloak-tofu-env.py <env>)"` and
   `tofu plan -detailed-exitcode` must exit 0 for staging and prod.

## Checks

`tofu fmt -check`, `tofu validate`, `keycloak-tofu-env.py --self-test` (9 pass), ruff 0.17.6,
`check-alert-rules.py`, `ansible-lint` (production), `site.yml --syntax-check`, prettier,
markdownlint.

Refs #576

Reviewed-on: #933
supernaut tvångsskickade feat/realm-state-passphrase från 5d16a7ebe2
Alla kontroller lyckades
ci / ci (pull_request) Successful in 22m25s
till 15e7584df6
Alla kontroller lyckades
ci / ci (pull_request) Successful in 25m22s
2026-11-30 20:44:58 +00:00
Jämför
supernaut ändrade titeln från feat(keycloak): give the realm state its own passphrase till feat(keycloak): own realm state passphrase and scheduled realm drift check 2026-11-30 20:46:02 +00:00
supernaut schemalade den här ändringsförfrågan för automatisk sammanfogning när alla kontroller lyckas 2026-11-30 21:09:11 +00:00
supernaut sammanfogade incheckning 1b1b7bee72 till main 2026-11-30 21:10:53 +00:00
supernaut tog bort grenen feat/realm-state-passphrase 2026-11-30 21:10:53 +00:00
Logga in för att delta i denna konversation.
Inga granskare
Ingen milstolpe
Inget projekt
Inga tilldelade
1 deltagare
Notiser
Förfallodatum
Förfallodatumet är ogiltigt eller utanför gränserna. Använd formatet "åååå-mm-dd".

Inget förfallodatum satt.

Beroenden

Inga beroenden satta

Referens
bitborg/bitborg-infra!932
Ingen beskrivning angiven.