feat(keycloak): scheduled realm drift check with alerts #934

Sammanfogat
supernaut sammanfogade 3 incheckningar från feat/realm-drift-check in i feat/realm-state-passphrase-cleanup 2026-11-30 09:32:59 +00:00
Ägare

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

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
supernaut lade till 3 incheckningar 2026-11-30 09:06:17 +00:00
A timer on the prod services host plans opentofu/keycloak against the
live realm every 6 hours and records the plan's exit code in the
textfile collector. KeycloakRealmDrift fires on a non-empty plan,
KeycloakRealmDriftCheckFailed on a failed one, and
KeycloakRealmDriftCheckStale when no plan completed for 14 hours.

The check authenticates as opentofu. The provider reads every client's
secret on refresh, which Keycloak allows only with manage rights, so a
read-only client cannot plan this root. It runs as bitborg-id, which
already owns Keycloak's database. --tags keycloak copies the root, the
encrypted state and the TF_VAR inputs from the applying checkout.

Closes #576
Skip the plan and report a failure when the host has no state copy,
since every resource would otherwise plan as a create. Record the
applying checkout's commit on the host, name it in each run's journal
line, and warn when that checkout is not at origin/main. Retry a failed
run after 5 minutes, at most twice an hour, so a race with a Keycloak
restart or a boot clears itself. Do not diff the encrypted state copy.

Refs #576
fix(keycloak): give the drift check only the realm passphrase
Alla kontroller lyckades
ci / ci (pull_request) Successful in 26m28s
1c765acf3b
The drift env now carries vault_keycloak_opentofu_state_passphrase, the
realm state's own key, so the main root's passphrase never reaches the
services host. The self-test fails if the role's inputs include it. The
check stays prod-only: the monitoring VM does not scrape staging.

Refs #576
supernaut sammanfogade incheckning c393f7ba89 till feat/realm-state-passphrase-cleanup 2026-11-30 09:32:59 +00:00
supernaut tog bort grenen feat/realm-drift-check 2026-11-30 09:32:59 +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!934
Ingen beskrivning angiven.