8000 Return LDAP users imported by a concurrent request from user search by ChethankumarGS · Pull Request #55768 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Open
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 @@ -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);
}
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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);
Copy link
Copy Markdown
Contributor

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_EXISTING here 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.

}

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);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpick: a logger.debugf before this return, noting that the entry was recovered because another request imported it, would make this path diagnosable. It is completely invisible otherwise, and it only fires in a case that is hard to reproduce on purpose.

}

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;
}

/**
Expand Down
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 {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 importUserFromLDAP(session, realm, ldapObject, ImportType.NOT_FORCED_RETURN_NULL), left everything else in place, and all four still passed. They only exercise findConcurrentlyImportedUser in isolation, so the one line that actually fixes the bug has no coverage.

Please add one test that goes through searchForUserStream itself. Two small production changes make that possible:

  • route filterLocalUsers through getLocalUserByUsername (see my other comment in line 1166 of DAPStorageProvider), so a single seam controls both username lookups;
  • make searchLDAP protected, so the subclass can return a fixed LDAPObject.

With those, the race becomes deterministic instead of a matter of timing: have getLocalUserByUsername return null on the first call and the imported user on the second. That is exactly the interleaving the issue describes, the first call being filterLocalUsers and the second your fallback. Keep importUserFromLDAP stubbed to null as you already do, then assert searchForUserStream yields the proxied user.

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 expected:<1> but was:<0> when line 412 is reverted, which is the guard that is missing today. Add a second case where getLocalUserByUsername returns null both times and assert the result is empty, so the test cannot pass by simply returning everything. Both of those stayed correct for me while the rest of the module stayed green.

Keep the existing four for the LDAP_ID mismatch and no-local-user branches. testImportedUserIsReturnedAsIs becomes largely redundant once the pipeline test exists, since it mostly asserts that your stub was called with the expected ImportType, but no harm in leaving it.


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));
}
}
Loading
0