Skip to content

NPE in RoleUtils.expandCompositeRoles when a cached client scope references a deleted role #51589

Closed

Description

@ssilvert

Before reporting an issue

  • I have read and understood the above terms for submitting issues, and I understand that my issue may be closed without action if I do not follow them.

Area

core

Describe the bug

Note: Analysis by Claude Opus 5

ClientScopeAdapter.getScopeMappingsStream() in the realm cache (model/infinispan) maps
cached role IDs through RealmCacheSession.getRoleById() without filtering nulls:

// model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/ClientScopeAdapter.java
return cached.getScope().stream()
  .map(id -> cacheSession.getRoleById(cachedRealm, id));

Version

Nightly / main (999.0.0-SNAPSHOT), verified 2026-08-10. Originally observed on 26.x.

Regression

  • The issue is a regression

Expected behavior

A scope mapping pointing at a role that no longer resolves is ignored, exactly as the JPA adapter
already does. Token issuance succeeds and the remaining scope mappings are evaluated normally.

Actual behavior

java.lang.NullPointerException escapes to KeycloakErrorHandler and the token endpoint returns
HTTP 500. On the affected node this repeats for every subsequent token request for that client.

Stack trace as seen on 26.x:
ERROR [org.keycloak.services.error.KeycloakErrorHandler] (executor-thread-NNN) Uncaught server error: java.lang.NullPointerException
at java.base/java.util.ArrayDeque.addLast(ArrayDeque.java:302)
at java.base/java.util.ArrayDeque.add(ArrayDeque.java:493)
at org.keycloak.models.utils.RoleUtils.expandCompositeRolesStream(RoleUtils.java:143)
at org.keycloak.models.utils.RoleUtils.lambda$expandCompositeRoles$6(RoleUtils.java:172)
at java.base/java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:273)
at java.base/java.util.HashMap$KeySpliterator.forEachRemaining(HashMap.java:1715)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:921)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682)
at org.keycloak.models.utils.RoleUtils.expandCompositeRoles(RoleUtils.java:173)
at org.keycloak.services.util.DefaultClientSessionContext.isClientScopePermittedForUser(DefaultClientSessionContext.java:266)
at org.keycloak.services.util.DefaultClientSessionContext.isAllowed(DefaultClientSessionContext.java:236)
at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:178)
at java.base/java.util.HashMap$KeySpliterator.forEachRemaining(HashMap.java:1715)
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682)
at org.keycloak.services.util.DefaultClientSessionContext.getClientScopesStream(DefaultClientSessionContext.java:127)
at org.keycloak.services.util.DefaultClientSessionContext.getScopeString(DefaultClientSessionContext.java:182)
at org.keycloak.services.util.DefaultClientSessionContext.getScopeString(DefaultClientSessionContext.java:165)
at org.keycloak.protocol.oidc.TokenManager.initToken(TokenManager.java:1036)
at org.keycloak.protocol.oidc.TokenManager.createClientAccessToken(TokenManager.java:600)
at org.keycloak.protocol.oidc.TokenManager$AccessTokenResponseBuilder.generateAccessToken(TokenManager.java:1166)
at org.keycloak.protocol.oidc.grants.ClientCredentialsGrantType.process(ClientCredentialsGrantType.java:143)
at org.keycloak.protocol.oidc.endpoints.TokenEndpoint.processGrantRequest(TokenEndpoint.java:151)

The failing frame is the seed stack.add(role) at RoleUtils.java:143 — not the stack.add(r)
inside the forEach (that would show a lambda$expandCompositeRolesStream$N frame). So the null
is a top-level element of the set built from clientScope.getScopeMappingsStream().

On current main the refactored expandCompositeRoles still NPEs on the same input, just at a
different line — realmOf() (role.getContainer(), RoleUtils.java:250) or role.getId()
(RoleUtils.java:162).

How to Reproduce?

The natural trigger is a role deletion whose cache invalidation doesn't reach a node. These steps
put a node into that state deterministically:

  1. In a realm, create realm role role-a.

  2. Create client scope test-scope and add role-a to its Scope (role scope mappings).

  3. Create client test-client with service accounts enabled, assign test-scope as a default
    client scope, and grant role-a to the client's service account user.

  4. Request a token so the client scope is loaded into the realm cache:
    POST /realms/<realm>/protocol/openid-connect/token with grant_type=client_credentials.
    This succeeds and populates CachedClientScope with role-a's ID.

  5. Make role-a unresolvable without invalidating the cached client scope on that node — i.e.
    simulate the lost/delayed invalidation. Directly in the database:

    DELETE FROM SCOPE_MAPPING WHERE ROLE_ID = '<role-a-id>';
    DELETE FROM KEYCLOAK_ROLE WHERE ID = '<role-a-id>';
    
  6. Repeat the token request from step 4.

Result: HTTP 500 and the NPE above. Every subsequent request for that client fails the same
way until the node restarts or the client scope is otherwise invalidated.

Step 5 substitutes for the production condition (a deleted role whose RoleRemovedEvent did not
invalidate this node's CachedClientScope); the code path exercised from step 6 is identical.

Anything else?

Suggested fix — make the cached adapters null-safe, matching the JPA adapters:

// model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/ClientScopeAdapter.java
return cached.getScope().stream()
  .map(id -> cacheSession.getRoleById(cachedRealm, id))
  .filter(Objects::nonNull);

ClientAdapter.getScopeMappingsStream() in the same package needs the same change.

Relevant code:

model/infinispan/.../cache/infinispan/ClientScopeAdapter.java — getScopeMappingsStream(), no null filter
model/infinispan/.../cache/infinispan/ClientAdapter.java — same omission
model/jpa/.../jpa/ClientScopeAdapter.java — has .filter(Objects::nonNull)
model/jpa/.../jpa/ClientAdapter.java — has .filter(Objects::nonNull)
model/infinispan/.../cache/infinispan/RealmCacheSession.java — getRoleById() returns null for a missing role
model/infinispan/.../cache/infinispan/entities/CachedClientScope.java — builds scope from the JPA adapter, so cached IDs were valid at load time
server-spi/.../models/utils/RoleUtils.java — expandCompositeRoles(), where the null surfaces
Whether RoleUtils.expandCompositeRoles() should additionally reject nulls defensively (fail fast
with a clear message rather than a bare NPE from ArrayDeque) is worth a maintainer's opinion.

Activity

  1. added theissue type on Aug 10, 2026
  2. added
    kind/bug
    on Aug 10, 2026
  3. added
    area/core
    on Aug 10, 2026
  4. PRAHLAD09-dev commented on Aug 11, 2026

    @PRAHLAD09-dev
    Contributor

    I traced through this — confirmed both ClientScopeAdapter.getScopeMappingsStream() and ClientAdapter.getScopeMappingsStream() in model/infinispan still map role IDs through cacheSession.getRoleById() without filtering nulls on current main, while the JPA equivalents (model/jpa/.../ClientScopeAdapter.java) already have .filter(Objects::nonNull). I'd like to send a PR applying the same null-filter to both infinispan adapters, mirroring the existing JPA pattern. Happy to add a regression test simulating a stale cached role ID.

  5. self-assigned this
    on Aug 24, 2026
  6. ahus1 commented on Aug 24, 2026

    @ahus1
    Member

    I've discussed this with AI, and it might also happen when there is a concurrent deletion while another call is iterating over the entries. I'll also prepare a backport to 26.7 + 26.6.

    It would be good to keep an eye on this one if this was happening due to networking problems, due to a bug in the invalidation, concurrency, or a mis-configuration of the cluster where nodes were unable to talk to each other.

  7. added a commit that references this issue on Aug 25, 2026
    12f8a41
  8. 1 remaining item

  9. added a commit that references this issue on Aug 27, 2026
    28d95cd
  10. added a commit that references this issue on Aug 27, 2026
    4dd3600
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

Fields

No fields configured for bug.

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions