Repository navigation
Return LDAP users imported by a concurrent request from user search #55768
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -409,7 +409,7 @@ public Stream<UserModel> searchForUserStream(RealmModel realm, Map<String, Strin | |
| } | ||
| return StreamsUtil.paginatedStream( | ||
| // search users but not force import returning null as they were returned before by the DB | ||
| result.map(ldapObject -> importUserFromLDAP(session, realm, ldapObject, ImportType.NOT_FORCED_RETURN_NULL)) | ||
| result.map(ldapObject -> importUserForSearch(realm, ldapObject)) | ||
| .filter(Objects::nonNull), | ||
| firstResult, maxResults); | ||
| } | ||
|
|
@@ -613,7 +613,7 @@ private Stream<LDAPObject> searchLDAPByAttributes(RealmModel realm, Map<String, | |
| * | ||
| * This method serves for {@code search} param of {@link org.keycloak.services.resources.admin.UsersResource#getUsers} | ||
| */ | ||
| private Stream<LDAPObject> searchLDAP(RealmModel realm, String search, Integer firstResult, Integer maxResults) { | ||
| protected Stream<LDAPObject> searchLDAP(RealmModel realm, String search, Integer firstResult, Integer maxResults) { | ||
|
|
||
| try (LDAPQuery ldapQuery = LDAPUtils.createQueryForUserSearch(this, realm)) { | ||
| LDAPQueryConditionsBuilder conditionsBuilder = new LDAPQueryConditionsBuilder(); | ||
|
|
@@ -1134,8 +1134,41 @@ public LDAPObject loadLDAPUserByDN(RealmModel realm, LDAPDn dn) { | |
| } | ||
| } | ||
|
|
||
| protected UserModel importUserForSearch(RealmModel realm, LDAPObject ldapObject) { | ||
| UserModel user = importUserFromLDAP(session, realm, ldapObject, ImportType.NOT_FORCED_RETURN_NULL); | ||
| return user != null ? user : findConcurrentlyImportedUser(realm, ldapObject); | ||
| } | ||
|
|
||
| protected UserModel getLocalUserByUsername(RealmModel realm, String username) { | ||
| return UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(realm, username); | ||
| } | ||
|
|
||
| /** | ||
| * The search filters out the LDAP entries that already have a local user, so an entry that reaches the import | ||
| * had no local user with that username at that time. If the import still reports an existing user, another | ||
| * request imported the same LDAP user in between and the DB search could not have returned it. Return that | ||
| * user so the search does not drop it. | ||
| * <p> | ||
| * Known separate case, not handled here: if the LDAP entry was renamed while the local user still has the old | ||
| * username, the DB search does not match it, the lookup by the new username finds nothing and the user is still | ||
| * dropped from the result. | ||
| */ | ||
| private UserModel findConcurrentlyImportedUser(RealmModel realm, LDAPObject ldapObject) { | ||
| if (!model.isImportEnabled()) { | ||
| return null; | ||
| } | ||
| String username = LDAPUtils.getUsername(ldapObject, ldapIdentityStore.getConfig()); | ||
| UserModel local = getLocalUserByUsername(realm, username); | ||
| if (local == null || !ldapObject.getUuid().equals(local.getFirstAttribute(LDAPConstants.LDAP_ID)) | ||
| || !model.getId().equals(local.getFederationLink())) { | ||
| return null; | ||
| } | ||
| logger.debugf("Returning LDAP user '%s' in the search result, it was imported by another request in the meantime", username); | ||
| return proxy(realm, local, ldapObject, false); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nitpick: a |
||
| } | ||
|
|
||
| private Predicate<LDAPObject> filterLocalUsers(RealmModel realm) { | ||
| return ldapObject -> UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(realm, LDAPUtils.getUsername(ldapObject, LDAPStorageProvider.this.ldapIdentityStore.getConfig())) == null; | ||
| return ldapObject -> getLocalUserByUsername(realm, LDAPUtils.getUsername(ldapObject, LDAPStorageProvider.this.ldapIdentityStore.getConfig())) == null; | ||
| } | ||
|
|
||
| /** | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,168 @@ | ||
| /* | ||
| * 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.storage.ldap; | ||
|
|
||
| import java.util.Iterator; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.stream.Collectors; | ||
| import java.util.stream.Stream; | ||
|
|
||
| import org.keycloak.common.util.MultivaluedHashMap; | ||
| import org.keycloak.component.ComponentModel; | ||
| import org.keycloak.models.KeycloakSession; | ||
| import org.keycloak.models.LDAPConstants; | ||
| import org.keycloak.models.RealmModel; | ||
| import org.keycloak.models.UserModel; | ||
| import org.keycloak.models.utils.UserModelDelegate; | ||
| import org.keycloak.storage.ldap.idm.model.LDAPObject; | ||
| import org.keycloak.storage.ldap.idm.store.ldap.LDAPIdentityStore; | ||
|
|
||
| import org.junit.Assert; | ||
| import org.junit.Before; | ||
| import org.junit.Test; | ||
|
|
||
| /** | ||
| * Tests how a user search treats an LDAP user that another request imported while the search was running. | ||
| */ | ||
| public class LDAPStorageProviderSearchTest { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. These four tests do not guard the fix. I reverted line 412 back to Please add one test that goes through
With those, the race becomes deterministic instead of a matter of timing: have I tried this on your branch to make sure I was not asking for something that does not work. It passes as written and fails with Keep the existing four for the LDAP_ID mismatch and no-local-user branches. |
||
|
|
||
| private static final String PROVIDER_ID = "ldap-provider"; | ||
| private static final String LDAP_UUID = "5f2c1d0e-0000-4000-8000-000000000001"; | ||
|
|
||
| private UserModel localUser; | ||
| private UserModel importResult; | ||
| private Iterator<UserModel> localLookups; | ||
| private final UserModel proxied = new UserModelDelegate(null); | ||
| private LDAPStorageProvider provider; | ||
| private LDAPObject ldapUser; | ||
|
|
||
| @Before | ||
| public void setUp() { | ||
| MultivaluedHashMap<String, String> config = new MultivaluedHashMap<>(); | ||
| config.add(LDAPConstants.USERNAME_LDAP_ATTRIBUTE, LDAPConstants.UID); | ||
| config.add(LDAPConstants.UUID_LDAP_ATTRIBUTE, LDAPConstants.ENTRY_UUID); | ||
| ComponentModel model = new ComponentModel(); | ||
| model.setId(PROVIDER_ID); | ||
| model.setConfig(config); | ||
| LDAPIdentityStore store = new LDAPIdentityStore(null, new LDAPConfig(config)); | ||
|
|
||
| provider = new LDAPStorageProvider(null, null, model, store) { | ||
| @Override | ||
| protected UserModel importUserFromLDAP(KeycloakSession session, RealmModel realm, LDAPObject ldapObject, ImportType importType) { | ||
| Assert.assertEquals(ImportType.NOT_FORCED_RETURN_NULL, importType); | ||
| return importResult; | ||
| } | ||
|
|
||
| @Override | ||
| protected UserModel getLocalUserByUsername(RealmModel realm, String username) { | ||
| Assert.assertEquals("jdoe", username); | ||
| return localLookups != null ? localLookups.next() : localUser; | ||
| } | ||
|
|
||
| @Override | ||
| protected Stream<LDAPObject> searchLDAP(RealmModel realm, String search, Integer firstResult, Integer maxResults) { | ||
| return Stream.of(ldapUser); | ||
| } | ||
|
|
||
| @Override | ||
| protected UserModel proxy(RealmModel realm, UserModel local, LDAPObject ldapObject, boolean newUser) { | ||
| Assert.assertSame(localUser, local); | ||
| return proxied; | ||
| } | ||
| }; | ||
|
|
||
| ldapUser = new LDAPObject(); | ||
| ldapUser.setUuid(LDAP_UUID); | ||
| ldapUser.setSingleAttribute(LDAPConstants.UID, "JDoe"); | ||
| } | ||
|
|
||
| private static UserModel userWithLdapId(String ldapId) { | ||
| return userWithLdapId(ldapId, PROVIDER_ID); | ||
| } | ||
|
|
||
| private static UserModel userWithLdapId(String ldapId, String federationLink) { | ||
| return new UserModelDelegate(null) { | ||
| @Override | ||
| public String getFederationLink() { | ||
| return federationLink; | ||
| } | ||
|
|
||
| @Override | ||
| public String getFirstAttribute(String name) { | ||
| return LDAPConstants.LDAP_ID.equals(name) ? ldapId : null; | ||
| } | ||
| }; | ||
| } | ||
|
|
||
| @Test | ||
| public void testImportedUserIsReturnedAsIs() { | ||
| importResult = userWithLdapId(LDAP_UUID); | ||
| Assert.assertSame(importResult, provider.importUserForSearch(null, ldapUser)); | ||
| } | ||
|
|
||
| @Test | ||
| public void testUserImportedConcurrentlyIsNotDropped() { | ||
| // the import finds a local user and returns null, but the user was not there when the search filtered local users | ||
| importResult = null; | ||
| localUser = userWithLdapId(LDAP_UUID); | ||
| Assert.assertSame(proxied, provider.importUserForSearch(null, ldapUser)); | ||
| } | ||
|
|
||
| @Test | ||
| public void testSearchReturnsUserImportedBetweenFilterAndImport() { | ||
| // first lookup is the filter of local users, the second one is the fallback after the import returned null | ||
| importResult = null; | ||
| localUser = userWithLdapId(LDAP_UUID); | ||
| localLookups = Stream.of(null, localUser).iterator(); | ||
| List<UserModel> result = provider.searchForUserStream(null, Map.of(UserModel.SEARCH, "jdoe"), 0, 10).collect(Collectors.toList()); | ||
| Assert.assertEquals(1, result.size()); | ||
| Assert.assertSame(proxied, result.get(0)); | ||
| } | ||
|
|
||
| @Test | ||
| public void testSearchReturnsNothingWhenUserStaysMissing() { | ||
| importResult = null; | ||
| localLookups = Stream.<UserModel>of(null, null).iterator(); | ||
| List<UserModel> result = provider.searchForUserStream(null, Map.of(UserModel.SEARCH, "jdoe"), 0, 10).collect(Collectors.toList()); | ||
| Assert.assertTrue(result.isEmpty()); | ||
| } | ||
|
|
||
| @Test | ||
| public void testNullWhenNoLocalUserExists() { | ||
| // the import was skipped for another reason, for example a duplicate that was cleaned up | ||
| importResult = null; | ||
| localUser = null; | ||
| Assert.assertNull(provider.importUserForSearch(null, ldapUser)); | ||
| } | ||
|
|
||
| @Test | ||
| public void testNullWhenLocalUserBelongsToAnotherProvider() { | ||
| // same directory-scoped id, but the user was imported by a different LDAP provider | ||
| importResult = null; | ||
| localUser = userWithLdapId(LDAP_UUID, "another-provider"); | ||
| Assert.assertTrue("a user of another provider must not be returned", provider.importUserForSearch(null, ldapUser) == null); | ||
| } | ||
|
|
||
| @Test | ||
| public void testNullWhenLocalUserIsLinkedToAnotherLdapEntry() { | ||
| importResult = null; | ||
| localUser = userWithLdapId("another-uuid"); | ||
| Assert.assertNull(provider.importUserForSearch(null, ldapUser)); | ||
| } | ||
| } | ||
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.
Just for the record, your reasoning for not reaching for
NOT_FORCED_RETURN_EXISTINGhere is correct: it would convert the rename drop into a duplicate whenever the DB side search did return the user under its old username. Worth moving that paragraph from the PR description into the commit message so it survives in the history.