8000 Match client policy source groups by full group path by graziang · Pull Request #52608 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
8000
Merged
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 @@ -35,6 +35,12 @@ Note that {project_name}'s trust store (or mTLS store) is shared for all the rea

Revalidating certificates can be problematic in certain installations (for example if a proxy is configured for TLS termination and the certificates are passed to {project_name} using headers). The trust-store or mTLS store in {project_name} should always be configured correctly to validate the client certificate chain. Please see link:https://www.keycloak.org/server/reverseproxy[Using a reverse proxy] and link:https://www.keycloak.org/server/mutual-tls[Configuring trusted certificates for mTLS], for more information if you are using a TLS termination proxy and X509 client authentication.

=== Client policy source groups condition matches the full group path
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.

Not 100% sure if this is correct file (as the issue is supposed to be backported to the 26.7 as well and maybe we would have the 26.7 micro-release before the 26.8 release). But maybe we can change later if needed (as not 100% sure whether we would have new micro-release or not).


The `client-updater-source-groups` client policy condition now matches groups by their full path instead of the simple group name. A configured value without a leading slash is treated as a top level group, so a condition configured with `topGroup` matches `/topGroup` and keeps behaving as before. Top level groups configured by their simple name do not require any change.

Only the conditions configured with the simple name of a subgroup need to be updated to the full path of that group, for example `/topGroup/level2group`.

// ------------------------ Notable changes ------------------------ //
== Notable changes

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1179,7 +1179,7 @@ searchForProtocol=Search protocol mapper
eventTypes.CLIENT_INFO.name=Client info
eventTypes.OAUTH2_DEVICE_CODE_TO_TOKEN.description=OAuth2 device code to token
eventTypes.UPDATE_TOTP_ERROR.name=Update totp error
client-updater-source-groups.tooltip=Name of groups to check. The condition evaluates to true if the entity who creates or updates the client is a member of one or more of the specified groups. Configured groups are specified by their simple name, which must match the name of the Keycloak group. No support for group hierarchy is used here.
client-updater-source-groups.tooltip=Path of groups to check. The condition evaluates to true if the entity who creates or updates the client is a member of one or more of the specified groups. Configured groups are specified by their full path, for example /topGroup/level2group. No support for group hierarchy is used here.
webAuthnPolicyRpId=Relying party ID
ldapRolesDnHelp=LDAP DN where roles of this tree are saved. For example, 'ou\=finance,dc\=example,dc\=org'.
serviceAccount=Service account roles
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,18 @@

package org.keycloak.services.clientpolicy.condition;

import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import org.keycloak.OAuthErrorException;
import org.keycloak.authorization.fgap.AdminPermissionsSchema;
import org.keycloak.models.GroupModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.representations.JsonWebToken;
import org.keycloak.representations.idm.ClientPolicyConditionConfigurationRepresentation;
import org.keycloak.services.clientpolicy.ClientPolicyContext;
Expand Down Expand Up @@ -122,24 +125,35 @@ private boolean isGroupMatched(String subjectId) {
private boolean isGroupsMatched(UserModel user) {
if (user == null) return false;

Set<String> expectedGroups = instantiateGroupsForMatching();
if (expectedGroups == null) return false;
List<String> configuredGroups = configuration.getGroups();
if (configuredGroups == null) return false;

// user.getGroupsStream() never returns null according to {@link UserModel.getGroupsStream}
Set<String> groups = user.getGroupsStream().map(GroupModel::getName).collect(Collectors.toSet());
Set<String> expectedGroups = configuredGroups.stream().map(this::resolveGroup).filter(Objects::nonNull)
.map(GroupModel::getId).collect(Collectors.toSet());

Set<String> groups = user.getGroupsStream().map(GroupModel::getId).collect(Collectors.toSet());

if (logger.isTraceEnabled()) {
groups.forEach(i -> logger.tracev("user group = {0}", i));
expectedGroups.forEach(i -> logger.tracev("expected user group = {0}", i));
groups.forEach(i -> logger.tracev("user group id = {0}", i));
expectedGroups.forEach(i -> logger.tracev("expected user group id = {0}", i));
}

return expectedGroups.removeAll(groups); // may change expectedGroups so that it has needed to be instantiated.
return groups.stream().anyMatch(expectedGroups::contains);
}

private Set<String> instantiateGroupsForMatching() {
List<String> groups = configuration.getGroups();
if (groups == null) return null;
return new HashSet<>(groups);
private GroupModel resolveGroup(String group) {
if (group == null) return null;

RealmModel realm = session.getContext().getRealm();

// the configured groups are resolved regardless of the groups the user performing the request is allowed to view
return AdminPermissionsSchema.runWithoutAuthorization(session, () -> {
Comment thread
graziang marked this conversation as resolved.
Resolved
// a value with a leading slash is the full path of the group, otherwise it is the name of a top level group
if (group.startsWith("/")) {
return KeycloakModelUtils.findGroupByPath(session, realm, group);
}
return session.groups().getGroupByName(realm, null, group);
});
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@

import org.keycloak.OAuth2Constants;
import org.keycloak.OAuthErrorException;
import org.keycloak.admin.client.CreatedResponseUtil;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.authentication.authenticators.client.JWTClientAuthenticator;
import org.keycloak.authentication.authenticators.client.JWTClientSecretAuthenticator;
import org.keycloak.authentication.authenticators.client.X509ClientAuthenticator;
Expand All @@ -43,6 +45,7 @@
import org.keycloak.representations.idm.C 8000 lientScopeRepresentation;
import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.representations.idm.ErrorRepresentation;
import org.keycloak.representations.idm.GroupRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.representations.oidc.OIDCClientRepresentation;
Expand Down Expand Up @@ -97,6 +100,8 @@
*/
public class ClientPoliciesConditionTest extends AbstractClientPoliciesTest {

private static final String DUPLICATED_GROUP_PARENT_NAME = "duplicate-source-groups-parent";

@Page
protected OAuthGrantPage grantPage;

Expand Down Expand Up @@ -296,6 +301,71 @@ public void testClientUpdateSourceGroupsCondition() throws Exception {
}
}

@Test
public void testClientUpdateSourceGroupsConditionMatchesFullGroupPath() throws Exception {
// register profiles
String json = (new ClientProfilesBuilder()).addProfile(
(new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Den Andre Profil")
.addExecutor(SecureClientAuthenticatorExecutorFactory.PROVIDER_ID,
createSecureClientAuthenticatorExecutorConfig(
List.of(JWTClientAuthenticator.PROVIDER_ID),
null)
)
.toRepresentation()
).toString();
updateProfiles(json);

// make manage-clients a member of the subgroup /duplicate-source-groups-parent/topGroup, whose name
// duplicates the one of the top level group /topGroup the create-clients user belongs to
RealmResource realm = adminClient.realm(REALM_NAME);
GroupRepresentation parentGroup = new GroupRepresentation();
parentGroup.setName(DUPLICATED_GROUP_PARENT_NAME);
String parentGroupId = CreatedResponseUtil.getCreatedId(realm.groups().add(parentGroup));
testContext.getOrCreateCleanup(REALM_NAME).addGroupId(parentGroupId);
GroupRepresentation duplicatedGroup = new GroupRepresentation();
duplicatedGroup.setName("topGroup");
String duplicatedGroupId = CreatedResponseUtil.getCreatedId(realm.groups().group(parentGroupId).subGroup(duplicatedGroup));
String userId = realm.users().search("manage-clients", true).get(0).getId();
realm.users().get(userId).joinGroup(duplicatedGroupId);

// a simple name only matches the top level group, the subgroup with the duplicated name is not matched
updateClientUpdateSourceGroupsPolicy("topGroup");
authCreateClients();
assertClientRegistrationFails();
authManageClients();
createClientDynamically(generateSuffixedName(CLIENT_NAME), (OIDCClientRepresentation clientRep) -> {
});

// the subgroup is matched when it is configured by its full path
updateClientUpdateSourceGroupsPolicy("/" + DUPLICATED_GROUP_PARENT_NAME + "/topGroup");
authManageClients();
assertClientRegistrationFails();
authCreateClients();
createClientDynamically(generateSuffixedName(CLIENT_NAME), (OIDCClientRepresentation clientRep) -> {
});
}

private void updateClientUpdateSourceGroupsPolicy(String group) throws Exception {
String json = (new ClientPoliciesBuilder()).addPolicy(
(new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "Den Andre Politik", Boolean.TRUE)
.addCondition(ClientUpdaterSourceGroupsConditionFactory.PROVIDER_ID,
createClientUpdateSourceGroupsConditionConfig(List.of(group)))
.addProfile(PROFILE_NAME)
.toRepresentation()
).toString();
updatePolicies(json);
}

private void assertClientRegistrationFails() throws Exception {
try {
createClientDynamically(generateSuffixedName(CLIENT_NAME), (OIDCClientRepresentation clientRep) -> {
});
fail();
} catch (ClientRegistrationException e) {
assertEquals(ERR_MSG_CLIENT_REG_FAIL, e.getMessage());
}
}

@Test
public void testClientUpdateSourceRolesCondition() throws Exception {
// register profiles
Expand Down
Loading
0