Repository navigation
Description
Version
Keycloak 26.8.2, official container image (quay.io/keycloak/keycloak:26.8.2).
Observed with:
start-devand the default H2 database;start-devwith PostgreSQL 16.
Summary
GET /admin/realms/{realm}/authentication/flows/{flowAlias}/executions can return 500 Internal Server Error when it runs at the same time as a request that adds a sub-flow to that same flow (POST /admin/realms/{realm}/authentication/flows/{flowAlias}/executions/flow). The server log shows a NullPointerException in AuthenticationManagementResource.recurseExecutions.
Server log
ERROR [org.keycloak.services.error.KeycloakErrorHandler] (executor-thread-2) Uncaught server error: java.lang.NullPointerException: Cannot invoke "org.keycloak.models.AuthenticationFlowModel.getProviderId()" because "flowRef" is null
at org.keycloak.services.resources.admin.AuthenticationManagementResource.lambda$recurseExecutions$7(AuthenticationManagementResource.java:706)
at java.base/java.util.LinkedList$LLSpliterator.forEachRemaining(LinkedList.java:1249)
at java.base/java.util.stream.ReferencePipeline$Head.forEachOrdered(ReferencePipeline.java:772)
at org.keycloak.services.resources.admin.AuthenticationManagementResource.recurseExecutions(AuthenticationManagementResource.java:698)
at org.keycloak.services.resources.admin.AuthenticationManagementResource.getExecutions(AuthenticationManagementResource.java:679)
Response body
{"error":"unknown_error","error_description":"For more on this error consult the server log."}Steps to reproduce
- Start Keycloak 26.8.2 with an admin user (
KC_BOOTSTRAP_ADMIN_USERNAME/KC_BOOTSTRAP_ADMIN_PASSWORD), for example:
docker run -p 127.0.0.1:8080:8080 -e KC_BOOTSTRAP_ADMIN_USERNAME=admin -e KC_BOOTSTRAP_ADMIN_PASSWORD=<password> quay.io/keycloak/keycloak:26.8.2 start-dev - Run the script below (Python 3 standard library only). Each round:
- creates a new top-level
basic-flow; - adds 4 sub-flows to it concurrently;
- meanwhile, 2 other threads read the flow's executions 5 times each.
- creates a new top-level
- Count the responses with status 500.
Result on our side: 3 rounds out of 200 had a 500 on the GET …/executions call, each with the log above. When the same sub-flows are added one after another, the error cannot happen by construction, since no read runs concurrently with a write. The error also appears, rarely, when a fresh realm is configured with the Terraform/OpenTofu provider, which creates sibling sub-flows in parallel. We saw it once in a few dozen CI runs, and once in about 45 local runs.
import json, os, threading, urllib.error, urllib.parse, urllib.request
BASE = os.environ.get("KC_URL", "http://localhost:8080")
PASSWORD = os.environ["KC_ADMIN_PASSWORD"]
def token():
data = urllib.parse.urlencode({"grant_type": "password", "client_id": "admin-cli",
"username": "admin", "password": PASSWORD}).encode()
with urllib.request.urlopen(f"{BASE}/realms/master/protocol/openid-connect/token", data) as r:
return json.load(r)["access_token"]
def call(tok, method, path, body=None):
req = urllib.request.Request(f"{BASE}/admin/realms{path}", method=method,
data=json.dumps(body).encode() if body is not None else None,
headers={"Authorization": f"Bearer {tok}", "Content-Type": "application/json"})
try:
with urllib.request.urlopen(req) as r:
return r.status
except urllib.error.HTTPError as e:
return e.code
tok = token()
assert call(tok, "POST", "", {"realm": "race", "enabled": True}) == 201
errors = []
for n in range(200):
tok = token() # master realm tokens are short-lived
parent = f"parent-{n}"
assert call(tok, "POST", "/race/authentication/flows",
{"alias": parent, "providerId": "basic-flow", "topLevel": True, "builtIn": False}) == 201
def add(i):
status = call(tok, "POST", f"/race/authentication/flows/{parent}/executions/flow",
{"alias": f"{parent}-child-{i}", "type": "basic-flow",
"provider": "registration-page-form", "description": ""})
if status >= 500:
errors.append((n, "add", status))
def read():
for _ in range(5):
status = call(tok, "GET", f"/race/authentication/flows/{parent}/executions")
if status >= 500:
errors.append((n, "read", status))
threads = [threading.Thread(target=add, args=(i,)) for i in range(4)] + \
[threading.Thread(target=read) for _ in range(2)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"{len(errors)} responses >= 500 in 200 rounds: {errors}")Expected behaviour
Reading a flow's executions while a sub-flow is being added should either return the executions as they were before the change, or as they are after it. It should never return 500.
Possible cause (not verified)
The new execution seems to be visible to the reader before its referenced sub-flow (flowRef) can be resolved. recurseExecutions then dereferences a null AuthenticationFlowModel. A null check, or reading both within a consistent transaction or cache view, would avoid the 500.
Workaround
Serialise configuration changes, so that no sub-flow is added while the same flow's executions are being read.
Related issues
- Cannot invoke "org.keycloak.models.AuthenticationFlowModel.getProviderId()" because "flowRef" is null #17443 reported the same
NullPointerExceptionon Keycloak 21.0.0, when creating sub-flows with the Terraform provider. It was closed on 2024-03-15 as "should be fixed by Keycloak Operator fails to install realm authentication flow because "flow is null" #23980", with a request to open a new issue, with steps to reproduce without Terraform, if it was still valid. - It is still reproducible on 26.8.2, and the script above uses only the admin REST API, without Terraform.
Metadata
Metadata
Assignees
Labels
Type
Fields
Projects
- StatusShow more project fieldsOpen
Activity