crbench//

← all cases

Add Client resource type and scopes to authorization schema

Tier 2 easy java · local · real merged PR from keycloak/keycloak #36880

Ground-truth defects

d3 · security · medium
In getClientsWithPermission(String scope), iterating resourceStore.findByType(server, AdminPermissionsSchema.CLIENTS_RESOURCE_TYPE) and returning resource.getName() will only ever consider the type-level 'Clients' resource (per-client resources have no type) and return its name, while AvailableRoleMappingResource#getRoleIdsWithPermissions expects actual client IDs to pass to realm.getClientById, which can lead to incorrect behavior or a null client and subsequent failures.

The change under review

diff (truncated — full diff)
diff --git a/server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java b/server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java
index 22c8119816..5fc43a34f5 100644
--- a/server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java
+++ b/server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java
@@ -50,8 +50,9 @@ import org.keycloak.representations.idm.authorization.ScopePermissionRepresentat
 import org.keycloak.representations.idm.authorization.ScopeRepresentation;
 
 public class AdminPermissionsSchema extends AuthorizationSchema {
-
+    
     public static final String USERS_RESOURCE_TYPE = "Users";
+    public static final String CLIENTS_RESOURCE_TYPE = "Clients";
 
     //scopes
     public static final String MANAGE = "manage";
@@ -59,13 +60,17 @@ public class AdminPermissionsSchema extends AuthorizationSchema {
     public static final String IMPERSONATE = "impersonate";
     public static final String MAP_ROLES = "map-roles";
     public static final String MANAGE_GROUP_MEMBERSHIP = "manage-group-membership";
+    public static final String CONFIGURE = "configure";
+    public static final String MAP_ROLES_CLIENT_SCOPE = "map-roles-client-scope";
+    public static final String MAP_ROLES_COMPOSITE = "map-roles-composite";
 
     public static final ResourceType USERS = new ResourceType(USERS_RESOURCE_TYPE, Set.of(MANAGE, VIEW, IMPERSONATE, MAP_ROLES, MANAGE_GROUP_MEMBERSHIP));
+    public static final ResourceType CLIENTS = new ResourceType(CLIENTS_RESOURCE_TYPE, Set.of(CONFIGURE, MANAGE, MAP_ROLES, MAP_ROLES_CLIENT_SCOPE, MAP_ROLES_COMPOSITE, VIEW));
 
     public static final AdminPermissionsSchema SCHEMA = new AdminPermissionsSchema();
 
     private AdminPermissionsSchema() {
-        super(Map.of(USERS_RESOURCE_TYPE, USERS));
+        super(Map.of(USERS_RESOURCE_TYPE, USERS, CLIENTS_RESOURCE_TYPE, CLIENTS));
     }
 
     public Resource getOrCreateResource(KeycloakSession session, ResourceServer resourceServer, String policyType, String resourceType, String id) {
@@ -85,6 +90,8 @@ public class AdminPermissionsSchema extends AuthorizationSchema {
 
         if (USERS.getType().equals(resourceType)) {
             name = resolveUser(session, id);
+        } else if (CLIENTS.getType().equals(resourceType)) {
+            name = resolveClient(session, id);
         }
 
         if (name == null) {
@@ -165,6 +172,17 @@ public class AdminPermissionsSchema extends AuthorizationSchema {
         return user == null ? null : user.getId();
     }
 
+    private String resolveClient(KeycloakSession session, String id) {
+        RealmModel realm = session.getContext().getRealm();
+        ClientModel client = session.clients().getClientById(realm, id);
+
+        if (client == null) {
+            client = session.clients().getClientByClientId(realm, id);
+        }
+
+        return client == null ? null : client.getId();
+    }
+
     private StoreFactory getStoreFactory(KeycloakSession session) {
         AuthorizationProvider authzProvider = session.getProvider(AuthorizationProvider.class);
         return authzProvider.getStoreFactory();
diff --git a/services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java b/services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java
index d40a7f4e71..08da4663b9 100644
--- a/services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java
+++ b/services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java
@@ -74,23 +74,25 @@ public class AdminPermissions {
         manager.register(new ProviderEventListener() {
             @Override
             public void onEvent(ProviderEvent event) {
-                if (event instanceof RoleContainerModel.RoleRemovedEvent) {
-                    RoleContainerModel.RoleRemovedEvent cast = (RoleContainerModel.RoleRemovedEvent)event;
-                    RoleModel role = cast.getRole();
-                    RealmModel realm;
-                    if (role.getContainer() instanceof ClientModel) {
-                        realm = ((ClientModel)role.getContainer()).getRealm();
+                if (Profile.isFeatureEnabled(Profile.Feature.ADMIN_FINE_GRAINED_AUTHZ)) {
+                    if (event instanceof RoleContainerModel.RoleRemovedEvent) {
+                        RoleContainerModel.RoleRemovedEvent cast = (RoleContainerModel.RoleRemovedEvent) event;
+                        RoleModel role = cast.getRole();
+                        RealmModel realm;
+                        if (role.getContainer() instanceof ClientModel) {
+                            realm = ((ClientModel) role.getContainer()).getRealm();
 
-                    } else {
-                        realm = (RealmModel)role.getContainer();
+                        } else {
+                            realm = (RealmModel) role.getContainer();
+                        }
+                        management(cast.getKeycloakSession(), realm).roles().setPermissionsEnabled(role, false);
+                    } else if (event instanceof ClientModel.ClientRemovedEvent) {
+                        ClientModel.ClientRemovedEvent cast = (ClientModel.ClientRemovedEvent) event;
+                        management(cast.getKeycloakSession(), cast.getClient().getRealm()).clients().setPermissionsEnabled(cast.getClient(), false);
+                    } else if (event instanceof GroupModel.GroupRemovedEvent) {
+                        GroupModel.GroupRemovedEvent cast = (GroupModel.GroupRemovedEvent) event;
+                        management(cast.getKeycloakSession(), cast.getRealm()).groups().setPermissionsEnabled(cast.getGroup(), false);
                     }
-                    management(cast.getKeycloakSession(), realm).roles().setPermissionsEnabled(role, false);
-                } else if (event instanceof ClientModel.ClientRemovedEvent) {
-                    ClientModel.ClientRemovedEvent cast = (ClientModel.ClientRemovedEvent)event;
-                    management(cast.getKeycloakSession(), cast.getClient().getRealm()).clients().setPermissionsEnabled(cast.getClient(), false);
-                } else if (event instanceof GroupModel.GroupRemovedEvent) {
-                    GroupModel.GroupRemovedEvent cast = (GroupModel.GroupRemovedEvent)event;
-                    management(cast.getKeycloakSession(), cast.getRealm()).groups().setPermissionsEnabled(cast.getGroup(), false);
                 }
             }
         });
diff --git a/services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionEvaluator.java b/services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionEvaluator.java
index ad3f94f900..c5fbe70f96 100644
--- a/services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionEvaluator.java
+++ b/services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionEvaluator.java
@@ -16,6 +16,7 @@
  */
 package org.keycloak.services.resources.admin.permissions;
 
+import org.keycloak.models.AdminRoles;
 import org.keycloak.models.ClientModel;
 import org.keycloak.models.ClientScopeModel;
 
@@ -31,54 +32,161 @@ public interface ClientPermissionEvaluator {
 
     void setPermissionsEnabled(ClientModel client, boolean enable);
 
+    /**
+     * Throws ForbiddenException if {@link #canListClientScopes()} returns {@code false}.
+     */
     void requireListClientScopes();
 
+    /**
+     * Returns {@code true} if the caller has {@link org.keycloak.models.AdminRoles#MANAGE_CLIENTS} role.
+     * <p/>
+     * For V2 only: Also if it has permission to {@link org.keycloak.authorization.AdminPermissionsSchema#MANAGE}.
+     */
     boolean canManage();
 
+    /**
+     * Throws ForbiddenException if {@link #canManage()} returns {@code false}.
+     */
     void requireManage();
 
+    /**
+     * Returns {@code true} if the caller has {@link org.keycloak.models.AdminRoles#MANAGE_CLIENTS} role.
+     * <p/>
+     * For V2 only: Also if it has permission to {@link org.keycloak.authorization.AdminPermissionsSchema#MANAGE}.
+     */
     boolean canManageClientScopes();
 
+    /**
+     * Throws ForbiddenException if {@link #canManageClientScopes()} returns {@code false}.
+     */
     void requireManageClientScopes();
 
+    /**
+     * Returns {@code true} if the caller has at least one of the {@link org.keycloak.models.AdminRoles#MANAGE_CLIENTS} or {@link org.keycloak.models.AdminRoles#VIEW_CLIENTS} roles.
+     * <p/>
+     * For V2 only: Also if it has permission to {@link org.keycloak.authorization.AdminPermissionsSchema#VIEW}.
+     */
     boolean canView();
 
+    /**
+     * Returns {@code true} if {@link #canView()} returns {@code true}.
+     * <p/>
+     * Or if the caller has at least one of the {@link AdminRoles#QUERY_CLIENTS} or {@link AdminRoles#QUERY_USERS} roles.
+     */
     boolean canList();
 
+    /**
+     * Returns {@code true} if {@link #canView()} returns {@code true}.
+     */
     boolean canViewClientScopes();
 
+    /**
+     * Throws ForbiddenException if {@link #canList()} returns {@code false}.
+     */
     void requireList();
 
+    /**
+     * Returns {@code true} if {@link #canView()} returns {@code true}.
+     * <p/>
+     * Or if the caller has {@link AdminRoles#QUERY_CLIENTS} role.
+     */
     boolean canListClientScopes();
 
+    /**
+     * Returns {@code true} if {@link #canView()} returns {@code true}.
+     */
     void requireView();
 
+    /**
+     * Returns {@code true} if {@link #canViewClientScopes()} returns {@code true}.
+     */
     void requireViewClientScopes();
 
+    /**
+     * Returns {@code true} if the caller has {@link org.keycloak.models.AdminRoles#MANAGE_CLIENTS} role.
+     * <p/>
+     * Or if the caller has a permission to {@link AdminPermissionManagement#MANAGE_SCOPE} the client.
+     * <p/>
+     * For V2 only: Also if the caller has a permission to {@link org.keycloak.authorization.AdminPermissionsSchema#MANAGE} all clients.
+     */
     boolean canManage(ClientModel client);
 
+    /**
+     * Returns {@code true} if {@link #canManage(ClientModel)} returns {@code true}.
+     * <p/>
+     * Or if the caller has a permission to {@link ClientPermissionManagement#CONFIGURE_SCOPE} the client.
+     * <p/>
+     * For V2 only: Also if the caller has a permission to {@link org.keycloak.authorization.AdminPermissionsSchema#CONFIGURE} all clients.
+     */
     boolean canConfigure(ClientModel client);
 
+    /**
+     * Throws ForbiddenException if {@link #canConfigure(ClientModel)} returns {@code false}.
+     */
     void requireConfigure(ClientModel client);
 
+    /**
+     * Throws ForbiddenException if {@link #canManage(ClientModel)}  returns {@code false}.
+     */
     void requireManage(ClientModel client);
 
+    /**
+     * Returns {@code true} if {@link #canView()} or {@link #canConfigure(ClientModel)} returns {@code true}.
+     * <p/>
+     * Or if the caller has a permission to {@link AdminPermissionManagement#VIEW_SCOPE} the client.
+     * <p/>
+     * For V2 only: Also if the caller has a permission to {@link org.keycloak.authorization.AdminPermissionsSchema#VIEW} all clients.
+     */
     boolean canView(ClientModel client);
 
+    /**
+     * Throws ForbiddenException if {@link #canView(ClientModel)}  returns {@code false}.
+     */
     void requireView(ClientModel client);
 
+    /**
+     * Returns {@code true} if the caller has {@link org.keycloak.models.AdminRoles#MANAGE_CLIENTS} role.
+     * <p/>
+     * For V2 only: Also if it has permission to {@link org.keycloak.authorization.AdminPermissionsSchema#MANAGE}.
+     */
     boolean canManage(ClientScopeModel clientScope);
 
+    /**
+     * Throws ForbiddenException if {@link #canManage(ClientScopeModel)} returns {@code false}.
+     */
     void requireManage(ClientScopeModel clientScope);
 
+    /**
+     * Returns {@code true} if the caller has at least one of the {@link org.keycloak.models.AdminRoles#VIEW_CLIENTS} or {@link org.keycloak.models.AdminRoles#MANAGE_CLIENTS} roles.
+     * <p/>
+     * For V2 only: Also if it has permission to {@link org.keycloak.authorization.AdminPermissionsSchema#VIEW} or {@link org.keycloak.authorization.AdminPermissionsSchema#MANAGE}.
+     */
     boolean canView(ClientScopeModel clientScope);
 
+    /**
+     * Throws ForbiddenException if {@link #canView(ClientScopeModel)} returns {@code false}.
+     */
     void requireView(ClientScopeModel clientScope);
 
+    /**
+     * Returns {@code true} if the caller has a permission to {@link ClientPermissionManagement#MAP_ROLES_SCOPE} for the client.
+     * <p/>
+     * For V2 only: Also if the caller has a permission to {@link org.keycloak.authorization.AdminPermissionsSchema#MAP_ROLES} for all clients.
+     */
     boolean canMapRoles(ClientModel client);
 
+    /**
+     * Returns {@code true} if the caller has a permission to {@link ClientPermissionManagement#MAP_ROLES_COMPOSITE_SCOPE} for the client.
+     * <p/>
+     * For V2 only: Also if the caller has a permission to {@link org.keycloak.authorization.AdminPermissionsSchema#MAP_ROLES_COMPOSITE} for all clients.
+     */
     boolean canMapCompositeRoles(ClientModel client);
 
+    /**
+     * Returns {@code true} if the caller has a permission to {@link ClientPermissionManagement#MAP_ROLES_CLIENT_SCOPE} for the client.
+     * <p/>
+     * For V2 only: Also if the caller has a permission to {@link org.keycloak.authorization.AdminPermissionsSchema#MAP_ROLES_CLIENT_SCOPE} for all clients.
+     */
     boolean canMapClientScopeRoles(ClientModel client);
 
     Map<String, Boolean> getAccess(ClientModel client);
diff --git a/services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java b/services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java
new file mode 100644
index 0000000000..a751293df7
--- /dev/null
+++ b/services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java
@@ -0,0 +1,287 @@
+/*
+ * Copyright 2025 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.services.resources.admin.permissions;
+
+import org.jboss.logging.Logger;
+import org.keycloak.authorization.AdminPermissionsSchema;
+import org.keycloak.authorization.AuthorizationProvider;
+import org.keycloak.authorization.common.ClientModelIdentity;
+import org.keycloak.authorization.common.DefaultEvaluationContext;
+import org.keycloak.authorization.model.Policy;
+import org.keycloak.authorization.model.Resource;
+import org.keycloak.authorization.model.ResourceServer;
+import org.keycloak.authorization.model.Scope;
+import org.keycloak.authorization.permission.ResourcePermission;
+import org.keycloak.authorization.policy.evaluation.EvaluationContext;
+import org.keycloak.models.AdminRoles;
+import org.keycloak.models.ClientModel;
+import org.keycloak.models.ClientScopeModel;
+import org.keycloak.models.KeycloakSession;
+import org.keycloak.models.RealmModel;
+import org.keycloak.representations.AccessToken;
+import org.keycloak.representations.idm.authorization.Permission;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.keycloak.services.resources.admin.permissions.AdminPermissionManagement.TOKEN_EXCHANGE;
+
+
+public class ClientPermissionsV2 extends ClientPermissions {
+
+    private static final Logger logger = Logger.getLogger(ClientPermissionsV2.class);
+
+    public ClientPermissionsV2(KeycloakSession session, RealmModel realm, AuthorizationProvider authz, MgmtPermissionsV2 root) {
+        super(session, realm, authz, root);
+    }
+
+    @Override
+    public boolean canConfigure(ClientModel client) {
+        if (canManage(client)) return true;
+
+        return hasPermission(client, AdminPermissionsSchema.CONFIGURE);
+    }
+
+    @Override
+    public boolean canManage(ClientModel client) {
+        if (root.hasOneAdminRole(AdminRoles.MANAGE_CLIENTS)) return true;
+
+        return hasPermission(client, AdminPermissionsSchema.MANAGE);
+    }
+
+    @Override
+    public boolean canManage() {
+        return super.canManage() || hasPermission(AdminPermissionsSchema.MANAGE);
+    }
+
+    @Override
+    public boolean canView(ClientModel client) {
+        if (canView() || canConfigure(client)) {
+            return true;
+        }
+
+        return hasPermission(client, AdminPermissionsSchema.VIEW);
+    }
+
+    @Override
+    public boolean canView() {
+        return canViewClientDefault() || hasPermission(AdminPermissionsSchema.VIEW);
+    }
+
+    @Override
+    public boolean canMapRoles(ClientModel client) {
+        return hasPermission(client, AdminPermissionsSchema.MAP_ROLES);
+    }
+
+    @Override
+    public boolean canMapCompositeRoles(ClientModel client) {
+        return hasPermission(client, AdminPermissionsSchema.MAP_ROLES_COMPOSITE);
+    }
+
+    @Override
+    public boolean canMapClientScopeRoles(ClientModel client) {
+        return hasPermission(client, AdminPermissionsSchema.MAP_ROLES_CLIENT_SCOPE);
+    }
+
+    @Override
+    public boolean canManageClientScopes() {
+        if (root.hasOneAdminRole(AdminRoles.MANAGE_CLIENTS)) return true;
+
+        return hasPermission(AdminPermissionsSchema.MANAGE);
+    }
+
+    @Override
+    public boolean canManage(ClientScopeModel clientScope) {
+        return canManageClientScopes();
+    }
+
+    @Override
+    public boolean canView(ClientScopeModel clientScope) {
+        if (root.hasOneAdminRole(AdminRoles.VIEW_CLIENTS, AdminRoles.MANAGE_CLIENTS)) return true;
+
+        return hasPermission(AdminPermissionsSchema.VIEW) || hasPermission(AdminPermissionsSchema.MANAGE);
+    }
+
+    @Override
+    public Set<String> getClientsWithPermission(String scope) {
+        if (!root.isAdminSameRealm()) {
+            return Collections.emptySet();
+        }
+
+        ResourceServer server = root.realmResourceServer();
+
+        if (server == null) {
+            return Collections.emptySet();
+        }
+
+        Set<String> granted = new HashSet<>();
+
+        resourceStore.findByType(server, AdminPermissionsSchema.CLIENTS_RESOURCE_TYPE, resource -> {
+            if (hasGrantedPermission(resource, scope)) {
+                granted.add(resource.getName());
+            }
+        });
+
+        return granted;
+    }
+
+    @Override
+    public boolean canExchangeTo(ClientModel authorizedClient, ClientModel to, AccessToken token) {
+        throw new UnsupportedOperationException("Not supported in V2");
+    }
+
+    @Override
+    public Policy exchangeToPermission(ClientModel client) {
+        throw new UnsupportedOperationException("Not supported in V2");
+    }
+
+    @Override
+    public Policy mapRolesPermission(ClientModel client) {
+        throw new UnsupportedOperationException("Not supported in V2");
+    }
+
+    @Override
+    public Policy mapRolesClientScopePermission(ClientModel client) {
+        throw new UnsupportedOperationException("Not supported in V2");
+    }
+
+    @Override
+    public Policy mapRolesCompositePermission(ClientModel client) {
+        throw new UnsupportedOperationException("Not supported in V2");
+    }
+
+    @Override
+    public Policy managePermission(ClientModel client) {
+        throw new UnsupportedOperationException("Not supported in V2");
+    }
+
+    @Override
+    public Policy configurePermission(ClientModel client) {
+        throw new UnsupportedOperationException("Not supported in V2");
+    }
+
+    @Override
+    public Policy viewPermission(ClientModel client) {
+        throw new UnsupportedOperationException("Not supported in V2");
+    }
+
+    @Override
+    public boolean isPermissionsEnabled(ClientModel client) {
+        throw new UnsupportedOperationException("Not supported in V2");
+    }
+
+    @Override
+    public void setPermissionsEnabled(ClientModel client, boolean enable) {
+        throw new UnsupportedOperationException("Not supported in V2");
+    }
+
+    @Override
+    public Resource resource(ClientModel client) {
+        throw new UnsupportedOperationException("Not supported in V2");
+    }
+
+    @Override
+    public Map<String, String> getPermissions(ClientModel client) {
+        throw new UnsupportedOperationException("Not supported in V2");
+    }
+
+    private boolean hasPermission(ClientModel client, String scope) {
+        if (!root.isAdminSameRealm()) {
+            return false;
+        }
+        ResourceServer server = root.realmResourceServer();
+        if (server == null) return false;
+
+        Resource resource =  resourceStore.findByName(server, client.getId(), server.getId());

Leaderboard for this case

easy · 7 of 9 bots fully caught it (78% solve rate) · 78% avg coverage.

#BotResultCaughtCoverageFindingsFalse alarms
1 cursor solved 1/1 100.0% 4 0
2 Drape (Review) solved 1/1 100.0% 6 0
3 greptile solved 1/1 100.0% 2 0
4 Mjolnir (Opus 5.5) solved 1/1 100.0% 4 0
5 Cubic solved 1/1 100.0% 5 1
6 Mjolnir (Sonnet 5.5) solved 1/1 100.0% 3 1
7 qodo solved 1/1 100.0% 6 2
8 Claude Code (Opus 5.5) miss 0/1 0.0% 4 0
9 Drape (Deep Review) miss 0/1 0.0% 7 0

Bot results

Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d3 medium ✗ —
valid · impact high
AbstractTokenExchangeProvider line 276 calls AdminPermissions.management(...).clients().canExchangeTo(client, targetClient, token). MgmtPermissionsV2.clients() now returns ClientPermissionsV2, whose canExchangeTo throws, while before this change it used the inherited V1 implementation. TOKEN_EXCHANGE does not depend on V1 FGAP, so the two features can be enabled together. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
canView() ignores the MANAGE scope while canManage() and canView(ClientScopeModel) accept it. canList()/requireList() depend on canView(), so an admin with only all-clients MANAGE and no query role is refused when listing clients. This is a real inconsistency, but its impact is limited. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
The change adds per-client V2 resources (named by client id via resolveClient). The removal listener is now skipped unless V1 is enabled, and ClientApplicationSynchronizer removes only the client's own resource server, not entries in the admin-permissions server. So the new per-client resources and permissions are orphaned when a client is deleted. [grounded: diff] [consensus 3/3: valid=3]
valid · impact medium
getResourceTypeResource can return null, either when the schema isn't supported or when the 'Clients' resource is missing. The resource is missing for realms whose admin-permissions client was initialized before CLIENTS was added, because init() returns early when the client already exists. The null is then passed to findByResource and resource.getScopes() without a check, unlike the guarded hasPermission(String) sibling. [grounded: diff] [consensus 3/3: valid=3]
raw comments (4)
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:148
`canExchangeTo` now throws UnsupportedOperationException. `MgmtPermissionsV2.clients()` now returns `ClientPermissionsV2`, and `AbstractTokenExchangeProvider` (line 276) calls `AdminPermissions.management(...).clients().canExchangeTo(client, targetClient, token)` for every token exchange to a different audience client. The V1 `TOKEN_EXCHANGE` feature has no dependency on `ADMIN_FINE_GRAINED_AUTHZ`, so it can be enabled alongside `ADMIN_FINE_GRAINED_AUTHZ_V2`. Before this change, the inherited V1 client permissions handled that call. With both features on, every such exchange now fails with an unhandled exception (HTTP 500) instead of a proper allow/deny decision.
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:86
`canView()` only checks the VIEW scope on the all-clients resource. An admin granted MANAGE on all clients gets `canManage() == true` but `canView() == false`. In V1, `canView()` also returns true for manage rights, and `canView(ClientScopeModel)` in this same class accepts VIEW or MANAGE. Because `canList()`, `canListClientScopes()` and `requireView()` all depend on `canView()`, such an admin can manage clients but is refused when listing them.
services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java:77
The removal listener now runs only when V1 `ADMIN_FINE_GRAINED_AUTHZ` is enabled. That avoids the new UnsupportedOperationException from `ClientPermissionsV2.setPermissionsEnabled`, but nothing in V2 replaces the cleanup. When a client is deleted, its per-client resource (named after the client id) and its permissions stay behind in the realm's admin-permissions resource server, and the stale data builds up over time.
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:214
If the per-client resource is missing and `getResourceTypeResource` returns null (for example, the schema isn't supported for this server or the 'Clients' type resource hasn't been created yet), `findByResource(server, null)` and then `resource.getScopes()` throw a NullPointerException instead of returning false. Unlike the user V2 version, the per-client branch also never checks that each returned permission's resourceId matches the evaluated resource.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d3 medium ✓ exact
valid · impact medium
init() returns early when the admin-permissions client already exists, so realms initialized before this change never get the new Clients resource or the new configure/map-roles-* scopes. Adding the new resource type without reconciling existing realms is what causes this. [grounded: tree server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java] [consensus 5/5: valid=5]
invalid
ResourceServerAdapter.getClientId() returns getId(), so server.getId() and server.getClientId() are the same value. The lookup therefore matches the owner used when the resource was created. [invalid: contradiction] [consensus 5/5: invalid=5]
valid · impact low
getResourceName only special-cases USERS. Client resources are created with only a name (no display name), so they fall through to a null display name. This is an incomplete change: the Clients type was added to getOrCreateResource but not here. [grounded: tree server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java] [consensus 5/5: valid=5]
valid · matches d3 · impact medium
valid · impact medium
The all-clients resource is evaluated only when no per-client resource exists. Per-client resources are created without a type, so DefaultPolicyEvaluator does not pull in type-level policies. As a result, an all-clients MANAGE grant is ignored for a client that only has, for example, a per-client VIEW permission, which contradicts the javadoc saying all-clients permission also grants. [grounded: diff] [consensus 5/5: valid=5]
raw comments (6)
server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:68
<!-- cubic:v=f19a8d40-1e1a-4720-972d-25e0df799202 --> <!-- cubic:review-run=32945b70-1943-52e6-bdc0-4dff2a30fc2a --> <!-- metadata:{"confidence":9} --> P1: When an existing realm already has the admin-permissions client, `init()` skips the newly added client scopes and `Clients` resource, so client permissions cannot be created after upgrade. Reconcile missing schema scopes and resources even when the client already exists. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java, line 68: <comment>When an existing realm already has the admin-permissions client, `init()` skips the newly added client scopes and `Clients` resource, so client permissions cannot be created after upgrade. Reconcile missing schema scopes and resources even when the client already exists.</comment> <file context> @@ -50,22 +50,27 @@ + public static final String MAP_ROLES_COMPOSITE = "map-roles-composite"; public static final ResourceType USERS = new ResourceType(USERS_RESOURCE_TYPE, Set.of(MANAGE, VIEW, IMPERSONATE, MAP_ROLES, MANAGE_GROUP_MEMBERSHIP)); + public static final ResourceType CLIENTS = new ResourceType(CLIENTS_RESOURCE_TYPE, Set.of(CONFIGURE, MANAGE, MAP_ROLES, MAP_ROLES_CLIENT_SCOPE, MAP_ROLES_COMPOSITE, VIEW)); public static final AdminPermissionsSchema SCHEMA = new AdminPermissionsSchema(); </file context> ``` </details>
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:214
<!-- cubic:v=7a335443-46f4-4eaa-b37a-caefe4f36178 --> <!-- cubic:review-run=32945b70-1943-52e6-bdc0-4dff2a30fc2a --> <!-- metadata:{"confidence":9} --> P1: Per-client permission checks never find schema-created client resources because the lookup uses the resource-server ID instead of the owner used when creating them. Use `server.getClientId()` here so client-specific grants are evaluated. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java, line 214: <comment>Per-client permission checks never find schema-created client resources because the lookup uses the resource-server ID instead of the owner used when creating them. Use `server.getClientId()` here so client-specific grants are evaluated.</comment> <file context> @@ -0,0 +1,287 @@ + ResourceServer server = root.realmResourceServer(); + if (server == null) return false; + + Resource resource = resourceStore.findByName(server, client.getId(), server.getId()); + if (resource == null) { + // check if there is permission for "all-clients". If so, load its resource and proceed with evaluation </file context> ``` </details>
server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:94
<!-- cubic:v=78e1a1d1-a7b9-40ed-8760-6e6499b7b7af --> <!-- cubic:review-run=32945b70-1943-52e6-bdc0-4dff2a30fc2a --> <!-- metadata:{"confidence":8} --> P2: When a client resource appears in a policy response, `getResourceName()` falls through to `resource.getDisplayName()`, which is null for resources created here. Add a `Clients` branch that resolves the internal ID to the client’s `clientId` (or otherwise sets a display name). <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java, line 94: <comment>When a client resource appears in a policy response, `getResourceName()` falls through to `resource.getDisplayName()`, which is null for resources created here. Add a `Clients` branch that resolves the internal ID to the client’s `clientId` (or otherwise sets a display name).</comment> <file context> @@ -85,6 +90,8 @@ public Resource getOrCreateResource(KeycloakSession session, ResourceServer reso if (USERS.getType().equals(resourceType)) { name = resolveUser(session, id); + } else if (CLIENTS.getType().equals(resourceType)) { + name = resolveClient(session, id); } </file context> ``` </details>
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:138
<!-- cubic:v=88bd19c3-7759-459d-ae5a-4bed01997826 --> <!-- cubic:review-run=32945b70-1943-52e6-bdc0-4dff2a30fc2a --> <!-- metadata:{"confidence":10} --> P2: `getClientsWithPermission` omits client-specific grants and returns `Clients` for an aggregate grant, so role-mapping callers receive no usable client IDs under V2. Enumerate the per-client resources and expand an all-clients grant to the realm’s actual client IDs before returning this set. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java, line 138: <comment>`getClientsWithPermission` omits client-specific grants and returns `Clients` for an aggregate grant, so role-mapping callers receive no usable client IDs under V2. Enumerate the per-client resources and expand an all-clients grant to the realm’s actual client IDs before returning this set.</comment> <file context> @@ -0,0 +1,287 @@ + + Set<String> granted = new HashSet<>(); + + resourceStore.findByType(server, AdminPermissionsSchema.CLIENTS_RESOURCE_TYPE, resource -> { + if (hasGrantedPermission(resource, scope)) { + granted.add(resource.getName()); </file context> ``` </details>
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:215
<!-- cubic:v=890615e7-4009-4a12-aae4-ec7600ee93f5 --> <!-- cubic:review-run=32945b70-1943-52e6-bdc0-4dff2a30fc2a --> <!-- metadata:{"confidence":9} --> P2: When a client has any per-client resource, an all-clients `VIEW`, `MANAGE`, or other scope grant is ignored for that client. Evaluate the all-clients resource as an additional grant instead of using it only when the per-client resource is absent. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java, line 215: <comment>When a client has any per-client resource, an all-clients `VIEW`, `MANAGE`, or other scope grant is ignored for that client. Evaluate the all-clients resource as an additional grant instead of using it only when the per-client resource is absent.</comment> <file context> @@ -0,0 +1,287 @@ + if (server == null) return false; + + Resource resource = resourceStore.findByName(server, client.getId(), server.getId()); + if (resource == null) { + // check if there is permission for "all-clients". If so, load its resource and proceed with evaluation + resource = AdminPermissionsSchema.SCHEMA.getResourceTypeResource(session, server, AdminPermissionsSchema.CLIENTS_RESOURCE_TYPE); </file context> ``` </details>
PR-level
<!-- cubic:review-summary:start --> **5 issues found** across 10 files <!-- cubic:review-summary:end --> <details> <summary>Prompt for AI agents (unresolved issues)</summary> ```text Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately. <file name="server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java"> <violation number="1" location="server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:68"> P1: When an existing realm already has the admin-permissions client, `init()` skips the newly added client scopes and `Clients` resource, so client permissions cannot be created after upgrade. Reconcile missing schema scopes and resources even when the client already exists.</violation> <violation number="2" location="server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:94"> P2: When a client resource appears in a policy response, `getResourceName()` falls through to `resource.getDisplayName()`, which is null for resources created here. Add a `Clients` branch that resolves the internal ID to the client’s `clientId` (or otherwise sets a display name).</violation> </file> <file name="services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java"> <violation number="1" location="services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:138"> P2: `getClientsWithPermission` omits client-specific grants and returns `Clients` for an aggregate grant, so role-mapping callers receive no usable client IDs under V2. Enumerate the per-client resources and expand an all-clients grant to the realm’s actual client IDs before returning this set.</violation> <violation number="2" location="services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:214"> P1: Per-client permission checks never find schema-created client resources because the lookup uses the resource-server ID instead of the owner used when creating them. Use `server.getClientId()` here so client-specific grants are evaluated.</violation> <violation number="3" location="services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:215"> P2: When a client has any per-client resource, an all-clients `VIEW`, `MANAGE`, or other scope grant is ignored for that client. Evaluate the all-clients resource as an additional grant instead of using it only when the per-client resource is absent.</violation> </file> ``` </details> <sub>Reply with feedback, questions, or to request a fix.<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/91/ai_pr_review_github_delivery_d316f9d3353e104334bb6c5b82fe9dc98491ba75edf25346771e2c1d4b1715c8?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F91)</sub> <!-- cubic:review-post:ai_pr_review_github_delivery_d316f9d3353e104334bb6c5b82fe9dc98491ba75edf25346771e2c1d4b1715c8:1329955dc7a097a6164e8ceb195992825bab39be:32945b70-1943-52e6-bdc0-4dff2a30fc2a -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d3 medium ✓ exact
valid · impact high
AbstractTokenExchangeProvider:276 calls AdminPermissions.management(session, realm).clients().canExchangeTo(...). With V2 enabled, MgmtPermissionsV2.clients() now returns ClientPermissionsV2, whose canExchangeTo throws. Before this change it fell back to the V1 implementation. [grounded: diff] [consensus 5/5: valid=5]
valid · impact medium
V2 canView() ignores MANAGE, but canManageClientScopes() accepts it. ClientScopesResource.getClientScopes gates on requireListClientScopes and canViewClientScopes, which both delegate to canView(). So an all-clients manage admin can create client scopes but cannot list them. [grounded: diff] [consensus 5/5: valid=5]
valid · impact low
The change added the CLIENTS resource type but left getResourceName handling only USERS. PolicyResourceService uses it to set the display name, so client resources fall back to getDisplayName(), which is never set when the resource is created. This is an incomplete change with only display impact. [grounded: tree server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java] [consensus 5/5: valid=5]
valid · matches d3 · impact medium
raw comments (5)
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:150
### Token exchange throws in V2 **High Severity** <!-- DESCRIPTION START --> `canExchangeTo` always throws `UnsupportedOperationException` under FGAP V2. Token exchange still calls this path when a client exchanges to another audience, so those requests fail with a server error instead of being denied or evaluated. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: 1a57e0a1-1345-443e-8d0b-097108450e1e --> <!-- LOCATIONS START services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java#L146-L150 LOCATIONS END --> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjcyNzM2OGRiLWIxMDgtNDhmMy1iZDNhLTRiZmUyMjFiODM4MyIsImVuY3J5cHRpb25LZXkiOiJOUkhpRW5ZMlRuNHR0UGJiVU5fdmtjVmtGSGMtdE5VMGV3UEkxWXd5YWs0IiwiYnJhbmNoIjoidDIta2V5Y2xvYWstMzY4ODAiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjcyNzM2OGRiLWIxMDgtNDhmMy1iZDNhLTRiZmUyMjFiODM4MyIsImVuY3J5cHRpb25LZXkiOiJOUkhpRW5ZMlRuNHR0UGJiVU5fdmtjVmtGSGMtdE5VMGV3UEkxWXd5YWs0IiwiYnJhbmNoIjoidDIta2V5Y2xvYWstMzY4ODAiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByTnVtYmVyIjo1MywiY29tbWl0U2hhIjoiNDE5NTc4MDFlZTFlNjc2NTZjZTc4MjMzMGNhYmMyZDNhMDllYzEzZSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 41957801ee1e67656ce782330cabc2d3a09ec13e. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:88
### Manage permission does not imply view **Medium Severity** <!-- DESCRIPTION START --> Global `canView()` only checks the `view` scope, not `manage`. Realm-level client-scope listing uses `canViewClientScopes()`, which delegates to `canView()`, so an admin granted all-clients `manage` can create client scopes but cannot list them. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: e2630ac1-e689-4f2b-9c24-7b3558793d47 --> <!-- LOCATIONS START services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java#L84-L88 LOCATIONS END --> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjMxOWZjYTA5LWQxZDctNGYxYS1iNmJlLTM3NDRlMGRlMTMyOSIsImVuY3J5cHRpb25LZXkiOiI1UlRvaEJpN1FyRGQzcS1xWlBWQkxJaXIyM1dES2NsU3dsc252NjhZb3B3IiwiYnJhbmNoIjoidDIta2V5Y2xvYWstMzY4ODAiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjMxOWZjYTA5LWQxZDctNGYxYS1iNmJlLTM3NDRlMGRlMTMyOSIsImVuY3J5cHRpb25LZXkiOiI1UlRvaEJpN1FyRGQzcS1xWlBWQkxJaXIyM1dES2NsU3dsc252NjhZb3B3IiwiYnJhbmNoIjoidDIta2V5Y2xvYWstMzY4ODAiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByTnVtYmVyIjo1MywiY29tbWl0U2hhIjoiNDE5NTc4MDFlZTFlNjc2NTZjZTc4MjMzMGNhYmMyZDNhMDllYzEzZSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 41957801ee1e67656ce782330cabc2d3a09ec13e. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:185
### Client resource names not resolved **Medium Severity** <!-- DESCRIPTION START --> `getResourceName` still only special-cases `Users`. Client permission resources fall through to `getDisplayName()`, which is never set, so the admin API shows empty names instead of the client id or an all-clients label. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: 375e6524-9933-4d7f-a88a-acba69261190 --> <!-- LOCATIONS START server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java#L303-L326 LOCATIONS END --> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjQzNWZhZjgzLTNhZmYtNGFhOS1hZjRiLWJhY2FjYWE4MTk0NCIsImVuY3J5cHRpb25LZXkiOiI4Y1pNeFdGMUVVdl9xaUszNVFyd2Y1V09NcGxBLVVkdXF4WEF2TElMaHJJIiwiYnJhbmNoIjoidDIta2V5Y2xvYWstMzY4ODAiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjQzNWZhZjgzLTNhZmYtNGFhOS1hZjRiLWJhY2FjYWE4MTk0NCIsImVuY3J5cHRpb25LZXkiOiI4Y1pNeFdGMUVVdl9xaUszNVFyd2Y1V09NcGxBLVVkdXF4WEF2TElMaHJJIiwiYnJhbmNoIjoidDIta2V5Y2xvYWstMzY4ODAiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByTnVtYmVyIjo1MywiY29tbWl0U2hhIjoiNDE5NTc4MDFlZTFlNjc2NTZjZTc4MjMzMGNhYmMyZDNhMDllYzEzZSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 41957801ee1e67656ce782330cabc2d3a09ec13e. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:145
### Client permission lookup misses instances **Medium Severity** <!-- DESCRIPTION START --> `getClientsWithPermission` finds resources by type `Clients`, but `getOrCreateResource` never sets that type on per-client resources. The query therefore misses granted clients and can return the type-wide resource named `Clients` as if it were a client id. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: aba75b88-b690-4d8a-85d3-a5bd3b0e717f --> <!-- LOCATIONS START services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java#L124-L145 server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java#L102-L110 LOCATIONS END --> <details> <summary>Additional Locations (1)</summary> - [`server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java#L102-L110`](https://github.com/drape-io/crbench-cursor-2026-09/blob/41957801ee1e67656ce782330cabc2d3a09ec13e/server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java#L102-L110) </details> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjMxMzVkNGM4LTI1OGYtNGNiMy1iYWIzLTUwZTZhMTY2YTQ4MyIsImVuY3J5cHRpb25LZXkiOiJjODBGOG9VQnVuZGpOXzVnQ0h5ZEljOG80Q2Zwc1VoZ3VZOUJJNkJEaUxnIiwiYnJhbmNoIjoidDIta2V5Y2xvYWstMzY4ODAiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjMxMzVkNGM4LTI1OGYtNGNiMy1iYWIzLTUwZTZhMTY2YTQ4MyIsImVuY3J5cHRpb25LZXkiOiJjODBGOG9VQnVuZGpOXzVnQ0h5ZEljOG80Q2Zwc1VoZ3VZOUJJNkJEaUxnIiwiYnJhbmNoIjoidDIta2V5Y2xvYWstMzY4ODAiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByTnVtYmVyIjo1MywiY29tbWl0U2hhIjoiNDE5NTc4MDFlZTFlNjc2NTZjZTc4MjMzMGNhYmMyZDNhMDllYzEzZSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 41957801ee1e67656ce782330cabc2d3a09ec13e. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
PR-level
<!-- BUGBOT_REVIEW --> Cursor Bugbot has reviewed your changes using high effort and found 4 potential issues. <!-- BUGBOT_FIX_ALL --> <a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aTphOTZjNWQwOC0wYTY1LTRmZmMtODE2Ny05MDZlNGZhNGQyMjMiLCJlbmNyeXB0aW9uS2V5IjoiRzJJRDItWEQ2WndlamROUmVOd2dmeThDZ1RGcTR1cjRXbklpcklqZGFEVSIsImJyYW5jaCI6InQyLWtleWNsb2FrLTM2ODgwIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <!-- /BUGBOT_FIX_ALL --> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN --> <sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END --> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 41957801ee1e67656ce782330cabc2d3a09ec13e. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d3 medium ✗ —
valid · impact medium
init() returns early for realms that already have an admin-permissions client, so those realms have no 'Clients' resource. getResourceTypeResource then returns null, and the store's findByResource calls resource.getId(), which throws a NullPointerException. [grounded: tree services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java] [consensus 3/3: valid=3]
valid · impact medium
Before this change, MgmtPermissionsV2.clients() returned the V1 ClientPermissions, whose canExchangeTo works. It now returns ClientPermissionsV2, which throws, and AbstractTokenExchangeProvider calls canExchangeTo directly. TOKEN_EXCHANGE v1 has no dependency that rules out FGAP v2. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
Each check on a client runs its own full policy evaluation, and getAccess repeats them. This is real redundant work, but it is a performance concern with modest impact. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
This change adds V2 per-client resources named by client ID, but nothing removes them when a client is deleted. ClientApplicationSynchronizer only removes the deleted client's own resource server and its client policies, and the listener is now limited to V1, so the resources and permissions stay behind. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
The change adds the Clients resource type but does not add a matching branch to getResourceName. Client resources are created without a display name, so getDisplayName() returns null for them. [grounded: tree server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java] [consensus 3/3: valid=3]
valid · impact low
In V1, canView() treats manage as implying view, and V2 canView(ClientScopeModel) also accepts MANAGE. V2 canView() checks only VIEW, so an admin with MANAGE on all clients but no roles fails requireViewClientScopes. The javadoc describes this behaviour, but it is still inconsistent with the rest of the code. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
init returns early when the admin-permissions client already exists. Existing realms therefore never get the new configure and map-roles-* scopes, and getOrCreateResource throws for any per-client permission. This only affects an experimental feature. [grounded: tree server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java] [consensus 3/3: valid=3]
raw comments (7)
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:221
**Client permission check crashes when "Clients" resource missing** Realms whose admin-permissions client predates this change (or was imported from such an export) have no "Clients" resource. `getResourceTypeResource` then returns null, and `findByResource(server, null)` throws a NullPointerException, e.g. when a query-clients admin lists clients. Return false when the type resource is null. ``` services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:216 // check if there is permission for "all-clients". If so, load its resource and proceed with evaluation services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:217 resource = AdminPermissionsSchema.SCHEMA.getResourceTypeResource(session, server, AdminPermissionsSchema.CLIENTS_RESOURCE_TYPE); services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:219 if (authz.getStoreFactory().getPolicyStore().findByResource(server, resource).isEmpty()) { services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:220 return false; server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:131 ResourceStore resourceStore = getStoreFactory(session).getResourceStore(); server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:133 return resourceStore.findByName(resourceServer, type.getType()); model/jpa/src/main/java/org/keycloak/authorization/jpa/store/JPAPolicyStore.java:211 public void findByResource(ResourceServer resourceServer, Resource resource, Consumer<Policy> consumer) { model/jpa/src/main/java/org/keycloak/authorization/jpa/store/JPAPolicyStore.java:212 TypedQuery<PolicyEntity> query = entityManager.createNamedQuery("findPolicyIdByResource", PolicyEntity.class); model/jpa/src/main/java/org/keycloak/authorization/jpa/store/JPAPolicyStore.java:214 query.setFlushMode(FlushModeType.COMMIT); model/jpa/src/main/java/org/keycloak/authorization/jpa/store/JPAPolicyStore.java:215 query.setParameter("resourceId", resource.getId()); ```
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:146
**Legacy token exchange crashes under FGAP v2** With token-exchange v1 and fine-grained admin permissions v2 both on, exchanging to another audience client calls `canExchangeTo`, which now throws `UnsupportedOperationException`. The request returns 500 instead of a permission decision. Return false (deny) from `canExchangeTo` in V2 instead of throwing. ``` services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:145 } services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:147 @Override services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:148 public boolean canExchangeTo(ClientModel authorizedClient, ClientModel to, AccessToken token) { services/src/main/java/org/keycloak/services/resources/admin/permissions/MgmtPermissionsV2.java:63 @Override common/src/main/java/org/keycloak/common/Profile.java:76 TOKEN_EXCHANGE("Token Exchange Service", Type.PREVIEW, 1), services/src/main/java/org/keycloak/protocol/oidc/tokenexchange/AbstractTokenExchangeProvider.java:276 if (!AdminPermissions.management(session, realm).clients().canExchangeTo(client, targetClient, token)) { ```
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:76
**Client listing repeats policy evaluations per client** `canView(client)` re-evaluates `canView()` plus separate full evaluations for manage, configure and view. `getAccess` then repeats most of them. Each `hasPermission` evaluates every scope of the resource but checks only one. Let `hasPermission` take several scopes (as UserPermissionsV2 does) and evaluate once per client. ``` services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:76 @Override services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:77 public boolean canView(ClientModel client) { services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:78 if (canView() || canConfigure(client)) { services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:79 return true; services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:228 if (expectedScopes.contains(s)) { services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:229 return true; ```
services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java:77
**Deleted clients keep their admin-permission resources** The removal listener now runs only under V1, and nothing removes V2 per-client resources. A deleted client's resource and permissions stay behind, and a client re-created with the same id inherits them. Under V2, on ClientRemovedEvent delete the client's resource and any permissions left empty. ``` services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java:77 if (Profile.isFeatureEnabled(Profile.Feature.ADMIN_FINE_GRAINED_AUTHZ)) { services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java:78 if (event instanceof RoleContainerModel.RoleRemovedEvent) { services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java:79 RoleContainerModel.RoleRemovedEvent cast = (RoleContainerModel.RoleRemovedEvent) event; services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java:80 RoleModel role = cast.getRole(); server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:101 resource = resourceStore.findByName(resourceServer, name); server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:103 if (resource == null) { server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:104 resource = resourceStore.create(resourceServer, name, resourceServer.getClientId()); server-spi-private/src/main/java/org/keycloak/authorization/store/syncronization/ClientApplicationSynchronizer.java:49 private void removeFromClientPolicies(ClientRemovedEvent event, AuthorizationProvider authorizationProvider) { server-spi-private/src/main/java/org/keycloak/authorization/store/syncronization/ClientApplicationSynchronizer.java:50 StoreFactory storeFactory = authorizationProvider.getStoreFactory(); server-spi-private/src/main/java/org/keycloak/authorization/store/syncronization/ClientApplicationSynchronizer.java:51 ResourceServerStore store = storeFactory.getResourceServerStore(); ```
server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:310
**Client permission resources show no display name** `getResourceName` handles only Users, so Clients permission resources (named by client UUID) fall through to a null display name. Add a Clients branch returning "All clients" or the client's clientId. ``` server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:93 } else if (CLIENTS.getType().equals(resourceType)) { server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:94 name = resolveClient(session, id); server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:95 } server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:101 resource = resourceStore.findByName(resourceServer, name); server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:103 if (resource == null) { server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:104 resource = resourceStore.create(resourceServer, name, resourceServer.getClientId()); server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:310 if (USERS.getType().equals(resourceType)) { server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:311 if (resource.getName().equals(USERS_RESOURCE_TYPE)) { server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:312 return "All users"; server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:313 } ```
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:86
**Manage-all-clients admins can't list client scopes** `canView()` checks only the VIEW permission on all clients, not MANAGE. An admin granted MANAGE on all clients passes `canManageClientScopes` but fails `requireListClientScopes` and `requireViewClientScopes`. Elsewhere, manage implies view: both `canViewClientDefault` and `canView(ClientScopeModel)` treat it that way. Also accept `hasPermission(AdminPermissionsSchema.MANAGE)` in `canView()`. ``` services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:85 @Override services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:86 public boolean canView() { services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:87 return canViewClientDefault() || hasPermission(AdminPermissionsSchema.VIEW); services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:88 } services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:105 @Override services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:106 public boolean canManageClientScopes() { services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:107 if (root.hasOneAdminRole(AdminRoles.MANAGE_CLIENTS)) return true; services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:109 return hasPermission(AdminPermissionsSchema.MANAGE); services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:117 @Override services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:118 public boolean canView(ClientScopeModel clientScope) { ```
server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:68
**Client permissions can't be created in existing realms** `init` creates scopes only for a new admin-permissions client, so older realms lack configure, map-roles-client-scope and map-roles-composite. In those realms `getOrCreateResource` throws "No scopes found" for any per-client permission. Have `init` add the missing scopes and type resources to existing realms. ``` server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:63 public static final String CONFIGURE = "configure"; server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:64 public static final String MAP_ROLES_CLIENT_SCOPE = "map-roles-client-scope"; server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:65 public static final String MAP_ROLES_COMPOSITE = "map-roles-composite"; server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:67 public static final ResourceType USERS = new ResourceType(USERS_RESOURCE_TYPE, Set.of(MANAGE, VIEW, IMPERSONATE, MAP_ROLES, MANAGE_GROUP_MEMBERSHIP)); server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:222 public void init(KeycloakSession session, RealmModel realm) { server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:223 ClientProvider clients = session.clients(); server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:224 ClientModel client = realm.getAdminPermissionsClient(); server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:226 if (client != null) { server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:227 return; server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:228 } ```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d3 medium ✓ off by one
valid · impact medium
canList() = canView() || query roles; with only an all-clients MANAGE permission and no query-* role, canView() is false, so requireList() forbids GET /clients. canView(ClientScopeModel) and canView(client) both accept MANAGE, but this method does not. The tests pass only because myadmin has QUERY_USERS. [grounded: diff] [consensus 3/3: valid=3]
valid · impact high
MgmtPermissionsV2.clients() now returns ClientPermissionsV2, whose canExchangeTo throws. AbstractTokenExchangeProvider calls management(...).clients().canExchangeTo(client, targetClient, token) on every exchange to a different client, so token exchange fails with a runtime exception whenever V2 is enabled. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
The change adds the Clients type, and its per-client resources are named by the client UUID, but getResourceName was not given a CLIENTS branch. Those resources therefore fall through to getDisplayName(), which is never set. This is an incomplete change. [grounded: tree server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java] [consensus 3/3: valid=3]
valid · matches d3 · impact medium
valid · impact low
V1 and V2 are versions of the same feature, so they cannot both be on. Under V2 the listener now does nothing, and the change adds no cleanup for the per-client resources it introduces, which are left behind after the client is deleted. [grounded: diff] [consensus 3/4: valid=3, uncertain=1]
valid · impact medium
init() returns early for realms that already have the admin-permissions client, so the new Clients type resource and its new scopes are never created there. getResourceTypeResource then returns null, and that null is passed to findByResource in ClientPermissionsV2.hasPermission without a check. [grounded: tree server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java] [consensus 3/3: valid=3]
raw comments (6)
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:87
**Manage-all-clients permission cannot list clients** `canView()` only checks the VIEW scope on the Clients type resource. A caller granted only MANAGE on all clients fails `canView()`, so `canList()` and `requireList()` deny the clients list. `canView(ClientScopeModel)` accepts VIEW or MANAGE. Make `canView()` also accept `hasPermission(AdminPermissionsSchema.MANAGE)`, as `canView(ClientScopeModel)` does. ``` services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:85 @Override services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:86 public boolean canView() { services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:87 return canViewClientDefault() || hasPermission(AdminPermissionsSchema.VIEW); services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:88 } services/src/main/java/org/keycloak/services/resources/admin/permissions/UserPermissionsV2.java:52 boolean result = hasPermission(user, null, AdminPermissionsSchema.VIEW, AdminPermissionsSchema.MANAGE); ```
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:147
**Token exchange throws UnsupportedOperationException with V2 enabled** `canExchangeTo` now throws in V2, but `AbstractTokenExchangeProvider` calls it for every exchange to a different client. Previously V1 logic ran and returned false/true. Return false (or keep the V1 behavior) instead of throwing. ``` services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:147 @Override services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:148 public boolean canExchangeTo(ClientModel authorizedClient, ClientModel to, AccessToken token) { services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:149 throw new UnsupportedOperationException("Not supported in V2"); services/src/main/java/org/keycloak/services/resources/admin/permissions/MgmtPermissionsV2.java:63 @Override services/src/main/java/org/keycloak/protocol/oidc/tokenexchange/AbstractTokenExchangeProvider.java:276 if (!AdminPermissions.management(session, realm).clients().canExchangeTo(client, targetClient, token)) { ```
server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:304
**Client permissions show no readable resource name** `getResourceName` only maps the Users type. A Clients permission on a specific client falls through to `resource.getDisplayName()`, which is unset because the resource is named by the client id. Add a CLIENTS branch that resolves the client and returns its clientId, and return "All clients" for the type resource. ``` server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:93 } else if (CLIENTS.getType().equals(resourceType)) { server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:94 name = resolveClient(session, id); server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:95 } server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:304 public String getResourceName(KeycloakSession session, Policy policy, Resource resource) { server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:305 ResourceServer resourceServer = policy.getResourceServer(); server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:307 if (supportsAuthorizationSchema(session, resourceServer)) { server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:308 String resourceType = policy.getResourceType(); server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:310 if (USERS.getType().equals(resourceType)) { server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:311 if (resource.getName().equals(USERS_RESOURCE_TYPE)) { server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:312 return "All users"; ```
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:138
**getClientsWithPermission returns "Clients", not client ids** Per-client resources are created without a type, so the findByType("Clients") lookup in ClientPermissionsV2.getClientsWithPermission only finds the all-clients resource. The method then returns the name "Clients" instead of client ids. Set the type on per-client resources, or search by name, and translate the all-clients grant into real ids. ``` services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:125 public Set<String> getClientsWithPermission(String scope) { services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:126 if (!root.isAdminSameRealm()) { services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:127 return Collections.emptySet(); services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:128 } server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:101 resource = resourceStore.findByName(resourceServer, name); server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:103 if (resource == null) { server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:104 resource = resourceStore.create(resourceServer, name, resourceServer.getClientId()); server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:105 ScopeStore scopeStore = storeFactory.getScopeStore(); server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:246 //create 'all-resource' resources defined in the schema server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:247 resourceServerRep.setResources(SCHEMA.getResourceTypes().keySet().stream() ```
services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java:77
**V2 client permissions left behind on delete** The removal listener now only runs when the V1 feature is on. Under V2 (V1 off), deleting a client leaves its per-client resource and permission association orphaned in the admin-permissions server. Add a V2 branch that removes the deleted client's resource. ``` services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java:77 if (Profile.isFeatureEnabled(Profile.Feature.ADMIN_FINE_GRAINED_AUTHZ)) { services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java:78 if (event instanceof RoleContainerModel.RoleRemovedEvent) { services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java:79 RoleContainerModel.RoleRemovedEvent cast = (RoleContainerModel.RoleRemovedEvent) event; services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java:80 RoleModel role = cast.getRole(); common/src/main/java/org/keycloak/common/Profile.java:260 String unversionedFeature = entry.getKey(); common/src/main/java/org/keycloak/common/Profile.java:261 ProfileConfigResolver.FeatureConfig unversionedConfig = getFeatureConfig(unversionedFeature, resolvers); common/src/main/java/org/keycloak/common/Profile.java:262 Feature enabledFeature = null; common/src/main/java/org/keycloak/common/Profile.java:263 if (unversionedConfig == FeatureConfig.ENABLED) { common/src/main/java/org/keycloak/common/Profile.java:264 enabledFeature = entry.getValue().iterator().next(); common/src/main/java/org/keycloak/common/Profile.java:265 if (!enabledFeature.isAvailable()) { ```
server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:222
**Existing realms never get the Clients resource type** `init()` returns early when the admin-permissions client exists, so existing realms never get the new Clients scopes or type resource. `hasPermission(client, ...)` then passes a null type resource to `findByResource`. Create missing scopes and type resources for existing realms, and null-check in `ClientPermissionsV2`. ``` server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:68 public static final ResourceType CLIENTS = new ResourceType(CLIENTS_RESOURCE_TYPE, Set.of(CONFIGURE, MANAGE, MAP_ROLES, MAP_ROLES_CLIENT_SCOPE, MAP_ROLES_COMPOSITE, VIEW)); server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:70 public static final AdminPermissionsSchema SCHEMA = new AdminPermissionsSchema(); server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:72 private AdminPermissionsSchema() { server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:73 super(Map.of(USERS_RESOURCE_TYPE, USERS, CLIENTS_RESOURCE_TYPE, CLIENTS)); server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:116 public Resource getResourceTypeResource(KeycloakSession session, ResourceServer resourceServer, String resourceType) { server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:117 if (!supportsAuthorizationSchema(session, resourceServer)) { server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:118 return null; server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:119 } server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:121 if (resourceType == null) { server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java:122 return null; ```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d3 medium ✓ off by one
valid · impact medium
The new hasPermission(ClientModel, String) falls back to the 'Clients' type resource only when no per-client resource exists. A per-client resource gets created whenever any permission names that client, and getOrCreateResource never sets a type on it. DefaultPolicyEvaluator only adds resource-type policies when resource.getType() != null, so once such a resource exists the all-clients grant is never evaluated for that client. A per-client permission with a different scope or for a different admin can therefore hide a valid all-clients grant. This is new code in ClientPermissionsV2. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d3 · impact medium
raw comments (3)
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:222
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Type Grant Gets Masked** When an individual client resource exists but lacks the requested scope, this code evaluates only that resource and never evaluates the `Clients` type resource. Individual resources can exist independently of the requested grant, while all-client grants are expected to authorize operations on existing clients. A narrower permission can therefore mask a valid all-client grant and cause an authorized operation to return forbidden.
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:141
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Synthetic Resource Becomes Client** This type query also returns the synthetic `Clients` resource, and the code adds its name to a set that callers treat as internal client IDs. For an all-clients mapping grant, `AvailableRoleMappingResource` passes `"Clients"` to `realm.getClientById(...)` and immediately dereferences the null result, causing the available-role-mapping request to fail with a null-pointer error.
PR-level
<h3>Greptile Summary</h3> This PR adds fine-grained V2 authorization for client resources and scopes, wires the implementation into V2 permission management, and expands authorization integration tests. - Adds the Clients resource type and client-specific authorization scopes. - Implements object-level and resource-type-level client permission evaluation. - Adds coverage for managing, configuring, viewing, and mapping roles for clients. - Contains two authorization/listing defects involving coexistence of individual and type resources. <h3>Confidence Score: 3/5</h3> The PR is not safe to merge because valid all-client grants can be denied and all-client role-mapping grants can crash the available-role-mapping endpoint. The evaluator incorrectly treats individual and type-level resources as mutually exclusive, while client enumeration returns a synthetic authorization resource as though it were a real client ID. **Files Needing Attention:** services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java <details><summary><h3>Important Files Changed</h3></summary> | Filename | Overview | |----------|----------| | services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java | Adds V2 client authorization evaluation, but individual resources can mask type-level grants and synthetic type resources leak into client-ID results. | | server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java | Extends the schema with client resources and scopes; its synthetic type-resource representation exposes an assumption violated by client enumeration. | | services/src/main/java/org/keycloak/services/resources/admin/permissions/MgmtPermissionsV2.java | Wires the new client permission evaluator into V2 management. | | tests/base/src/test/java/org/keycloak/tests/admin/authz/fgap/PermissionClientTest.java | Adds broad client-authorization coverage but does not exercise coexistence of type-level and individual resources or synthetic-resource enumeration. | </details> <details open><summary><h3>Flowchart</h3></summary> ```mermaid %%{init: {'theme': 'neutral'}}%% flowchart TD A[Client authorization check] --> B{Individual client resource exists?} B -->|Yes| C[Evaluate only individual resource] B -->|No| D[Evaluate Clients type resource] C --> E{Requested scope granted?} D --> E E -->|Yes| F[Allow operation] E -->|No| G[Deny operation] H[Clients type query] --> I[Individual client resources] H --> J[Synthetic Clients resource] I --> K[Return resource names as client IDs] J --> K K --> L[AvailableRoleMappingResource] ``` </details> <!-- greptile_other_comments_section --> <sub>Reviews (1): Last reviewed commit: ["Update server-spi-private/src/main/java/..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/8460d9a417f62c0703ce9f986ff42d7b1c89d198) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64288988)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d3 medium ✓ off by one
valid · impact medium
AbstractTokenExchangeProvider:276 calls clients().canExchangeTo(client, targetClient, token) for any cross-client exchange. In Profile, TOKEN_EXCHANGE v1 has no dependency on FGAP, so it can be enabled alongside FGAP v2. Before this change MgmtPermissionsV2.clients() returned the base ClientPermissions, which denied the exchange with a 403. Now ClientPermissionsV2 throws, which results in a 500. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
getOrCreateResource never sets a type on per-client resources, so findByType matches only the all-clients resource and returns its name, "Clients", rather than client IDs. That is wrong, but the only caller (AvailableRoleMappingResource) reaches this method only when FGAP v1 is enabled. v1 and v2 are versions of the same feature and cannot both be on, so the NPE cannot happen today. [grounded: diff] [consensus 3/5: valid=3, invalid=2]
valid · impact medium
The new V2 canView() checks only the VIEW scope, so an admin with an all-clients MANAGE grant gets false. canList() and requireList() then fail unless the admin also holds a query role. The test admin passes only because it has QUERY_USERS. This is also inconsistent with canView(ClientScopeModel), which accepts VIEW or MANAGE. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d3 · impact medium
raw comments (4)
PR-level
[P2] V2 `canExchangeTo` now throws instead of denying token exchange services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:147-150 `AbstractTokenExchangeProvider` (line 276) calls `AdminPermissions.management(session, realm).clients().canExchangeTo(client, targetClient, token)` for any cross-client exchange. When FGAP v2 is enabled, `clients()` now returns `ClientPermissionsV2`, and that method throws `UnsupportedOperationException`. The legacy `token-exchange` (v1) feature does not depend on `admin-fine-grained-authz` in `Profile`, so it can be enabled alongside `admin-fine-grained-authz:v2`. In that setup, a client exchanging a token for another audience used to get a 403 from the inherited v1 logic, because no `client.resource.‹id›` resource exists in the admin-permissions resource server. After this change the same request fails with an internal server error. Returning `false`, or otherwise mapping the call to a denial, would keep the token endpoint returning a proper error response.
PR-level
[P3] V2 `getClientsWithPermission` returns the "Clients" type resource name, not client IDs services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:137-141 Per-client resources created by `AdminPermissionsSchema.getOrCreateResource` never get a type set. The only resource with type `Clients` is the all-clients resource created in `init`, and its name is `"Clients"`. So `findByType(server, CLIENTS_RESOURCE_TYPE, ...)` skips every per-client grant and, when an all-clients permission applies, returns the literal string `"Clients"` as if it were a client ID. The only current caller, `AvailableRoleMappingResource.getRoleIdsWithPermissions`, runs `realm.getClientById(cid).getRolesStream()` on each result, so it would hit an NPE there. That path is currently gated on the v1 feature flag, so this override can't be reached today, but it is incorrect as written and will break as soon as the role-mapping UI is wired up for v2.
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:85
[P2] `canView()` doesn't count an all-clients MANAGE permission as view access In V2, an admin can be granted MANAGE on all clients (through the `Clients` resource type) and still get `false` from `canView()`, because it only checks the VIEW scope. Anything gated on `canView()`, `canList()` or `requireView()` then denies that admin even though they can create, update and delete every client. `ClientsResource.getClients` calls `requireList()` and returns 403 unless the admin also has query-clients. Without query-clients, `ClientInitialAccessResource` (`requireView()`) is also forbidden. Even when listing does work, it falls back to checking each client and paginating in memory, because `canView` is false. This doesn't match the rest of the change: `canView(ClientScopeModel)` in the same class accepts VIEW or MANAGE, and in V1 the manage-clients role already implies view. `canView()` should also accept `hasPermission(AdminPermissionsSchema.MANAGE)`.
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:138
[P3] `getClientsWithPermission` finds only the all-clients resource and returns `"Clients"` instead of client IDs `resourceStore.findByType(server, "Clients")` only matches the all-clients resource that `AdminPermissionsSchema.init` creates with `setType(type)`. Per-client resources come from `getOrCreateResource`, which never sets a type, so per-client grants are never found. When the all-clients permission is granted, the method returns the set `{"Clients"}`, which is the resource name and not a client ID. The only caller, `AvailableRoleMappingResource.getRoleIdsWithPermissions`, passes each returned ID to `realm.getClientById(cid).getRolesStream()`, which would throw a `NullPointerException` on `"Clients"`. Today that path only runs when V1 is enabled, so this V2 override can't be reached yet, but the override is wrong as written.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d3 medium ✓ exact
invalid
ADMIN_FINE_GRAINED_AUTHZ (v1) and ADMIN_FINE_GRAINED_AUTHZ_V2 (v2) are versions of the same unversioned feature, and Profile only allows one version to be enabled. So the 'both enabled' trigger can't happen: with V2 on, the V1 gate skips the listener, and with V1 on, management() returns V1. [invalid: contradiction] [consensus 3/3: invalid=3]
valid · impact medium
V1TokenExchangeProviderFactory is enabled only by TOKEN_EXCHANGE, which does not depend on FGAP v1. It inherits AbstractTokenExchangeProvider line 276, which calls management().clients().canExchangeTo(...). Under FGAP V2 that now goes to ClientPermissionsV2, which throws unconditionally. Before this change, the inherited V1 ClientPermissions returned a boolean. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d3 · impact medium
raw comments (3)
services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java:77
[P2] Client removal now throws when V1 and V2 FGAP are both enabled The listener is now gated on `ADMIN_FINE_GRAINED_AUTHZ` (V1), but `management()` picks `MgmtPermissionsV2` whenever `ADMIN_FINE_GRAINED_AUTHZ_V2` is on, and V2 does not depend on V1 (`Profile.java`). With both features enabled, deleting a client fires `ClientRemovedEvent`. That calls `clients().setPermissionsEnabled(...)`, which now resolves to `ClientPermissionsV2` and throws `UnsupportedOperationException("Not supported in V2")`, so the client delete fails. Before this change the V1 `ClientPermissions` implementation was used and the delete succeeded. The gate should key off V2 being disabled, or the V2 class should no-op for the removal case.
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:141
[P2] Legacy client token exchange throws UnsupportedOperationException under V2 `canExchangeTo(client, to, token)` now throws unconditionally. `AbstractTokenExchangeProvider` (line 276) calls `AdminPermissions.management(session, realm).clients().canExchangeTo(...)` on every exchange to a target client. When `ADMIN_FINE_GRAINED_AUTHZ_V2` and `TOKEN_EXCHANGE` are both enabled, any client-to-client token exchange now returns a 500 instead of a permission decision. Before this change, `MgmtPermissionsV2` inherited the V1 `ClientPermissions`, which evaluated the exchange permission. Return false (deny), or fall back to the V1 behaviour, rather than throwing.
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:138
[P2] getClientsWithPermission searches for resources that are never typed The method calls `resourceStore.findByType(server, "Clients", ...)` and returns `resource.getName()`. In V2, per-client resources come from `AdminPermissionsSchema.getOrCreateResource`, which calls `resourceStore.create(...)` and never `setType`. Only the "Clients" all-clients resource created in `init` has that type. If the caller has a granted scope on all clients, the method returns the literal string "Clients" instead of client UUIDs. Per-client grants are never returned. The only caller, `AvailableRoleMappingResource.getRoleIdsWithPermissions`, then does `realm.getClientById(cid).getRolesStream()` and would throw an NPE for "Clients". That caller is only reached when V1 is also enabled, so this is limited to configurations with both features on. Even so, the result is wrong. It should enumerate the per-client resources, for example by owner/name, and exclude the type resource
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d3 medium ✓ off by one
valid · impact medium
RolePermissions.canMapRole returns true right away when root.clients().canMapRoles(container) is true, and it skips checkAdminRoles. V1 has the same shortcut, but V2 now grants that check through new schema permissions, including a single 'all clients' grant that also covers realm-management. So a delegated admin can map protected admin roles without holding them. [grounded: diff] [consensus 3/4: valid=3, invalid=1]
invalid
ResourceServerAdapter.getClientId() returns getId(), and the JPA store sets the entity id to the client id. So server.getId() and server.getClientId() are the same value, the owner matches, and the lookup finds the resource. [invalid: contradiction] [consensus 3/3: invalid=3]
valid · matches d3 · impact medium
valid · impact medium
AbstractTokenExchangeProvider line 276 calls AdminPermissions.management(...).clients().canExchangeTo(...) for every cross-client audience. With V2 enabled, that call now reaches ClientPermissionsV2, which throws. The legacy TOKEN_EXCHANGE feature does not depend on FGAP v1, so token exchange plus FGAP v2 is a valid setup, and the request fails with an internal error instead of a 403. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
The listener now runs only when V1 is enabled. V1 and V2 share a feature key and cannot both be enabled, so with V2 on, removal events do nothing. Meanwhile the new CLIENTS schema creates per-client resources and permissions that are never cleaned up when the client is deleted. [grounded: diff] [consensus 3/3: valid=3]
invalid
ADMIN_FINE_GRAINED_AUTHZ and ADMIN_FINE_GRAINED_AUTHZ_V2 are versions 1 and 2 of the same feature key, and Keycloak allows only one version of a feature at a time. The 'both enabled' setup the finding depends on cannot happen. [invalid: contradiction] [consensus 3/3: invalid=3]
raw comments (8)
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:93
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 1\. Delegated admins gain realm control <code>🐞 Bug</code> <code>⛨ Security</code> <pre> <b><i>canMapRoles</i></b> accepts a client-level permission without applying the protected-role validation in <b><i>RolePermissions.checkAdminRoles</i></b>. An administrator delegated mapping permission over a user and the realm-management client can therefore assign protected roles such as <b><i>manage-realm</i></b> even when the caller does not hold those privileges. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description V2 client-level role-mapping permissions return success before `RolePermissions.checkAdminRoles` verifies that the caller may delegate protected realm-management roles, enabling privilege escalation. ## Fix Focus Areas - services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java[91-98] - services/src/main/java/org/keycloak/services/resources/admin/permissions/RolePermissions.java[301-325] - services/src/main/java/org/keycloak/services/resources/admin/permissions/RolePermissions.java[391-418] - tests/base/src/test/java/org/keycloak/tests/admin/authz/fgap/PermissionClientTest.java[325-365] ## Recommended Fix When a client-level mapping permission succeeds, require `checkAdminRoles(role)` before authorizing direct role mapping or composite mapping. Add V2 tests proving that a caller without the corresponding realm privilege cannot map protected realm-management roles despite holding client and target-user mapping permissions. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:214
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 2\. Fine-grained client grants never authorize users <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> <b><i>ClientPermissionsV2.hasPermission(ClientModel, String)</i></b> looks up the client resource with <b><i>server.getId()</i></b> as its owner, although schema-created resources are owned by <b><i>resourceServer.getClientId()</i></b>. Every per-client check misses its resource and falls back to the all-clients resource, so a grant such as the new single-client manage or configure permission is denied when no all-clients policy exists. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` Issue description Client permission lookups use the resource-server ID as the resource owner, but resources created by the admin-permissions schema use the resource-server client ID. This prevents individual client grants, and the all-clients lookup has the same owner mismatch. Fix Focus Areas - services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2[214-244] - server-spi-private/src/main/java/org/keycloak/authorization/store/ResourceStore[135-154] Recommended Fix Use the two-argument `findByName(server, name)` overload, or pass `server.getClientId()` as the owner, for both the individual-client and all-clients lookups. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:141
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 3\. Role mapping crashes for all-client grants <code>🐞 Bug</code> <code>☼ Reliability</code> <pre> <b><i>getClientsWithPermission</i></b> filters on the <b><i>Clients</i></b> resource type and adds each resource name as though it were an internal client ID, but individual client resources created by the schema have no type while the aggregate resource is named <b><i>Clients</i></b>. A caller granted an all-clients role-mapping scope therefore passes <b><i>Clients</i></b> to <b><i>realm.getClientById()</i></b> and dereferences null, while callers with individual grants receive an empty role list. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` Issue description The V2 role-mapping helper treats resources of type `Clients` as individual clients. The schema assigns that type only to the aggregate all-clients resource, and does not assign a type to resources created for individual clients. Fix Focus Areas - services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2[125-145] - server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java[101-113] - rest/admin-ui-ext/src/main/java/org/keycloak/admin/ui/rest/AvailableRoleMappingResource.java[227-231] Recommended Fix Do not return the aggregate type-resource name as a client ID. Enumerate individual client resources using a reliable discriminator or resolve applicable permissions against real realm clients; expand an all-clients grant to valid client IDs before returning them. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:150
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 4\. Cross-client token exchange returns server errors <code>🐞 Bug</code> <code>☼ Reliability</code> <pre> <b><i>ClientPermissionsV2.canExchangeTo</i></b> unconditionally throws <b><i>UnsupportedOperationException</i></b> instead of returning an authorization decision. When V2 is enabled, the normal token-exchange path invokes this method for every target audience different from the requesting client, so cross-client requests propagate an unchecked internal failure rather than reaching the caller’s normal forbidden response. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description Cross-client token exchange invokes the V2 client evaluator, whose `canExchangeTo` implementation throws an unchecked exception instead of making an authorization decision. This causes ordinary token endpoint requests for another client as audience to fail internally rather than produce the existing forbidden response. ## Fix Focus Areas - services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java[147-150] - services/src/main/java/org/keycloak/protocol/oidc/tokenexchange/AbstractTokenExchangeProvider.java[261-281] ## Recommended Fix Implement `canExchangeTo` using the appropriate V2 token-exchange authorization policy, scope, and evaluation context, with tests for both allowed and denied cross-client exchanges. If token-exchange permissions are not yet supported in V2, return `false` until that support is implemented so the caller produces its normal forbidden response instead of propagating an exception. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java:77
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> 5\. Deleted clients leave authorization records behind <code>🐞 Bug</code> <code>⚙ Maintainability</code> <pre> The revised removal listener performs cleanup only when the V1 feature is enabled, while V2 client policies create schema resources for referenced clients. With V2 enabled alone, deleting a client skips cleanup entirely, leaving its resource and policies in the admin-permissions resource server. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` Issue description The client-removal listener does nothing when only V2 fine-grained authorization is enabled. V2 policy creation can create resources for clients, so deletion leaves stale resources and policies that can no longer be resolved to a client. Fix Focus Areas - services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java[77-96] - server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java[76-113] - server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java[288-301] Recommended Fix Add V2-aware cleanup for client-removal events that deletes policies/resources referencing the deleted client, without calling the V1 `setPermissionsEnabled` API that V2 deliberately does not support. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java:195
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> 6\. Client deletion fails when both versions run <code>🐞 Bug</code> <code>☼ Reliability</code> <pre> When both fine-grained authorization feature flags are enabled, the V1-gated listener calls <b><i>ClientPermissionsV2.setPermissionsEnabled(client, false)</i></b>, which now always throws <b><i>UnsupportedOperationException</i></b>. The V2 selector takes precedence in <b><i>management</i></b>, so deleting any client in that configuration aborts from the removal event instead of completing cleanup. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` Issue description The V1 listener remains active whenever the V1 flag is enabled, but management selects V2 whenever the V2 flag is also enabled. The new V2 client cleanup method throws, so a client removal event fails in a valid dual-feature configuration. Fix Focus Areas - services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java[66-98] - services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java[192-195] Recommended Fix Make removal-event cleanup select an implementation compatible with the active authorization model, and do not invoke the unsupported V1 client permission-management method on the V2 evaluator. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
PR-level
<h3>PR Summary by Qodo</h3> Add fine-grained V2 client administration permissions <code>✨ Enhancement</code> <code>🧪 Tests</code> <code>🕐 40+ Minutes</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <details> <summary>AI Description</summary> <dl> <dd> <br/> ><pre> >• Add client resource types and scopes to fine-grained admin authorization V2. >• Evaluate per-client and all-client grants for administration and role mapping. >• Expand integration coverage and centralize reusable permission-policy test helpers. ></pre> </dd> </dl> </details> <details> <summary>Diagram</summary> <dl> <dd> <br/> ```mermaid graph TD A["Admin Requests"] --> M["Mgmt V2"] --> E["Client Permissions"] --> Z["Authorization Store"] E --> S["Client Schema"] --> C["Client Models"] S --> Z ``` </dd> </dl> </details> <details> <summary>High-Level Assessment</summary> <dl> <dd> <br/> >The following are alternative approaches to this PR: <details> <summary><b>1. Implement the V2 evaluator directly</b></summary> <dl> <dd> - ➕ Avoids inheriting unsupported legacy permission-management methods. - ➕ Keeps V2 behavior isolated from the legacy resource model. - ➖ Duplicates shared role checks, list semantics, and require-method behavior. - ➖ Requires broader service wiring and increases this PR&#x27;s implementation scope. </dd> </dl> </details> <details> <summary><b>2. Extract a shared V2 resource evaluator</b></summary> <dl> <dd> - ➕ Could reuse policy evaluation across user, client, and future resource types. - ➕ Would centralize per-resource and resource-type permission fallback logic. - ➖ Introduces a larger cross-cutting refactor alongside the client feature. - ➖ May over-generalize before additional resource types establish stable requirements. </dd> </dl> </details> >**Recommendation:** Extending the existing client evaluator is the best incremental approach because it preserves established admin-role fallbacks and enforcement methods while overriding V2 policy evaluation. If additional V2 resource types are added, extracting the duplicated authorization-store evaluation into a shared V2 base should be considered. </dd> </dl> </details> <details> <summary> Files changed (10) <code> +866 / -138 </code> </summary> <dl> <dd> <br/> <details> <summary>Enhancement (3) <code> +316 / -2 </code></summary> <dl> <dd> <details> <summary>AdminPermissionsSchema.java<code>Define client resources and scopes in the V2 schema</code> <code>+20/-2</code></summary> <br/> >Define client resources and scopes in the V2 schema > ><pre> >• Adds the Clients resource type with configure, manage, view, and role-mapping scopes. Client identifiers can now be resolved by internal ID or client ID when authorization resources are created. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/51/files#diff-cdea184f4d80846b982b9f6c0b523d021733f68015cd75d6a3e27700e3bf6c7c'>server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java</a> </details> <details> <summary>ClientPermissionsV2.java<code>Implement V2 client permission evaluation</code> <code>+287/-0</code></summary> <br/> >Implement V2 client permission evaluation > ><pre> >• Introduces a V2 evaluator for global and per-client manage, configure, view, and role-mapping grants. It evaluates authorization resources and policies while retaining legacy admin-role fallbacks, and explicitly rejects unsupported V1 permission-management APIs. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/51/files#diff-0043415745566c18f268165ee3ce34459eec9f918d6a741e027cfbb26352e6fa'>services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java</a> </details> <details> <summary>MgmtPermissionsV2.java<code>Wire the V2 client permission evaluator</code> <code>+9/-0</code></summary> <br/> >Wire the V2 client permission evaluator > ><pre> >• Adds lazy creation and caching of ClientPermissionsV2 so V2 management requests use the new client authorization behavior. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/51/files#diff-ddfc48829f1ed75f23401f0065e8abaf19809f5c1cb8f2397b4c5733eb4ef91c'>services/src/main/java/org/keycloak/services/resources/admin/permissions/MgmtPermissionsV2.java</a> </details> </dd> </dl> </details> <details> <summary>Bug fix (1) <code> +17 / -15 </code></summary> <dl> <dd> <details> <summary>AdminPermissions.java<code>Limit legacy cleanup listeners to the legacy FGAP feature</code> <code>+17/-15</code></summary> <br/> >Limit legacy cleanup listeners to the legacy FGAP feature > ><pre> >• Guards role, client, and group permission cleanup behind the legacy fine-grained authorization feature. This prevents V2 management from invoking unsupported legacy permission lifecycle operations. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/51/files#diff-a92b9f9a1a007b3924ac2756489c25f9ae8bb1cc92a367a0a839ee2e9b89c998'>services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java</a> </details> </dd> </dl> </details> <details> <summary>Tests (5) <code> +425 / -121 </code></summary> <dl> <dd> <details> <summary>AbstractPermissionTest.java<code>Centralize reusable authorization test helpers</code> <code>+80/-7</code></summary> <br/> >Centralize reusable authorization test helpers > ><pre> >• Refactors permission-resource helpers to accept an explicit managed client. Adds shared builders for user policies, client policies, resource-type permissions, and resource-specific permissions. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/51/files#diff-647cc1cb566cf255ed25e9ccea997c5f9d782a4a15160183886d2437bdbe77b1'>tests/base/src/test/java/org/keycloak/tests/admin/authz/fgap/AbstractPermissionTest.java</a> </details> <details> <summary>PermissionClientTest.java<code>Cover V2 client administration scopes</code> <code>+283/-2</code></summary> <br/> >Cover V2 client administration scopes > ><pre> >• Adds integration tests for per-client manage and configure grants, global manage and view grants, and client role mapping. The tests verify both allowed operations and denied access before or outside each grant. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/51/files#diff-1ad89c79f0c1a0f8c099a78dfd85347298c6018594d3e424f44c4af74a1567d6'>tests/base/src/test/java/org/keycloak/tests/admin/authz/fgap/PermissionClientTest.java</a> </details> <details> <summary>PermissionRESTTest.java<code>Adopt explicit-client permission helpers</code> <code>+4/-4</code></summary> <br/> >Adopt explicit-client permission helpers > ><pre> >• Updates REST permission tests to pass the managed authorization client into the shared permission creation helper. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/51/files#diff-d1a3ba9903f8ad5f777e55e2f4669efbdaa5df579741d126de166304bc39448f'>tests/base/src/test/java/org/keycloak/tests/admin/authz/fgap/PermissionRESTTest.java</a> </details> <details> <summary>UserResourceTypeEvaluationTest.java<code>Reuse generalized resource permission helpers</code> <code>+41/-91</code></summary> <br/> >Reuse generalized resource permission helpers > ><pre> >• Migrates user authorization scenarios to shared policy and resource permission builders. Removes duplicated user-specific helper implementations while preserving evaluation coverage. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/51/files#diff-fde5a7dfe09d86f0252e99baca6831778629e61ffe301e36259b40562000c3e3'>tests/base/src/test/java/org/keycloak/tests/admin/authz/fgap/UserResourceTypeEvaluationTest.java</a> </details> <details> <summary>UserResourceTypePermissionTest.java<code>Update user resource tests for explicit clients</code> <code>+17/-17</code></summary> <br/> >Update user resource tests for explicit clients > ><pre> >• Updates permission lookup, creation, modification, and cleanup calls to use the generalized helpers with an explicit managed client. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/51/files#diff-68bc920fdcce39f226704fa9bbbee06538d727126e6a8afaf97fde5b052eee7e'>tests/base/src/test/java/org/keycloak/tests/admin/authz/fgap/UserResourceTypePermissionTest.java</a> </details> </dd> </dl> </details> <details> <summary>Documentation (1) <code> +108 / -0 </code></summary> <dl> <dd> <details> <summary>ClientPermissionEvaluator.java<code>Document client permission evaluation contracts</code> <code>+108/-0</code></summary> <br/> >Document client permission evaluation contracts > ><pre> >• Adds detailed Javadocs describing admin-role fallbacks, V2 scopes, transitive permissions, and require-method behavior across client and client-scope operations. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/51/files#diff-8cc76b15dc006b29886153ba2f83dc980bb199c5dd36a76cd189560629059f72'>services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionEvaluator.java</a> </details> </dd> </dl> </details> </dd> </dl> </details>
PR-level
<h3>Code Review by Qodo</h3> <code>🐞 Bugs (6)</code> <code>📘 Rule violations (0)</code> <code>📜 Skill insights (0)</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <br/> <img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> <details> <summary> 1. Delegated admins gain realm control <code>🐞 Bug</code> <code>⛨ Security</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>canMapRoles</i></b> accepts a client-level permission without applying the protected-role validation in ><b><i>RolePermissions.checkAdminRoles</i></b>. An administrator delegated mapping permission over a user and the >realm-management client can therefore assign protected roles such as <b><i>manage-realm</i></b> even when the >caller does not hold those privileges. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java[R91-93]](https://github.com/drape-io/crbench-qodo-2026-09/pull/51/files#diff-0043415745566c18f268165ee3ce34459eec9f918d6a741e027cfbb26352e6faR91-R93)</code> > >```diff >+ public boolean canMapRoles(ClientModel client) { >+ return hasPermission(client, AdminPermissionsSchema.MAP_ROLES); >+ } >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The new evaluator returns the client permission directly. <b><i>RolePermissions.canMapRole</i></b> immediately >accepts that result before reaching its protected-role validation, while admin roles such as ><b><i>manage-realm</i></b> are explicitly rejected by that validation when the caller lacks the corresponding >permission; user and client role-mapping endpoints rely on <b><i>requireMapRole</i></b>, making the bypass >reachable. ></pre> > > <code>[services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java[91-98]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java/#L91-L98)</code> > <code>[services/src/main/java/org/keycloak/services/resources/admin/permissions/RolePermissions.java[149-165]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/services/src/main/java/org/keycloak/services/resources/admin/permissions/RolePermissions.java/#L149-L165)</code> > <code>[services/src/main/java/org/keycloak/services/resources/admin/permissions/RolePermissions.java[205-262]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/services/src/main/java/org/keycloak/services/resources/admin/permissions/RolePermissions.java/#L205-L262)</code> > <code>[services/src/main/java/org/keycloak/services/resources/admin/permissions/RolePermissions.java[301-325]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/services/src/main/java/org/keycloak/services/resources/admin/permissions/RolePermissions.java/#L301-L325)</code> > <code>[services/src/main/java/org/keycloak/services/resources/admin/RoleMapperResource.java[271-271]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/services/src/main/java/org/keycloak/services/resources/admin/RoleMapperResource.java/#L271-L271)</code> > <code>[services/src/main/java/org/keycloak/services/resources/admin/ClientRoleMappingsResource.java[175-175]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/services/src/main/java/org/keycloak/services/resources/admin/ClientRoleMappingsResource.java/#L175-L175)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >V2 client-level role-mapping permissions return success before `RolePermissions.checkAdminRoles` verifies that the caller may delegate protected realm-management roles, enabling privilege escalation. > >## Fix Focus Areas >- services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java[91-98] >- services/src/main/java/org/keycloak/services/resources/admin/permissions/RolePermissions.java[301-325] >- services/src/main/java/org/keycloak/services/resources/admin/permissions/RolePermissions.java[391-418] >- tests/base/src/test/java/org/keycloak/tests/admin/authz/fgap/PermissionClientTest.java[325-365] > >## Recommended Fix >When a client-level mapping permission succeeds, require `checkAdminRoles(role)` before authorizing direct role mapping or composite mapping. Add V2 tests proving that a caller without the corresponding realm privilege cannot map protected realm-management roles despite holding client and target-user mapping permissions. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <details> <summary> 2. Fine-grained client grants never authorize users <code>🐞 Bug</code> <code>≡ Correctness</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>ClientPermissionsV2.hasPermission(ClientModel, String)</i></b> looks up the client resource with ><b><i>server.getId()</i></b> as its owner, although schema-created resources are owned by ><b><i>resourceServer.getClientId()</i></b>. Every per-client check misses its resource and falls back to the >all-clients resource, so a grant such as the new single-client manage or configure permission is >denied when no all-clients policy exists. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java[214]](https://github.com/drape-io/crbench-qodo-2026-09/pull/51/files#diff-0043415745566c18f268165ee3ce34459eec9f918d6a741e027cfbb26352e6faR214-R214)</code> > >```diff >+ Resource resource = resourceStore.findByName(server, client.getId(), server.getId()); >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The resource-store API defines its default owner as <b><i>resourceServer.getClientId()</i></b>, and the schema >explicitly creates individual resources with that owner. The new V2 implementation instead supplies ><b><i>server.getId()</i></b> for both lookups, which is the resource-server identifier rather than its owner. ></pre> > > <code>[services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java[207-220]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java/#L207-L220)</code> > <code>[services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java[237-247]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java/#L237-L247)</code> > <code>[server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java[101-110]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java/#L101-L110)</code> > <code>[server-spi-private/src/main/java/org/keycloak/authorization/store/ResourceStore.java[135-154]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/server-spi-private/src/main/java/org/keycloak/authorization/store/ResourceStore.java/#L135-L154)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >Issue description >Client permission lookups use the resource-server ID as the resource owner, but resources created by the admin-permissions schema use the resource-server client ID. This prevents individual client grants, and the all-clients lookup has the same owner mismatch. > >Fix Focus Areas >- services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2[214-244] >- server-spi-private/src/main/java/org/keycloak/authorization/store/ResourceStore[135-154] > >Recommended Fix >Use the two-argument `findByName(server, name)` overload, or pass `server.getClientId()` as the owner, for both the individual-client and all-clients lookups. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <details> <summary> 3. Role mapping crashes for all-client grants <code>🐞 Bug</code> <code>☼ Reliability</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>getClientsWithPermission</i></b> filters on the <b><i>Clients</i></b> resource type and adds each resource name as >though it were an internal client ID, but individual client resources created by the schema have no >type while the aggregate resource is named <b><i>Clients</i></b>. A caller granted an all-clients role-mapping >scope therefore passes <b><i>Clients</i></b> to <b><i>realm.getClientById()</i></b> and dereferences null, while callers >with individual grants receive an empty role list. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java[R138-141]](https://github.com/drape-io/crbench-qodo-2026-09/pull/51/files#diff-0043415745566c18f268165ee3ce34459eec9f918d6a741e027cfbb26352e6faR138-R141)</code> > >```diff >+ resourceStore.findByType(server, AdminPermissionsSchema.CLIENTS_RESOURCE_TYPE, resource -> { >+ if (hasGrantedPermission(resource, scope)) { >+ granted.add(resource.getName()); >+ } >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The aggregate schema resource is explicitly created with type and name <b><i>Clients</i></b>; individual >resources are created without <b><i>setType</i></b>. The only consumer treats all returned strings as client IDs >and immediately dereferences the resolved client, making the aggregate name a null-dereference >trigger. ></pre> > > <code>[services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java[125-145]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java/#L125-L145)</code> > <code>[server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java[101-113]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java/#L101-L113)</code> > <code>[server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java[246-254]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java/#L246-L254)</code> > <code>[rest/admin-ui-ext/src/main/java/org/keycloak/admin/ui/rest/AvailableRoleMappingResource.java[227-231]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/rest/admin-ui-ext/src/main/java/org/keycloak/admin/ui/rest/AvailableRoleMappingResource.java/#L227-L231)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >Issue description >The V2 role-mapping helper treats resources of type `Clients` as individual clients. The schema assigns that type only to the aggregate all-clients resource, and does not assign a type to resources created for individual clients. > >Fix Focus Areas >- services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2[125-145] >- server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java[101-113] >- rest/admin-ui-ext/src/main/java/org/keycloak/admin/ui/rest/AvailableRoleMappingResource.java[227-231] > >Recommended Fix >Do not return the aggregate type-resource name as a client ID. Enumerate individual client resources using a reliable discriminator or resolve applicable permissions against real realm clients; expand an all-clients grant to valid client IDs before returning them. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <details><summary><ins><strong>View high (1)</strong></ins></summary><br/> <details> <summary> 4. Cross-client token exchange returns server errors <code>🐞 Bug</code> <code>☼ Reliability</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>ClientPermissionsV2.canExchangeTo</i></b> unconditionally throws <b><i>UnsupportedOperationException</i></b> instead >of returning an authorization decision. When V2 is enabled, the normal token-exchange path invokes >this method for every target audience different from the requesting client, so cross-client requests >propagate an unchecked internal failure rather than reaching the caller’s normal forbidden response. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java[R147-150]](https://github.com/drape-io/crbench-qodo-2026-09/pull/51/files#diff-0043415745566c18f268165ee3ce34459eec9f918d6a741e027cfbb26352e6faR147-R150)</code> > >```diff >+ @Override >+ public boolean canExchangeTo(ClientModel authorizedClient, ClientModel to, AccessToken token) { >+ throw new UnsupportedOperationException("Not supported in V2"); >+ } >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> ><b><i>AdminPermissions.management</i></b> selects <b><i>MgmtPermissionsV2</i></b> when the V2 feature is enabled, and that >manager constructs the new <b><i>ClientPermissionsV2</i></b>. For every target audience different from the >requesting client, the token-exchange provider directly calls its three-argument <b><i>canExchangeTo</i></b> >method and converts only a false result into the intended access-denied response; because the >override throws <b><i>UnsupportedOperationException</i></b> and the provider does not handle it, the exception >escapes the production exchange path. ></pre> > > <code>[services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java[66-70]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java/#L66-L70)</code> > <code>[services/src/main/java/org/keycloak/services/resources/admin/permissions/MgmtPermissionsV2.java[63-68]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/services/src/main/java/org/keycloak/services/resources/admin/permissions/MgmtPermissionsV2.java/#L63-L68)</code> > <code>[services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java[147-150]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java/#L147-L150)</code> > <code>[services/src/main/java/org/keycloak/protocol/oidc/tokenexchange/AbstractTokenExchangeProvider.java[261-281]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/services/src/main/java/org/keycloak/protocol/oidc/tokenexchange/AbstractTokenExchangeProvider.java/#L261-L281)</code> > <code>[services/src/main/java/org/keycloak/services/resources/admin/permissions/MgmtPermissionsV2.java[63-67]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/services/src/main/java/org/keycloak/services/resources/admin/permissions/MgmtPermissionsV2.java/#L63-L67)</code> > <code>[services/src/main/java/org/keycloak/protocol/oidc/tokenexchange/AbstractTokenExchangeProvider.java[261-280]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/services/src/main/java/org/keycloak/protocol/oidc/tokenexchange/AbstractTokenExchangeProvider.java/#L261-L280)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >Cross-client token exchange invokes the V2 client evaluator, whose `canExchangeTo` implementation throws an unchecked exception instead of making an authorization decision. This causes ordinary token endpoint requests for another client as audience to fail internally rather than produce the existing forbidden response. > >## Fix Focus Areas >- services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java[147-150] >- services/src/main/java/org/keycloak/protocol/oidc/tokenexchange/AbstractTokenExchangeProvider.java[261-281] > >## Recommended Fix >Implement `canExchangeTo` using the appropriate V2 token-exchange authorization policy, scope, and evaluation context, with tests for both allowed and denied cross-client exchanges. If token-exchange permissions are not yet supported in V2, return `false` until that support is implemented so the caller produces its normal forbidden response instead of propagating an exception. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> </details> <br/> <img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> <details> <summary> 5. Deleted clients leave authorization records behind <code>🐞 Bug</code> <code>⚙ Maintainability</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> >The revised removal listener performs cleanup only when the V1 feature is enabled, while V2 client >policies create schema resources for referenced clients. With V2 enabled alone, deleting a client >skips cleanup entirely, leaving its resource and policies in the admin-permissions resource server. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java[77]](https://github.com/drape-io/crbench-qodo-2026-09/pull/51/files#diff-a92b9f9a1a007b3924ac2756489c25f9ae8bb1cc92a367a0a839ee2e9b89c998R77-R77)</code> > >```diff >+ if (Profile.isFeatureEnabled(Profile.Feature.ADMIN_FINE_GRAINED_AUTHZ)) { >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The new listener guard is V1-only, whereas V2 policy creation maps client references through the new ><b><i>Clients</i></b> schema and creates missing resources. The schema&#x27;s orphan-removal logic runs when policies >are deleted, but this event path does not delete those policies under V2. ></pre> > > <code>[services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java[73-98]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java/#L73-L98)</code> > <code>[server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java[76-113]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java/#L76-L113)</code> > <code>[server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java[288-301]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java/#L288-L301)</code> > <code>[services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java[187-205]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java/#L187-L205)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >Issue description >The client-removal listener does nothing when only V2 fine-grained authorization is enabled. V2 policy creation can create resources for clients, so deletion leaves stale resources and policies that can no longer be resolved to a client. > >Fix Focus Areas >- services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java[77-96] >- server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java[76-113] >- server-spi-private/src/main/java/org/keycloak/authorization/AdminPermissionsSchema.java[288-301] > >Recommended Fix >Add V2-aware cleanup for client-removal events that deletes policies/resources referencing the deleted client, without calling the V1 `setPermissionsEnabled` API that V2 deliberately does not support. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <details> <summary> 6. Client deletion fails when both versions run <code>🐞 Bug</code> <code>☼ Reliability</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> >When both fine-grained authorization feature flags are enabled, the V1-gated listener calls ><b><i>ClientPermissionsV2.setPermissionsEnabled(client, false)</i></b>, which now always throws ><b><i>UnsupportedOperationException</i></b>. The V2 selector takes precedence in <b><i>management</i></b>, so deleting any >client in that configuration aborts from the removal event instead of completing cleanup. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java[R192-195]](https://github.com/drape-io/crbench-qodo-2026-09/pull/51/files#diff-0043415745566c18f268165ee3ce34459eec9f918d6a741e027cfbb26352e6faR192-R195)</code> > >```diff >+ @Override >+ public void setPermissionsEnabled(ClientModel client, boolean enable) { >+ throw new UnsupportedOperationException("Not supported in V2"); >+ } >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The two feature flags are independently declared, the listener executes when V1 is enabled, and ><b><i>management</i></b> independently selects V2 first. That call path reaches the new throwing override for a >client-removal event. ></pre> > > <code>[common/src/main/java/org/keycloak/common/Profile.java[56-58]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/common/src/main/java/org/keycloak/common/Profile.java/#L56-L58)</code> > <code>[services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java[66-98]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java/#L66-L98)</code> > <code>[services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java[192-195]](https://github.com/drape-io/crbench-qodo-2026-09/blob/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8/services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java/#L192-L195)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >Issue description >The V1 listener remains active whenever the V1 flag is enabled, but management selects V2 whenever the V2 flag is also enabled. The new V2 client cleanup method throws, so a client removal event fails in a valid dual-feature configuration. > >Fix Focus Areas >- services/src/main/java/org/keycloak/services/resources/admin/permissions/AdminPermissions.java[66-98] >- services/src/main/java/org/keycloak/services/resources/admin/permissions/ClientPermissionsV2.java[192-195] > >Recommended Fix >Make removal-event cleanup select an implementation compatible with the active authorization model, and do not invoke the unsupported V1 client permission-management method on the V2 evaluator. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-context:start --> <details><summary><strong>Context sources</strong></summary> <div>Review mode: <code>🧠 Deep</code>: This is a broad authorization/security-sensitive change with substantial new permission-evaluation logic across multiple independent code paths and 47 hunks, making redundant review materially valuable.</div> <!-- qodo-context:end --> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-daily-tip:start --> <details> <summary><strong>Tip of the day</strong></summary> <br/> <pre>💡 Did you know, you can reply &#x27;qodo&#x27; on any finding to push back, ask questions, or dig deeper</pre> <a href="https://docs.qodo.ai/tips-and-tricks">More tips ↗</a> | <a href="https://app.qodo.ai/configurations?tab=display-preferences">Customize Qodo ↗</a> | <a href="https://docs.qodo.ai">Qodo docs ↗</a> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-daily-tip:end --> <!-- https://github.com/drape-io/crbench-qodo-2026-09/commit/f4c47fb1fc870346fb84d46ff3785c7c5b9cdbf8 --> <a href="https://www.qodo.ai"><img src="https://www.qodo.ai/wp-content/uploads/2025/03/qodo-logo.svg" width="80" alt="Qodo Logo"></a>