refactor(keycloak): drop the shared passphrase from the realm root #933

Sammanfogat
supernaut sammanfogade 2 incheckningar från feat/realm-state-passphrase-cleanup in i feat/realm-state-passphrase 2026-11-30 10:36:12 +00:00
Ägare

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

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
supernaut lade till 1 incheckning 2026-11-30 09:06:13 +00:00
refactor(keycloak): drop the shared passphrase from the realm root
Alla kontroller lyckades
ci / ci (pull_request) Successful in 25m1s
52e723bc3f
Every realm workspace is rewritten with its own passphrase, so the
fallback to the main root's passphrase goes, and keycloak-tofu-env.py
no longer reads the prod vault for staging or exports that passphrase.

Refs #576
supernaut lade till 1 incheckning 2026-11-30 09:33:01 +00:00
feat(keycloak): scheduled realm drift check with alerts (#934)
Alla kontroller lyckades
ci / ci (pull_request) Successful in 26m43s
c393f7ba89
feat(keycloak): scheduled realm drift check with alerts

Stack: `feat/realm-state-passphrase`, then `feat/realm-state-passphrase-cleanup`, then **this PR
(3 of 3)**. Merge and deploy in that order. This PR needs the realm state on its own passphrase,
so the main root's passphrase never reaches the services host.

## What

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, so a changed flow, execution, required action,
client, scope or permission raises `KeycloakRealmDrift`. So does a merged realm change that was
never applied.

## Design

- **Runs on the services host**, as `bitborg-id`, in the OpenTofu container (`ghcr.io/opentofu/opentofu`,
  pulled 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`, and Keycloak allows that
  only with manage rights on the client. A client allowed to read the `opentofu` secret can act as
  `opentofu`, so a narrower client would not be narrower. `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
  workspace state (still encrypted) from the checkout that runs Ansible, and templates the
  `TF_VAR_*` inputs into a 0600 env file. `scripts/keycloak-tofu-env.py --self-test` now fails if the
  role and the script read different vault keys.
- **Own passphrase.** The host gets `vault_keycloak_opentofu_state_passphrase`, the realm state's
  own key, and never the main root's. `keycloak-tofu-env.py --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, so a staging check would put the admin
  secret on that host for results nobody reads. The role also 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, without failing, when that checkout is not at `origin/main`.
- **Failures.** With no state copy, the run skips the plan and reports status 1. A failed run retries
  after 5 minutes, at most twice an hour, so a race with a Keycloak restart or a boot clears itself.
- The OpenTofu image is pinned by tag like every other mirrored image. None is pinned by digest.

Rejected:

- CI: needs the admin secret, the state and an SSH path into prod in CI, and CI never touches prod.
- Monitoring VM: puts the admin secret on a second host and needs a network path to the admin API.
- Dedicated read-only client: cannot refresh the clients (see above).
- `plan -refresh-only`: needs no secrets, but misses merged changes that were never applied.

## Operator steps

The first two PRs' steps come first: the realm vault keys, and every workspace rewritten with its
own passphrase.

1. Run the registry mirror once so `bitborg/opentofu:1.13.9` exists in the registry.
2. From the checkout that applies the realm, run `--tags keycloak` on prod.
3. Start `bitborg-keycloak-realm-drift.service` as `bitborg-id`. Expect status 0.
4. Apply the monitoring role so the rules load.
5. Prove it: change a client description in the admin console, start the check, expect status 2
   and `KeycloakRealmDrift`. Apply the realm to undo it.

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

## Proof against a local Keycloak 26.8.2

The root was applied to a throwaway Keycloak (stock theme in place of `bitborg`), then the rendered
script ran with the host layout and the encrypted state:

- clean realm: `No changes`, status 0;
- OTP execution set to `DISABLED` over the admin API: `~ requirement = "DISABLED" -> "ALTERNATIVE"`,
  status 2, unit exit 0;
- Keycloak stopped: provider error, status 1, unit exit 1, last success timestamp kept.
- Against a stub `podman`: no state gives status 1 and skips the plan; a failed run followed by a
  successful retry leaves status 0 with a fresh timestamp.

## Checks

- `scripts/test-alert-rules.py`, `scripts/check-alert-rules.py`
- `scripts/check-metric-names.py`, `scripts/check-renovate-annotations.py`,
  `scripts/lint-rendered-templates.py`, `scripts/check-podman-run-log-driver.py`
- `scripts/keycloak-tofu-env.py --self-test`
- `ansible-lint`, `ansible-playbook site.yml --syntax-check`, shellcheck, ruff

Closes #576

Reviewed-on: #934
supernaut sammanfogade incheckning 5d16a7ebe2 till feat/realm-state-passphrase 2026-11-30 10:36:12 +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!933
Ingen beskrivning angiven.