E30F Invalidate all matching SAML adapter sessions on logout by abstractj · Pull Request #55521 · 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 @@ -456,7 +456,8 @@ protected AuthOutcome handleLoginResponse(SAMLDocumentHolder responseHolder, boo
SubjectType subject = assertion.getSubject();
SubjectType.STSubType subType = subject.getSubType();
NameIDType subjectNameID = subType == null ? null : (NameIDType) subType.getBaseID();
String principalName = subjectNameID == null ? null : subjectNameID.getValue();
String samlSubject = subjectNameID == null ? null : subjectNameID.getValue();
String principalName = samlSubject;

Set<String> roles = new HashSet<>();
MultivaluedHashMap<String, String> attributes = new MultivaluedHashMap<>();
Expand Down Expand Up @@ -530,7 +531,7 @@ protected AuthOutcome handleLoginResponse(SAMLDocumentHolder responseHolder, boo
String nameFormatString = nameFormat == null ? JBossSAMLURIConstants.NAMEID_FORMAT_UNSPECIFIED.get() : nameFormat.toString();
final SamlPrincipal principal = new SamlPrincipal(assertion,
deployment.isKeepDOMAssertion()? getAssertionDocumentFromElement(assertionElement) : null,
principalName, principalName, nameFormatString, attributes, friendlyAttributes);
principalName, samlSubject, nameFormatString, attributes, friendlyAttributes);
final String sessionIndex = authn == null ? null : authn.getSessionIndex();
final XMLGregorianCalendar sessionNotOnOrAfter = authn == null ? null : authn.getSessionNotOnOrAfter();
SamlSession account = new SamlSession(principal, roles, sessionIndex, sessionNotOnOrAfter);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
package org.keycloak.adapters.saml.elytron;

import java.net.URI;
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

Expand Down Expand Up @@ -84,9 +85,7 @@ public void logoutAccount() {
log.debug("Logging out - current account");
SamlSession samlSession = (SamlSession)session.getAttachment(SamlSession.class.getName());
if (samlSession != null) {
if (samlSession.getSessionIndex() != null) {
idMapperUpdater.removeSession(idMapper, session.getID());
}
idMapperUpdater.removeSession(idMapper, session.getID());
session.setAttachment(SamlSession.class.getName(), null);
}
session.setAttachment(SAML_REDIRECT_URI, null);
Expand All @@ -98,28 +97,25 @@ public void logoutByPrincipal(String principal) {
Set<String> sessions = idMapper.getUserSessions(principal);
if (sessions != null) {
log.debugf("Logging out - by principal: %s", sessions);
List<String> ids = new LinkedList<>();
ids.addAll(sessions);
logoutSessionIds(ids);
for (String id : ids) {
idMapperUpdater.removeSession(idMapper, id);
}
logoutMappedSessions(sessions);
}

}

@Override
public void logoutBySsoId(List<String> ssoIds) {
if (ssoIds == null) return;
log.debugf("Logging out - by session IDs: %s", ssoIds);
List<String> sessionIds = new LinkedList<>();
Set<String> sessionIds = new LinkedHashSet<>();
for (String id : ssoIds) {
String sessionId = idMapper.getSessionFromSSO(id);
if (sessionId != null) {
sessionIds.add(sessionId);
idMapperUpdater.removeSession(idMapper, sessionId);
}
sessionIds.addAll(idMapper.getSessionsFromSSO(id));
}
logoutMappedSessions(sessionIds);
}

private void logoutMappedSessions(Set<String> sessions) {
List<String> sessionIds = new ArrayList<>(sessions);
for (String id : sessionIds) {
idMapperUpdater.removeSession(idMapper, id);
}
logoutSessionIds(sessionIds);
}
Expand All @@ -128,7 +124,7 @@ protected void logoutSessionIds(List<String> sessionIds) {
sessionIds.forEach(id -> {
HttpScope scope = exchange.getScope(Scope.SESSION, id);

if (scope.exists()) {
if (scope != null && scope.exists()) {
log.debugf("Invalidating session %s", id);
scope.setAttachment(SamlSession.class.getName(), null);
scope.invalidate();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,6 @@ private void unmap(String sessionId, Object value) {
return;
}

SamlSession samlSession = (SamlSession) value;
if (samlSession.getSessionIndex() != null) {
idMapper.removeSession(sessionId);
}
idMapper.removeSession(sessionId);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* Copyright 2016 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.adapters.saml.elytron;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.keycloak.adapters.spi.InMemorySessionIdMapper;
import org.keycloak.adapters.spi.SessionIdMapper;
import org.keycloak.adapters.spi.SessionIdMapperUpdater;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class ElytronSamlSessionStoreTest {

@Test
public void logoutBySsoIdInvalidatesAllMatchingSessionsOnce() {
SessionIdMapper mapper = new InMemorySessionIdMapper();
mapper.map("shared", "alice", "first");
mapper.map("shared", "alice", "second");
mapper.map("other", "alice", "third");

List<String> invalidated = new ArrayList<>();
ElytronSamlSessionStore store = new ElytronSamlSessionStore(null, mapper, SessionIdMapperUpdater.DIRECT, null) {
@Override
protected void logoutSessionIds(List<String> sessionIds) {
invalidated.addAll(sessionIds);
}
};
store.logoutBySsoId(List.of("shared", "unknown", "shared"));

assertEquals(2, invalidated.size());
assertEquals(Set.of("first", "second"), Set.copyOf(invalidated));
assertFalse(mapper.hasSession("first"));
assertFalse(mapper.hasSession("second"));
assertTrue(mapper.hasSession("third"));
}
}
10BC8
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@

package org.keycloak.adapters.spi;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.jboss.logging.Logger;

Expand All @@ -34,80 +35,71 @@ public class InMemorySessionIdMapper implements SessionIdMapper {

private static final Logger LOG = Logger.getLogger(InMemorySessionIdMapper.class.getName());

ConcurrentHashMap<String, String> ssoToSession = new ConcurrentHashMap<>();
ConcurrentHashMap<String, String> sessionToSso = new ConcurrentHashMap<>();
ConcurrentHa 10000 shMap<String, Set<String>> principalToSession = new ConcurrentHashMap<>();
ConcurrentHashMap<String, String> sessionToPrincipal = new ConcurrentHashMap<>();
private final Map<String, Set<String>> ssoToSessions = new HashMap<>();
private final Map<String, String> sessionToSso = new HashMap<>();
private final Map<String, Set<String>> principalToSessions = new HashMap<>();
private final Map<String, String> sessionToPrincipal = new HashMap<>();

@Override
public boolean hasSession(String id) {
return sessionToSso.containsKey(id) || sessionToPrincipal.containsKey(id);
public synchronized boolean hasSession(String id) {
return sessionToSso.containsKey(id);
}

@Override
public void clear() {
ssoToSession.clear();
public synchronized void clear() {
ssoToSessions.clear();
sessionToSso.clear();
principalToSession.clear();
principalToSessions.clear();
sessionToPrincipal.clear();
}

@Override
public Set<String> getUserSessions(String principal) {
Set<String> lookup = principalToSession.get(principal);
if (lookup == null) return null;
Set<String> copy = new HashSet<>();
copy.addAll(lookup);
return copy;
public synchronized Set<String> getUserSessions(String principal) {
Set<String> sessions = principalToSessions.get(principal);
return sessions == null ? null : new HashSet<>(sessions);
}

@Override
public String getSessionFromSSO(String sso) {
return ssoToSession.get(sso);
public synchronized Set<String> getSessionsFromSSO(String sso) {
Set<String> sessions = ssoToSessions.get(sso);
return sessions == null ? Set.of() : Set.copyOf(sessions);
}

@Override
public void map(String sso, String principal, String session) {
public synchronized void map(String sso, String principal, String session) {
LOG.debugf("Adding mapping (%s, %s, %s)", sso, principal, session);

Objects.requireNonNull(session, "session");
unmap(session);
// The local session is still authenticated when the assertion has no SessionIndex or NameID.
sessionToSso.put(session, sso);
if (sso != null) {
ssoToSession.put(sso, session);
sessionToSso.put(session, sso);
ssoToSessions.computeIfAbsent(sso, key -> new HashSet<>()).add(session);
}

if (principal == null) {
return;
}

Set<String> userSessions = principalToSession.get(principal);
if (userSessions == null) {
final Set<String> tmp = Collections.synchronizedSet(new HashSet<String>());
userSessions = principalToSession.putIfAbsent(principal, tmp);
if (userSessions == null) {
userSessions = tmp;
}
if (principal != null) {
principalToSessions.computeIfAbsent(principal, key -> new HashSet<>()).add(session);
sessionToPrincipal.put(session, principal);
}
userSessions.add(session);
sessionToPrincipal.put(session, principal);
}

@Override
public void removeSession(String session) {
public synchronized void removeSession(String session) {
LOG.debugf("Removing session %s", session);
unmap(session);
}

String sso = sessionToSso.remove(session);
if (sso != null) {
ssoToSession.remove(sso);
}
String principal = sessionToPrincipal.remove(session);
if (principal != null) {
Set<String> sessions = principalToSession.get(principal);
private void unmap(String session) {
removeMapping(ssoToSessions, sessionToSso.remove(session), session);
removeMapping(principalToSessions, sessionToPrincipal.remove(session), session);
}

private static void removeMapping(Map<String, Set<String>> index, String key, String session) {
if (key != null) {
Set<String> sessions = index.get(key);
sessions.remove(session);
if (sessions.isEmpty()) {
principalToSession.remove(principal, sessions);
index.remove(key);
}
}
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,18 @@ public interface SessionIdMapper {
/**
* Returns HTTP session ID from the given user session ID.
* @param sso User session ID
* @return
* @deprecated Use {@link #getSessionsFromSSO(String)} to obtain every matching session.
*/
@Deprecated
default String getSessionFromSSO(String sso) {
return getSessionsFromSSO(sso).stream().findFirst().orElse(null);
}

/**
* Returns a snapshot of all HTTP session IDs associated with the given SSO session ID.
* Returns an empty set if there are no matches.
*/
String getSessionFromSSO(String sso);
Set<String> getSessionsFromSSO(String sso);

/**
* Establishes mapping between user session ID, principal and HTTP session ID.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Copyright 2016 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.adapters.spi;

import java.util.Set;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

public class InMemorySessionIdMapperTest {

private final SessionIdMapper mapper = new InMemorySessionIdMapper();

@Test
public void removingOneSessionPreservesOtherSessionsForTheSameIndex() {
mapper.map("index", "alice", "first");
mapper.map("index", "alice", "second");
mapper.map("other-index", "alice", "third");

Set<String> sessions = mapper.getSessionsFromSSO("index");
mapper.removeSession("first");
mapper.removeSession("first");

assertEquals(Set.of("first", "second"), sessions);
assertEquals(Set.of("second"), mapper.getSessionsFromSSO("index"));
assertEquals(Set.of("second", "third"), mapper.getUserSessions("alice"));
mapper.removeSession("second");
assertEquals(Set.of(), mapper.getSessionsFromSSO("index"));
assertEquals(Set.of("third"), mapper.getSessionsFromSSO("other-index"));
}

@Test
public void tracksLocalSessionsWithoutASubjectOrSessionIndex() {
mapper.map(null, null, "local");
assertTrue(mapper.hasSession("local"));
mapper.removeSession("local");
assertFalse(mapper.hasSession("local"));
}

@Test
public void remappingReplacesPreviousIndexAndSubject() {
mapper.map("index", "alice", "local");
mapper.map(null, "bob", "local");

assertEquals(Set.of(), mapper.getSessionsFromSSO("index"));
assertNull(mapper.getUserSessions("alice"));
assertEquals(Set.of("local"), mapper.getUserSessions("bob"));

mapper.removeSession("local");
assertFalse(mapper.hasSession("local"));
assertNull(mapper.getUserSessions("bob"));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
== Breaking changes

=== SAML adapter session mapper

Custom implementations of `org.keycloak.adapters.spi.SessionIdMapper` must implement `getSessionsFromSSO(String)` and be rebuilt before upgrading the adapter.
Return a snapshot containing every local HTTP session ID associated with the SAML session index, or an empty set if there are no matches.
The adapter uses this lookup for single logout.

When using `FROM_ATTRIBUTE`, sessions created before the upgrade may still be indexed by the mapped attribute.
Expire those sessions during the upgrade if logout by the asserted `NameID` must take effect immediately.
Loading
Loading
0