KEYCLOAK-16908 Refactor UserSessionPersisterProvider

This commit is contained in:
Martin Kanis 2021-01-25 17:18:08 +01:00 committed by Hynek Mlnařík
parent 922d7da3ae
commit 8432513daa
12 changed files with 56 additions and 50 deletions

View file

@ -26,6 +26,7 @@ import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.UserSessionModel; import org.keycloak.models.UserSessionModel;
import org.keycloak.models.session.UserSessionPersisterProvider;
import org.keycloak.models.sessions.infinispan.changes.InfinispanChangelogBasedTransaction; import org.keycloak.models.sessions.infinispan.changes.InfinispanChangelogBasedTransaction;
import org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper; import org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper;
import org.keycloak.models.sessions.infinispan.changes.ClientSessionUpdateTask; import org.keycloak.models.sessions.infinispan.changes.ClientSessionUpdateTask;
@ -85,6 +86,9 @@ public class AuthenticatedClientSessionAdapter implements AuthenticatedClientSes
*/ */
@Override @Override
public void detachFromUserSession() { public void detachFromUserSession() {
if (this.userSession.isOffline()) {
kcSession.getProvider(UserSessionPersisterProvider.class).removeClientSession(userSession.getId(), client.getId(), true);
}
// Intentionally do not remove the clientUUID from the user session, invalid session is handled // Intentionally do not remove the clientUUID from the user session, invalid session is handled
// as nonexistent in org.keycloak.models.sessions.infinispan.UserSessionAdapter.getAuthenticatedClientSessions() // as nonexistent in org.keycloak.models.sessions.infinispan.UserSessionAdapter.getAuthenticatedClientSessions()
this.userSession = null; this.userSession = null;

View file

@ -36,6 +36,7 @@ import org.keycloak.models.UserLoginFailureModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel; import org.keycloak.models.UserSessionModel;
import org.keycloak.models.UserSessionProvider; import org.keycloak.models.UserSessionProvider;
import org.keycloak.models.session.UserSessionPersisterProvider;
import org.keycloak.models.sessions.infinispan.changes.Tasks; import org.keycloak.models.sessions.infinispan.changes.Tasks;
import org.keycloak.models.sessions.infinispan.changes.sessions.CrossDCLastSessionRefreshStore; import org.keycloak.models.sessions.infinispan.changes.sessions.CrossDCLastSessionRefreshStore;
import org.keycloak.models.sessions.infinispan.changes.sessions.PersisterLastSessionRefreshStore; import org.keycloak.models.sessions.infinispan.changes.sessions.PersisterLastSessionRefreshStore;
@ -467,6 +468,7 @@ public class InfinispanUserSessionProvider implements UserSessionProvider {
log.debugf("Removing expired sessions"); log.debugf("Removing expired sessions");
removeExpiredUserSessions(realm); removeExpiredUserSessions(realm);
removeExpiredOfflineUserSessions(realm); removeExpiredOfflineUserSessions(realm);
session.getProvider(UserSessionPersisterProvider.class).removeExpired(realm);
} }
private void removeExpiredUserSessions(RealmModel realm) { private void removeExpiredUserSessions(RealmModel realm) {
@ -613,7 +615,8 @@ public class InfinispanUserSessionProvider implements UserSessionProvider {
removeLocalUserSessions(realmId, false); removeLocalUserSessions(realmId, false);
} }
private void removeLocalUserSessions(String realmId, boolean offline) { // public for usage in the testsuite
public void removeLocalUserSessions(String realmId, boolean offline) {
FuturesHelper futures = new FuturesHelper(); FuturesHelper futures = new FuturesHelper();
Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = getCache(offline); Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = getCache(offline);
@ -725,6 +728,11 @@ public class InfinispanUserSessionProvider implements UserSessionProvider {
clusterEventsSenderTx.addEvent( clusterEventsSenderTx.addEvent(
RealmRemovedSessionEvent.createEvent(RealmRemovedSessionEvent.class, InfinispanUserSessionProviderFactory.REALM_REMOVED_SESSION_EVENT, session, realm.getId(), true), RealmRemovedSessionEvent.createEvent(RealmRemovedSessionEvent.class, InfinispanUserSessionProviderFactory.REALM_REMOVED_SESSION_EVENT, session, realm.getId(), true),
ClusterProvider.DCNotify.LOCAL_DC_ONLY); ClusterProvider.DCNotify.LOCAL_DC_ONLY);
UserSessionPersisterProvider sessionsPersister = session.getProvider(UserSessionPersisterProvider.class);
if (sessionsPersister != null) {
sessionsPersister.onRealmRemoved(realm);
}
} }
protected void onRealmRemovedEvent(String realmId) { protected void onRealmRemovedEvent(String realmId) {
@ -738,6 +746,10 @@ public class InfinispanUserSessionProvider implements UserSessionProvider {
// clusterEventsSenderTx.addEvent( // clusterEventsSenderTx.addEvent(
// ClientRemovedSessionEvent.createEvent(ClientRemovedSessionEvent.class, InfinispanUserSessionProviderFactory.CLIENT_REMOVED_SESSION_EVENT, session, realm.getId(), true), // ClientRemovedSessionEvent.createEvent(ClientRemovedSessionEvent.class, InfinispanUserSessionProviderFactory.CLIENT_REMOVED_SESSION_EVENT, session, realm.getId(), true),
// ClusterProvider.DCNotify.LOCAL_DC_ONLY); // ClusterProvider.DCNotify.LOCAL_DC_ONLY);
UserSessionPersisterProvider sessionsPersister = session.getProvider(UserSessionPersisterProvider.class);
if (sessionsPersister != null) {
sessionsPersister.onClientRemoved(realm, client);
}
} }
protected void onClientRemovedEvent(String realmId, String clientUuid) { protected void onClientRemovedEvent(String realmId, String clientUuid) {
@ -750,6 +762,11 @@ public class InfinispanUserSessionProvider implements UserSessionProvider {
removeUserSessions(realm, user, false); removeUserSessions(realm, user, false);
removeUserLoginFailure(realm, user.getId()); removeUserLoginFailure(realm, user.getId());
UserSessionPersisterProvider persisterProvider = session.getProvider(UserSessionPersisterProvider.class);
if (persisterProvider != null) {
persisterProvider.onUserRemoved(realm, user);
}
} }
@Override @Override
@ -803,6 +820,8 @@ public class InfinispanUserSessionProvider implements UserSessionProvider {
offlineUserSession.getEntity().setStarted(currentTime); offlineUserSession.getEntity().setStarted(currentTime);
offlineUserSession.setLastSessionRefresh(currentTime); offlineUserSession.setLastSessionRefresh(currentTime);
session.getProvider(UserSessionPersisterProvider.class).createUserSession(userSession, true);
return offlineUserSession; return offlineUserSession;
} }
@ -828,6 +847,7 @@ public class InfinispanUserSessionProvider implements UserSessionProvider {
if (userSessionEntity != null) { if (userSessionEntity != null) {
removeUserSession(userSessionEntity, true); removeUserSession(userSessionEntity, true);
} }
session.getProvider(UserSessionPersisterProvider.class).removeUserSession(userSession.getId(), true);
} }
@Override @Override
@ -842,6 +862,8 @@ public class InfinispanUserSessionProvider implements UserSessionProvider {
// update timestamp to current time // update timestamp to current time
offlineClientSession.setTimestamp(Time.currentTime()); offlineClientSession.setTimestamp(Time.currentTime());
session.getProvider(UserSessionPersisterProvider.class).createClientSession(clientSession, true);
return offlineClientSession; return offlineClientSession;
} }

View file

@ -85,7 +85,7 @@ public class JpaUserSessionPersisterProvider implements UserSessionPersisterProv
@Override @Override
public void createClientSession(AuthenticatedClientSessionModel clientSession, boolean offline) { public void createClientSession(AuthenticatedClientSessionModel clientSession, boolean offline) {
PersistentAuthenticatedClientSessionAdapter adapter = new PersistentAuthenticatedClientSessionAdapter(clientSession); PersistentAuthenticatedClientSessionAdapter adapter = new PersistentAuthenticatedClientSessionAdapter(session, clientSession);
PersistentClientSessionModel model = adapter.getUpdatedModel(); PersistentClientSessionModel model = adapter.getUpdatedModel();
PersistentClientSessionEntity entity = new PersistentClientSessionEntity(); PersistentClientSessionEntity entity = new PersistentClientSessionEntity();
@ -318,7 +318,7 @@ public class JpaUserSessionPersisterProvider implements UserSessionPersisterProv
model.setUserId(userSession.getUserId()); model.setUserId(userSession.getUserId());
model.setTimestamp(entity.getTimestamp()); model.setTimestamp(entity.getTimestamp());
model.setData(entity.getData()); model.setData(entity.getData());
return new PersistentAuthenticatedClientSessionAdapter(model, realm, client, userSession); return new PersistentAuthenticatedClientSessionAdapter(session, model, realm, client, userSession);
} }
@Override @Override

View file

@ -20,6 +20,7 @@ package org.keycloak.models.jpa.session;
import org.keycloak.Config; import org.keycloak.Config;
import org.keycloak.connections.jpa.JpaConnectionProvider; import org.keycloak.connections.jpa.JpaConnectionProvider;
import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.session.UserSessionPersisterProvider; import org.keycloak.models.session.UserSessionPersisterProvider;
import org.keycloak.models.session.UserSessionPersisterProviderFactory; import org.keycloak.models.session.UserSessionPersisterProviderFactory;
@ -43,6 +44,11 @@ public class JpaUserSessionPersisterProviderFactory implements UserSessionPersis
} }
@Override
public void postInit(KeycloakSessionFactory factory) {
}
@Override @Override
public void close() { public void close() {

View file

@ -20,6 +20,7 @@ package org.keycloak.models.session;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import org.keycloak.models.AuthenticatedClientSessionModel; import org.keycloak.models.AuthenticatedClientSessionModel;
import org.keycloak.models.ClientModel; import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ModelException; import org.keycloak.models.ModelException;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.UserSessionModel; import org.keycloak.models.UserSessionModel;
@ -36,6 +37,7 @@ import java.util.Set;
*/ */
public class PersistentAuthenticatedClientSessionAdapter implements AuthenticatedClientSessionModel { public class PersistentAuthenticatedClientSessionAdapter implements AuthenticatedClientSessionModel {
private final KeycloakSession session;
private final PersistentClientSessionModel model; private final PersistentClientSessionModel model;
private final RealmModel realm; private final RealmModel realm;
private final ClientModel client; private final ClientModel client;
@ -43,7 +45,7 @@ public class PersistentAuthenticatedClientSessionAdapter implements Authenticate
private PersistentClientSessionData data; private PersistentClientSessionData data;
public PersistentAuthenticatedClientSessionAdapter(AuthenticatedClientSessionModel clientSession) { public PersistentAuthenticatedClientSessionAdapter(KeycloakSession session, AuthenticatedClientSessionModel clientSession) {
data = new PersistentClientSessionData(); data = new PersistentClientSessionData();
data.setAction(clientSession.getAction()); data.setAction(clientSession.getAction());
data.setAuthMethod(clientSession.getProtocol()); data.setAuthMethod(clientSession.getProtocol());
@ -56,12 +58,14 @@ public class PersistentAuthenticatedClientSessionAdapter implements Authenticate
model.setUserSessionId(clientSession.getUserSession().getId()); model.setUserSessionId(clientSession.getUserSession().getId());
model.setTimestamp(clientSession.getTimestamp()); model.setTimestamp(clientSession.getTimestamp());
this.session = session;
realm = clientSession.getRealm(); realm = clientSession.getRealm();
client = clientSession.getClient(); client = clientSession.getClient();
userSession = clientSession.getUserSession(); userSession = clientSession.getUserSession();
} }
public PersistentAuthenticatedClientSessionAdapter(PersistentClientSessionModel model, RealmModel realm, ClientModel client, UserSessionModel userSession) { public PersistentAuthenticatedClientSessionAdapter(KeycloakSession session, PersistentClientSessionModel model, RealmModel realm, ClientModel client, UserSessionModel userSession) {
this.session = session;
this.model = model; this.model = model;
this.realm = realm; this.realm = realm;
this.client = client; this.client = client;
@ -115,6 +119,9 @@ public class PersistentAuthenticatedClientSessionAdapter implements Authenticate
@Override @Override
public void detachFromUserSession() { public void detachFromUserSession() {
if (this.userSession.isOffline()) {
session.getProvider(UserSessionPersisterProvider.class).removeClientSession(userSession.getId(), client.getId(), true);
}
setUserSession(null); setUserSession(null);
} }

View file

@ -17,32 +17,10 @@
package org.keycloak.models.session; package org.keycloak.models.session;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.UserModel;
import org.keycloak.provider.ProviderEvent;
import org.keycloak.provider.ProviderEventListener;
import org.keycloak.provider.ProviderFactory; import org.keycloak.provider.ProviderFactory;
/** /**
* @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
*/ */
public interface UserSessionPersisterProviderFactory extends ProviderFactory<UserSessionPersisterProvider> { public interface UserSessionPersisterProviderFactory extends ProviderFactory<UserSessionPersisterProvider> {
@Override
default void postInit(KeycloakSessionFactory factory) {
factory.register(new ProviderEventListener() {
@Override
public void onEvent(ProviderEvent event) {
if (event instanceof UserModel.UserRemovedEvent) {
UserModel.UserRemovedEvent userRemovedEvent = (UserModel.UserRemovedEvent) event;
UserSessionPersisterProvider provider = userRemovedEvent.getKeycloakSession().getProvider(UserSessionPersisterProvider.class, getId());
provider.onUserRemoved(userRemovedEvent.getRealm(), userRemovedEvent.getUser());
}
}
});
}
} }

View file

@ -138,8 +138,15 @@ public interface UserSessionProvider extends Provider {
void removeUserSession(RealmModel realm, UserSessionModel session); void removeUserSession(RealmModel realm, UserSessionModel session);
void removeUserSessions(RealmModel realm, UserModel user); void removeUserSessions(RealmModel realm, UserModel user);
/** Implementation doesn't need to propagate removal of expired userSessions to userSessionPersister. Cleanup on persister will be called separately **/ /**
* Removes expired user sessions owned by this realm from this provider.
* If this `UserSessionProvider` uses `UserSessionPersister`, the removal of the expired
* {@link UserSessionModel user sessions} is also propagated to relevant `UserSessionPersister`.
*
* @param realm {@link RealmModel} Realm where all the expired user sessions to be removed from.
*/
void removeExpired(RealmModel realm); void removeExpired(RealmModel realm);
void removeUserSessions(RealmModel realm); void removeUserSessions(RealmModel realm);
UserLoginFailureModel getUserLoginFailure(RealmModel realm, String userId); UserLoginFailureModel getUserLoginFailure(RealmModel realm, String userId);

View file

@ -30,7 +30,6 @@ import org.keycloak.models.RealmModel;
import org.keycloak.models.UserManager; import org.keycloak.models.UserManager;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionProvider; import org.keycloak.models.UserSessionProvider;
import org.keycloak.models.session.UserSessionPersisterProvider;
import org.keycloak.models.utils.RepresentationToModel; import org.keycloak.models.utils.RepresentationToModel;
import org.keycloak.protocol.LoginProtocol; import org.keycloak.protocol.LoginProtocol;
import org.keycloak.protocol.LoginProtocolFactory; import org.keycloak.protocol.LoginProtocolFactory;
@ -100,11 +99,6 @@ public class ClientManager {
sessions.onClientRemoved(realm, client); sessions.onClientRemoved(realm, client);
} }
UserSessionPersisterProvider sessionsPersister = realmManager.getSession().getProvider(UserSessionPersisterProvider.class);
if (sessionsPersister != null) {
sessionsPersister.onClientRemoved(realm, client);
}
AuthenticationSessionProvider authSessions = realmManager.getSession().authenticationSessions(); AuthenticationSessionProvider authSessions = realmManager.getSession().authenticationSessions();
if (authSessions != null) { if (authSessions != null) {
authSessions.onClientRemoved(realm, client); authSessions.onClientRemoved(realm, client);

View file

@ -33,7 +33,6 @@ import org.keycloak.models.RealmProvider;
import org.keycloak.models.RoleModel; import org.keycloak.models.RoleModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionProvider; import org.keycloak.models.UserSessionProvider;
import org.keycloak.models.session.UserSessionPersisterProvider;
import org.keycloak.models.utils.DefaultAuthenticationFlows; import org.keycloak.models.utils.DefaultAuthenticationFlows;
import org.keycloak.models.utils.DefaultClientScopes; import org.keycloak.models.utils.DefaultClientScopes;
import org.keycloak.models.utils.DefaultRequiredActions; import org.keycloak.models.utils.DefaultRequiredActions;
@ -265,11 +264,6 @@ public class RealmManager {
sessions.onRealmRemoved(realm); sessions.onRealmRemoved(realm);
} }
UserSessionPersisterProvider sessionsPersister = session.getProvider(UserSessionPersisterProvider.class);
if (sessionsPersister != null) {
sessionsPersister.onRealmRemoved(realm);
}
AuthenticationSessionProvider authSessions = session.authenticationSessions(); AuthenticationSessionProvider authSessions = session.authenticationSessions();
if (authSessions != null) { if (authSessions != null) {
authSessions.onRealmRemoved(realm); authSessions.onRealmRemoved(realm);

View file

@ -107,7 +107,6 @@ public class UserSessionManager {
} }
clientSession.detachFromUserSession(); clientSession.detachFromUserSession();
persister.removeClientSession(userSession.getId(), client.getId(), true);
checkOfflineUserSessionHasClientSessions(realm, user, userSession); checkOfflineUserSessionHasClientSessions(realm, user, userSession);
anyRemoved.set(true); anyRemoved.set(true);
} }
@ -121,7 +120,6 @@ public class UserSessionManager {
logger.tracef("Removing offline user session '%s' for user '%s' ", userSession.getId(), userSession.getLoginUsername()); logger.tracef("Removing offline user session '%s' for user '%s' ", userSession.getId(), userSession.getLoginUsername());
} }
kcSession.sessions().removeOfflineUserSession(userSession.getRealm(), userSession); kcSession.sessions().removeOfflineUserSession(userSession.getRealm(), userSession);
persister.removeUserSession(userSession.getId(), true);
} }
public boolean isOfflineTokenAllowed(ClientSessionContext clientSessionCtx) { public boolean isOfflineTokenAllowed(ClientSessionContext clientSessionCtx) {
@ -141,7 +139,6 @@ public class UserSessionManager {
} }
UserSessionModel offlineUserSession = kcSession.sessions().createOfflineUserSession(userSession); UserSessionModel offlineUserSession = kcSession.sessions().createOfflineUserSession(userSession);
persister.createUserSession(offlineUserSession, true);
return offlineUserSession; return offlineUserSession;
} }
@ -152,7 +149,6 @@ public class UserSessionManager {
} }
kcSession.sessions().createOfflineClientSession(clientSession, offlineUserSession); kcSession.sessions().createOfflineClientSession(clientSession, offlineUserSession);
persister.createClientSession(clientSession, true);
} }
// Check if userSession has any offline clientSessions attached to it. Remove userSession if not // Check if userSession has any offline clientSessions attached to it. Remove userSession if not
@ -166,6 +162,5 @@ public class UserSessionManager {
logger.tracef("Removing offline userSession for user %s as it doesn't have any client sessions attached. UserSessionID: %s", user.getUsername(), userSession.getId()); logger.tracef("Removing offline userSession for user %s as it doesn't have any client sessions attached. UserSessionID: %s", user.getUsername(), userSession.getId());
} }
kcSession.sessions().removeOfflineUserSession(realm, userSession); kcSession.sessions().removeOfflineUserSession(realm, userSession);
persister.removeUserSession(userSession.getId(), true);
} }
} }

View file

@ -21,7 +21,6 @@ import org.jboss.logging.Logger;
import org.keycloak.common.util.Time; import org.keycloak.common.util.Time;
import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSession;
import org.keycloak.models.UserSessionProvider; import org.keycloak.models.UserSessionProvider;
import org.keycloak.models.session.UserSessionPersisterProvider;
import org.keycloak.timer.ScheduledTask; import org.keycloak.timer.ScheduledTask;
/** /**
@ -41,7 +40,6 @@ public class ClearExpiredUserSessions implements ScheduledTask {
session.realms().getRealmsStream().forEach(realm -> { session.realms().getRealmsStream().forEach(realm -> {
sessions.removeExpired(realm); sessions.removeExpired(realm);
session.authenticationSessions().removeExpired(realm); session.authenticationSessions().removeExpired(realm);
session.getProvider(UserSessionPersisterProvider.class).removeExpired(realm);
}); });
long took = Time.currentTimeMillis() - currentTimeMillis; long took = Time.currentTimeMillis() - currentTimeMillis;

View file

@ -32,6 +32,7 @@ import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel; import org.keycloak.models.UserSessionModel;
import org.keycloak.models.UserSessionProvider; import org.keycloak.models.UserSessionProvider;
import org.keycloak.models.UserSessionProviderFactory; import org.keycloak.models.UserSessionProviderFactory;
import org.keycloak.models.sessions.infinispan.InfinispanUserSessionProvider;
import org.keycloak.models.utils.KeycloakModelUtils; import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.protocol.oidc.OIDCLoginProtocol; import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.RealmRepresentation;
@ -210,13 +211,13 @@ public class UserSessionInitializerTest extends AbstractTestRealmKeycloakTest {
KeycloakSession currentSession = inheritClientConnection(session, createSessionPersister3); KeycloakSession currentSession = inheritClientConnection(session, createSessionPersister3);
RealmModel realm = currentSession.realms().getRealmByName(realmName); RealmModel realm = currentSession.realms().getRealmByName(realmName);
// Delete cache (persisted sessions are still kept) // Delete local user cache (persisted sessions are still kept)
currentSession.sessions().onRealmRemoved(realm); InfinispanUserSessionProvider userSessionProvider = (InfinispanUserSessionProvider) currentSession.getProvider(UserSessionProvider.class);
userSessionProvider.removeLocalUserSessions(realm.getId(), true);
// Clear ispn cache to ensure initializerState is removed as well // Clear ispn cache to ensure initializerState is removed as well
InfinispanConnectionProvider infinispan = currentSession.getProvider(InfinispanConnectionProvider.class); InfinispanConnectionProvider infinispan = currentSession.getProvider(InfinispanConnectionProvider.class);
infinispan.getCache(InfinispanConnectionProvider.WORK_CACHE_NAME).clear(); infinispan.getCache(InfinispanConnectionProvider.WORK_CACHE_NAME).clear();
}); });
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession createSessionPersister4) -> { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession createSessionPersister4) -> {