8000 Skip admin permission filters for LDAP group mapper group lookups by mohitduhan19 · Pull Request #54065 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Closed
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 @@ -19,6 +19,7 @@

import java.util.stream.Stream;

import org.keycloak.authorization.fgap.AdminPermissionsSchema;
import org.keycloak.component.ComponentModel;
import org.keycloak.models.GroupModel;
import org.keycloak.models.ModelException;
Expand Down Expand Up @@ -102,7 +103,9 @@ public void onImportUserFromLDAP(LDAPObject ldapUser, UserModel user, RealmModel

private GroupModel getGroup(RealmModel realm) {
String groupName = mapperModel.getConfig().getFirst(HardcodedLDAPGroupStorageMapper.GROUP);
GroupModel group = KeycloakModelUtils.findGroupByPath(getSession(), realm, groupName);
// internal lookup, it must not be filtered by the admin permissions of the user in the session context
GroupModel group = AdminPermissionsSchema.runWithoutAuthorization(getSession(),
() -> KeycloakModelUtils.findGroupByPath(getSession(), realm, groupName));
if (group == null) {
logger.warnf("Hardcoded group '%s' configured in mapper '%s' is not available anymore", groupName, mapperModel.getName());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,11 @@
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.keycloak.authorization.fgap.AdminPermissionsSchema;
import org.keycloak.component.ComponentModel;
import org.keycloak.models.GroupModel;
import org.keycloak.models.ModelException;
Expand Down Expand Up @@ -383,7 +385,7 @@ protected GroupModel findKcGroupByLDAPGroup(RealmModel realm, GroupModel parent,
.filter(group -> Objects.equals(group.getName(), groupName)).findFirst().orElse(null);
} else {
// Without preserved inheritance, it's always at groups path
return getSession().groups().getGroupByName(realm, parent, groupName);
return runWithoutAuthorization(() -> getSession().groups().getGroupByName(realm, parent, groupName));
}
}

Expand Down Expand Up @@ -819,7 +821,7 @@ protected String getKcGroupPathFromLDAPGroupName(String ldapGroupName) {
* Provides KC group defined as groups path or null (top-level group) if corresponding group is not available.
*/
protected GroupModel getKcGroupsPathGroup(RealmModel realm) {
return config.isTopLevelGroupsPath() ? null : KeycloakModelUtils.findGroupByPath(getSession(), realm, config.getGroupsPath());
return config.isTopLevelGroupsPath() ? null : findGroupsPathGroup(realm);
}

protected boolean isGroupInGroupPath(RealmModel realm, GroupModel group) {
Expand All @@ -829,7 +831,7 @@ protected boolean isGroupInGroupPath(RealmModel realm, GroupModel group) {
if (config.isTopLevelGroupsPath()) {
return true; // any group is in the path of the top level path.
}
GroupModel groupPathGroup = KeycloakModelUtils.findGroupByPath(getSession(), realm, config.getGroupsPath());
GroupModel groupPathGroup = findGroupsPathGroup(realm);
if (groupPathGroup != null) {
while(!groupPathGroup.getId().equals(group.getId())) {
group = group.getParent();
Expand Down Expand Up @@ -863,15 +865,21 @@ protected Stream<GroupModel> getKcSubGroups(RealmModel realm, GroupModel parentG
if (parentGroup == null) {
parentGroup = getKcGroupsPathGroup(realm);
}
return parentGroup == null ? getSession().groups().getTopLevelGroupsStream(realm) :
parentGroup.getSubGroupsStream();
GroupModel parent = parentGroup;
// collected here so the query runs without the authorization filters, not later when the stream is consumed.
// This also covers the sub groups of a parent group: once the parent was updated in this transaction (its
// attributes during a sync for example), the cache delegates to the JPA query, which applies the filters.
return runWithoutAuthorization(() -> (parent == null
? getSession().groups().getTopLevelGroupsStream(realm)
: parent.getSubGroupsStream()).toList()).stream();
}

/**
* Provides a stream of all KC groups (with their sub groups) from groups path configured by the "Groups Path" configuration property.
*/
protected Stream<GroupModel> getAllKcGroups(RealmModel realm, GroupModel topParentGroup) {
Stream<GroupModel> allGroups = realm.getGroupsStream();
// collected here so the query runs without the authorization filters, not later when the stream is consumed
Stream<GroupModel> allGroups = runWithoutAuthorization(() -> realm.getGroupsStream().toList()).stream();
if (topParentGroup == null) return allGroups;

return allGroups.filter(group -> {
Expand All @@ -886,4 +894,19 @@ protected Stream<GroupModel> getAllKcGroups(RealmModel realm, GroupModel topPare
return false;
});
}

private GroupModel findGroupsPathGroup(RealmModel realm) {
return runWithoutAuthorization(() -> KeycloakModelUtils.findGroupByPath(getSession(), realm, config.getGroupsPath()));
}

/**
* Group lookups done by this mapper are internal: they resolve the groups that LDAP says a user belongs to, or
* reconcile groups during a sync. They must see every group in the realm, whatever admin permissions the user in
* the current session context has. Otherwise, a user holding a {@code query-*} admin role but not
* {@code view-users} gets the fine-grained admin permission filters applied to these lookups, an existing group
* is not found, and the mapper tries to create it again.
*/
private <T> T runWithoutAuthorization(Supplier<T> supplier) {
return AdminPermissionsSchema.runWithoutAuthorization(getSession(), supplier);
}
}
Original file line number Diff line number Diff line change
8000 Expand Up @@ -24,6 +24,8 @@
import javax.naming.directory.SearchControls;

import org.keycloak.component.ComponentModel;
import org.keycloak.models.AdminRoles;
import org.keycloak.models.Constants;
import org.keycloak.models.GroupModel;
import org.keycloak.models.LDAPConstants;
import org.keycloak.models.ModelException;
Expand All @@ -33,13 +35,15 @@
import org.keycloak.representations.idm.ComponentRepresentation;
import org.keycloak.storage.ReadOnlyException;
import org.keycloak.storage.UserStoragePrivateUtil;
import org.keycloak.storage.UserStorageProviderModel;
import org.keycloak.storage.ldap.LDAPConfig;
import org.keycloak.storage.ldap.LDAPStorageProvider;
import org.keycloak.storage.ldap.LDAPUtils;
import org.keycloak.storage.ldap.idm.model.LDAPDn;
import org.keycloak.storage.ldap.idm.model.LDAPObject;
import org.keycloak.storage.ldap.idm.query.internal.LDAPQuery;
import org.keycloak.storage.ldap.idm.query.internal.LDAPQueryConditionsBuilder;
import org.keycloak.storage.ldap.mappers.HardcodedLDAPRoleStorageMapper;
import org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapper;
import org.keycloak.storage.ldap.mappers.membership.LDAPGroupMapperMode;
import org.keycloak.storage.ldap.mappers.membership.MembershipType;
Expand All @@ -48,6 +52,7 @@
import org.keycloak.storage.ldap.mappers.membership.group.GroupMapperConfig;
import org.keycloak.testsuite.util.LDAPRule;
import org.keycloak.testsuite.util.LDAPTestUtils;
import org.keycloak.testsuite.util.oauth.AccessTokenResponse;
import org.keycloak.testsuite.util.runonserver.LdapHelper;

import org.junit.ClassRule;
Expand All @@ -62,6 +67,7 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;

Expand Down Expand Up @@ -1156,6 +1162,115 @@ private void leaveOutOfPathGroupDoesNotAffectSameNameLdapManagedGroup(LDAPGroupM
});
}

// https://github.com/keycloak/keycloak/issues/54054
@Test
public void test10c_userWithQueryAdminRoleGetsLdapGroupMappings() {
userWithQueryAdminRoleGetsLdapGroupMappings(false, "FgapFlat");
}

// https://github.com/keycloak/keycloak/issues/54054
@Test
public void test10d_userWithQueryAdminRoleGetsLdapGroupMappingsWithPreservedInheritance() {
userWithQueryAdminRoleGetsLdapGroupMappings(true, "FgapTree");
}

// A user holding a query-* admin role, but not view-users or manage-users, gets the fine-grained admin permissions
// filters applied to group queries once that user is in the session context (login, token endpoint, account
// console). The group lookups of the mapper must not be filtered, otherwise an existing group is not found and the
// mapper tries to create it again. As in the test above, each variant uses its own OU/mapper/group names.
private void userWithQueryAdminRoleGetsLdapGroupMappings(boolean preserveInheritance, String suffix) {
String mapperName = "group-mapper-" + suffix;
String groupName = "Group" + suffix;

String groupId = testingClient.server().fetch(session -> {
LDAPTestContext ctx = LDAPTestContext.init(session);
RealmModel realm = ctx.getRealm();

realm.removeComponent(LDAPTestUtils.getSubcomponentByName(realm, ctx.getLdapModel(), "groupsMapper"));

// Without the user cache, the group mappings of the user are resolved by the mapper in every request
ctx.getLdapModel().setCachePolicy(UserStorageProviderModel.CachePolicy.NO_CACHE);
realm.updateComponent(ctx.getLdapModel());

ComponentModel ldapModel = LDAPTestUtils.getLdapProviderModel(realm);
LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ldapModel);
String baseDn = ldapModel.getConfig().getFirst(LDAPConstants.BASE_DN);
String descriptionName = getGroupDescriptionLDAPAttrName(ldapProvider);
LDAPTestUtils.addLdapOUinBaseDn(ldapProvider, "OU" + suffix);
LDAPTestUtils.addOrUpdateGroupMapper(mapperName, realm, ldapModel, LDAPGroupMapperMode.READ_ONLY, descriptionName,
GroupMapperConfig.GROUPS_DN, "ou=OU" + suffix + "," + baseDn,
GroupMapperConfig.PRESERVE_GROUP_INHERITANCE, String.valueOf(preserveInheritance));
LDAPObject ldapGroup = LDAPTestUtils.createLDAPGroup(mapperName, session, realm, ldapModel, groupName, descriptionName, groupName + " Description");
if (preserveInheritance) {
// An existing sub group, it must still be found when the group tree is synced again later
LDAPObject ldapChildGroup = LDAPTestUtils.createLDAPGroup(mapperName, session, realm, ldapModel, groupName + "Child", descriptionName, groupName + "Child Description");
LDAPUtils.addMember(ldapProvider, MembershipType.DN, LDAPConstants.MEMBER, "not-used", ldapGroup, ldapChildGroup);
}

ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(realm, ldapModel, mapperName);
GroupLDAPStorageMapper groupMapper = LDAPTestUtils.getGroupMapper(mapperModel, ldapProvider, realm);
groupMapper.syncDataFromFederationProviderToKeycloak(realm);

GroupModel group = KeycloakModelUtils.findGroupByPath(session, realm, "/" + groupName);
groupMapper.addGroupMappingInLDAP(realm, group, ldapProvider.loadLDAPUserByUsername(realm, "johnkeycloak"));

// LDAP users get a query-* admin role, but neither view-users nor manage-users. A hardcoded role mapper is
// used so that it also works when the users are not imported.
LDAPTestUtils.addOrUpdateHardcodedRoleMapper(realm, ldapModel, HardcodedLDAPRoleStorageMapper.ROLE,
Constants.REALM_MANAGEMENT_CLIENT_ID + "." + AdminRoles.QUERY_CLIENTS);
realm.setAdminPermissionsEnabled(true);
realm.getClientByClientId("test-app").setDirectAccessGrantsEnabled(true);

return group.getId();
}, String.class);

AccessTokenResponse tokenResponse = oauth.doPasswordGrantRequest("johnkeycloak", "Password1");
Assertions.assertTrue(tokenResponse.isSuccess(), tokenResponse.getError() + ": " + tokenResponse.getErrorDescription());

if (preserveInheritance) {
// A new LDAP sub group that John belongs to, but that is not in Keycloak yet. When John's group mappings
// are resolved, the mapper syncs the group tree on demand: it updates the existing groups and looks up
// their sub groups, and the existing child group must be found instead of being created again.
testingClient.server().run(session -> {
RealmModel realm = session.getContext().getRealm();
ComponentModel ldapModel = LDAPTestUtils.getLdapProviderModel(realm);
LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ldapModel);
String descriptionName = getGroupDescriptionLDAPAttrName(ldapProvider);
ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(realm, ldapModel, mapperName);
GroupLDAPStorageMapper groupMapper = LDAPTestUtils.getGroupMapper(mapperModel, ldapProvider, realm);

LDAPObject ldapGroup = groupMapper.loadLDAPGroupByName(groupName);
LDAPObject ldapNewGroup = LDAPTestUtils.createLDAPGroup(mapperName, session, realm, ldapModel, groupName + "New", descriptionName, groupName + "New Description");
LDAPUtils.addMember(ldapProvider, MembershipType.DN, LDAPConstants.MEMBER, "not-used", ldapGroup, ldapNewGroup);
LDAPUtils.addMember(ldapProvider, MembershipType.DN, LDAPConstants.MEMBER, "not-used", ldapNewGroup, ldapProvider.loadLDAPUserByUsername(realm, "johnkeycloak"));
});
}

// Start with no cached group queries, as after a restart or after the group was updated
adminClient.realm(TEST_REALM_NAME).clearRealmCache();

// When refreshing the token, John's user session is set to the session context before his roles, and so his
// LDAP group mappings, are resolved. Refresh twice, the group must be found both times.
for (int i = 0; i < 2; i++) {
tokenResponse = oauth.doRefreshTokenRequest(tokenResponse.getRefreshToken());
Assertions.assertTrue(tokenResponse.isSuccess(), tokenResponse.getError() + ": " + tokenResponse.getErrorDescription());
}

testingClient.server(TEST_REALM_NAME).run(session -> {
RealmModel realm = session.getContext().getRealm();

// The group was found, it was not created a second time
Assertions.assertEquals(1, realm.getGroupsStream().filter(group -> groupName.equals(group.getName())).count());
if (preserveInheritance) {
Assertions.assertEquals(1, realm.getGroupsStream().filter(group -> (groupName + "Child").equals(group.getName())).count());
Assertions.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, "/" + groupName + "/" + groupName + "New"));
}

UserModel john = session.users().getUserByUsername(realm, "johnkeycloak");
assertThat(john.getGroupsStream().map(GroupModel::getId).collect(Collectors.toSet()), hasItem(groupId));
});
}

@Test
public void test11_fetchUsersGroupsWithPaginationAndInvalidBatchSize() {
// Add some groups to Keycloak
Expand Down
Loading
Loading
0