8000 Add option to include parent groups in group membership mappers by tdebatty · Pull Request #55291 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
8000
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 @@ -23,6 +23,7 @@
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Calendar;
Expand Down Expand Up @@ -971,6 +972,33 @@ public static String buildGroupPath(GroupModel group, GroupModel otherParentGrou
return sb.toString();
}

/**
* Returns the ancestor chain of the given group, ordered from the top-level group down to the
* given group, i.e. the reverse of walking up {@link GroupModel#getParent()}.
* <p>
* For {@link GroupModel.Type#ORGANIZATION} groups, the hierarchy consists of the group itself:
* organization groups form a hierarchy rooted at the internal organization group and should not
* be expanded above it.
*
* @param group the group to start from
* @return the list of groups from the top-level ancestor to {@code group}, or an empty list if
* {@code group} is {@code null}
*/
public static List<GroupModel> getGroupHierarchy(GroupModel group) {
if (group == null) {
return Collections.emptyList();
}
if (group.getType() == GroupModel.Type.ORGANIZATION) {
return Collections.singletonList(group);
}
List<GroupModel> hierarchy = new ArrayList<>();
for (GroupModel current = group; current != null; current = current.getParent()) {
hierarchy.add(current);
}
Collections.reverse(hierarchy);
return hierarchy;
}

/**
* Returns {@code true} if the given {@code group} is the {@code ancestor} itself or one of its
* descendants, i.e. if {@code ancestor} can be reached from {@code group} by walking up the
Expand Down
8000
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,18 @@

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.keycloak.models.GroupModel;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.models.utils.ModelToRepresentation;
import org.keycloak.protocol.ProtocolMapperUtils;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
Expand All @@ -53,6 +57,14 @@ public class GroupMembershipMapper extends AbstractOIDCProtocolMapper implements
property1.setHelpText("Include full path to group i.e. /top/level1/level2, false will just specify the group name. Make sure to enable this setting if your realm has a group hierarchy with duplicated group names.");
configProperties.add(property1);

ProviderConfigProperty property2 = new ProviderConfigProperty();
property2.setName("include.parent.groups");
property2.setLabel("Include parent groups");
property2.setType(ProviderConfigProperty.BOOLEAN_TYPE);
property2.setDefaultValue("false");
property2.setHelpText("Include all parent groups of each group the user is a member of, i.e. if the user is a member of /Users/Superusers, the claim also contains /Users. The list of groups is de-duplicated.");
configProperties.add(property2);

OIDCAttributeMapperHelper.addIncludeInTokensConfig(configProperties, GroupMembershipMapper.class);
}

Expand Down Expand Up @@ -87,6 +99,10 @@ public static boolean useFullPath(ProtocolMapperModel mappingModel) {
return "true".equals(mappingModel.getConfig().get("full.path"));
}

public static boolean includeParentGroups(ProtocolMapperModel mappingModel) {
return "true".equals(mappingModel.getConfig().get("include.parent.groups"));
}


/**
* Adds the group membership information to the {@link IDToken#otherClaims}.
Expand All @@ -97,7 +113,17 @@ public static boolean useFullPath(ProtocolMapperModel mappingModel) {
protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession) {
Function<GroupModel, String> toGroupRepresentation = useFullPath(mappingModel) ?
ModelToRepresentation::buildGroupPath : GroupModel::getName;
List<String> membership = userSession.getUser().getGroupsStream().map(toGroupRepresentation).collect(Collectors.toList());
Stream<GroupModel> groups = userSession.getUser().getGroupsStream();

if (includeParentGroups(mappingModel)) {
// de-duplicate by group id, as the user may be a direct member of a group and of one
// of its ancestors, and group names are not unique across the hierarchy
Set<String> seen = new HashSet<>();
groups = groups
.flatMap(group -> KeycloakModelUtils.getGroupHierarchy(group).stream())
.filter(group -> seen.add(group.getId()));
}
List<String> membership = groups.map(toGroupRepresentation).collect(Collectors.toList());

// force multivalued as the attribute is not defined for this mapper.
// do this on a copy of the model so that the shared, cached mapper config is not mutated
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,21 @@

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;

import org.keycloak.dom.saml.v2.assertion.AttributeStatementType;
import org.keycloak.dom.saml.v2.assertion.AttributeType;
import org.keycloak.models.AuthenticatedClientSessionModel;
import org.keycloak.models.GroupModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.models.utils.ModelToRepresentation;
import org.keycloak.protocol.saml.SamlProtocol;
import org.keycloak.provider.ProviderConfigProperty;
Expand Down Expand Up @@ -81,6 +86,13 @@ public class GroupMembershipMapper extends AbstractSAMLProtocolMapper implements
property.setDefaultValue("true");
property.setHelpText("Include full path to group i.e. /top/level1/level2, false will just specify the group name");
configProperties.add(property);
property = new ProviderConfigProperty();
property.setName("include.parent.groups");
property.setLabel("Include parent groups");
property.setType(ProviderConfigProperty.BOOLEAN_TYPE);
property.setDefaultValue("false");
property.setHelpText("Include all parent groups of each group the user is a member of, i.e. if the user is a member of /Users/Superusers, the attribute also contains /Users. The list of groups is de-duplicated.");
configProperties.add(property);


}
Expand Down Expand Up @@ -115,6 +127,10 @@ public static boolean useFullPath(ProtocolMapperModel mappingModel) {
return "true".equals(mappingModel.getConfig().get("full.path"));
}

public static boolean includeParentGroups(ProtocolMapperModel mappingModel) {
return "true".equals(mappingModel.getConfig().get("include.parent.groups"));
}


@Override
public void transformAttributeStatement(AttributeStatementType attributeStatement, ProtocolMapperModel mappingModel, KeycloakSession session, UserSessionModel userSession, AuthenticatedClientSessionModel clientSession) {
Expand All @@ -123,7 +139,16 @@ public void transformAttributeStatement(AttributeStatementType attributeStatemen

boolean fullPath = useFullPath(mappingModel);
final AtomicReference<AttributeType> singleAttributeType = new AtomicReference<>(null);
userSession.getUser().getGroupsStream().forEach(group -> {
Stream<GroupModel> groups = userSession.getUser().getGroupsStream();
if (includeParentGroups(mappingModel)) {
// de-duplicate by group id, as the user may be a direct member of a group and of one
// of its ancestors, and group names are not unique across the hierarchy
Set<String> seen = new HashSet<>();
groups = groups
.flatMap(group -> KeycloakModelUtils.getGroupHierarchy(group).stream())
.filter(group -> seen.add(group.getId()));
}
groups.forEach(group -> {
String groupName;
if (fullPath) {
groupName = ModelToRepresentation.buildGroupPath(group);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,28 @@ private static UserSessionModel createUserSessionWithGroups(String... groupNames
return stub(UserSessionModel.class, sessionReturns);
}

/**
* Creates a group stub with a name, id and an optional parent group.
*/
private static GroupModel createGroup(String name, String id, GroupModel parent) {
Map<String, Object> returns = new HashMap<>();
returns.put("getName", name);
returns.put("getId", id);
if (parent != null) {
returns.put("getParent", parent);
}
return stub(GroupModel.class, returns);
}

private static UserSessionModel createUserSessionWithGroups(GroupModel... groups) {
List<GroupModel> groupList = Arrays.asList(groups);
Map<String, Object> userReturns = Collections.singletonMap("getGroupsStream",
(Supplier<Stream<GroupModel>>) () -> groupList.stream());
UserModel user = stub(UserModel.class, userReturns);
Map<String, Object> sessionReturns = Collections.singletonMap("getUser", user);
return stub(UserSessionModel.class, sessionReturns);
}

@Test
public void testSetClaimMapsGroupsWithoutMutatingTheMappingModel() {
ProtocolMapperModel mappingModel = createMappingModel();
Expand Down Expand Up @@ -128,4 +150,87 @@ public void testSetClaimCanBeRepeatedlyInvokedWithTheSameMappingModel() {
MatcherAssert.assertThat(secondToken.getOtherClaims().get("groups"), Matchers.equalTo(Collections.singletonList("admins")));
MatcherAssert.assertThat(mappingModel.getConfig(), Matchers.not(Matchers.hasKey("multivalued")));
}

@Test
public void testSetClaimExcludesParentGroupsByDefault() {
ProtocolMapperModel mappingModel = createMappingModel();
GroupModel top = createGroup("top", "id-top", null);
GroupModel level1 = createGroup("level1", "id-level1", top);
UserSessionModel userSession = createUserSessionWithGroups(level1);
GroupMembershipMapper mapper = new GroupMembershipMapper();

IDToken token = new IDToken();
mapper.setClaim(token, mappingModel, userSession);

// without include.parent.groups, only the direct group membership is mapped
MatcherAssert.assertThat(token.getOtherClaims().get("groups"), Matchers.equalTo(Collections.singletonList("level1")));
}

@Test
public void testSetClaimIncludesParentGroupsWhenEnabled() {
ProtocolMapperModel mappingModel = createMappingModel();
mappingModel.getConfig().put("include.parent.groups", "true");
GroupModel top = createGroup("top", "id-top", null);
GroupModel level1 = createGroup("level1", "id-level1", top);
UserSessionModel userSession = createUserSessionWithGroups(level1);
GroupMembershipMapper mapper = new GroupMembershipMapper();

IDToken token = new IDToken();
mapper.setClaim(token, mappingModel, userSession);

// the parent group is included, ordered from the top-level group down
MatcherAssert.assertThat(token.getOtherClaims().get("groups"), Matchers.equalTo(Arrays.asList("top", "level1")));
}

@Test
public void testSetClaimIncludesParentGroupsWithFullPath() {
ProtocolMapperModel mappingModel = createMappingModel();
mappingModel.getConfig().put("full.path", "true");
mappingModel.getConfig().put("include.parent.groups", "true");
GroupModel top = createGroup("top", "id-top", null);
GroupModel level1 = createGroup("level1", "id-level1", top);
UserSessionModel userSession = createUserSessionWithGroups(level1);
GroupMembershipMapper mapper = new GroupMembershipMapper();

IDToken token = new IDToken();
mapper.setClaim(token, mappingModel, userSession);

MatcherAssert.assertThat(token.getOtherClaims().get("groups"), Matchers.equalTo(Arrays.asList("/top", "/top/level1")));
}

@Test
public void testSetClaimDeduplicatesWhenMemberOfAncestorAndDescendant() {
ProtocolMapperModel mappingModel = createMappingModel();
mappingModel.getConfig().put("include.parent.groups", "true");
GroupModel top = createGroup("top", "id-top", null);
GroupModel level1 = createGroup("level1", "id-level1", top);
// the user is a direct member of both the group and its ancestor
UserSessionModel userSession = createUserSessionWithGroups(top, level1);
GroupMembershipMapper mapper = new GroupMembershipMapper();

IDToken token = new IDToken();
mapper.setClaim(token, mappingModel, userSession);

// the ancestor appears only once
MatcherAssert.assertThat(token.getOtherClaims().get("groups"), Matchers.equalTo(Arrays.asList("top", "level1")));
}

@Test
public void testSetClaimKeepsDistinctGroupsSharingName() {
ProtocolMapperModel mappingModel = createMappingModel();
mappingModel.getConfig().put("include.parent.groups", "true");
GroupModel branchA = createGroup("A", "id-A", null);
GroupModel branchB = createGroup("B", "id-B", null);
GroupModel teamA = createGroup("team", "id-team-A", branchA);
GroupModel teamB = createGroup("team", "id-team-B", branchB);
// two different groups happen to share the name "team"
UserSessionModel userSession = createUserSessionWithGroups(teamA, teamB);
GroupMembershipMapper mapper = new GroupMembershipMapper();

IDToken token = new IDToken();
mapper.setClaim(token, mappingModel, userSession);

// de-duplication is by group id, so both "team" groups are kept
MatcherAssert.assertThat(token.getOtherClaims().get("groups"), Matchers.equalTo(Arrays.asList("A", "team", "B", "team")));
}
}
Loading
0