From 40e0e68914db42ea0c391af65fc6d429cd561e28 Mon Sep 17 00:00:00 2001 From: Flipcyde <169501444+flipcyde101@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:53:05 -0700 Subject: [PATCH] Avoid NPE when reading flow executions during concurrent sub-flow creation Closes #55794 Signed-off-by: Flipcyde <169501444+flipcyde101@users.noreply.github.com> --- .../infinispan/entities/CachedRealm.java | 5 + .../infinispan/entities/CachedRealmTest.java | 143 ++++++++++++++++ .../AuthenticationManagementResource.java | 10 +- .../AuthenticationManagementResourceTest.java | 156 ++++++++++++++++++ 4 files changed, 313 insertions(+), 1 deletion(-) create mode 100644 model/infinispan/src/test/java/org/keycloak/models/cache/infinispan/entities/CachedRealmTest.java create mode 100644 services/src/test/java/org/keycloak/services/resources/admin/AuthenticationManagementResourceTest.java diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/CachedRealm.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/CachedRealm.java index c9f941802a70..e96abd9cb738 100755 --- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/CachedRealm.java +++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/CachedRealm.java @@ -284,7 +284,12 @@ public CachedRealm(long revision, RealmModel model) { for (AuthenticationFlowModel flow : authenticationFlowList) { this.authenticationFlows.put(flow.getId(), flow); authenticationExecutions.put(flow.getId(), new LinkedList<>()); + } + for (AuthenticationFlowModel flow : authenticationFlowList) { model.getAuthenticationExecutionsStream(flow.getId()).forEachOrdered(execution -> { + if (execution.isAuthenticatorFlow() && (execution.getFlowId() == null || !this.authenticationFlows.containsKey(execution.getFlowId()))) { + return; + } authenticationExecutions.add(flow.getId(), execution); executionsById.put(execution.getId(), execution); if (execution.getFlowId() != null) { diff --git a/model/infinispan/src/test/java/org/keycloak/models/cache/infinispan/entities/CachedRealmTest.java b/model/infinispan/src/test/java/org/keycloak/models/cache/infinispan/entities/CachedRealmTest.java new file mode 100644 index 000000000000..617eae14230c --- /dev/null +++ b/model/infinispan/src/test/java/org/keycloak/models/cache/infinispan/entities/CachedRealmTest.java @@ -0,0 +1,143 @@ +/* + * Copyright 2026 Red Hat, Inc. and/or its affiliates + * and other contributors as indicated by the @author tags. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.keycloak.models.cache.infinispan.entities; + +import java.lang.reflect.Proxy; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Stream; + +import org.keycloak.models.AuthenticationExecutionModel; +import org.keycloak.models.AuthenticationFlowModel; +import org.keycloak.models.RealmModel; +import org.keycloak.models.RoleModel; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +public class CachedRealmTest { + + @Test + public void skipsSubFlowExecutionWhoseReferencedFlowIsMissingFromSnapshot() { + AuthenticationFlowModel parentFlow = new AuthenticationFlowModel(); + parentFlow.setId("parent-id"); + parentFlow.setAlias("parent"); + parentFlow.setProviderId("basic-flow"); + + AuthenticationFlowModel existingChildFlow = new AuthenticationFlowModel(); + existingChildFlow.setId("child-existing-id"); + existingChildFlow.setAlias("child-existing"); + existingChildFlow.setProviderId("basic-flow"); + + // Execution referencing a sub-flow that is present later in authenticationFlowList + AuthenticationExecutionModel validSubFlowExec = new AuthenticationExecutionModel(); + validSubFlowExec.setId("exec-valid-subflow"); + validSubFlowExec.setParentFlow(parentFlow.getId()); + validSubFlowExec.setFlowId(existingChildFlow.getId()); + validSubFlowExec.setAuthenticatorFlow(true); + + // Execution referencing a sub-flow committed concurrently after getAuthenticationFlowsStream() + AuthenticationExecutionModel missingSubFlowExec = new AuthenticationExecutionModel(); + missingSubFlowExec.setId("exec-missing-subflow"); + missingSubFlowExec.setParentFlow(parentFlow.getId()); + missingSubFlowExec.setFlowId("child-concurrent-id"); + missingSubFlowExec.setAuthenticatorFlow(true); + + // Non-flow authenticator execution + AuthenticationExecutionModel regularExec = new AuthenticationExecutionModel(); + regularExec.setId("exec-regular"); + regularExec.setParentFlow(parentFlow.getId()); + regularExec.setAuthenticator("auth-cookie"); + regularExec.setAuthenticatorFlow(false); + + RealmModel realmModel = createRealmProxy( + List.of(parentFlow, existingChildFlow), + Map.of(parentFlow.getId(), List.of(validSubFlowExec, missingSubFlowExec, regularExec))); + + CachedRealm cached = new CachedRealm(1L, realmModel); + + List parentExecutions = cached.getAuthenticationExecutions().get(parentFlow.getId()); + assertNotNull(parentExecutions); + assertEquals(2, parentExecutions.size()); + assertEquals("exec-valid-subflow", parentExecutions.get(0).getId()); + assertEquals("exec-regular", parentExecutions.get(1).getId()); + + assertNotNull(cached.getExecutionsById().get("exec-valid-subflow")); + assertNotNull(cached.getExecutionsById().get("exec-regular")); + assertNull(cached.getExecutionsById().get("exec-missing-subflow")); + assertNotNull(cached.getAuthenticationExecutionByFlowId(existingChildFlow.getId())); + assertNull(cached.getAuthenticationExecutionByFlowId("child-concurrent-id")); + } + + private static RealmModel createRealmProxy( + List flows, + Map> executionsByParent) { + RoleModel defaultRole = (RoleModel) Proxy.newProxyInstance( + RoleModel.class.getClassLoader(), + new Class[]{RoleModel.class}, + (proxy, method, args) -> "getId".equals(method.getName()) ? "default-role-id" : defaultValue(method.getReturnType())); + return (RealmModel) Proxy.newProxyInstance( + RealmModel.class.getClassLoader(), + new Class[]{RealmModel.class}, + (proxy, method, args) -> { + switch (method.getName()) { + case "getId": + case "getName": + return "test-realm"; + case "getDefaultRole": + return defaultRole; + case "getAuthenticationFlowsStream": + return flows.stream(); + case "getAuthenticationExecutionsStream": + return executionsByParent.getOrDefault((String) args[0], Collections.emptyList()).stream(); + default: + return defaultValue(method.getReturnType()); + } + }); + } + + private static Object defaultValue(Class returnType) { + if (returnType == boolean.class) { + return false; + } + if (returnType == int.class) { + return 0; + } + if (returnType == long.class) { + return 0L; + } + if (returnType == Stream.class) { + return Stream.empty(); + } + if (returnType == Map.class) { + return Collections.emptyMap(); + } + if (returnType == Set.class) { + return Collections.emptySet(); + } + if (returnType == List.class) { + return Collections.emptyList(); + } + return null; + } +} diff --git a/services/src/main/java/org/keycloak/services/resources/admin/AuthenticationManagementResource.java b/services/src/main/java/org/keycloak/services/resources/admin/AuthenticationManagementResource.java index 79a9c59839e1..fbcc40e11d84 100755 --- a/services/src/main/java/org/keycloak/services/resources/admin/AuthenticationManagementResource.java +++ b/services/src/main/java/org/keycloak/services/resources/admin/AuthenticationManagementResource.java @@ -708,13 +708,21 @@ private String getAuthenticationConfig(String flowAlias, AuthenticationExecution public void recurseExecutions(AuthenticationFlowModel flow, List result, int level) { AtomicInteger index = new AtomicInteger(0); realm.getAuthenticationExecutionsStream(flow.getId()).forEachOrdered(execution -> { + AuthenticationFlowModel flowRef = null; + if (execution.isAuthenticatorFlow()) { + flowRef = realm.getAuthenticationFlowById(execution.getFlowId()); + if (flowRef == null) { + logger.warnf("Authentication flow '%s' referenced by execution '%s' in flow '%s' was not found", + execution.getFlowId(), execution.getId(), flow.getAlias()); + return; + } + } AuthenticationExecutionInfoRepresentation rep = new AuthenticationExecutionInfoRepresentation(); rep.setLevel(level); rep.setIndex(index.getAndIncrement()); rep.setRequirementChoices(new LinkedList<>()); rep.setPriority(execution.getPriority()); if (execution.isAuthenticatorFlow()) { - AuthenticationFlowModel flowRef = realm.getAuthenticationFlowById(execution.getFlowId()); if (AuthenticationFlow.BASIC_FLOW.equals(flowRef.getProviderId())) { rep.getRequirementChoices().add(AuthenticationExecutionModel.Requirement.REQUIRED.name()); rep.getRequirementChoices().add(AuthenticationExecutionModel.Requirement.ALTERNATIVE.name()); diff --git a/services/src/test/java/org/keycloak/services/resources/admin/AuthenticationManagementResourceTest.java b/services/src/test/java/org/keycloak/services/resources/admin/AuthenticationManagementResourceTest.java new file mode 100644 index 000000000000..d594da58c6e1 --- /dev/null +++ b/services/src/test/java/org/keycloak/services/resources/admin/AuthenticationManagementResourceTest.java @@ -0,0 +1,156 @@ +/* + * Copyright 2026 Red Hat, Inc. and/or its affiliates + * and other contributors as indicated by the @author tags. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.keycloak.services.resources.admin; + +import java.lang.reflect.Proxy; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import org.keycloak.authentication.AuthenticationFlow; +import org.keycloak.events.admin.AdminEvent; +import org.keycloak.events.admin.AuthDetails; +import org.keycloak.models.AuthenticationExecutionModel; +import org.keycloak.models.AuthenticationFlowModel; +import org.keycloak.models.KeycloakContext; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.KeycloakSessionFactory; +import org.keycloak.models.RealmModel; +import org.keycloak.representations.idm.AuthenticationExecutionInfoRepresentation; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class AuthenticationManagementResourceTest { + + @Test + public void recurseExecutionsSkipsMissingSubFlowWithoutNpe() { + AuthenticationFlowModel parentFlow = new AuthenticationFlowModel(); + parentFlow.setId("parent-id"); + parentFlow.setAlias("parent"); + parentFlow.setProviderId(AuthenticationFlow.BASIC_FLOW); + + AuthenticationFlowModel childFlow1 = new AuthenticationFlowModel(); + childFlow1.setId("child-1-id"); + childFlow1.setAlias("child-1"); + childFlow1.setProviderId(AuthenticationFlow.BASIC_FLOW); + + AuthenticationFlowModel childFlow2 = new AuthenticationFlowModel(); + childFlow2.setId("child-2-id"); + childFlow2.setAlias("child-2"); + childFlow2.setProviderId(AuthenticationFlow.BASIC_FLOW); + + AuthenticationExecutionModel exec1 = new AuthenticationExecutionModel(); + exec1.setId("exec-1"); + exec1.setParentFlow(parentFlow.getId()); + exec1.setFlowId(childFlow1.getId()); + exec1.setAuthenticatorFlow(true); + exec1.setRequirement(AuthenticationExecutionModel.Requirement.DISABLED); + exec1.setPriority(10); + + AuthenticationExecutionModel missingFlowExec = new AuthenticationExecutionModel(); + missingFlowExec.setId("exec-missing"); + missingFlowExec.setParentFlow(parentFlow.getId()); + missingFlowExec.setFlowId("missing-subflow-id"); + missingFlowExec.setAuthenticatorFlow(true); + missingFlowExec.setRequirement(AuthenticationExecutionModel.Requirement.DISABLED); + missingFlowExec.setPriority(20); + + AuthenticationExecutionModel exec2 = new AuthenticationExecutionModel(); + exec2.setId("exec-2"); + exec2.setParentFlow(parentFlow.getId()); + exec2.setFlowId(childFlow2.getId()); + exec2.setAuthenticatorFlow(true); + exec2.setRequirement(AuthenticationExecutionModel.Requirement.DISABLED); + exec2.setPriority(30); + + Map flowsById = Map.of( + parentFlow.getId(), parentFlow, + childFlow1.getId(), childFlow1, + childFlow2.getId(), childFlow2); + Map> executionsByParent = Map.of( + parentFlow.getId(), List.of(exec1, missingFlowExec, exec2)); + + RealmModel realm = (RealmModel) Proxy.newProxyInstance( + RealmModel.class.getClassLoader(), + new Class[]{RealmModel.class}, + (proxy, method, args) -> { + switch (method.getName()) { + case "getAuthenticationExecutionsStream": + return executionsByParent.getOrDefault((String) args[0], Collections.emptyList()).stream(); + case "getAuthenticationFlowById": + return flowsById.get((String) args[0]); + case "getEventsListenersStream": + return Stream.empty(); + default: + if (method.getReturnType() == boolean.class) { + return false; + } + return null; + } + }); + + KeycloakContext context = (KeycloakContext) Proxy.newProxyInstance( + KeycloakContext.class.getClassLoader(), + new Class[]{KeycloakContext.class}, + (proxy, method, args) -> "getRealm".equals(method.getName()) ? realm : null); + + KeycloakSessionFactory sessionFactory = (KeycloakSessionFactory) Proxy.newProxyInstance( + KeycloakSessionFactory.class.getClassLoader(), + new Class[]{KeycloakSessionFactory.class}, + (proxy, method, args) -> "getProviderFactoriesStream".equals(method.getName()) ? Stream.empty() : null); + + KeycloakSession session = (KeycloakSession) Proxy.newProxyInstance( + KeycloakSession.class.getClassLoader(), + new Class[]{KeycloakSession.class}, + (proxy, method, args) -> { + switch (method.getName()) { + case "getContext": + return context; + case "getKeycloakSessionFactory": + return sessionFactory; + case "getAllProviders": + return Collections.emptySet(); + default: + if (method.getReturnType() == boolean.class) { + return false; + } + return null; + } + }); + + AdminEvent event = new AdminEvent(); + event.setAuthDetails(new AuthDetails()); + AdminEventBuilder adminEvent = new AdminEventBuilder(realm, null, session, "127.0.0.1", event); + AuthenticationManagementResource resource = new AuthenticationManagementResource(session, null, adminEvent); + + List result = new LinkedList<>(); + resource.recurseExecutions(parentFlow, result, 0); + + assertEquals(2, result.size()); + assertEquals("exec-1", result.get(0).getId()); + assertEquals("child-1", result.get(0).getDisplayName()); + assertEquals(0, result.get(0).getIndex()); + assertEquals("exec-2", result.get(1).getId()); + assertEquals("child-2", result.get(1).getDisplayName()); + assertEquals(1, result.get(1).getIndex()); + } +}