8000 Cache federated-identity/service-account queries for already-managed users by sguilhen · Pull Request #55240 · 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 @@ -72,8 +72,11 @@ public void fullUserInvalidation(String userId, String username, String email, S
invalidations.add(UserCacheSession.getVerifiableCredentialsCacheKey(userId));
}

public void federatedIdentityLinkUpdatedInvalidation(String userId, Set<String> invalidations) {
invalidations.add(UserCacheSession.getFederatedIdentityLinksCacheKey(userId));
public void federatedIdentityLinkUpdatedInvalidation(String userId, String realmId, String identityProviderId, String socialUserId, Set<String> invalidations) {
// Needs to invalidate both directions, otherwise a federated identity query for this link that is looked up
// (and thereby cached) while the transaction that added/updated the link is still open would stay cached
// with a stale result if that transaction is later rolled back.
federatedIdentityLinkRemovedInvalidation(userId, realmId, identityProviderId, socialUserId, invalidations);
}

public void federatedIdentityLinkRemovedInvalidation(String userId, String realmId, String identityProviderId, String socialUserId, Set<String> invalidations) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,17 @@ public UserModel getUserByFederatedIdentity(RealmModel realm, FederatedIdentityM
if (model == null) return null;
userId = model.getId();
if (invalidations.contains(userId)) return model;
if (managedUsers.containsKey(userId)) return managedUsers.get(userId).user();
ManagedUser managed = managedUsers.get(userId);
if (managed != null && realm.getId().equals(managed.realmId())) {
// the user was already loaded by another lookup in this session (for example by username/email),
// so the federated identity query for this key still needs to be cached
UserModel managedUser = managed.user();
if (managedUser instanceof UserAdapter) {
query = new FederatedIdentityUserListQuery(loaded, cacheKey, realm, userId, socialLink.getIdentityProvider());
cache.addRevisioned(query, startupRevision, getLifespan(realm, managedUser));
}
return managedUser;
}

UserModel adapter = getUserAdapter(realm, userId, loaded, model);
if (adapter instanceof UserAdapter) {
Expand Down Expand Up @@ -611,9 +621,17 @@ public UserModel findServiceAccount(ClientModel client) {
}
userId = model.getId();
if (invalidations.contains(userId)) return model;
if (managedUsers.containsKey(userId)) {
ManagedUser managed = managedUsers.get(userId);
if (managed != null && realm.getId().equals(managed.realmId())) {
logger.tracev("return managed user");
return managedUsers.get(userId).user();
// the user was already loaded by another lookup in this session (for example by getUserById),
// so the service account username query for this key still needs to be cached
UserModel managedUser = managed.user();
if (managedUser instanceof UserAdapter && client.getId().equals(managedUser.getServiceAccountClientLink())) {
query = new UserListQuery(loaded, cacheKey, realm, userId);
cache.addRevisioned(query, startupRevision, getLifespan(realm, managedUser));
}
return managedUser;
}

UserModel adapter = getUserAdapter(realm, userId, loaded, model);
Expand Down Expand Up @@ -1056,19 +1074,22 @@ public boolean removeUser(RealmModel realm, UserModel user) {

@Override
public void addFederatedIdentity(RealmModel realm, UserModel user, FederatedIdentityModel socialLink) {
invalidateFederationLink(user.getId());
invalidateFederationLink(realm, user.getId(), socialLink);
getDelegate().addFederatedIdentity(realm, user, socialLink);
}

@Override
public void updateFederatedIdentity(RealmModel realm, UserModel federatedUser, FederatedIdentityModel federatedIdentityModel) {
invalidateFederationLink(federatedUser.getId());
invalidateFederationLink(realm, federatedUser.getId(), federatedIdentityModel);
getDelegate().updateFederatedIdentity(realm, federatedUser, federatedIdentityModel);
}

private void invalidateFederationLink(String userId) {
cache.federatedIdentityLinkUpdatedInvalidation(userId, invalidations);
invalidationEvents.add(UserFederationLinkUpdatedEvent.create(userId));
// Needs to invalidate both directions: otherwise a lookup of the reverse (federated identity) key that is
// cached while the transaction adding/updating the link is still open would stay cached if that transaction
// is later rolled back
private void invalidateFederationLink(RealmModel realm, String userId, FederatedIdentityModel socialLink) {
cache.federatedIdentityLinkUpdatedInvalidation(userId, realm.getId(), socialLink.getIdentityProvider(), socialLink.getUserId(), invalidations);
invalidationEvents.add(UserFederationLinkUpdatedEvent.create(userId, realm.getId(), socialLink));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,15 @@
*/
package org.keycloak.models.cache.infinispan.events;

import java.util.Objects;
import java.util.Set;

import org.keycloak.marshalling.Marshalling;
import org.keycloak.models.FederatedIdentityModel;
import org.keycloak.models.cache.infinispan.UserCacheManager;

import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoTypeId;

/**
Expand All @@ -30,23 +33,63 @@
@ProtoTypeId(Marshalling.USER_FEDERATION_LINK_UPDATED_EVENT)
public class UserFederationLinkUpdatedEvent extends InvalidationEvent implements UserCacheInvalidationEvent {

private UserFederationLinkUpdatedEvent(String id) {
final String realmId;
final String identityProviderId;
final String socialUserId;

private UserFederationLinkUpdatedEvent(String id, String realmId, String identityProviderId, String socialUserId) {
super(id);
this.realmId = realmId;
this.identityProviderId = identityProviderId;
this.socialUserId = socialUserId;
}

public static UserFederationLinkUpdatedEvent create(String id, String realmId, FederatedIdentityModel socialLink) {
return new UserFederationLinkUpdatedEvent(id, realmId, socialLink.getIdentityProvider(), socialLink.getUserId());
}

@ProtoFactory
public static UserFederationLinkUpdatedEvent create(String id) {
return new UserFederationLinkUpdatedEvent(id);
static UserFederationLinkUpdatedEvent protoFactory(String id, String realmId, String identityProviderId, String socialUserId) {
return new UserFederationLinkUpdatedEvent(id, realmId, identityProviderId, socialUserId);
}

@ProtoField(2)
public String getRealmId() {
return realmId;
}

@ProtoField(3)
public String getIdentityProviderId() {
return identityProviderId;
}

@ProtoField(4)
public String getSocialUserId() {
return socialUserId;
}

@Override
public String toString() 8000 {
return String.format("UserFederationLinkUpdatedEvent [ userId=%s ]", getId());
return String.format("UserFederationLinkUpdatedEvent [ userId=%s, identityProviderId=%s, socialUserId=%s ]", getId(), identityProviderId, socialUserId);
}

@Override
public void addInvalidations(UserCacheManager userCache, Set<String> invalidations) {
userCache.federatedIdentityLinkUpdatedInvalidation(getId(), invalidations);
userCache.federatedIdentityLinkUpdatedInvalidation(getId(), realmId, identityProviderId, socialUserId, invalidations);
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
UserFederationLinkUpdatedEvent that = (UserFederationLinkUpdatedEvent) o;
return Objects.equals(realmId, that.realmId) && Objects.equals(identityProviderId, that.identityProviderId) && Objects.equals(socialUserId, that.socialUserId);
}

@Override
public int hashCode() {
return Objects.hash(super.hashCode(), realmId, identityProviderId, socialUserId);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
/*
* 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.tests.model;

import jakarta.ws.rs.core.Response;

import org.keycloak.common.constants.ServiceAccountConstants;
import org.keycloak.connections.infinispan.InfinispanConnectionProvider;
import org.keycloak.models.ClientModel;
import org.keycloak.models.FederatedIdentityModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.representations.idm.FederatedIdentityRepresentation;
import org.keycloak.representations.idm.IdentityProviderRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.testframework.annotations.InjectRealm;
import org.keycloak.testframework.annotations.KeycloakIntegrationTest;
import org.keycloak.testframework.realm.ClientBuilder;
import org.keycloak.testframework.realm.ManagedRealm;
import org.keycloak.testframework.remote.runonserver.InjectRunOnServer;
import org.keycloak.testframework.remote.runonserver.RunOnServerClient;
import org.keycloak.testframework.util.ApiUtil;

import org.infinispan.Cache;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
* Verifies that {@code UserCacheSession.getUserByFederatedIdentity()} and {@code getServiceAccount()} cache their
* lookup query even when the resolved user was already managed in the session through a different, earlier lookup.
* See https://github.com/keycloak/keycloak/issues/55237.
*/
@KeycloakIntegrationTest
public class UserCacheManagedUserQueryTest {

private static final String IDP_ALIAS = "oidc";
private static final String USERNAME = "broker-user";
private static final String BROKER_USER_ID = "broker-user-id";

private static final String IDP_ALIAS_ROLLBACK = "oidc-rollback";
private static final String USERNAME_ROLLBACK = "broker-user-rollback";
private static final String BROKER_USER_ID_ROLLBACK = "broker-user-id-rollback";

@InjectRealm
ManagedRealm managedRealm;

@InjectRunOnServer
RunOnServerClient runOnServer;

@Test
public void federatedIdentityQueryIsCachedWhenUserAlreadyManaged() {
String realmName = managedRealm.getName();

IdentityProviderRepresentation idp = new IdentityProviderRepresentation();
idp.setAlias(IDP_ALIAS);
idp.setProviderId("oidc");
idp.setEnabled(true);
managedRealm.admin().identityProviders().create(idp).close();

UserRepresentation user = new UserRepresentation();
user.setUsername(USERNAME);
String userId;
try (Response response = managedRealm.admin().users().create(user)) {
userId = ApiUtil.getCreatedId(response);
}

FederatedIdentityRepresentation link = new FederatedIdentityRepresentation();
link.setIdentityProvider(IDP_ALIAS);
link.setUserId(BROKER_USER_ID);
link.setUserName(USERNAME);
try (Response response = managedRealm.admin().users().get(userId).addFederatedIdentity(IDP_ALIAS, link)) {
assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus());
}

runOnServer.run(session -> {
RealmModel realm = session.realms().getRealmByName(realmName);
session.getContext().setRealm(realm);

// first lookup manages the user via the username key
UserModel byUsername = session.users().getUserByUsername(realm, USERNAME);
assertNotNull(byUsername, "user should be found by username");

// second lookup resolves the same, already-managed user via the federated identity key
FederatedIdentityModel socialLink = new FederatedIdentityModel(IDP_ALIAS, BROKER_USER_ID, USERNAME);
UserModel byFederatedIdentity = session.users().getUserByFederatedIdentity(realm, socialLink);
assertNotNull(byFederatedIdentity, "user should be found by its federated identity");
assertEquals(byUsername.getId(), byFederatedIdentity.getId());

String cacheKey = realm.getId() + ".idp." + IDP_ALIAS + "." + BROKER_USER_ID;
Cache<Object, Object> cache = session.getProvider(InfinispanConnectionProvider.class)
.getCache(InfinispanConnectionProvider.USER_CACHE_NAME);
assertTrue(cache.containsKey(cacheKey),
"federated identity query must be cached even though the user was already managed in the session");
});
}

@Test
public void serviceAccountQueryIsCachedWhenUserAlreadyManaged() {
String realmName = managedRealm.getName();
String clientId = "service-client";

String createdClientId;
String serviceAccountUserId;
try (Response response = managedRealm.admin().clients().create(ClientBuilder.create(clientId).serviceAccountsEnabled().build())) {
createdClientId = ApiUtil.getCreatedId(response);
}
managedRealm.cleanup().add(r -> r.clients().get(createdClientId).remove());
serviceAccountUserId = managedRealm.admin().clients().get(createdClientId).toRepresentation().getServiceAccountUserId();

String serviceAccountUsername = (ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + clientId).toLowerCase();

runOnServer.run(session -> {
RealmModel realm = session.realms().getRealmByName(realmName);
session.getContext().setRealm(realm);

ClientModel client = realm.getClientByClientId(clientId);
assertNotNull(client, "client should exist");

String cacheKey = realm.getId() + ".username." + serviceAccountUsername;
Cache<Object, Object> cache = session.getProvider(InfinispanConnectionProvider.class)
.getCache(InfinispanConnectionProvider.USER_CACHE_NAME);
// the client representation fetched above already called getServiceAccount() once and cached this
// query; remove it so this test actually exercises the managed-user cache-miss path below
cache.remove(cacheKey);

// first lookup manages the user via its id, without touching the username cache key
UserModel byId = session.users().getUserById(realm, serviceAccountUserId);
assertNotNull(byId, "service account user should exist");

// second lookup resolves the same, already-managed user via the service account username key
UserModel byServiceAccount = session.users().getServiceAccount(client);
assertNotNull(byServiceAccount, "service account user should be found via getServiceAccount");
assertEquals(byId.getId(), byServiceAccount.getId());

assertTrue(cache.containsKey(cacheKey),
"service account username query must be cached even though the user was already managed in the session");
});
}

@Test
public void federatedIdentityLookupIsNotCachedWhenAddingTransactionIsRolledBack() {
String realmName = managedRealm.getName();

IdentityProviderRepresentation idp = new IdentityProviderRepresentation();
idp.setAlias(IDP_ALIAS_ROLLBACK);
idp.setProviderId("oidc");
idp.setEnabled(true);
managedRealm.admin().identityProviders().create(idp).close();

UserRepresentation user = new UserRepresentation();
user.setUsername(USERNAME_ROLLBACK);
String userId;
try (Response response = managedRealm.admin().users().create(user)) {
userId = ApiUtil.getCreatedId(response);
}

runOnServer.run(session -> {
RealmModel realm = session.realms().getRealmByName(realmName);
session.getContext().setRealm(realm);

UserModel addedUser = session.users().getUserById(realm, userId);
assertNotNull(addedUser, "user should exist");

FederatedIdentityModel socialLink = new FederatedIdentityModel(IDP_ALIAS_ROLLBACK, BROKER_USER_ID_ROLLBACK, USERNAME_ROLLBACK);
session.users().addFederatedIdentity(realm, addedUser, socialLink);

// looking the link up while its adding transaction is still open must not leave a stale cache entry
// behind once the transaction is rolled back
UserModel byFederatedIdentity = session.users().getUserByFederatedIdentity(realm, socialLink);
assertNotNull(byFederatedIdentity, "link should be visible within its own transaction");

session.getTransactionManager().setRollbackOnly();
});

runOnServer.run(session -> {
RealmModel realm = session.realms().getRealmByName(realmName);
session.getContext().setRealm(realm);

FederatedIdentityModel socialLink = new FederatedIdentityModel(IDP_ALIAS_ROLLBACK, BROKER_USER_ID_ROLLBACK, USERNAME_ROLLBACK);
UserModel byFederatedIdentity = session.users().getUserByFederatedIdentity(realm, socialLink);
assertNull(byFederatedIdentity, "federated identity link must not be visible after its adding transaction was rolled back");
});
}
}
Loading
0