8000 Avoid NPE when reading flow executions during concurrent sub-flow creation by flipcyde101 · Pull Request #55800 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
8000 }
authenticationExecutions.add(flow.getId(), execution);
executionsById.put(execution.getId(), execution);
if (execution.getFlowId() != null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -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<AuthenticationExecutionModel> 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( 8000 ).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<AuthenticationFlowModel> flows,
Map<String, List<AuthenticationExecutionModel>> 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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -708,13 +708,21 @@ private String getAuthenticationConfig(String flowAlias, AuthenticationExecution
public void recurseExecutions(AuthenticationFlowModel flow, List<AuthenticationExecutionInfoRepresentation> 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());
Expand Down
448E
Original file line number Diff line number Diff line change
@@ -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;
imp 8BD0 ort 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<String, AuthenticationFlowModel> flowsById = Map.of(
parentFlow.getId(), parentFlow,
childFlow1.getId(), childFlow1,
childFlow2.getId(), childFlow2);
Map<String, List<AuthenticationExecutionModel>> 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<AuthenticationExecutionInfoRepresentation> 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());
}
}
0