8000 Only use a managed user for getUserByUsername/getUserByEmail if it ma… by sguilhen · Pull Request #55555 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -307,12 +307,12 @@ public UserModel getUserByUsername(RealmModel realm, String rawUsername) {
String userId = model.getId();
if (invalidations.contains(userId)) return model;
ManagedUser managed = managedUsers.get(userId);
if (managed != null) {
if (managed != null && realm.getId().equals(managed.realmId())) {
logger.tracev("return managed user");
UserModel managedUser = managed.user();
// the user was loaded by another lookup in this session (for example by email), so the query for
// this key still needs to be cached, but only if the managed user is really a match for the key
if (realm.getId().equals(managed.realmId()) && username.equalsIgnoreCase(managedUser.getUsername())) {
if (username.equalsIgnoreCase(managedUser.getUsername())) {
cacheUserQuery(realm, cacheKey, loaded, managedUser);
}
return managedUser;
Expand Down Expand Up @@ -391,9 +391,13 @@ protected UserModel getUserAdapter(RealmModel realm, String userId, Long loaded,
CachedUser cached = cache.get(userId, CachedUser.class);
if (cached == null) {
return cacheUser(realm, delegate, loaded);
} else {
return validateCache(realm, cached, () -> getDelegate().getUserById(realm, userId));
}
if (!realm.getId().equals(cached.getRealm())) {
// the shared cache holds an entry for this id under a different realm; the delegate already resolved
// the user for the requested realm, so return it rather than losing it to validateCache's realm check
return delegate;
}
return validateCache(realm, cached, () -> getDelegate().getUserById(realm, userId));
}

protected UserModel validateCache(RealmModel realm, CachedUser cached, Supplier<UserModel> supplier) {
Expand Down Expand Up @@ -493,10 +497,10 @@ public UserModel getUserByEmail(RealmModel realm, String rawEmail) {
String userId = model.getId();
if (invalidations.contains(userId)) return model;
ManagedUser managed = managedUsers.get(userId);
if (managed != null) {
if (managed != null && realm.getId().equals(managed.realmId())) {
UserModel managedUser = managed.user();
// see getUserByUsername: cache the query for this key, but only if the managed user is a match for it
if (realm.getId().equals(managed.realmId()) && email.equalsIgnoreCase(managedUser.getEmail())) {
if (email.equalsIgnoreCase(managedUser.getEmail())) {
cacheUserQuery(realm, cacheKey, loaded, managedUser);
}
return managedUser;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.cache.CachedUserModel;
import org.keycloak.models.cache.infinispan.entities.CachedUser;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.services.managers.RealmManager;
import org.keycloak.storage.CacheableStorageProviderModel.CachePolicy;
Expand Down Expand Up @@ -58,6 +59,8 @@ public class UserCacheQueryTest {
private static final String EMAIL = "alice@example.org";
private static final String LOCAL_USERNAME = "bob";
private static final String LOCAL_EMAIL = "bob@example.org";
private static final String COLLIDING_REALM_1 = "user-cache-query-collision-1";
private static final String COLLIDING_REALM_2 = "user-cache-query-collision-2";

@InjectRunOnServer
RunOnServerClient runOnServer;
Expand Down Expand Up @@ -188,6 +191,111 @@ public void queryIsNotCachedForUserInvalidatedInSession(KeycloakSession session)
assertThat(CountingUserStorageProvider.BY_USERNAME_CALLS.get(), equalTo(0));
}

@TestOnServer
public void getUserByUsernameResolvesUserWhenCachedEntryBelongsToAnotherRealm(KeycloakSession session) {
try {
String bobId = setUpCollidingRealms(session);

// realm2's own user must still resolve, even though the shared cache entry for its id was forged to belong to realm1
inSession(session, s -> {
RealmModel realm1 = s.realms().getRealmByName(COLLIDING_REALM_1);
RealmModel realm2 = s.realms().getRealmByName(COLLIDING_REALM_2);

// force the forged cache entry into this session's managed-user map under realm1, as if it had
// already been resolved earlier in the session, so the lookup below cannot just rely on the
// distributed cache's own realm check
s.users().getUserById(realm1, bobId);

UserModel user = s.users().getUserByUsername(realm2, "bob");
assertThat(user, notNullValue());
assertThat(user.getEmail(), equalTo("bob@example.org"));

// the resolved user must not have been lost to a poisoned null managed-user entry for the rest of the session
assertThat(s.users().getUserById(realm2, bobId), notNullValue());
});
} finally {
removeCollidingRealms(session);
}
}

@TestOnServer
public void getUserByEmailResolvesUserWhenCachedEntryBelongsToAnotherRealm(KeycloakSession session) {
try {
String bobId = setUpCollidingRealms(session);

// realm2's own user must still resolve, even though the shared cache entry for its id was forged to belong to realm1
inSession(session, s -> {
RealmModel realm1 = s.realms().getRealmByName(COLLIDING_REALM_1);
RealmModel realm2 = s.realms().getRealmByName(COLLIDING_REALM_2);

// force the forged cache entry into this session's managed-user map under realm1, as if it had
// already been resolved earlier in the session, so the lookup below cannot just rely on the
// distributed cache's own realm check
s.users().getUserById(realm1, bobId);

UserModel user = s.users().getUserByEmail(realm2, "bob@example.org");
assertThat(user, notNullValue());
assertThat(user.getUsername(), equalTo("bob"));

// the resolved user must not have been lost to a poisoned null managed-user entry for the rest of the session
assertThat(s.users().getUserById(realm2, bobId), notNullValue());
});
} finally {
removeCollidingRealms(session);
}
}

/**
* Sets up two realms, each with their own local user (realm1/alice, realm2/bob). Since a user's id is the
* primary key of its table, two real users can never actually share the same id. To still exercise the shared
* user cache's behavior for that case (which is only keyed by id, not by realm), this forges a collision by
* directly planting a {@link CachedUser} for alice (realm1) under bob's (realm2) id, as if the shared cache had
* (wrongly) returned alice's entry for a lookup of bob's id.
*
* @return bob's id, under which the forged cache entry for realm1 was planted
*/
private static String setUpCollidingRealms(KeycloakSession session) {
String[] ids = new String[2];
inSession(session, s -> {
RealmModel realm1 = new RealmManager(s).createRealm(COLLIDING_REALM_1);
UserModel alice = s.users().addUser(realm1, "alice");
alice.setEmail("alice@example.org");
ids[0] = alice.getId();
});
inSession(session, s -> {
RealmModel realm2 = new RealmManager(s).createRealm(COLLIDING_REALM_2);
UserModel bob = s.users().addUser(realm2, "bob");
bob.setEmail("bob@example.org");
ids[1] = bob.getId();
});
String bobId = ids[1];

inSession(session, s -> {
RealmModel realm1 = s.realms().getRealmByName(COLLIDING_REALM_1);
UserModel alice = s.users().getUserByUsername(realm1, "alice");
CachedUser forged = new CachedUser(0, realm1, alice, 0);

Cache<String, Object> userCache = s.getProvider(InfinispanConnectionProvider.class).getCache(InfinispanConnectionProvider.USER_CACHE_NAME);
Cache<String, Object> revisions = s.getProvider(InfinispanConnectionProvider.class).getCache(InfinispanConnectionProvider.USER_REVISIONS_CACHE_NAME);
userCache.put(bobId, forged);
revisions.put(bobId, 0L);
});

return bobId;
}

private static void removeCollidingRealms(KeycloakSession session) {
inSession(session, s -> {
RealmManager realmManager = new RealmManager(s);
for (String realmName : new String[] { COLLIDING_REALM_1, COLLIDING_REALM_2 }) {
RealmModel realm = realmManager.getRealmByName(realmName);
if (realm != null) {
realmManager.removeRealm(realm);
}
}
});
}

@TestOnServer
public void queriesAreCachedForLocalUsers(KeycloakSession session) {
inSession(session, s -> {
Expand Down
Loading
0