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 @@ -17,23 +17,35 @@
package org.keycloak.models.map.storage.jpa.role;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Selection;

import org.hibernate.query.NativeQuery;

import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RoleModel;
import org.keycloak.models.map.common.StringKeyConverter;
import org.keycloak.models.map.role.MapRoleEntity;
import static org.keycloak.models.map.storage.jpa.Constants.CURRENT_SCHEMA_VERSION_ROLE;

import org.keycloak.models.map.storage.MapKeycloakTransactionWithHasRole;
import org.keycloak.models.map.storage.jpa.JpaMapKeycloakTransaction;
import org.keycloak.models.map.storage.jpa.JpaModelCriteriaBuilder;
import org.keycloak.models.map.storage.jpa.JpaRootEntity;
import org.keycloak.models.map.storage.jpa.role.delegate.JpaMapRoleEntityDelegate;
import org.keycloak.models.map.storage.jpa.role.entity.JpaRoleCompositeEntity;
import org.keycloak.models.map.storage.jpa.role.entity.JpaRoleEntity;

public class JpaRoleMapKeycloakTransaction extends JpaMapKeycloakTransaction<JpaRoleEntity, MapRoleEntity, RoleModel> {
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class JpaRoleMapKeycloakTransaction extends JpaMapKeycloakTransaction<JpaRoleEntity, MapRoleEntity, RoleModel>
implements MapKeycloakTransactionWithHasRole<MapRoleEntity, RoleModel> {

@SuppressWarnings("unchecked")
public JpaRoleMapKeycloakTransaction(KeycloakSession session, EntityManager em) {
super(session, JpaRoleEntity.class, RoleModel.class, em);
}
Expand Down Expand Up @@ -65,4 +77,47 @@ public JpaModelCriteriaBuilder createJpaModelCriteriaBuilder() {
protected MapRoleEntity mapToEntityDelegate(JpaRoleEntity original) {
return new JpaMapRoleEntityDelegate(original, em);
}

@Override
public boolean hasRole(String realmId, Set<String> roleIds, Set<String> targetRoleIds) {
// TODO: add prevention to infinite recursion
Query nativeQuery = em.createNativeQuery("WITH RECURSIVE rr AS (SELECT cr.role_id as role_id, cr.child_role_id as child_role_id " +
" FROM kc_role_composite cr JOIN kc_role kr on kr.id = cr.role_id WHERE cr.role_id IN :roleIds AND kr.realmid = :realmId " +
"UNION ALL " +
"SELECT cr.role_id, cr.child_role_id FROM rr JOIN kc_role kr ON kr.id = uuid(rr.child_role_id) JOIN kc_role_composite cr ON kr.id = cr.role_id) " +
"select rr.child_role_id from rr where rr.child_role_id IN :targetRoleIds");
//noinspection unchecked
nativeQuery.unwrap(NativeQuery.class)
.addSynchronizedEntityClass(JpaRoleEntity.class, JpaRoleCompositeEntity.class);
nativeQuery.setParameter("roleIds", roleIds.stream().map(StringKeyConverter.UUIDKey.INSTANCE::fromString).collect(Collectors.toSet()));
nativeQuery.setParameter("targetRoleIds", targetRoleIds);
nativeQuery.setParameter("realmId", realmId);
nativeQuery.setMaxResults(1);
List<?> result = nativeQuery.getResultList();
return result.size() > 0;
}

@Override
public Set<MapRoleEntity> expandCompositeRoles(String realmId, Set<String> targetRoles) {
// TODO: add prevention to infinite recursion
Query nativeQuery = em.createNativeQuery("WITH RECURSIVE rr AS (SELECT cr.role_id as role_id, cr.child_role_id as child_role_id " +
" FROM kc_role_composite cr JOIN kc_role kr on kr.id = cr.role_id WHERE cr.role_id IN :targetRoles AND kr.realmid = :realmId " +
"UNION ALL " +
"SELECT cr.role_id, cr.child_role_id FROM rr JOIN kc_role kr ON kr.id = uuid(rr.child_role_id) JOIN kc_role_composite cr ON kr.id = cr.role_id) " +
"SELECT DISTINCT rr.child_role_id FROM rr");
//noinspection unchecked
nativeQuery.unwrap(NativeQuery.class)
.addSynchronizedEntityClass(JpaRoleEntity.class, JpaRoleCompositeEntity.class);
nativeQuery.setParameter("targetRoles", targetRoles.stream().map(StringKeyConverter.UUIDKey.INSTANCE::fromString).collect(Collectors.toSet()));
nativeQuery.setParameter("realmId", realmId);
Set<MapRoleEntity> result = new HashSet<>();
@SuppressWarnings("unchecked") List<String> sqlResult = (List<String>) nativeQuery.getResultList();
for (String targetRole : targetRoles) {
result.add(read(targetRole));
}
for (String targetRole : sqlResult) {
result.add(read(targetRole));
}
return result;
Comment on lines +113 to +121

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.

Would it make sense to use criteria() instead of for loops?

Suggested change
Set<MapRoleEntity> result = new HashSet<>();
@SuppressWarnings("unchecked") List<String> sqlResult = (List<String>) nativeQuery.getResultList();
for (String targetRole : targetRoles) {
result.add(read(targetRole));
}
for (String targetRole : sqlResult) {
result.add(read(targetRole));
}
return result;
@SuppressWarnings("unchecked") List<String> sqlResult = (List<String>) nativeQuery.getResultList();
targetRoles.addAll(sqlResult);
DefaultModelCriteria<RoleModel> mcb = criteria();
mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realmId)
.compare(SearchableFields.ID, Operator.IN, targetRoles);
return read(withCriteria(mcb)).collect(Collectors.toSet());

note: if it'll be decided to return Stream, then return statement could loo like: return read(withCriteria(mcb));

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,10 @@ public Stream<String> getAttributeStream(String name) {
return getAttributes().getOrDefault(name, Collections.EMPTY_LIST).stream();
}

public RealmModel getRealm() {

@vramik vramik Jul 19, 2022 •

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.

The method could be probably introduced in RoleModel as the "other" models also has access to the RealmModel as well. This way it could be avoided to cast RoleModel to MapRoleAdapter in MapRoleProvider.

@hmlnarik I'm not sure whether this can be postponed too much as the RoleModel is located in server-spi package and I'm not sure if we would be able to change it in future.

return realm;
}

@Override
public String toString() {
return String.format("%s@%08x", getName(), System.identityHashCode(this));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,11 @@

package org.keycloak.models.map.role;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.jboss.logging.Logger;
import org.keycloak.models.ClientModel;
Expand All @@ -27,11 +30,13 @@
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.map.storage.MapKeycloakTransaction;
import org.keycloak.models.map.storage.MapKeycloakTransactionWithHasRole;
import org.keycloak.models.map.storage.MapStorage;
import org.keycloak.models.RoleModel.SearchableFields;
import org.keycloak.models.RoleProvider;
import org.keycloak.models.map.storage.ModelCriteriaBuilder.Operator;
import org.keycloak.models.map.storage.criteria.DefaultModelCriteria;
import org.keycloak.models.utils.RoleUtils;

import static org.keycloak.common.util.StackUtil.getShortStackTrace;
import static org.keycloak.models.map.common.AbstractMapProviderFactory.MapProviderObjectType.ROLE_AFTER_REMOVE;
Expand Down Expand Up @@ -287,6 +292,52 @@ public void preRemove(RealmModel realm, RoleModel role) {
tx.read(withCriteria(mcb)).forEach(mapRoleEntity -> mapRoleEntity.removeCompositeRole(role.getId()));
}

@Override
public boolean hasRole(Stream<RoleModel> roles, Stream<RoleModel> targetRoles) {
if (tx instanceof MapKeycloakTransactionWithHasRole) {
List<MapRoleAdapter> rolesList = roles.map(roleModel -> ((MapRoleAdapter) roleModel)).collect(Collectors.toList());
if (rolesList.size() == 0) {
return false;
}
String realmId = rolesList.get(0).getRealm().getId();
// TODO: check if all roles are part of the same realm
Set<String> rolesAsSet = rolesList.stream().map(RoleModel::getId).collect(Collectors.toSet());
Set<String> targetRolesAsSet = targetRoles.map(RoleModel::getId).collect(Collectors.toSet());
// fast path: the targetRoles is assumed to be smaller. If this is already contained in the roles, don't go to the store.
for (String roleId : targetRolesAsSet) {
if (rolesAsSet.contains(roleId)) {
return true;
}
}

return ((MapKeycloakTransactionWithHasRole<MapRoleEntity, RoleModel>) tx).hasRole(realmId, rolesAsSet, targetRolesAsSet);
}
return RoleProvider.super.hasRole(roles, targetRoles);
}

@Override
public Stream<RoleModel> expandCompositeRoles(Stream<RoleModel> roles) {
if (tx instanceof MapKeycloakTransactionWithHasRole) {
List<RoleModel> rolesAsList = roles.collect(Collectors.toList());
if (rolesAsList.size() == 0) {
return Stream.empty();
}
// fetch the first role here to retrieve the realm used to the next step
RoleModel first = rolesAsList.get(0);
String realmId = ((MapRoleAdapter) first).getRealm().getId();
// make it failsafe and ensure that all roles are from the same realm
for (RoleModel roleModel : rolesAsList) {
if (!Objects.equals(((MapRoleAdapter) roleModel).getRealm().getId(), realmId)) {
throw new IllegalArgumentException("all realms should be of realmId" + realmId + ", now found role " + roleModel.getId() + " from realmId " + ((MapRoleAdapter) roleModel).getRealm().getId());
}
}
Set<MapRoleEntity> entities = ((MapKeycloakTransactionWithHasRole<MapRoleEntity, RoleModel>) tx).expandCompositeRoles(realmId,
rolesAsList.stream().map(RoleModel::getId).collect(Collectors.toSet()));
return entities.stream().map(mapRoleEntity -> entityToAdapterFunc(((MapRoleAdapter) first).getRealm()).apply(mapRoleEntity));
}
return RoleUtils.expandCompositeRolesStream(roles);
}

@Override
public void close() {
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Copyright 2022 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.models.map.storage;

import org.keycloak.models.map.role.MapRoleEntity;

import java.util.Set;

/**
* A map store transaction that can check if a role is part of another role.
* This must only be used if this store contains all the role information for the given realm.
* @author Alexander Schwartz
*/
public interface MapKeycloakTransactionWithHasRole<V extends MapRoleEntity, M> extends MapKeycloakTransaction<V, M> {


boolean hasRole(String realmId, Set<String> roleIds, Set<String> targetRoleIds);

Set<V> expandCompositeRoles(String realmId, Set<String> targetRoles);

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.

If the Stream would be returned we might get rid of some collecting-and-then-making-stream-again.

Suggested change
Set<V> expandCompositeRoles(String realmId, Set<String> targetRoles);
Stream<V> expandCompositeRoles(String realmId, Set<String> targetRoles);

}
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ public boolean hasDirectRole(RoleModel role) {

@Override
public boolean hasRole(RoleModel role) {
return RoleUtils.hasRole(getRoleMappingsStream(), role)
return session.roles().hasRole(getRoleMappingsStream(), Stream.of(role))
|| RoleUtils.hasRoleFromGroup(getGroupsStream(), role, true);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import org.keycloak.models.ClientModel;
import org.keycloak.models.GroupModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleContainerModel;
import org.keycloak.models.RoleModel;
Expand Down Expand Up @@ -217,10 +218,10 @@ public static Stream<RoleModel> expandCompositeRolesStream(Stream<RoleModel> rol
* @param user
* @return all user role mappings including all groups of user. Composite roles will be expanded
*/
public static Set<RoleModel> getDeepUserRoleMappings(UserModel user) {
public static Set<RoleModel> getDeepUserRoleMappings(KeycloakSession session, UserModel user) {
Set<RoleModel> roleMappings = user.getRoleMappingsStream().collect(Collectors.toSet());
user.getGroupsStream().forEach(group -> addGroupRoles(group, roleMappings));
return expandCompositeRoles(roleMappings);
return session.roles().expandCompositeRoles(roleMappings.stream()).collect(Collectors.toSet());
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.keycloak.models.ClientModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.utils.RoleUtils;

/**
* Abstraction interface for lookup of both realm roles and client roles by id, name and description.
Expand Down Expand Up @@ -71,4 +72,19 @@ public interface RoleLookupProvider {
* Never returns {@code null}.
*/
Stream<RoleModel> searchForClientRolesStream(ClientModel client, String search, Integer first, Integer max);

/**
* Check if the target role is one of the roles or one of the composite roles of the role.
* @param roles roles to search in (haystack).
* @param targetRoles role to search (needle).
* @return <code>true</code> if found, .
*/
default boolean hasRole(Stream<RoleModel> roles, Stream<RoleModel> targetRoles) {
return targetRoles.anyMatch(targetRole -> RoleUtils.hasRole(roles, targetRole));
}

default Stream<RoleModel> expandCompositeRoles(Stream<RoleModel> roles) {
return RoleUtils.expandCompositeRolesStream(roles);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ private ApplicationEntry toApplicationEntry(final KeycloakSession session, final
client.getClientScopes(false).values().stream());
allClientScopes = Stream.concat(allClientScopes, Stream.of(client)).distinct();

Set<RoleModel> availableRoles = TokenManager.getAccess(user, client, allClientScopes);
Set<RoleModel> availableRoles = TokenManager.getAccess(session, user, client, allClientScopes);

// Don't show applications, which user doesn't have access into (any available roles)
// unless this is can be changed by approving/revoking consent
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -584,8 +584,8 @@ public static void dettachClientSession(AuthenticatedClientSessionModel clientSe
}


public static Set<RoleModel> getAccess(UserModel user, ClientModel client, Stream<ClientScopeModel> clientScopes) {
Set<RoleModel> roleMappings = RoleUtils.getDeepUserRoleMappings(user);
public static Set<RoleModel> getAccess(KeycloakSession session, UserModel user, ClientModel client, Stream<ClientScopeModel> clientScopes) {
Set<RoleModel> roleMappings = RoleUtils.getDeepUserRoleMappings(session, user);

if (client.isFullScopeAllowed()) {
if (logger.isTraceEnabled()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,8 @@ private void addRealmAccess(RealmModel realm, UserModel user, Map<String, Set<St
}

private void addMasterRealmAccess(UserModel user, Map<String, Set<String>> realmAdminAccess) {
session.realms().getRealmsStream().forEach(realm -> {
// TODO: remove the filtering by master realm before merging this. This has only be done to make the UI usable with lots of realms
session.realms().getRealmsStream().filter(realm -> realm.getName().equals("master")).forEach(realm -> {
ClientModel realmAdminApp = realm.getMasterAdminClient();
getRealmAdminAccess(realm, realmAdminApp, user, realmAdminAccess);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ public RealmsAdminResource(AdminAuth auth, TokenManager tokenManager) {
@Produces(MediaType.APPLICATION_JSON)
public Stream<RealmRepresentation> getRealms(@DefaultValue("false") @QueryParam("briefRepresentation") boolean briefRepresentation) {
Stream<RealmRepresentation> realms = session.realms().getRealmsStream()
// TODO: remove the filtering by master realm before merging this. This has only be done to make the UI usable with lots of realms
.filter(realm -> realm.getName().equals("master"))
.map(realm -> toRealmRep(realm, briefRepresentation))
.filter(Objects::nonNull);
return throwIfEmpty(realms, new ForbiddenException());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ private boolean isClientScopePermittedForUser(ClientScopeModel clientScope) {
private Set<RoleModel> loadRoles() {
UserModel user = clientSession.getUserSession().getUser();
ClientModel client = clientSession.getClient();
return TokenManager.getAccess(user, client, getClientScopesStream());
return TokenManager.getAccess(session, user, client, getClientScopesStream());
}


Expand All @@ -295,7 +295,7 @@ private Set<ProtocolMapperModel> loadProtocolMappers() {

private Set<RoleModel> loadUserRoles() {
UserModel user = clientSession.getUserSession().getUser();
return RoleUtils.getDeepUserRoleMappings(user);
return RoleUtils.getDeepUserRoleMappings(session, user);
}

}