-
Notifications
You must be signed in to change notification settings - Fork 8.7k
Flush auto-created roles during user import to avoid duplicate role inserts in batch mode #50056
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
121 changes: 121 additions & 0 deletions
121
server-spi-private/src/test/java/org/keycloak/models/utils/RepresentationToModelTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| /* | ||
| * Copyright 2016 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.utils; | ||
|
|
||
| import java.lang.reflect.Proxy; | ||
| import java.util.Collections; | ||
| import java.util.HashMap; | ||
| import java.util.Map; | ||
| import java.util.concurrent.atomic.AtomicInteger; | ||
|
|
||
| import org.keycloak.models.ClientModel; | ||
| import org.keycloak.models.RealmModel; | ||
| import org.keycloak.models.RoleModel; | ||
| import org.keycloak.representations.idm.RoleRepresentation; | ||
| import org.keycloak.representations.idm.RolesRepresentation; | ||
|
|
||
| import org.junit.Test; | ||
|
|
||
| import static org.junit.Assert.assertEquals; | ||
|
|
||
| public class RepresentationToModelTest { | ||
|
|
||
| @Test | ||
| public void importRolesReusesExistingClientRole() { | ||
| Map<String, RoleModel> clientRoles = new HashMap<>(); | ||
| AtomicInteger addedRoles = new AtomicInteger(); | ||
|
|
||
| RoleModel existingRole = role("CALL_ACCESS"); | ||
| clientRoles.put("CALL_ACCESS", existingRole); | ||
|
|
||
| ClientModel client = client(clientRoles, addedRoles); | ||
| RealmModel realm = realm("account", client); | ||
|
|
||
| RolesRepresentation roles = new RolesRepresentation(); | ||
| roles.setClient(Collections.singletonMap("account", | ||
| Collections.singletonList(new RoleRepresentation("CALL_ACCESS", "imported", false)))); | ||
|
|
||
| RepresentationToModel.importRoles(roles, realm); | ||
|
|
||
| assertEquals(0, addedRoles.get()); | ||
| assertEquals("imported", existingRole.getDescription()); | ||
| } | ||
|
|
||
| private static RealmModel realm(String clientId, ClientModel client) { | ||
| return (RealmModel) Proxy.newProxyInstance(RepresentationToModelTest.class.getClassLoader(), new Class[]{RealmModel.class}, | ||
| (proxy, method, args) -> { | ||
| if ("getClientByClientId".equals(method.getName()) && clientId.equals(args[0])) { | ||
| return client; | ||
| } | ||
| return defaultValue(method.getReturnType()); | ||
| }); | ||
| } | ||
|
|
||
| private static ClientModel client(Map<String, RoleModel> roles, AtomicInteger addedRoles) { | ||
| return (ClientModel) Proxy.newProxyInstance(RepresentationToModelTest.class.getClassLoader(), new Class[]{ClientModel.class}, | ||
| (proxy, method, args) -> { | ||
| if ("getRole".equals(method.getName())) { | ||
| return roles.get(args[0]); | ||
| } | ||
| if ("addRole".equals(method.getName())) { | ||
| addedRoles.incrementAndGet(); | ||
| RoleModel role = role(args.length == 1 ? (String) args[0] : (String) args[1]); | ||
| roles.put(role.getName(), role); | ||
| return role; | ||
| } | ||
| return defaultValue(method.getReturnType()); | ||
| }); | ||
| } | ||
|
|
||
| private static RoleModel role(String name) { | ||
| return (RoleModel) Proxy.newProxyInstance(RepresentationToModelTest.class.getClassLoader(), new Class[]{RoleModel.class}, | ||
| new Object() { | ||
| private String description; | ||
|
|
||
| public Object invoke(Object proxy, java.lang.reflect.Method method, Object[] args) { | ||
| if ("getName".equals(method.getName())) { | ||
| return name; | ||
| } | ||
| if ("getDescription".equals(method.getName())) { | ||
| return description; | ||
| } | ||
| if ("setDescription".equals(method.getName())) { | ||
| description = (String) args[0]; | ||
| return null; | ||
| } | ||
| return defaultValue(method.getReturnType()); | ||
| } | ||
| }::invoke); | ||
| } | ||
|
|
||
| private static Object defaultValue(Class<?> returnType) { | ||
| if (void.class.equals(returnType)) { | ||
| return null; | ||
| } | ||
| if (!returnType.isPrimitive()) { | ||
| return null; | ||
| } | ||
| if (boolean.class.equals(returnType)) { | ||
| return false; | ||
| } | ||
| if (char.class.equals(returnType)) { | ||
| return '\0'; | ||
| } | ||
| return 0; | ||
| } | ||
|
Comment on lines
+106
to
+120
|
||
| } | ||
87 changes: 87 additions & 0 deletions
87
...st/java/org/keycloak/testsuite/exportimport/RealmImportSharedUndefinedClientRoleTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| /* | ||
| * Copyright 2026 Red Hat Inc. and/or its affiliates and other contributors | ||
| * as indicated by the @author tags. All rights reserved. | ||
| * | ||
| * 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.testsuite.exportimport; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| import org.junit.Test; | ||
| import org.keycloak.admin.client.resource.RealmResource; | ||
| import org.keycloak.representations.idm.RealmRepresentation; | ||
| import org.keycloak.representations.idm.RoleRepresentation; | ||
| import org.keycloak.testframework.realm.ClientBuilder; | ||
| import org.keycloak.testframework.realm.RealmBuilder; | ||
| import org.keycloak.testframework.realm.UserBuilder; | ||
| import org.keycloak.testsuite.AbstractKeycloakTest; | ||
|
|
||
| import static org.junit.Assert.assertEquals; | ||
| import static org.junit.Assert.assertTrue; | ||
|
|
||
| /** | ||
| * Reproduces the duplicate KEYCLOAK_ROLE primary key violation reported in issue #49731: when several users | ||
| * reference the same client role that is not declared in {@code roles.client}, the role must be auto-created | ||
| * only once during the batch-mode user import instead of being created for every user that references it. | ||
| */ | ||
| public class RealmImportSharedUndefinedClientRoleTest extends AbstractKeycloakTest { | ||
|
|
||
| private static final String REALM_NAME = "shared-undefined-client-role"; | ||
| private static final String CLIENT_ID = "shared-role-client"; | ||
| private static final String ROLE_NAME = "CALL_ACCESS"; | ||
| private static final String USER_1 = "user-one"; | ||
| private static final String USER_2 = "user-two"; | ||
|
|
||
| @Override | ||
| public void addTestRealms(List<RealmRepresentation> testRealms) { | ||
| // The realm under test is imported and removed within the test itself. | ||
| } | ||
|
|
||
| @Test | ||
| public void importRealmWithSharedUndefinedClientRole() { | ||
| // The client declares no roles, yet both users reference the same client role. The import must | ||
| // auto-create the role exactly once instead of failing with a duplicate primary key violation. | ||
| RealmRepresentation realmRep = RealmBuilder.create() | ||
| .name(REALM_NAME) | ||
| .clients(ClientBuilder.create().clientId(CLIENT_ID).enabled(true)) | ||
| .users( | ||
| UserBuilder.create().username(USER_1).enabled(true).clientRoles(CLIENT_ID, ROLE_NAME), | ||
| UserBuilder.create().username(USER_2).enabled(true).clientRoles(CLIENT_ID, ROLE_NAME)) | ||
| .build(); | ||
|
|
||
| try { | ||
| // (a) The import must succeed without a duplicate-key / PK violation. | ||
| adminClient.realms().create(realmRep); | ||
|
|
||
| RealmResource realm = adminClient.realm(REALM_NAME); | ||
| String clientUuid = realm.clients().findByClientId(CLIENT_ID).get(0).getId(); | ||
|
|
||
| // (b) Exactly one such client role exists on the client after import. | ||
| long matching = realm.clients().get(clientUuid).roles().list().stream() | ||
| .filter(role -> ROLE_NAME.equals(role.getName())) | ||
| .count(); | ||
| assertEquals("The shared client role must be created exactly once", 1, matching); | ||
|
|
||
| // (c) Both users end up with the shared client-role mapping. | ||
| for (String username : List.of(USER_1, USER_2)) { | ||
| String userId = realm.users().search(username).get(0).getId(); | ||
| List<RoleRepresentation> mappings = realm.users().get(userId).roles().clientLevel(clientUuid).listAll(); | ||
| assertTrue("User " + username + " must have the shared client role mapped", | ||
| mappings.stream().anyMatch(role -> ROLE_NAME.equals(role.getName()))); | ||
| } | ||
| } finally { | ||
| removeRealm(REALM_NAME); | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consolidating this using lambda expressions would add unnecessary cognitive complexity and reduce maintainability.
Additionally, while similar, the realm role and client role logic is distinct enough in source class and intent, that keeping the methods distinct makes sense to me.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for reporting this and for taking the time to review, @SomeDeveloper13. I agree on keeping importRealmRole and importClientRole as separate helpers rather than folding them into shared lambda-based code; as you noted, the lambda version adds cognitive complexity, and the two paths read from different sources (realm roles vs a client's roles), so keeping them distinct makes the intent clearer.