8000 Keep shared auth session roots and per-session client states on logout by krishhgg · Pull Request #55136 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
12 changes: 12 additions & 0 deletions docs/documentation/upgrading/topics/changes/changes-27_0_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -769,6 +769,18 @@ As a workaround, use the default value of a property that is not defined, for ex
This did not work before, as the `$` prevented the placeholder from being closed.
It only works as long as the property is not defined.

=== Logout progress of clients is recorded per user session
// https://github.com/keycloak/keycloak/issues/55118

While a browser logout is in progress, {project_name} records in the logout authentication session which clients have already been notified.
These records are now stored per user session, in auth notes named `logout.state.<user session id>.<client UUID>` instead of `logout.state.<client UUID>`, where the client UUID is the internal id of the client.
A logout authentication session that is used for the logout of another user session of the same browser therefore no longer suppresses the logout of the clients that both user sessions have in common.

During a rolling upgrade, the nodes do not see the records written by nodes of the other version.
For a browser logout that is in flight while the nodes are upgraded, a client can be notified a second time, with another back-channel logout token or another front-channel logout redirect.
The logout still completes.
No user action is required.

// ------------------------ Deprecated features ------------------------ //
== Deprecated features

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -785,8 +785,9 @@ private void checkTokenIssuedAt(long idTokenIssuedAt, UserSessionModel userSessi
}

private Response initiateBrowserLogout(UserSessionModel userSession, AuthenticationSessionModel logoutSession) {
// the logout session may have been created without a user session (e.g. only an id_token_hint), bind it now so it is reused
logoutSession.setAuthNote(AuthenticationManager.LOGOUT_USER_SESSION_ID, userSession.getId());
// the logout session may have been created without a user session (e.g. only an id_token_hint), or for the
// browser session while the id_token_hint names another one, bind it now so it is reused
AuthenticationManager.bindLogoutSessionToUserSession(logoutSession, userSession);
userSession.setNote(AuthenticationManager.KEYCLOAK_LOGOUT_PROTOCOL, OIDCLoginProtocol.LOGIN_PROTOCOL);
logger.tracef("Calling initiateBrowserLogout for user session '%s'", userSession.getId());
Response response = AuthenticationManager.browserLogout(session, realm, userSession, session.getContext().getUri(), clientConnection, headers);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -359,8 +359,18 @@ public static BackchannelLogoutResponse backchannelLogout(KeycloakSession sessio
userSessionOnlyHasLoggedOutClients =
checkUserSessionOnlyHasLoggedOutClients(realm, userSession, logoutAuthSession);
} finally {
logger.tracef("Removing logout session '%s' after backchannel logout", logoutAuthSession.getParentSession().getId());
session.authenticationSessions().removeRootAuthenticationSession(realm, logoutAuthSession.getParentSession());
// The logout session may have joined a root that the browser shares with other tabs (for example an
// unfinished login), so only remove the logout tab from such a root. A root that only holds the logout tab
// is removed through the provider, which also drops a root that has not been persisted yet.
RootAuthenticationSessionModel logoutRoot = logoutAuthSession.getParentSession();
String logoutTabId = logoutAuthSession.getTabId();
if (logoutRoot.getAuthenticationSessions().size() > 1) {
logger.tracef("Removing logout session tab '%s' from '%s' after backchannel logout", logoutTabId, logoutRoot.getId());
logoutRoot.removeAuthenticationSessionByTabId(logoutTabId);
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.

Resetting the root timestamp to the current time on tab removal is the standard behavior of RootAuthenticationSessionAdapter.removeAuthenticationSessionByTabId across all callers in Keycloak, not specific to logout cleanup. The provider SPI does not expose whether a root's expiration was previously shortened by updateAuthenticationSessionAfterSuccessfulAuthentication, so preserving or adjusting that timestamp behavior belongs in the provider adapter rather than working around provider internals in AuthenticationManager. Please file a follow-up issue if that behavior needs to be adjusted in the provider.

} else {
logger.tracef("Removing logout session '%s' after backchannel logout", logoutRoot.getId());
session.authenticationSessions().removeRootAuthenticationSession(realm, logoutRoot);
Comment thread
shawkins marked this conversation as resolved.
Resolved
}
}

userSession.setState(UserSessionModel.State.LOGGED_OUT);
Expand Down Expand Up @@ -456,31 +466,66 @@ public static AuthenticationSessionModel createOrJoinLogoutSession(KeycloakSessi
AuthenticationSessionModel prevAuthSession = null;
if (found.isPresent()) {
prevAuthSession = found.get();
if (!initiateLogout || client.getId().equals(prevAuthSession.getClient().getId())) {
// A logout session that belongs to another user session holds the logout states of that session's clients,
// which would suppress the logout of the same clients for this user session, so never reuse it
String prevUserSessionId = prevAuthSession.getAuthNote(LOGOUT_USER_SESSION_ID);
boolean otherUserSession = userSession != null && prevUserSessionId != null && !prevUserSessionId.equals(userSession.getId());
if (!otherUserSession && (!initiateLogout || (prevAuthSession.getClient() != null && client.getId().equals(prevAuthSession.getClient().getId())))) {
logoutAuthSession = prevAuthSession;
logger.tracef("Found existing logout session for client '%s'. Authentication session id: %s", client.getClientId(), rootLogoutSession.getId());
}
}

if (logoutAuthSession == null) {
// Remove the previous logout session first when other tabs remain in the root, so that creating the replacement
// at the authentication session limit cannot evict an unfinished login tab. A single-tab root keeps create-first,
// since removing its last tab removes the root.
boolean removePreviousFirst = prevAuthSession != null && rootLogoutSession.getAuthenticationSessions().size() > 1;
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.

This only occurs with the JPA provider configured with authSessionsLimit=1, as the default is 300. The root cause is in the JPA RootAuthenticationSessionAdapter: evicting the oldest tab via removeAuthenticationSessionByTabId removes the root entity when it becomes empty, even though createAuthenticationSession is about to add a tab to it. That is pre-existing behavior of the adapter rather than of the logout handling here, so it should be fixed separately in the JPA provider, not worked around in AuthenticationManager. Please file a follow-up issue instead of addressing it in this PR.

if (removePreviousFirst) {
rootLogoutSession.removeAuthenticationSessionByTabId(prevAuthSession.getTabId());
logger.tracef("Removing previous logout session tab '%s' in %s", prevAuthSession.getTabId(), rootLogoutSession.getId());
}
logoutAuthSession = rootLogoutSession.createAuthenticationSession(client);
logoutAuthSession.setAction(AuthenticationSessionModel.Action.LOGGING_OUT.name());
logger.tracef("Creating logout session for client '%s'. Authentication session id: %s", client.getClientId(), rootLogoutSession.getId());
if (prevAuthSession != null) {
// remove previous logout session for the other client
if (prevAuthSession != null && !removePreviousFirst) {
// remove previous logout session for the other client or user session
rootLogoutSession.removeAuthenticationSessionByTabId(prevAuthSession.getTabId());
logger.tracef("Removing previous logout session for client '%s' in %s", prevAuthSession.getClient().getClientId(), rootLogoutSession.getId());
logger.tracef("Removing previous logout session tab '%s' in %s", prevAuthSession.getTabId(), rootLogoutSession.getId());
}
}
if (userSession != null) {
logoutAuthSession.setAuthNote(LOGOUT_USER_SESSION_ID, userSession.getId());
if (userSession != null) {
logoutAuthSession.setAuthNote(LOGOUT_USER_SESSION_ID, userSession.getId());
}
} else if (userSession != null) {
bindLogoutSessionToUserSession(logoutAuthSession, userSession);
Comment thread
shawkins marked this conversation as resolved.
Resolved
}
session.getContext().setAuthenticationSession(logoutAuthSession);
session.getContext().setClient(client);

return logoutAuthSession;
}

/**
* Binds the logout session to the user session through the {@link #LOGOUT_USER_SESSION_ID} note. The logout states
* of clients are recorded per bound user session (see {@link #setClientLogoutAction}), so the states recorded for
* another user session are not seen after binding to this one.
* <p>
* When the binding changes, the states without a user session ({@link #CLIENT_LOGOUT_STATE} followed by the client
* UUID) are removed for the clients of the user session. Nodes of an older version write and read only those, so
* a state recorded for the previous binding must not suppress the logout of the clients of the new one.
*/
public static void bindLogoutSessionToUserSession(AuthenticationSessionModel logoutSession, UserSessionModel userSession) {
if (!userSession.getId().equals(logoutSession.getAuthNote(LOGOUT_USER_SESSION_ID))) {
userSession.getAuthenticatedClientSessions().keySet().forEach(clientUuid -> {
String key = CLIENT_LOGOUT_STATE + clientUuid;
if (logoutSession.getAuthNote(key) != null) {
logoutSession.removeAuthNote(key);
}
});
}
logoutSession.setAuthNote(LOGOUT_USER_SESSION_ID, userSession.getId());
Comment thread
Copilot marked this conversation as resolved.
Resolved
}

private static RootAuthenticationSessionModel findRecordedLogoutRoot(KeycloakSession session, RealmModel realm, UserSessionModel userSession) {
String recordedRootId = userSession.getNote(LOGOUT_ROOT_SESSION_ID);
if (recordedRootId == null) {
Expand All @@ -497,16 +542,18 @@ private static RootAuthenticationSessionModel findRecordedLogoutRoot(KeycloakSes
}

/**
* Makes the browser able to find the logout root again: points the AUTH_SESSION_ID cookie to it, unless the
* cookie already does or the root was recovered (see {@code createOrJoinLogoutSession}), and records its id in
* the user session.
* Makes the browser able to find the logout root again: points the AUTH_SESSION_ID cookie (and the
* KC_AUTH_SESSION_HASH cookie that authChecker.js compares with the page) to it, unless the cookie already does
* or the root was recovered (see {@code createOrJoinLogoutSession}), and records its id in the user session.
*/
private static void bindLogoutRootToBrowser(KeycloakSession session, AuthenticationSessionManager asm,
RootAuthenticationSessionModel cookieRoot, UserSessionModel userSession, RootAuthenticationSessionModel logoutRoot) {
// Never plant the id of a recovered root in the browser
boolean recovered = logoutRoot.getId().equals(session.getAttribute(RECOVERED_LOGOUT_ROOT_ID));
if (!recovered && (cookieRoot == null || !cookieRoot.getId().equals(logoutRoot.getId()))) {
asm.setAuthSessionCookie(logoutRoot.getId());
// A login that later joins this root renders its hash, a stale hash from a previous root makes the page reload
asm.setAuthSessionIdHashCookie(logoutRoot.getId());
}
if (userSession != null && !logoutRoot.getId().equals(userSession.getNote(LOGOUT_ROOT_SESSION_ID))) {
userSession.setNote(LOGOUT_ROOT_SESSION_ID, logoutRoot.getId());
Expand Down Expand Up @@ -712,17 +759,28 @@ private static Response frontchannelLogoutClientSession(KeycloakSession session,
}

/**
* Sets logout state of the particular client into the {@code logoutAuthSession}
* Sets logout state of the particular client into the {@code logoutAuthSession}. The state belongs to the user
* session the logout session is bound to, see {@link #LOGOUT_USER_SESSION_ID}.
* @param logoutAuthSession logoutAuthSession. May be {@code null} in which case this is a no-op.
* @param clientUuid Client. Must not be {@code null}
* @param action
*/
public static void setClientLogoutAction(AuthenticationSessionModel logoutAuthSession, String clientUuid, Action action) {
if (logoutAuthSession != null && clientUuid != null) {
logoutAuthSession.setAuthNote(CLIENT_LOGOUT_STATE + clientUuid, action.name());
logoutAuthSession.setAuthNote(clientLogoutStateKey(logoutAuthSession, clientUuid), action.name());
}
}

/**
* The state is keyed by the bound user session, so a logout session that is bound to another user session cannot
* suppress the logout of the same client for it, whichever clients and sessions still exist. A logout session
* that is not bound yet uses the key without a user session.
*/
private static String clientLogoutStateKey(AuthenticationSessionModel logoutAuthSession, String clientUuid) {
String boundUserSessionId = logoutAuthSession.getAuthNote(LOGOUT_USER_SESSION_ID);
return boundUserSessionId == null ? CLIENT_LOGOUT_STATE + clientUuid : CLIENT_LOGOUT_STATE + boundUserSessionId + "." + clientUuid;
}

/**
* Returns the logout state of the particular client as per the {@code logoutAuthSession}
* @param logoutAuthSession logoutAuthSession. May be {@code null} in which case this is a no-op.
Expand All @@ -734,7 +792,7 @@ public static Action getClientLogoutAction(AuthenticationSessionModel logoutAuth
return null;
}

String state = logoutAuthSession.getAuthNote(CLIENT_LOGOUT_STATE + clientUuid);
String state = logoutAuthSession.getAuthNote(clientLogoutStateKey(logoutAuthSession, clientUuid));
return state == null ? null : Action.valueOf(state);
}

Expand Down
Loading
Loading
0