Commit 38a4ebbd authored by Christos Tranoris's avatar Christos Tranoris
Browse files

keycloak upgrade

parent ef5e285b
Loading
Loading
Loading
Loading
Loading
+1
Changes for doc/getting_started/upgrade_guide/introduction.md: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
@@ -9,6 +9,7 @@ deployment is more than one release behind, work through each guide in order rat
ahead.

- [2025Q4 to 2026Q2](./2025Q4_2026Q2.md)
- [Keycloak 16.1.1 to 26.8.2](./keycloak_16_to_26.md) (docker compose, export / import)

## Before you begin

+172
Changes for doc/getting_started/upgrade_guide/keycloak_16_to_26.md: 172 added lines, 0 removed lines.
Original line number Diff line number Diff line
# Upgrading OpenSlice Keycloak 16.1.1 → 26.8.2 (export / import)

This procedure moves an OpenSlice **docker compose** installation from Keycloak 16.1.1 (WildFly) to
Keycloak 26.8.2 (Quarkus). It exports all realms from the old server and imports them into a new,
empty database. The old database is never modified, so you can always roll back.

It was rehearsed end to end on a copy of a production database (165 users, 3 realms, Google/GitHub login).
Users, passwords, roles, clients and signing keys came across unchanged (see [What is kept / lost](#what-is-kept--lost)).

**Expected downtime:** about 5 minutes (export ≈ 1 min, import + first start ≈ 3 min).
All users have to log in again afterwards.

## Kit contents

The kit lives in [`org.etsi.osl.main/compose/keycloak-upgrade/`](https://labs.etsi.org/rep/osl/code/org.etsi.osl.main/-/tree/develop/compose/keycloak-upgrade).

| File | Purpose |
|---|---|
| `kc16-export.sh` | Stops the KC 16 container and exports all realms to a folder using a one-shot KC 16 container. Then applies `kc26-fixup.jq`. |
| `kc26-fixup.jq` | Caps client session timeouts that exceed the realm limits. KC 16 accepted them, KC 26 refuses to import them. |
| `create-kc26-db.sql` | Creates the new empty `keycloak26` database (utf8mb4) and grants it to the `keycloak` DB user. |
| `keycloak26-service.yaml` | The new `keycloak:` service block for `docker-compose.yaml`. |
| `kc26-import.sh` | One-shot import into the empty DB, then starts Keycloak 26 and waits until it answers. |
| `kc26-verify.sh` | Prints users / clients / roles / IdPs / signing-key id per realm. Run it before and after, then compare. |

## Prerequisites

- **MySQL 8.0 or newer** for the new database. Keycloak 26 does not support MySQL 5.7.
  The default `docker-compose.yaml` already runs `mysql:8` as `amysql8`. If you still run MySQL 5.7
  (`docker-compose.yaml.configure`, older installs), add a MySQL 8 service first and point `KC_DB_URL` to it.
- `bash`, `curl` and Docker with the compose plugin. On Windows use Git Bash; the scripts handle its path conversion.
  The scripts pull `ghcr.io/jqlang/jq:1.7.1`, so jq does not need to be installed.
- The **master admin password** of the old Keycloak (`KEYCLOAK_PASSWORD`, default `keycloakadminpass`).
  It keeps working after the upgrade.
- Run all commands from `org.etsi.osl.main/compose` (the folder with `docker-compose.yaml`), with the kit copied
  into e.g. `compose/keycloak-upgrade/`.

## Procedure

### 0. Back up
```bash
docker exec amysql8 mysqldump -uroot -p<root-password> --single-transaction --routines --triggers \
       --databases keycloak > keycloak16-backup-$(date +%Y%m%d).sql
```

### 1. Record the current state (old server still running)
```bash
KC_ADMIN_PASSWORD=<admin-password> ./keycloak-upgrade/kc26-verify.sh http://localhost:8080/auth | tee kc-before.txt
```

### 2. Export (downtime starts here)
```bash
./keycloak-upgrade/kc16-export.sh keycloak ./keycloak-export
```
The script stops the `keycloak` container and prints `users= clients= realm-roles= idps=` per realm.
The numbers must match `kc-before.txt`. If the export fails, `docker start keycloak` brings the old server back.

> ⚠️ `./keycloak-export` contains password hashes, client secrets and the realms' private signing keys.
> Keep it on a protected disk and delete it once you are satisfied (step 7).

### 3. Create the new database
```bash
docker exec -i amysql8 mysql -uroot -p<root-password> < ./keycloak-upgrade/create-kc26-db.sql
```
If you changed the `keycloak` DB user's password, edit the SQL and `keycloak26-service.yaml` to match.

### 4. Switch the compose service
In `docker-compose.yaml`, comment out the old `keycloak:` service block (keep it for rollback) and paste
`keycloak26-service.yaml` in its place. What changes:

| Keycloak 16 | Keycloak 26 |
|---|---|
| `DB_VENDOR/DB_ADDR/DB_PORT/DB_DATABASE/DB_USER/DB_PASSWORD/JDBC_PARAMS` | `KC_DB=mysql`, `KC_DB_URL`, `KC_DB_USERNAME`, `KC_DB_PASSWORD` |
| `/auth` context path (built in) | `KC_HTTP_RELATIVE_PATH=/auth`, so all URLs, issuers and UI configs stay the same |
| `PROXY_ADDRESS_FORWARDING=true` | `KC_PROXY_HEADERS=xforwarded` |
| `KEYCLOAK_USER/KEYCLOAK_PASSWORD` | not needed: the admin comes from the import (see below) |
| `KEYCLOAK_IMPORT` + `./keycloak-init:/tmp` | `command: start --import-realm` + `realm-export.json` mounted in `/opt/keycloak/data/import`. It only imports a realm that does not exist yet, so after the upgrade it logs `Realm 'openslice' already exists. Import skipped`. |
| ports 8080 + 8443 | 8080 only (TLS is terminated by nginx). Health and metrics are on 9000 inside the network. |
| `JAVA_OPTS` | `JAVA_OPTS_APPEND`. KC 26 sizes the heap itself (70% of the container memory). |

> ⚠️ **Do not set `KC_BOOTSTRAP_ADMIN_USERNAME/PASSWORD`** on the upgrade path. The import brings the existing
> master admin, the bootstrap user then collides with it, and the **whole import is rolled back**.
> `kc26-import.sh` refuses to run if they are set.

### 5. Import and start
```bash
COMPOSE="docker compose --profile prod" ./keycloak-upgrade/kc26-import.sh ./keycloak-export keycloak
```
The script creates the schema, imports `master`, `chronos` and `openslice`, then starts the service and waits until it answers.
It stops with an error if the import logs any `ERROR`, or if Keycloak 26 is already running on that database.
Never let Keycloak 26 start on the new database **before** the import. If that happened, drop the database,
run `create-kc26-db.sql` again and repeat this step.

For about 15 s after start-up Keycloak 26 returns `503 Bootstrap in progress`. This is normal.

### 6. Verify
```bash
KC_ADMIN_PASSWORD=<admin-password> ./keycloak-upgrade/kc26-verify.sh http://localhost:8080/auth | tee kc-after.txt
diff <(sort kc-before.txt) <(sort kc-after.txt) && echo IDENTICAL
```
All counts **and the `signing-kid` of every realm** must be identical. The same kid means the realm keys were carried over,
so the OpenSlice back-ends (tmf.api, portal.api, …) keep validating tokens without a restart.
Then log in through the OpenSlice UI (`/tmf`, portal, chronos) with a normal user, and with Google/GitHub if you use them.

### 7. Clean up
Delete `./keycloak-export` securely. Keep the old `keycloak` database and the backup until you are sure you won't roll back.

## Rollback
The old database `keycloak` is untouched, so:
```bash
docker compose --profile prod stop keycloak      # Keycloak 26
# restore the old keycloak: block in docker-compose.yaml
docker compose --profile prod up -d keycloak     # Keycloak 16 on the old DB, exactly as before
```
Anything changed in Keycloak 26 after the switch (new users, new passwords) is not in the old database.

## What is kept / lost
Measured by comparing every table of the source and target databases, row by row.

**Kept unchanged**
- Users: IDs, usernames, e-mails, names, enabled flag (165 + 3 + 1). Since the user IDs (`sub`) are the same,
  references stored in OpenSlice (`relatedParty`, portal users) still match.
- Password hashes (105/105 identical). Users log in with their **old passwords**, including the master `admin`.
- Realm roles, client roles, composite roles and every user→role mapping (719).
- Pending required actions (63), e.g. "verify e-mail" or "update password".
- Clients: client IDs, redirect URIs, settings and the secrets of confidential clients.
- Identity providers (Google, GitHub) including their client secrets, and all 69 user↔Google/GitHub account links.
- Realm RSA signing keys (same `kid`), groups, user attributes, consents, authentication flows in use, SMTP and theme settings.

**Lost**
- **All sessions.** Logged-in users must log in again. Refresh tokens and offline tokens stop working.
  Access tokens issued just before the switch remain valid at the back-ends until they expire (minutes).
- The **event log** (login/error events in `EVENT_ENTITY`, ~5,300 rows in the rehearsal) and admin events.
  If you need them, keep the old database or the backup.
- Brute-force lockout counters, pending action tokens (e.g. password-reset links sent before the switch).
- The old database's migration history (not used by Keycloak 26).

**Changed by Keycloak 26 / the fix-up**
- `kc26-fixup.jq`: client session idle timeouts larger than the realm's SSO idle timeout are lowered to it.
  In the rehearsal these were `chronos-client` (3600 s) and `chronos-ui` (10800 s), both lowered to 1800 s.
  KC 16 already applied the realm limit at runtime, so the effective behaviour does not change.
- The built-in flows `http challenge` and `Authentication Options` were removed (deprecated in KC 16 and unused).
  New built-ins were added: organization flows, client scopes `basic`/`acr`/`service_account`, and an `hmac-generated-hs512` key.
- Public clients no longer store a secret. Internal confidential clients without a secret (`broker`, `realm-management`) get one generated.
- Log warnings about the deprecated features `identity-brokering-api:v1` and `twitter-broker:v1` are harmless.

### Check your client secrets
If a confidential client's secret in the export reads `"**********"`, that literal string is the secret stored in your database.
This happens if a realm was once created from a partial (masked) export. It is carried over as is. Consider regenerating it in the
admin console (Clients → *client* → Credentials) and updating whoever uses it:
```bash
docker run --rm -i ghcr.io/jqlang/jq:1.7.1 -r \
  '.clients[] | select(.secret == "**********" and (.publicClient | not)) | .clientId' < keycloak-export/openslice-realm.json
```

## Notes
- **Fresh installs** (no existing Keycloak): run `create-kc26-db.sql` and use `keycloak26-service.yaml` as is.
  On first start, `--import-realm` imports the `openslice` realm from `keycloak-init/realm-export.json`. The master realm then has
  no admin. Create one once (Keycloak may keep running):
  ```bash
  docker compose --profile prod run --rm --no-deps -e PW=<admin-password> keycloak \
         bootstrap-admin user --username admin --password:env PW
  ```
  Keycloak marks this admin as *temporary*. Log in to the admin console and create a permanent admin, or clear the flag.
  This was rehearsed on an empty database.
- **Kubernetes / Helm**: the same flow applies: scale Keycloak to 0, run the export as a Job with the KC 16 image and the
  `-Dkeycloak.migration.*` arguments on a PVC, create the new DB, then run `kc.sh import --dir … --override true` as a Job with the
  KC 26 image before starting the new Deployment. *Not rehearsed yet.*
- **Alternative: in-place upgrade.** Keycloak 26 can also migrate the old database directly, which also keeps the event log.
  Keycloak 16 databases created under MySQL 5.7 have `latin1` tables, though, and the KC 26.6 migration fails on them
  (`FK_GROUP_ORGANIZATION … incompatible`). The tables must first be converted to `utf8mb4`, and the DB must run on MySQL 8.
  This path also worked in rehearsal, but there's no rollback without restoring the backup, which is why export/import is the recommended path.
+1
Changes for mkdocs.yml: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
@@ -124,6 +124,7 @@ nav:
    - Upgrade guide: 
        - Introduction: ./getting_started/upgrade_guide/introduction.md
        - 2025Q4 -> 2026Q2: ./getting_started/upgrade_guide/2025Q4_2026Q2.md
        - Keycloak 16 -> 26: ./getting_started/upgrade_guide/keycloak_16_to_26.md
  - NaaS:
    - Introduction: ./naas/introduction.md
    - Services: