crbench//

← all cases

Implement access token context encoding framework

Tier 2 medium java · local · real merged PR from keycloak/keycloak #37634

Ground-truth defects

d1 · other · low
Wrong parameter in null check (grantType vs. rawTokenId)
d2 · security · low
In isAccessTokenId, the substring for the grant shortcut and the equality check look inverted: the grant shortcut occupies indices 4–5 (substring(4,6)), and a match should return true (combined with UUID check), not false.
d3 · correctness · medium
The client-credentials grant builds its token through `tokenManager.responseBuilder(...).generateAccessToken()` directly, bypassing the shared response path where the diff sets `Constants.GRANT_TYPE` on the client session context. `initToken` then reads that attribute, finds it null and substitutes the unknown marker, so every client-credentials token id encodes `na` rather than the shortcut the diff registers for this grant. Every other direct-responseBuilder path in the PR was updated; this one was missed.

The change under review

diff (truncated — full diff)
diff --git a/server-spi-private/src/main/java/org/keycloak/models/Constants.java b/server-spi-private/src/main/java/org/keycloak/models/Constants.java
index 08b4f7156f..8a904db2a5 100755
--- a/server-spi-private/src/main/java/org/keycloak/models/Constants.java
+++ b/server-spi-private/src/main/java/org/keycloak/models/Constants.java
@@ -203,5 +203,7 @@ public final class Constants {
     public static final String REQUESTED_AUDIENCE_CLIENTS = "req-aud-clients";
     // claim used in refresh token to know the requested audience
     public static final String REQUESTED_AUDIENCE = "req-aud";
+    // Note in clientSessionContext specifying token grant type used
+    public static final String GRANT_TYPE = OAuth2Constants.GRANT_TYPE;
 
 }
diff --git a/server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantType.java b/server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantType.java
index 32af14d2f7..582a20cbfb 100644
--- a/server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantType.java
+++ b/server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantType.java
@@ -26,6 +26,7 @@ import java.util.Collections;
 import java.util.Map;
 import java.util.Set;
 
+import org.keycloak.OAuth2Constants;
 import org.keycloak.common.ClientConnection;
 import org.keycloak.events.EventBuilder;
 import org.keycloak.events.EventType;
@@ -81,6 +82,7 @@ public interface OAuth2GrantType extends Provider {
         protected EventBuilder event;
         protected Cors cors;
         protected Object tokenManager;
+        protected String grantType;
 
         public Context(KeycloakSession session, Object clientConfig, Map<String, String> clientAuthAttributes,
                 MultivaluedMap<String, String> formParams, EventBuilder event, Cors cors, Object tokenManager) {
@@ -97,22 +99,7 @@ public interface OAuth2GrantType extends Provider {
             this.event = event;
             this.cors = cors;
             this.tokenManager = tokenManager;
-        }
-
-        public Context(Context context) {
-            this.session = context.session;
-            this.realm = context.realm;
-            this.client = context.client;
-            this.clientConfig = context.clientConfig;
-            this.clientConnection = context.clientConnection;
-            this.clientAuthAttributes = context.clientAuthAttributes;
-            this.request = context.request;
-            this.response = context.response;
-            this.headers = context.headers;
-            this.formParams = context.formParams;
-            this.event = context.event;
-            this.cors = context.cors;
-            this.tokenManager = context.tokenManager;
+            this.grantType = formParams.getFirst(OAuth2Constants.GRANT_TYPE);
         }
 
         public void setFormParams(MultivaluedHashMap<String, String> formParams) {
@@ -182,6 +169,10 @@ public interface OAuth2GrantType extends Provider {
         public Object getTokenManager() {
             return tokenManager;
         }
+
+        public String getGrantType() {
+            return grantType;
+        }
     }
 
 }
diff --git a/server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java b/server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java
index 5793956f08..020613d55c 100644
--- a/server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java
+++ b/server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java
@@ -26,4 +26,9 @@ import org.keycloak.provider.ProviderFactory;
  */
 public interface OAuth2GrantTypeFactory extends ProviderFactory<OAuth2GrantType> {
 
+    /**
+     * @return usually like 3-letters shortcut of specific grants. It can be useful for example in the tokens when the amount of characters should be limited and hence using full grant name
+     * is not ideal. Shortcut should be unique across grants.
+     */
+    String getShortcut();
 }
diff --git a/services/src/main/java/org/keycloak/protocol/oidc/TokenManager.java b/services/src/main/java/org/keycloak/protocol/oidc/TokenManager.java
index 2235792931..4cd8c0546f 100755
--- a/services/src/main/java/org/keycloak/protocol/oidc/TokenManager.java
+++ b/services/src/main/java/org/keycloak/protocol/oidc/TokenManager.java
@@ -64,6 +64,8 @@ import org.keycloak.models.utils.RoleUtils;
 import org.keycloak.organization.protocol.mappers.oidc.OrganizationScope;
 import org.keycloak.protocol.ProtocolMapper;
 import org.keycloak.protocol.ProtocolMapperUtils;
+import org.keycloak.protocol.oidc.encode.AccessTokenContext;
+import org.keycloak.protocol.oidc.encode.TokenContextEncoderProvider;
 import org.keycloak.protocol.oidc.mappers.TokenIntrospectionTokenMapper;
 import org.keycloak.protocol.oidc.mappers.OIDCAccessTokenMapper;
 import org.keycloak.protocol.oidc.mappers.OIDCAccessTokenResponseMapper;
@@ -243,6 +245,7 @@ public class TokenManager {
         if (oldToken.getNonce() != null) {
             clientSessionCtx.setAttribute(OIDCLoginProtocol.NONCE_PARAM, oldToken.getNonce());
         }
+        clientSessionCtx.setAttribute(Constants.GRANT_TYPE, OAuth2Constants.REFRESH_TOKEN);
 
         // recreate token.
         AccessToken newToken = createClientAccessToken(session, realm, client, user, userSession, clientSessionCtx);
@@ -861,9 +864,9 @@ public class TokenManager {
                         return ((OIDCAccessTokenMapper) mapper.getValue()).transformAccessToken(token, mapper.getKey(), session, userSession, clientSessionCtx);
                     }
                 });
-        final ClientModel[] requestedAucienceClients = clientSessionCtx.getAttribute(Constants.REQUESTED_AUDIENCE_CLIENTS, ClientModel[].class);
-        if (requestedAucienceClients != null) {
-            restrictRequestedAudience(accessToken, Arrays.stream(requestedAucienceClients)
+        final ClientModel[] requestedAudienceClients = clientSessionCtx.getAttribute(Constants.REQUESTED_AUDIENCE_CLIENTS, ClientModel[].class);
+        if (requestedAudienceClients != null) {
+            restrictRequestedAudience(accessToken, Arrays.stream(requestedAudienceClients)
                     .map(ClientModel::getClientId)
                     .collect(Collectors.toSet()));
         }
@@ -1045,7 +1048,11 @@ public class TokenManager {
     protected AccessToken initToken(KeycloakSession session, RealmModel realm, ClientModel client, UserModel user, UserSessionModel userSession,
                                     ClientSessionContext clientSessionCtx, UriInfo uriInfo) {
         AccessToken token = new AccessToken();
-        token.id(KeycloakModelUtils.generateId());
+
+        TokenContextEncoderProvider encoder = session.getProvider(TokenContextEncoderProvider.class);
+        AccessTokenContext tokenCtx = encoder.getTokenContextFromClientSessionContext(clientSessionCtx, KeycloakModelUtils.generateId());
+        token.id(encoder.encodeTokenId(tokenCtx));
+
         token.type(formatTokenType(client, token));
         if (UserSessionModel.SessionPersistenceState.TRANSIENT.equals(userSession.getPersistenceState())) {
             token.subject(user.getId());
diff --git a/services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java b/services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java
new file mode 100644
index 0000000000..8091812487
--- /dev/null
+++ b/services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java
@@ -0,0 +1,95 @@
+/*
+ * 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.protocol.oidc.encode;
+
+import java.util.Objects;
+
+/**
+ * Some context info about the token
+ *
+ * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+ */
+public class AccessTokenContext {
+
+    private final SessionType sessionType;
+    private final TokenType tokenType;
+    private final String grantType;
+    private final String rawTokenId;
+
+    public enum SessionType {
+        ONLINE("on"),
+        OFFLINE("of"),
+        TRANSIENT("tr"),
+        UNKNOWN("un");
+
+        private final String shortcut;
+
+        SessionType(String shortcut) {
+            this.shortcut = shortcut;
+        }
+
+        public String getShortcut() {
+            return shortcut;
+        }
+    }
+
+    public enum TokenType {
+        REGULAR("rt"),
+        LIGHTWEIGHT("lt"),
+        UNKNOWN("un");
+
+        private final String shortcut;
+
+        TokenType(String shortcut) {
+            this.shortcut = shortcut;
+        }
+
+        public String getShortcut() {
+            return shortcut;
+        }
+    }
+
+    public AccessTokenContext(SessionType sessionType, TokenType tokenType, String grantType, String rawTokenId) {
+        Objects.requireNonNull(sessionType, "Null sessionType not allowed");
+        Objects.requireNonNull(tokenType, "Null tokenType not allowed");
+        Objects.requireNonNull(grantType, "Null grantType not allowed");
+        Objects.requireNonNull(grantType, "Null rawTokenId not allowed");
+        this.sessionType = sessionType;
+        this.tokenType = tokenType;
+        this.grantType = grantType;
+        this.rawTokenId = rawTokenId;
+    }
+
+    public SessionType getSessionType() {
+        return sessionType;
+    }
+
+    public TokenType getTokenType() {
+        return tokenType;
+    }
+
+    public String getGrantType() {
+        return grantType;
+    }
+
+    public String getRawTokenId() {
+        return rawTokenId;
+    }
+}
diff --git a/services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProvider.java b/services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProvider.java
new file mode 100644
index 0000000000..3488759b34
--- /dev/null
+++ b/services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProvider.java
@@ -0,0 +1,124 @@
+/*
+ * 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.protocol.oidc.encode;
+
+import org.keycloak.models.ClientSessionContext;
+import org.keycloak.models.Constants;
+import org.keycloak.models.KeycloakSession;
+import org.keycloak.models.UserSessionModel;
+import org.keycloak.protocol.oidc.mappers.AbstractOIDCProtocolMapper;
+
+/**
+ * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+ */
+public class DefaultTokenContextEncoderProvider implements TokenContextEncoderProvider {
+
+    public static final String UNKNOWN = "na";
+
+    private final KeycloakSession session;
+    private final DefaultTokenContextEncoderProviderFactory factory;
+
+    public DefaultTokenContextEncoderProvider(KeycloakSession session,
+                                              DefaultTokenContextEncoderProviderFactory factory) {
+        this.session = session;
+        this.factory = factory;
+    }
+
+    @Override
+    public AccessTokenContext getTokenContextFromClientSessionContext(ClientSessionContext clientSessionContext, String rawTokenId) {
+        AccessTokenContext.SessionType sessionType;
+        UserSessionModel userSession = clientSessionContext.getClientSession().getUserSession();
+        if (userSession.getPersistenceState() == UserSessionModel.SessionPersistenceState.TRANSIENT) {
+            sessionType = AccessTokenContext.SessionType.TRANSIENT;
+        } else {
+            sessionType = userSession.isOffline() ? AccessTokenContext.SessionType.OFFLINE : AccessTokenContext.SessionType.ONLINE;
+        }
+
+        boolean useLightweightToken = AbstractOIDCProtocolMapper.getShouldUseLightweightToken(session);
+        AccessTokenContext.TokenType tokenType = useLightweightToken ? AccessTokenContext.TokenType.LIGHTWEIGHT : AccessTokenContext.TokenType.REGULAR;
+
+        String grantType = clientSessionContext.getAttribute(Constants.GRANT_TYPE, String.class);
+        if (grantType == null) {
+            grantType = UNKNOWN;
+        }
+
+        return new AccessTokenContext(sessionType, tokenType, grantType, rawTokenId);
+    }
+
+    @Override
+    public AccessTokenContext getTokenContextFromTokenId(String encodedTokenId) {
+        int indexOf = encodedTokenId.indexOf(':');
+        if (indexOf == -1) {
+            return new AccessTokenContext(AccessTokenContext.SessionType.UNKNOWN, AccessTokenContext.TokenType.UNKNOWN, UNKNOWN, encodedTokenId);
+        } else {
+            String encodedContext = encodedTokenId.substring(0, indexOf);
+            String rawId = encodedTokenId.substring(indexOf + 1);
+
+            if (encodedContext.length() != 6) {
+                throw new IllegalArgumentException("Incorrect token id: '" + encodedTokenId + "'. Expected length of 6.");
+            }
+
+            // First 2 chars are "sessionType", next 2 chars "tokenType", last 2 chars "grantType"
+            String stShortcut = encodedContext.substring(0, 2);
+            String ttShortcut = encodedContext.substring(2, 4);
+            String gtShortcut = encodedContext.substring(4, 6);
+
+            AccessTokenContext.SessionType st = factory.getSessionTypeByShortcut(stShortcut);
+            if (st == null) {
+                throw new IllegalArgumentException("Incorrect token id: " + encodedTokenId + ". Unknown value '" + stShortcut + "' for session type");
+            }
+            AccessTokenContext.TokenType tt = factory.getTokenTypeByShortcut(ttShortcut);
+            if (tt == null) {
+                throw new IllegalArgumentException("Incorrect token id: " + encodedTokenId + ". Unknown value '" + ttShortcut + "' for token type");
+            }
+            String gt = factory.getGrantTypeByShortcut(gtShortcut);
+            if (gt == null) {
+                throw new IllegalArgumentException("Incorrect token id: " + encodedTokenId + ". Unknown value '" + gtShortcut + "' for grant type");
+            }
+
+            return new AccessTokenContext(st, tt, gt, rawId);
+        }
+    }
+
+    @Override
+    public String encodeTokenId(AccessTokenContext tokenContext) {
+        if (tokenContext.getSessionType() == AccessTokenContext.SessionType.UNKNOWN) {
+            throw new IllegalStateException("Cannot encode token with unknown sessionType");
+        }
+        if (tokenContext.getTokenType() == AccessTokenContext.TokenType.UNKNOWN) {
+            throw new IllegalStateException("Cannot encode token with unknown tokenType");
+        }
+
+        String grantShort = factory.getShortcutByGrantType(tokenContext.getGrantType());
+        if (grantShort == null) {
+            throw new IllegalStateException("Cannot encode token with unknown grantType: " + tokenContext.getGrantType());
+        }
+
+        return tokenContext.getSessionType().getShortcut() +
+                tokenContext.getTokenType().getShortcut() +
+                grantShort +
+                ':' + tokenContext.getRawTokenId();
+    }
+
+    @Override
+    public void close() {
+
+    }
+}
diff --git a/services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProviderFactory.java b/services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProviderFactory.java
new file mode 100644
index 0000000000..54df0d22eb
--- /dev/null
+++ b/services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProviderFactory.java
@@ -0,0 +1,138 @@
+/*
+ * 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.protocol.oidc.encode;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.keycloak.Config;
+import org.keycloak.models.KeycloakSession;
+import org.keycloak.models.KeycloakSessionFactory;
+import org.keycloak.protocol.oidc.grants.OAuth2GrantType;
+import org.keycloak.protocol.oidc.grants.OAuth2GrantTypeFactory;
+
+/**
+ * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+ */
+public class DefaultTokenContextEncoderProviderFactory implements TokenContextEncoderProviderFactory {
+
+    private KeycloakSessionFactory sessionFactory;
+    private Map<String, AccessTokenContext.SessionType> sessionTypesByShortcut;
+    private Map<String, AccessTokenContext.TokenType> tokenTypesByShortcut;
+    Map<String, String> grantsByShortcuts;
+    Map<String, String> grantsToShortcuts;
+
+    @Override
+    public TokenContextEncoderProvider create(KeycloakSession session) {
+        return new DefaultTokenContextEncoderProvider(session, this);
+    }
+
+    @Override
+    public void init(Config.Scope config) {
+        sessionTypesByShortcut = new HashMap<>();
+        for (AccessTokenContext.SessionType st : AccessTokenContext.SessionType.values()) {
+            sessionTypesByShortcut.put(st.getShortcut(), st);
+        }
+        sessionTypesByShortcut = Collections.unmodifiableMap(sessionTypesByShortcut);
+
+        tokenTypesByShortcut = new HashMap<>();
+        for (AccessTokenContext.TokenType tt : AccessTokenContext.TokenType.values()) {
+            tokenTypesByShortcut.put(tt.getShortcut(), tt);
+        }
+        tokenTypesByShortcut = Collections.unmodifiableMap(tokenTypesByShortcut);
+    }
+
+    @Override
+    public void postInit(KeycloakSessionFactory factory) {
+        this.sessionFactory = factory;
+        grantsByShortcuts = new ConcurrentHashMap<>();
+        grantsToShortcuts = new ConcurrentHashMap<>();
+
+        factory.getProviderFactoriesStream(OAuth2GrantType.class)
+                .forEach((factory1) -> {
+                    OAuth2GrantTypeFactory gtf = (OAuth2GrantTypeFactory) factory1;
+                    String grantName = gtf.getId();
+                    String grantShortcut = gtf.getShortcut();
+                    grantsByShortcuts.put(grantShortcut, grantName);
+                    grantsToShortcuts.put(grantName, grantShortcut);
+                });
+        grantsByShortcuts.put(DefaultTokenContextEncoderProvider.UNKNOWN, DefaultTokenContextEncoderProvider.UNKNOWN);
+        grantsToShortcuts.put(DefaultTokenContextEncoderProvider.UNKNOWN, DefaultTokenContextEncoderProvider.UNKNOWN);
+
+        // Validation if there are not duplicated shortcuts (for example when introducing new grant impl...)
+        if (grantsByShortcuts.size() != grantsToShortcuts.size()) {
+            throw new IllegalStateException("Different lengths of maps. grantsByShortcuts.size=" + grantsByShortcuts.size() + ", grantsToShortcuts.size=" + grantsToShortcuts.size() +
+                    ". Make sure that there is no OAuth2GrantType implementation with same ID or shortcut like other grants");
+        }
+    }
+
+    @Override
+    public void close() {
+
+    }
+
+    @Override
+    public String getId() {
+        return "default";
+    }
+
+    protected AccessTokenContext.SessionType getSessionTypeByShortcut(String sessionTypeShortcut) {
+        return sessionTypesByShortcut.get(sessionTypeShortcut);
+    }
+
+    protected AccessTokenContext.TokenType getTokenTypeByShortcut(String tokenTypeShortcut) {
+        return tokenTypesByShortcut.get(tokenTypeShortcut);
+    }
+
+    protected String getShortcutByGrantType(String grantType) {
+        String grantShortcut = grantsToShortcuts.get(grantType);
+        if (grantShortcut == null) {
+            // Refresh maps in case new grant type was deployed
+            OAuth2GrantTypeFactory factory = (OAuth2GrantTypeFactory) sessionFactory.getProviderFactory(OAuth2GrantType.class, grantType);
+            if (factory != null) {
+                String shortcut = factory.getShortcut();
+                grantsByShortcuts.put(shortcut, grantType);
+                grantsToShortcuts.put(grantType, shortcut);
+            }
+            grantShortcut = grantsToShortcuts.get(grantType);
+        }
+        return grantShortcut;
+    }
+
+    protected String getGrantTypeByShortcut(String shortcut) {
+        String grantType = grantsByShortcuts.get(shortcut);
+        if (grantType == null) {
+            // Refresh maps in case new grant type was deployed
+            sessionFactory.getProviderFactoriesStream(OAuth2GrantType.class)
+                    .map(fct -> (OAuth2GrantTypeFactory) fct)
+                    .filter(fct -> shortcut.equals(fct.getShortcut()))
+                    .map(OAuth2GrantTypeFactory::getId)
+                    .findFirst()
+                    .ifPresent(newGrantType -> {
+                        grantsByShortcuts.put(shortcut, newGrantType);
+                        grantsToShortcuts.put(newGrantType, shortcut);
+                    });
+            grantType = grantsByShortcuts.get(shortcut);
+        }

Leaderboard for this case

medium · 5 of 9 bots fully caught it (56% solve rate) · 78% avg coverage.

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

Bot results

Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 low ✓ exact
d2 low ✓ off by one
d3 medium ✗ —
valid · impact medium
The change adds an abstract method with no default to the grant factory SPI. postInit then calls getShortcut() on every factory and puts the result into a ConcurrentHashMap. A custom factory compiled without the method fails with AbstractMethodError, and a null shortcut throws NPE at startup. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
The change removes the public copy constructor from the SPI Context class. Nothing in the repo uses it, but external extensions that call it will no longer compile or link. This is a real compatibility break of low severity. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
grantType is cached once in the constructor, and the public setFormParams() does not update it. No code in the repo calls setFormParams, so this only matters for extensions that replace the form params, which is unlikely. [grounded: diff] [consensus 3/4: valid=3, uncertain=1]
valid · matches d1 · impact low
valid · matches d2 · impact low
raw comments (5)
server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java:80
This adds the abstract method `String getShortcut()` to a public SPI interface with no default implementation. Any custom `OAuth2GrantTypeFactory` compiled against an earlier version will fail on startup: `DefaultTokenContextEncoderProviderFactory.postInit` calls `getShortcut()` on every grant factory and gets an `AbstractMethodError`. If a factory returns null, `ConcurrentHashMap.put` throws an NPE. A custom shortcut that isn't exactly 2 characters produces token IDs that `getTokenContextFromTokenId` rejects, because it requires a 6-character prefix. Fix: add a default implementation, and validate or skip bad shortcuts instead of crashing.
server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantType.java:100
The public copy constructor `Context(Context context)` was removed from the public SPI class `OAuth2GrantType.Context`. Extensions that subclass or copy the Context (for example, custom grants that wrap the context) will no longer compile or link. Nothing in this feature needs the removal. If it is kept, it should copy the new `grantType` field.
server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantType.java:102
`grantType` is captured from `formParams` once, in the constructor. `setFormParams()` can replace the form parameters later, but `getGrantType()` will still return the old value, so the token ID can encode a grant type that no longer matches the request.
services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java:207
Copy-paste error: the null check for `rawTokenId` passes `grantType` again (`Objects.requireNonNull(grantType, "Null rawTokenId not allowed")`). A null `rawTokenId` is accepted and later encoded as the literal string "null" in the token ID.
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java:483
The `isAccessTokenId` matcher can't detect a wrong grant type. The prefix is session(2) + token type(2) + grant(2), so the grant shortcut is at `substring(4, 6)`, not `substring(3, 5)`. The condition is also inverted: it returns false when the shortcut matches. Because the substring is off by one, it essentially never equals the expected value, so the matcher accepts any token ID with any grant. All the new grant-type assertions in `expectCodeToToken`, `expectRefresh`, and the others pass whether the encoding is right or not.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 low ✓ off by one
d2 low ✓ off by one
d3 medium ✓ exact
valid · matches d1 · impact low
valid · impact low
The maps are never invalidated, but the failure needs a grant provider to be hot-replaced with a different shortcut, and Keycloak's runtime hot-redeploy support makes that speculative. An undeployed grant can't issue tokens, so its stale entry is mostly harmless. [grounded: tree services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProviderFactory.java] [consensus 5/5: valid=5]
valid · impact medium
The SPI javadoc even suggests a '3-letters shortcut', and the factory stores shortcuts of any length. But decoding requires a 6-char context and reads exactly 2 chars for the grant, so a custom grant with a non-2-char shortcut produces token IDs that later fail to decode. [grounded: tree services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProvider.java] [consensus 5/5: valid=5]
valid · matches d2 · impact low
valid · matches d3 · impact medium
valid · impact medium
The new abstract interface method has no default. postInit calls gtf.getShortcut() on every grant factory, so a precompiled custom factory hits AbstractMethodError at startup. [grounded: tree server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java] [consensus 5/5: valid=5]
valid · impact low
The test never calls postInit, so sessionFactory is null. For 'ac', getGrantTypeByShortcut misses in the map and dereferences sessionFactory, throwing an NPE that the broad catch swallows. The test therefore passes without ever exercising the IllegalArgumentException path it is meant to check. [grounded: tree services/src/test/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProviderTest.java] [consensus 5/5: valid=5]
raw comments (8)
services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java:73
<!-- cubic:v=eefd68f6-9fb6-483c-8a13-b953ab296902 --> <!-- cubic:review-run=032946e6-2d46-5636-b2fd-dc2abeb31517 --> <!-- metadata:{"confidence":10} --> P2: When `rawTokenId` is null, this duplicated check accepts it and `encodeTokenId()` serializes it as the literal `null`, producing an invalid/colliding token ID. Validate `rawTokenId` here instead of checking `grantType` twice. <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/protocol/oidc/encode/AccessTokenContext.java, line 73: <comment>When `rawTokenId` is null, this duplicated check accepts it and `encodeTokenId()` serializes it as the literal `null`, producing an invalid/colliding token ID. Validate `rawTokenId` here instead of checking `grantType` twice.</comment> <file context> @@ -0,0 +1,95 @@ + Objects.requireNonNull(sessionType, "Null sessionType not allowed"); + Objects.requireNonNull(tokenType, "Null tokenType not allowed"); + Objects.requireNonNull(grantType, "Null grantType not allowed"); + Objects.requireNonNull(grantType, "Null rawTokenId not allowed"); + this.sessionType = sessionType; + this.tokenType = tokenType; </file context> ``` </details>
services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProviderFactory.java:107
<!-- cubic:v=16fa525e-4f39-4772-adc7-c8fad9d73653 --> <!-- cubic:review-run=032946e6-2d46-5636-b2fd-dc2abeb31517 --> <!-- metadata:{"confidence":8} --> P2: After an OAuth2 grant provider is undeployed or replaced, `getShortcutByGrantType` can keep returning the stale cached shortcut. Rebuild or invalidate these maps when the provider set changes, or revalidate cached entries against the current provider factory before returning them. <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/protocol/oidc/encode/DefaultTokenContextEncoderProviderFactory.java, line 107: <comment>After an OAuth2 grant provider is undeployed or replaced, `getShortcutByGrantType` can keep returning the stale cached shortcut. Rebuild or invalidate these maps when the provider set changes, or revalidate cached entries against the current provider factory before returning them.</comment> <file context> @@ -0,0 +1,138 @@ + } + + protected String getShortcutByGrantType(String grantType) { + String grantShortcut = grantsToShortcuts.get(grantType); + if (grantShortcut == null) { + // Refresh maps in case new grant type was deployed </file context> ``` </details>
services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProviderFactory.java:74
<!-- cubic:v=3716d601-32a6-4b62-a960-b9a4264e01b3 --> <!-- cubic:review-run=032946e6-2d46-5636-b2fd-dc2abeb31517 --> <!-- metadata:{"confidence":9} --> P2: When a custom OAuth2 grant returns a shortcut other than two characters, this factory registers it unchanged, but token decoding always reads exactly two grant characters. Enforce a two-character shortcut in both startup and dynamic registration, or change the token format to support the documented shortcut lengths. <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/protocol/oidc/encode/DefaultTokenContextEncoderProviderFactory.java, line 74: <comment>When a custom OAuth2 grant returns a shortcut other than two characters, this factory registers it unchanged, but token decoding always reads exactly two grant characters. Enforce a two-character shortcut in both startup and dynamic registration, or change the token format to support the documented shortcut lengths.</comment> <file context> @@ -0,0 +1,138 @@ + .forEach((factory1) -> { + OAuth2GrantTypeFactory gtf = (OAuth2GrantTypeFactory) factory1; + String grantName = gtf.getId(); + String grantShortcut = gtf.getShortcut(); + grantsByShortcuts.put(grantShortcut, grantName); + grantsToShortcuts.put(grantName, grantShortcut); </file context> ``` </details>
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java:483
<!-- cubic:v=0c0c1074-cc33-4b8a-9e70-2d48448ff99e --> <!-- cubic:review-run=032946e6-2d46-5636-b2fd-dc2abeb31517 --> <!-- metadata:{"confidence":10} --> P2: The grant-shortcut check in `isAccessTokenId` is inverted and reads the wrong slice, so it never rejects a token, whatever the grant. `DefaultTokenContextEncoderProvider.encodeTokenId` builds the id as `<sessionType(2)><tokenType(2)><grantShortcut(2)>:<uuid>`, i.e. the shortcut occupies chars 4-5 (`substring(4, 6)`), not `substring(3, 5)`, which grabs the last token-type char plus the first grant char. And `equals(...) return false` makes the matcher reject exactly the token it should accept. As written, a token like `onrtdg:<uuid>` also passes when `expectCodeToToken` expects grant `ac`, so the new assertion provides no real verification of the grant type. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java, line 483: <comment>The grant-shortcut check in `isAccessTokenId` is inverted and reads the wrong slice, so it never rejects a token, whatever the grant. `DefaultTokenContextEncoderProvider.encodeTokenId` builds the id as `<sessionType(2)><tokenType(2)><grantShortcut(2)>:<uuid>`, i.e. the shortcut occupies chars 4-5 (`substring(4, 6)`), not `substring(3, 5)`, which grabs the last token-type char plus the first grant char. And `equals(...) return false` makes the matcher reject exactly the token it should accept. As written, a token like `onrtdg:<uuid>` also passes when `expectCodeToToken` expects grant `ac`, so the new assertion provides no real verification of the grant type.</comment> <file context> @@ -469,6 +473,24 @@ public void describeTo(Description description) { + String[] items = item.split(":"); + if (items.length != 2) return false; + // Grant type shortcut starts at character 4th char and is 2-chars long + if (items[0].substring(3, 5).equals(expectedGrantShortcut)) return false; + return isUUID().matches(items[1]); + } </file context> ``` </details> ```suggestion if (!items[0].substring(4, 6).equals(expectedGrantShortcut)) return false; ```
services/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeBase.java:109
<!-- cubic:v=9a225322-a02d-47ec-92f5-8a6e9cbac537 --> <!-- cubic:review-run=032946e6-2d46-5636-b2fd-dc2abeb31517 --> <!-- metadata:{"confidence":9} --> P2: Client-credentials access tokens never receive the new grant-type attribute, so their encoded IDs use the `UNKNOWN`/`na` grant instead of `client_credentials`. Set `Constants.GRANT_TYPE` to `OAuth2Constants.CLIENT_CREDENTIALS` in `ClientCredentialsGrantType` before generating the access token. <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/protocol/oidc/grants/OAuth2GrantTypeBase.java, line 109: <comment>Client-credentials access tokens never receive the new grant-type attribute, so their encoded IDs use the `UNKNOWN`/`na` grant instead of `client_credentials`. Set `Constants.GRANT_TYPE` to `OAuth2Constants.CLIENT_CREDENTIALS` in `ClientCredentialsGrantType` before generating the access token.</comment> <file context> @@ -105,6 +106,7 @@ protected void setContext(Context context) { protected Response createTokenResponse(UserModel user, UserSessionModel userSession, ClientSessionContext clientSessionCtx, String scopeParam, boolean code, Function<TokenManager.AccessTokenResponseBuilder, ClientPolicyContext> clientPolicyContextGenerator) { + clientSessionCtx.setAttribute(Constants.GRANT_TYPE, context.getGrantType()); AccessToken token = tokenManager.createClientAccessToken(session, realm, client, user, userSession, clientSessionCtx); </file context> ``` </details>
server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java:33
<!-- cubic:v=d085091d-a94e-4d15-8bfe-38a2fa96193a --> <!-- cubic:review-run=032946e6-2d46-5636-b2fd-dc2abeb31517 --> <!-- metadata:{"confidence":8} --> P2: Existing custom OAuth2 grant factories fail during startup after this abstract method is added. Make the SPI evolution backward-compatible or provide an explicit migration path for already-installed providers. <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/protocol/oidc/grants/OAuth2GrantTypeFactory.java, line 33: <comment>Existing custom OAuth2 grant factories fail during startup after this abstract method is added. Make the SPI evolution backward-compatible or provide an explicit migration path for already-installed providers.</comment> <file context> @@ -26,4 +26,9 @@ + * @return usually like 3-letters shortcut of specific grants. It can be useful for example in the tokens when the amount of characters should be limited and hence using full grant name + * is not ideal. Shortcut should be unique across grants. + */ + String getShortcut(); } </file context> ``` </details>
services/src/test/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProviderTest.java:84
<!-- cubic:v=ac5df266-78c2-4309-8be0-1481e27d9775 --> <!-- cubic:review-run=032946e6-2d46-5636-b2fd-dc2abeb31517 --> <!-- metadata:{"confidence":9} --> P3: `testIncorrectGrantType` passes for the wrong reason. The test never calls `postInit()`, so `factory.sessionFactory` is null; for shortcut `"ac"` the provider's refresh branch dereferences the null `sessionFactory` and throws `NullPointerException`, which the broad `catch (RuntimeException)` swallows. The intended `IllegalArgumentException` (unknown grant type) is never exercised, so the test gives false confidence and masks the missing `sessionFactory` setup. Catch `IllegalArgumentException` specifically so the test pins the intended contract and fails loudly until the factory is properly initialized. <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/test/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProviderTest.java, line 82: <comment>`testIncorrectGrantType` passes for the wrong reason. The test never calls `postInit()`, so `factory.sessionFactory` is null; for shortcut `"ac"` the provider's refresh branch dereferences the null `sessionFactory` and throws `NullPointerException`, which the broad `catch (RuntimeException)` swallows. The intended `IllegalArgumentException` (unknown grant type) is never exercised, so the test gives false confidence and masks the missing `sessionFactory` setup. Catch `IllegalArgumentException` specifically so the test pins the intended contract and fails loudly until the factory is properly initialized.</comment> <file context> @@ -0,0 +1,114 @@ + String tokenId = "ofrtac:5678"; + AccessTokenContext ctx = provider.getTokenContextFromTokenId(tokenId); + Assert.fail("Not expected to success due incorrect grant type"); + } catch (RuntimeException iae) { + // ignored + } </file context> ``` </details> ```suggestion } catch (IllegalArgumentException expected) { // expected } ```
PR-level
<!-- cubic:review-summary:start --> **7 issues found** across 28 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="services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java"> <violation number="1" location="services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java:73"> P2: When `rawTokenId` is null, this duplicated check accepts it and `encodeTokenId()` serializes it as the literal `null`, producing an invalid/colliding token ID. Validate `rawTokenId` here instead of checking `grantType` twice.</violation> </file> <file name="services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProviderFactory.java"> <violation number="1" location="services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProviderFactory.java:74"> P2: When a custom OAuth2 grant returns a shortcut other than two characters, this factory registers it unchanged, but token decoding always reads exactly two grant characters. Enforce a two-character shortcut in both startup and dynamic registration, or change the token format to support the documented shortcut lengths.</violation> <violation number="2" location="services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProviderFactory.java:107"> P2: After an OAuth2 grant provider is undeployed or replaced, `getShortcutByGrantType` can keep returning the stale cached shortcut. Rebuild or invalidate these maps when the provider set changes, or revalidate cached entries against the current provider factory before returning them.</violation> </file> <file name="services/src/test/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProviderTest.java"> <violation number="1" location="services/src/test/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProviderTest.java:82"> P3: `testIncorrectGrantType` passes for the wrong reason. The test never calls `postInit()`, so `factory.sessionFactory` is null; for shortcut `"ac"` the provider's refresh branch dereferences the null `sessionFactory` and throws `NullPointerException`, which the broad `catch (RuntimeException)` swallows. The intended `IllegalArgumentException` (unknown grant type) is never exercised, so the test gives false confidence and masks the missing `sessionFactory` setup. Catch `IllegalArgumentException` specifically so the test pins the intended contract and fails loudly until the factory is properly initialized.</violation> </file> <file name="testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java"> <violation number="1" location="testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java:483"> P2: The grant-shortcut check in `isAccessTokenId` is inverted and reads the wrong slice, so it never rejects a token, whatever the grant. `DefaultTokenContextEncoderProvider.encodeTokenId` builds the id as `<sessionType(2)><tokenType(2)><grantShortcut(2)>:<uuid>`, i.e. the shortcut occupies chars 4-5 (`substring(4, 6)`), not `substring(3, 5)`, which grabs the last token-type char plus the first grant char. And `equals(...) return false` makes the matcher reject exactly the token it should accept. As written, a token like `onrtdg:<uuid>` also passes when `expectCodeToToken` expects grant `ac`, so the new assertion provides no real verification of the grant type.</violation> </file> <file name="services/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeBase.java"> <violation number="1" location="services/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeBase.java:109"> P2: Client-credentials access tokens never receive the new grant-type attribute, so their encoded IDs use the `UNKNOWN`/`na` grant instead of `client_credentials`. Set `Constants.GRANT_TYPE` to `OAuth2Constants.CLIENT_CREDENTIALS` in `ClientCredentialsGrantType` before generating the access token.</violation> </file> <file name="server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java"> <violation number="1" location="server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java:33"> P2: Existing custom OAuth2 grant factories fail during startup after this abstract method is added. Make the SPI evolution backward-compatible or provide an explicit migration path for already-installed providers.</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/55/ai_pr_review_github_delivery_6ce69f5c104153c9d9f6bca6a66adf16d9573dd48f066f8b9bd89cd6d32d5982?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F55)</sub> <!-- cubic:review-post:ai_pr_review_github_delivery_6ce69f5c104153c9d9f6bca6a66adf16d9573dd48f066f8b9bd89cd6d32d5982:58b3ebe93f93e70770a823bbbaea8f73fa37809a:032946e6-2d46-5636-b2fd-dc2abeb31517 -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 low ✓ exact
d2 low ✓ off by one
d3 medium ✗ —
valid · matches d1 · impact low
valid · matches d2 · impact low
raw comments (3)
services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java:73
### Constructor null-check uses wrong argument **Low Severity** <!-- DESCRIPTION START --> The constructor validates `grantType` twice and never checks `rawTokenId`, even though the second error message refers to `rawTokenId`. A null `rawTokenId` can therefore be stored and later string-concatenated into the access token `jti` as the literal `"null"`. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: ca978533-e42e-450c-96d3-35e7a64ccb0f --> <!-- LOCATIONS START services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java#L68-L73 LOCATIONS END --> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjM5MTU4M2JhLWI0MTgtNDZjZC04Mzc4LTVkOWFmNDY2YWJhYiIsImVuY3J5cHRpb25LZXkiOiJsWEUtUzd3RWxWdm1HMkJQUlhpODJyd2NPTl9Kbm5RV2w3UU9WVG5VMVBnIiwiYnJhbmNoIjoidDIta2V5Y2xvYWstMzc2MzQiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" 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=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjM5MTU4M2JhLWI0MTgtNDZjZC04Mzc4LTVkOWFmNDY2YWJhYiIsImVuY3J5cHRpb25LZXkiOiJsWEUtUzd3RWxWdm1HMkJQUlhpODJyd2NPTl9Kbm5RV2w3UU9WVG5VMVBnIiwiYnJhbmNoIjoidDIta2V5Y2xvYWstMzc2MzQiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByTnVtYmVyIjo1NywiY29tbWl0U2hhIjoiNjQ1NmY1YmJmMTYxYzViMjg0OTY0ZDE2MjQ3YTBlN2I1MjgzODVhOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" 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 6456f5bbf161c5b284964d16247a0e7b528385a9. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java:491
### Access token ID matcher is inverted **Medium Severity** <!-- DESCRIPTION START --> `isAccessTokenId` reads the grant shortcut from the wrong prefix indexes and returns false when that slice matches the expected grant. Refresh-token events whose prefix ends with `rt` fail the matcher, while other grants can pass even when the encoded grant is wrong. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: 3823e99d-29cc-4587-bcf7-bd2788917134 --> <!-- LOCATIONS START testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java#L475-L491 LOCATIONS END --> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmVmMzlmZjIyLTdkOGUtNDFjYy1hYWI0LWU1MDVkYzNkYjdlNiIsImVuY3J5cHRpb25LZXkiOiI0T3hPNGVOWjIwWk9RZmxVbHBpYnY1Q0daSlpjdTFtLU1EWGFrOXU3TE5VIiwiYnJhbmNoIjoidDIta2V5Y2xvYWstMzc2MzQiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" 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=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmVmMzlmZjIyLTdkOGUtNDFjYy1hYWI0LWU1MDVkYzNkYjdlNiIsImVuY3J5cHRpb25LZXkiOiI0T3hPNGVOWjIwWk9RZmxVbHBpYnY1Q0daSlpjdTFtLU1EWGFrOXU3TE5VIiwiYnJhbmNoIjoidDIta2V5Y2xvYWstMzc2MzQiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByTnVtYmVyIjo1NywiY29tbWl0U2hhIjoiNjQ1NmY1YmJmMTYxYzViMjg0OTY0ZDE2MjQ3YTBlN2I1MjgzODVhOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" 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 6456f5bbf161c5b284964d16247a0e7b528385a9. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
PR-level
<!-- BUGBOT_REVIEW --> Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues. <!-- BUGBOT_FIX_ALL --> <a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aTo2NWRhMTVkMC01ODc0LTQyYjQtOTUzOC0yMWQxYzI0ZmJkM2YiLCJlbmNyeXB0aW9uS2V5IjoiRVMxRUdkN3A5aWpMd3o0ZkduQk9WTGtvNUtsZlVaeHZDcHByQVAxRVlCYyIsImJyYW5jaCI6InQyLWtleWNsb2FrLTM3NjM0IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" 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 6456f5bbf161c5b284964d16247a0e7b528385a9. 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
d1 low ✓ exact
d2 low ✓ exact
d3 medium ✓ exact
valid · matches d1 · impact low
valid · matches d2 · impact low
valid · matches d3 · impact medium
valid · impact low
The UMA flow builds its own clientSessionCtx and calls generateAccessToken without setting Constants.GRANT_TYPE. The new encoder therefore falls back to 'na', even though the change registered 'pg' for this grant. This is an incomplete change. [grounded: tree services/src/main/java/org/keycloak/authorization/authorization/AuthorizationTokenService.java] [consensus 3/3: valid=3]
valid · impact low
The new javadoc suggests about 3-letter shortcuts, but the decoder requires exactly 2 characters and nothing checks the length. A grant with a 3-letter shortcut would encode without error, then fail when the token id is decoded. [grounded: tree services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProvider.java] [consensus 3/3: valid=3]
valid · impact low
In AbstractTokenExchangeProvider's exchangeClientToOIDCClient (the legacy path), generateAccessToken is called without setting GRANT_TYPE. Only the Standard provider was updated, so legacy exchange tokens are encoded with 'na'. [grounded: tree services/src/main/java/org/keycloak/protocol/oidc/tokenexchange/AbstractTokenExchangeProvider.java] [consensus 3/3: valid=3]
valid · impact medium
getShortcut() is a new abstract interface method with no default, and postInit calls it on every grant factory. A custom factory compiled against the old interface throws AbstractMethodError. A null shortcut makes ConcurrentHashMap.put throw a NullPointerException, so server startup fails. [grounded: diff] [consensus 3/3: valid=3]
raw comments (7)
services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java:73
**Null rawTokenId is not rejected** The fourth null check tests `grantType` again instead of `rawTokenId`, so a null raw id is accepted and later encoded as `...:null`. Use `Objects.requireNonNull(rawTokenId, ...)`. ``` services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java:73 Objects.requireNonNull(grantType, "Null rawTokenId not allowed"); services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java:70 Objects.requireNonNull(sessionType, "Null sessionType not allowed"); services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java:71 Objects.requireNonNull(tokenType, "Null tokenType not allowed"); services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java:72 Objects.requireNonNull(grantType, "Null grantType not allowed"); services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java:74 this.sessionType = sessionType; services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java:75 this.tokenType = tokenType; services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java:76 this.grantType = grantType; services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java:77 this.rawTokenId = rawTokenId; ```
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java:483
**isAccessTokenId never checks the grant type** The grant check reads the wrong slice (`substring(3,5)` instead of `(4,6)`) and returns false when it matches. With the wrong slice it never matches, so the grant shortcut is never verified, and fixing the offset alone would reject correct ids. Use `if (!items[0].substring(4, 6).equals(expectedGrantShortcut)) return false;`. ``` testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java:476 public static Matcher<String> isAccessTokenId(String expectedGrantShortcut) { testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java:477 return new TypeSafeMatcher<String>() { testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java:478 @Override testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java:479 protected boolean matchesSafely(String item) { testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java:482 // Grant type shortcut starts at character 4th char and is 2-chars long testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java:483 if (items[0].substring(3, 5).equals(expectedGrantShortcut)) return false; testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java:484 return isUUID().matches(items[1]); ```
services/src/main/java/org/keycloak/protocol/oidc/grants/ClientCredentialsGrantType.java:140
**Client credentials tokens get unknown grant 'na'** The client credentials grant goes straight to `responseBuilder(...).generateAccessToken()` without going through `createTokenResponse`, so nothing sets `Constants.GRANT_TYPE` on its client session context. Its token ids get the unknown marker even though a `cc` shortcut is registered for it. Set `Constants.GRANT_TYPE` to `context.getGrantType()` on clientSessionCtx before generating the access token. ``` services/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeBase.java:109 clientSessionCtx.setAttribute(Constants.GRANT_TYPE, context.getGrantType()); services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProvider.java:57 String grantType = clientSessionContext.getAttribute(Constants.GRANT_TYPE, String.class); services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProvider.java:58 if (grantType == null) { services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProvider.java:59 grantType = UNKNOWN; services/src/main/java/org/keycloak/protocol/oidc/grants/ClientCredentialsGrantType.java:122 ClientSessionContext clientSessionCtx = TokenManager.attachAuthenticationSession(session, userSession, authSession); services/src/main/java/org/keycloak/protocol/oidc/grants/ClientCredentialsGrantType.java:124 // Notes about client details services/src/main/java/org/keycloak/protocol/oidc/grants/ClientCredentialsGrantType.java:125 userSession.setNote(ServiceAccountConstants.CLIENT_ID_SESSION_NOTE, client.getClientId()); // This is for backwards compatibility services/src/main/java/org/keycloak/protocol/oidc/grants/ClientCredentialsGrantType.java:126 userSession.setNote(ServiceAccountConstants.CLIENT_ID, client.getClientId()); services/src/main/java/org/keycloak/protocol/oidc/grants/ClientCredentialsGrantType.java:127 userSession.setNote(ServiceAccountConstants.CLIENT_HOST, clientConnection.getRemoteHost()); services/src/main/java/org/keycloak/protocol/oidc/grants/ClientCredentialsGrantType.java:128 userSession.setNote(ServiceAccountConstants.CLIENT_ADDRESS, clientConnection.getRemoteAddr()); ```
services/src/main/java/org/keycloak/authorization/authorization/AuthorizationTokenService.java:358
**UMA permission tokens get unknown grant 'na'** The UMA ticket grant builds its token in `AuthorizationTokenService` and never sets `Constants.GRANT_TYPE`. Its token ids therefore carry `na` instead of the `pg` shortcut that was registered for this grant. Set the grant type attribute on the client session context in the UMA flow. ``` services/src/main/java/org/keycloak/protocol/oidc/grants/PermissionGrantTypeFactory.java:38 @Override services/src/main/java/org/keycloak/protocol/oidc/grants/PermissionGrantTypeFactory.java:39 public String getShortcut() { services/src/main/java/org/keycloak/protocol/oidc/grants/PermissionGrantTypeFactory.java:40 return "pg"; services/src/main/java/org/keycloak/protocol/oidc/grants/PermissionGrantTypeFactory.java:41 } services/src/main/java/org/keycloak/authorization/authorization/AuthorizationTokenService.java:350 clientSessionCtx = TokenManager.attachAuthenticationSession(keycloakSession, userSessionModel, authSession); services/src/main/java/org/keycloak/authorization/authorization/AuthorizationTokenService.java:351 } else { services/src/main/java/org/keycloak/authorization/authorization/AuthorizationTokenService.java:352 clientSessionCtx = DefaultClientSessionContext.fromClientSessionScopeParameter(clientSession, keycloakSession); services/src/main/java/org/keycloak/authorization/authorization/AuthorizationTokenService.java:353 } services/src/main/java/org/keycloak/authorization/authorization/AuthorizationTokenService.java:355 TokenManager tokenManager = request.getTokenManager(); services/src/main/java/org/keycloak/authorization/authorization/AuthorizationTokenService.java:356 EventBuilder event = request.getEvent(); ```
server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java:30
**Shortcut length: docs say 3, decoder needs 2** The `getShortcut` javadoc tells implementers to use about 3 letters, but `getTokenContextFromTokenId` only accepts a 6-character prefix, i.e. exactly 2 letters for the grant. Neither registration nor `encodeTokenId` checks the length. Make the javadoc say exactly 2 characters, and check the length in postInit. ``` server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java:29 /** server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java:30 * @return usually like 3-letters shortcut of specific grants. It can be useful for example in the tokens when the amount of characters should be limited and hence using full grant name server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java:31 * is not ideal. Shortcut should be unique across grants. server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java:32 */ services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProvider.java:74 if (encodedContext.length() != 6) { services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProvider.java:75 throw new IllegalArgumentException("Incorrect token id: '" + encodedTokenId + "'. Expected length of 6."); services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProvider.java:76 } ```
services/src/main/java/org/keycloak/protocol/oidc/tokenexchange/AbstractTokenExchangeProvider.java:410
**Legacy token exchange tokens encoded as unknown grant** Only `StandardTokenExchangeProvider` sets `Constants.GRANT_TYPE`. The legacy (V1) exchange path in `AbstractTokenExchangeProvider` generates the access token without it, so those tokens get `na` instead of `te`. Set the grant type attribute in the shared exchange code path, not only in the standard provider. ``` services/src/main/java/org/keycloak/protocol/oidc/tokenexchange/StandardTokenExchangeProvider.java:237 clientSessionCtx.setAttribute(Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE); services/src/main/java/org/keycloak/protocol/oidc/TokenManager.java:1052 TokenContextEncoderProvider encoder = session.getProvider(TokenContextEncoderProvider.class); services/src/main/java/org/keycloak/protocol/oidc/TokenManager.java:1053 AccessTokenContext tokenCtx = encoder.getTokenContextFromClientSessionContext(clientSessionCtx, KeycloakModelUtils.generateId()); services/src/main/java/org/keycloak/protocol/oidc/TokenManager.java:1054 token.id(encoder.encodeTokenId(tokenCtx)); services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProvider.java:57 String grantType = clientSessionContext.getAttribute(Constants.GRANT_TYPE, String.class); services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProvider.java:58 if (grantType == null) { services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProvider.java:59 grantType = UNKNOWN; services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProvider.java:60 } ```
server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java:33
**Existing custom grant providers break at startup** `getShortcut()` is added as an abstract method. A custom grant factory built against the old interface throws AbstractMethodError, and one that returns null throws a NullPointerException from ConcurrentHashMap. Either way the encoder's `postInit` fails during server boot. Give `getShortcut()` a default implementation, and skip or reject null shortcuts in `postInit`. ``` server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java:29 /** server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java:30 * @return usually like 3-letters shortcut of specific grants. It can be useful for example in the tokens when the amount of characters should be limited and hence using full grant name server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java:31 * is not ideal. Shortcut should be unique across grants. server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java:32 */ services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProviderFactory.java:73 String grantName = gtf.getId(); services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProviderFactory.java:74 String grantShortcut = gtf.getShortcut(); services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProviderFactory.java:75 grantsByShortcuts.put(grantShortcut, grantName); ```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 low ✓ exact
d2 low ✓ off by one
d3 medium ✓ exact
valid · matches d1 · impact low
valid · matches d2 · impact low
valid · impact low
The new javadoc suggests roughly 3-letter shortcuts. The new decoder, however, requires a context of exactly 6 characters (2+2+2), and postInit never checks shortcut length. A grant that follows the doc and uses a 3-letter shortcut would get token ids that encode fine but throw IllegalArgumentException when decoded. [grounded: tree services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProvider.java] [consensus 3/3: valid=3]
valid · matches d3 · impact medium
valid · impact low
This change sets GRANT_TYPE on the client session context for several grant paths and registers the 'pg' shortcut. The UMA RPT path in AuthorizationTokenService builds its own context and never sets the attribute, so RPT token ids get encoded with 'na' (unknown). This is an incomplete change: it doesn't crash, but the token context is wrong. [grounded: tree services/src/main/java/org/keycloak/authorization/authorization/AuthorizationTokenService.java] [consensus 3/3: valid=3]
raw comments (5)
services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java:76
**rawTokenId null check tests grantType instead** The constructor calls `Objects.requireNonNull(grantType, "Null rawTokenId not allowed")`, so `rawTokenId` is never checked. A null raw id is accepted. Call requireNonNull(rawTokenId, ...). ``` services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java:76 this.grantType = grantType; ```
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java:481
**Token ID matcher never checks grant shortcut** `isAccessTokenId` reads the wrong characters (3-5, not 4-6) and inverts the equality check. Any grant shortcut passes, and a correct one would be rejected if the offsets were fixed alone. Use `!items[0].substring(4, 6).equals(expectedGrantShortcut)` to return false. ``` testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java:481 if (items.length != 2) return false; testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java:482 // Grant type shortcut starts at character 4th char and is 2-chars long testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java:483 if (items[0].substring(3, 5).equals(expectedGrantShortcut)) return false; ```
server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java:29
**Shortcut doc says 3 letters, decoder needs 2** The `getShortcut()` javadoc says "usually like 3-letters", but token ids use a fixed 2-char grant field. A 3-letter shortcut encodes fine, but `getTokenContextFromTokenId` then rejects the id. Document exactly 2 chars and validate the length in postInit. ``` server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java:29 /** server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java:30 * @return usually like 3-letters shortcut of specific grants. It can be useful for example in the tokens when the amount of characters should be limited and hence using full grant name server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java:31 * is not ideal. Shortcut should be unique across grants. server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java:32 */ ```
services/src/main/java/org/keycloak/protocol/oidc/grants/ClientCredentialsGrantType.java:122
**Client credentials tokens get unknown grant in ID** `ClientCredentialsGrantType` builds its own `clientSessionCtx` and calls `responseBuilder().generateAccessToken()` without setting `Constants.GRANT_TYPE`. The grant is only set in `createTokenResponse`, which this grant skips. A `cc` shortcut is registered, but it is never used. Call clientSessionCtx.setAttribute(Constants.GRANT_TYPE, context.getGrantType()) after attachAuthenticationSession. ``` services/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeBase.java:109 clientSessionCtx.setAttribute(Constants.GRANT_TYPE, context.getGrantType()); services/src/main/java/org/keycloak/protocol/oidc/grants/ClientCredentialsGrantTypeFactory.java:38 @Override services/src/main/java/org/keycloak/protocol/oidc/grants/ClientCredentialsGrantTypeFactory.java:39 public String getShortcut() { services/src/main/java/org/keycloak/protocol/oidc/grants/ClientCredentialsGrantTypeFactory.java:40 return "cc"; services/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeBase.java:107 protected Response createTokenResponse(UserModel user, UserSessionModel userSession, ClientSessionContext clientSessionCtx, services/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeBase.java:108 String scopeParam, boolean code, Function<TokenManager.AccessTokenResponseBuilder, ClientPolicyContext> clientPolicyContextGenerator) { services/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeBase.java:110 AccessToken token = tokenManager.createClientAccessToken(session, realm, client, user, userSession, clientSessionCtx); ```
services/src/main/java/org/keycloak/authorization/authorization/AuthorizationTokenService.java:352
**UMA grant tokens get unknown grant in ID** The UMA permission grant creates its own `clientSessionCtx` in `AuthorizationTokenService` and never sets `Constants.GRANT_TYPE`. The `pg` shortcut is registered but unused. Set Constants.GRANT_TYPE to the UMA grant type on the context before the token is created. ``` services/src/main/java/org/keycloak/protocol/oidc/grants/PermissionGrantTypeFactory.java:38 @Override services/src/main/java/org/keycloak/protocol/oidc/grants/PermissionGrantTypeFactory.java:39 public String getShortcut() { services/src/main/java/org/keycloak/protocol/oidc/grants/PermissionGrantTypeFactory.java:40 return "pg"; services/src/main/java/org/keycloak/protocol/oidc/grants/PermissionGrantTypeFactory.java:41 } services/src/main/java/org/keycloak/authorization/authorization/AuthorizationTokenService.java:352 clientSessionCtx = DefaultClientSessionContext.fromClientSessionScopeParameter(clientSession, keycloakSession); ```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 low ✓ off by one
d2 low ✓ off by one
d3 medium ✓ off by one
valid · matches d3 · impact medium
valid · matches d2 · impact low
valid · matches d1 · impact low
invalid
Nothing in the repo calls setFormParams; a grep finds only its definition. TokenEndpoint also picks the grant implementation from the original grant_type before the Context is built. So the captured value is the grant that is actually running, and replacing the form params later would not change which grant runs. The "stale" value is only a problem for a hypothetical custom caller. [invalid: contradiction] [consensus 3/4: invalid=3, valid=1]
raw comments (5)
services/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeBase.java:109
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Client Credentials Lose Grant** Client-credentials issuance calls `generateAccessToken()` directly instead of this shared response helper, so it never sets `Constants.GRANT_TYPE`. The encoder then falls back to `na`, causing service-account access-token IDs to record an unknown grant instead of the registered `cc` shortcut.
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java:484
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> **Matcher Ignores Expected Grant** The grant shortcut occupies `substring(4, 6)`, but this matcher reads `substring(3, 5)` and rejects the value when it matches rather than when it differs. These event tests can therefore accept an incorrect grant shortcut and miss regressions in the new token-ID format. ```suggestion // Grant type shortcut starts at the 5th character and is 2 characters long if (!items[0].substring(4, 6).equals(expectedGrantShortcut)) return false; return isUUID().matches(items[1]); ```
services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java:73
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> **Raw Token ID Unchecked** This line checks `grantType` a second time instead of validating `rawTokenId`. A provider can therefore construct this context with a null raw ID, after which the default encoder emits an identifier ending in the literal `:null` instead of rejecting the invalid context. ```suggestion Objects.requireNonNull(rawTokenId, "Null rawTokenId not allowed"); ```
server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantType.java:102
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> **Grant Type Becomes Stale** `grantType` is captured only from the initial form parameters, while the public `setFormParams` method can replace those parameters without updating this field. If a custom grant uses that setter, `getGrantType()` can remain stale and the resulting token ID can encode a grant different from the effective request parameters.
PR-level
<h3>Greptile Summary</h3> This PR introduces an internal token-context encoder that embeds session type, token type, and OAuth grant type into access-token IDs, registers the new SPI, assigns grant context across issuance flows, and updates event-test expectations. - Adds the token-context model, encoder provider, factory, SPI, and service registrations. - Adds two-character shortcuts to built-in OAuth grant factories. - Changes access-token IDs from raw UUIDs to context-prefixed identifiers. - Leaves client-credentials tokens encoded with an unknown grant and introduces test and validation gaps around the new format. <h3>Confidence Score: 4/5</h3> The PR is not safe to merge until client-credentials access tokens encode their actual grant type; the remaining findings are lower-impact correctness and test-quality issues. Client-credentials issuance directly invokes access-token generation without setting the context consumed by the new encoder, so those tokens deterministically receive the unknown grant shortcut. The new matcher also cannot detect incorrect shortcuts, and two new context APIs permit stale or null identifier state. **Files Needing Attention:** services/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeBase.java, services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java, server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantType.java, testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java <details><summary><h3>Important Files Changed</h3></summary> | Filename | Overview | |----------|----------| | services/src/main/java/org/keycloak/protocol/oidc/TokenManager.java | Routes all access-token ID generation through the new context encoder. | | services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProvider.java | Encodes and decodes session, token, and grant metadata in access-token IDs. | | services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProviderFactory.java | Builds shortcut maps from registered OAuth grant factories and validates collisions. | | services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java | Defines encoded token metadata but fails to validate the raw token ID. | | services/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeBase.java | Propagates grant context for shared response flows but does not cover client credentials. | | server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantType.java | Snapshots request grant type in the grant context without synchronizing later form replacements. | | testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java | Updates event assertions for prefixed IDs, but the matcher reads the wrong characters and reverses the comparison. | </details> <details open><summary><h3>Sequence Diagram</h3></summary> ```mermaid sequenceDiagram participant Grant as OAuth grant participant CSC as ClientSessionContext participant TM as TokenManager participant Encoder as TokenContextEncoder participant Token as AccessToken Grant->>CSC: Set Constants.GRANT_TYPE Grant->>TM: Generate access token TM->>Encoder: Build context(session, token, grant, UUID) Encoder-->>TM: Encode prefix:raw UUID TM->>Token: Set prefixed jti ``` </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/6c7df0cd62c241fa77eb35b20fa15039768223ae) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64284632)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 low ✓ exact
d2 low ✓ off by one
d3 medium ✓ exact
valid · matches d3 · impact medium
valid · impact low
The RPT is built with responseBuilder(...).generateAccessToken(), and nothing sets Constants.GRANT_TYPE first. So the new encoder falls back to 'na' rather than 'pg'. The change only sets the attribute on some grant paths, which leaves this one incomplete. [grounded: tree services/src/main/java/org/keycloak/authorization/authorization/AuthorizationTokenService.java] [consensus 3/4: valid=3, invalid=1]
valid · matches d2 · impact low
valid · impact medium
The grant shortcut sits at indices 4–6, but substring(3,5) reads characters 3–4 instead (e.g. 'ta' for 'onrtac'). The check also returns false when the value matches, so the grant assertion is ineffective. [grounded: diff] [consensus 3/3: valid=3]
valid · impact medium
ClientCredentialsGrantType never calls createTokenResponse and never sets Constants.GRANT_TYPE. The encoder therefore falls back to 'na' instead of 'cc'. This is an incomplete rollout of the grant-type attribute. [grounded: tree services/src/main/java/org/keycloak/protocol/oidc/grants/ClientCredentialsGrantType.java] [consensus 3/3: valid=3]
valid · matches d1 · impact low
raw comments (6)
services/src/main/java/org/keycloak/protocol/oidc/grants/ClientCredentialsGrantTypeFactory.java:38
[P2] Client-credentials tokens are never tagged with their grant type `Constants.GRANT_TYPE` is only set on the client session context in `OAuth2GrantTypeBase.createTokenResponse`, the ROPC grant, the pre-authorized code grant, refresh and standard token exchange. `ClientCredentialsGrantType` does not go through `createTokenResponse`. It calls `tokenManager.responseBuilder(...).generateAccessToken()` directly and never sets the attribute. As a result, `DefaultTokenContextEncoderProvider.getTokenContextFromClientSessionContext` falls back to `na`, and service-account access tokens get IDs like `trrtna:‹uuid›` instead of using the new `cc` shortcut. The new unit test (`trltcc:1234`) expects the `cc` form, so the grant context this feature is meant to encode is lost for one of the most common grants.
services/src/main/java/org/keycloak/protocol/oidc/grants/PermissionGrantTypeFactory.java:38
[P2] UMA permission-grant tokens are also encoded with an unknown grant type The `pg` shortcut is registered here, but RPTs are created in `AuthorizationTokenService` through `tokenManager.responseBuilder(...).generateAccessToken()`, and that path never sets `Constants.GRANT_TYPE` on `clientSessionCtx`. Every RPT issued for `urn:ietf:params:oauth:grant-type:uma-ticket` therefore gets the `na` grant marker instead of `pg`, and the `pg` shortcut is never used.
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java:483
[P2] `isAccessTokenId` matcher checks the wrong substring and has its condition inverted, so it never verifies the grant The encoded prefix is `‹session:2›‹tokenType:2›‹grant:2›`, so the grant shortcut is at `substring(4, 6)`, not `substring(3, 5)`. For example, `"onrtac".substring(3, 5)` is `"ta"`. On top of that, the check returns `false` when the shortcut *does* match. With the wrong offsets the comparison is never true, so the matcher accepts any `xxxxxx:‹uuid›` ID regardless of grant. If only the offsets were fixed, it would reject every correct token. Because of this, the updated `expectCodeToToken`, `expectRefresh`, `expectDeviceCodeToToken` and `expectAuthReqIdToToken` assertions give no coverage that the right grant shortcut is encoded. This is how the missing client-credentials and UMA tagging above can go unnoticed.
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java:481
[P2] Grant check in `isAccessTokenId` is inverted and reads the wrong characters, so it never fails The grant shortcut is characters 4–5 of the 6-character prefix, so it should be `substring(4, 6)`. The code uses `substring(3, 5)`, which for `onrtac` returns `ta`. The check also returns `false` when the shortcut *matches*. Because the extracted value is never the real shortcut, the check never triggers. Any token ID in `xxxxxx:‹uuid›` form passes regardless of grant type. That includes `na` (unknown) and the wrong grant. As a result, `expectCodeToToken`, `expectRefresh`, `expectDeviceCodeToToken` and `expectAuthReqIdToToken` never catch a regression in the grant-type encoding.
services/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeBase.java:109
[P2] Client credentials tokens get the `na` grant instead of `cc` The grant type is now stored on the client session context in `createTokenResponse`, in the password grant, and in the refresh, pre-authorized and standard token-exchange paths. `ClientCredentialsGrantType` does not use any of these. It calls `tokenManager.responseBuilder(...).generateAccessToken()` directly and never sets `Constants.GRANT_TYPE`. So `DefaultTokenContextEncoderProvider` falls back to `UNKNOWN`, and every service-account access token is encoded as `..na:‹uuid›`. This happens even though `ClientCredentialsGrantTypeFactory` defines the `cc` shortcut and the unit test uses `trltcc` as the expected client-credentials ID. Anything that later decodes the token ID to tell client-credentials tokens apart gets the wrong answer. Legacy/V1, federated and impersonation token exchange (`AbstractTokenExchangeProvider`) have the same problem: only `StandardTokenExchangeProvider` sets the attribute.
services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java:73
[P3] Null check validates `grantType` twice and never `rawTokenId` The fourth `Objects.requireNonNull` passes `grantType` but uses the message "Null rawTokenId not allowed". As a result, a null `rawTokenId` is accepted. `encodeTokenId` would then produce an ID ending in `:null` instead of failing fast, as the constructor is clearly meant to.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 low ✓ exact
d2 low ✓ off by one
d3 medium ✗ —
valid · matches d2 · impact low
valid · matches d1 · impact low
valid · impact low
For an id like 'onrtac:<uuid>', substring(3,5) yields 'ta', which never equals the 2-char grant shortcut, so the check is skipped. The equality is also inverted, so the matcher accepts any grant type. The encoder puts the grant at chars 4-6. [grounded: tree testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java] [consensus 3/3: valid=3]
valid · impact low
The fourth null check validates grantType again instead of rawTokenId. A null rawTokenId therefore gets through the public constructor, and encodeTokenId appends it as the string 'null'. [grounded: tree services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java] [consensus 3/3: valid=3]
raw comments (4)
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java:482
[P2] isAccessTokenId matcher never actually checks the grant shortcut The shortcut check is wrong in two ways. The encoded id is `‹st:2›‹tt:2›‹gt:2›:uuid`, so the grant shortcut is at indices 4-6, but the code compares `substring(3, 5)`. The condition is also inverted: it returns false when the substring equals the expected shortcut. For `onrtac:...` the substring is `"ta"`, which never equals `"ac"`, so the matcher passes for any grant. If the indices were fixed alone, every correct id would be rejected. As written, the updated `expectCodeToToken`, `expectRefresh`, device and CIBA assertions don't verify the encoded grant type.
services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java:207
[P3] Wrong argument in null-check for rawTokenId The fourth `Objects.requireNonNull` call checks `grantType` a second time but is labelled "Null rawTokenId not allowed". A null `rawTokenId` is therefore accepted. It would only fail later at `encodeTokenId`, where it is concatenated as the literal string "null". The argument should be `rawTokenId`.
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java:1004
[P2] isAccessTokenId matcher never validates the grant shortcut The grant shortcut sits at chars 4–6 of the 6-char prefix (session[0..2], token type[2..4], grant[4..6]), but the matcher reads `substring(3, 5)`. It also returns false when the substring *equals* the expected shortcut, so the condition is inverted. The wrong slice never equals a 2-char shortcut, so the check is effectively skipped. The matcher then accepts any `xxxxxx:‹uuid›` id regardless of grant type, so `expectCodeToToken`, `expectRefresh`, `expectDeviceCodeToToken` and `expectAuthReqIdToToken` would not catch a wrong grant encoding. If the check is ever made to work as written, it would reject the correct grant. Use `substring(4, 6)` and return false when it does *not* equal the expected shortcut.
services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java:207
[P3] requireNonNull checks grantType twice and never checks rawTokenId The fourth null check is `Objects.requireNonNull(grantType, "Null rawTokenId not allowed")`. It checks `grantType` a second time instead of `rawTokenId`. A null `rawTokenId` passes construction, and `encodeTokenId` would then produce an id like `onrtac:null`. It should be `requireNonNull(rawTokenId, ...)`.
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 low ✗ —
d2 low ✗ —
d3 medium ✗ —
raw comments (2)
PR-level
<h3>Qodo is busy working</h3> Check back in a few minutes. Qodo's code review agents are on it. <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <img src="https://www.qodo.ai/wp-content/uploads/2026/01/anteater-looking-at-ants-01-transparent-bg-croped-ezgif.com-optimize-1.gif" width="30%">
PR-level
<h3>PR Summary by Qodo</h3> Encode access token context into token IDs <code>✨ Enhancement</code> <code>🧪 Tests</code> <code>⚙️ Configuration changes</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> >• Encode session, token, and grant metadata into access token identifiers. >• Introduce an internal encoder SPI with grant-specific shortcuts and legacy token decoding. >• Cover encoder round trips and adapt event assertions to contextual identifiers. ></pre> </dd> </dl> </details> <details> <summary>Diagram</summary> <dl> <dd> <br/> ```mermaid graph TD A["OAuth2 Request"] --> B["Grant Handler"] --> C["Session Context"] --> D["Token Manager"] --> E["Encoder SPI"] --> F["Contextual JTI"] G["Grant Factories"] --> E H["Token ID Reader"] --> E ``` </dd> </dl> </details> <details> <summary>High-Level Assessment</summary> <dl> <dd> <br/> >The following are alternative approaches to this PR: <details> <summary><b>1. Add proprietary token claims</b></summary> <dl> <dd> - ➕ Keeps token identifiers as plain UUIDs - ➕ Makes metadata directly visible after JWT decoding - ➖ Expands token payloads - ➖ Exposes internal metadata through non-standard claims - ➖ Requires claim handling across token representations </dd> </dl> </details> <details> <summary><b>2. Use a fixed encoding utility</b></summary> <dl> <dd> - ➕ Reduces SPI and service-loader complexity - ➕ Centralizes all shortcuts in one implementation - ➖ Couples token creation to one encoding format - ➖ Makes custom grant deployment and future encoders harder to support </dd> </dl> </details> >**Recommendation:** Retain the SPI-based contextual identifier approach. It avoids proprietary claims, supports dynamically deployed grant factories, and preserves decoding compatibility for legacy unprefixed identifiers; a fixed utility would be simpler but less extensible. </dd> </dl> </details> <details> <summary> Files changed (28) <code> +722 / -26 </code> </summary> <dl> <dd> <br/> <details> <summary>Enhancement (23) <code> +560 / -21 </code></summary> <dl> <dd> <details> <summary>Constants.java<code>Add client-session grant type attribute key</code> <code>+2/-0</code></summary> <br/> >Add client-session grant type attribute key > ><pre> >• Defines a shared attribute key for propagating the OAuth2 grant type through client session context. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-5c7a6fdebb1a96ff59901bc707388f6e79d591bbdbbff9fbec2b147838cbd2c0'>server-spi-private/src/main/java/org/keycloak/models/Constants.java</a> </details> <details> <summary>OAuth2GrantType.java<code>Capture grant type in grant processing context</code> <code>+7/-16</code></summary> <br/> >Capture grant type in grant processing context > ><pre> >• Reads the grant type from token request parameters and exposes it to grant implementations. The former context copy constructor is removed. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-e8d11d2da74abfb4b8ee2fe7c73a0b515179e5440ae5ab4ccfaf07d856913c12'>server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantType.java</a> </details> <details> <summary>OAuth2GrantTypeFactory.java<code>Require compact shortcuts from grant factories</code> <code>+5/-0</code></summary> <br/> >Require compact shortcuts from grant factories > ><pre> >• Extends the grant factory contract with a unique compact shortcut used in access-token identifiers. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-1c4eacaffb344677c496eba116fc5d56ce63517afeac7c39ee331887512187b0'>server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java</a> </details> <details> <summary>TokenManager.java<code>Generate contextual access-token identifiers</code> <code>+11/-4</code></summary> <br/> >Generate contextual access-token identifiers > ><pre> >• Delegates access-token ID generation to the token context encoder and marks refreshed access tokens with the refresh-token grant. It also corrects the spelling of a requested-audience local variable. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-fd8b1c47da5ec7ee42d5450d3f7b73cdeef9c08af26b825c9245e3e6052c5cdf'>services/src/main/java/org/keycloak/protocol/oidc/TokenManager.java</a> </details> <details> <summary>AccessTokenContext.java<code>Model access-token encoding context</code> <code>+95/-0</code></summary> <br/> >Model access-token encoding context > ><pre> >• Introduces an immutable context containing session type, token type, grant type, and raw token ID. Session and token categories provide compact two-character representations. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-17418e9f3fcb7c94b1bab8790116f1027e943dd9912f3ac094aa637918269802'>services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java</a> </details> <details> <summary>DefaultTokenContextEncoderProvider.java<code>Implement contextual token-ID encoding and decoding</code> <code>+124/-0</code></summary> <br/> >Implement contextual token-ID encoding and decoding > ><pre> >• Derives session, token, and grant metadata and prefixes it to the raw token ID. It decodes contextual IDs, rejects unknown encoded values, and treats unprefixed IDs as legacy tokens. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-3a9455186ab8cdc7235677f8f0dc74000fc718805ae2698f1c0c62fd4c9b92d8'>services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProvider.java</a> </details> <details> <summary>DefaultTokenContextEncoderProviderFactory.java<code>Build and maintain token shortcut registries</code> <code>+138/-0</code></summary> <br/> >Build and maintain token shortcut registries > ><pre> >• Registers session, token, and grant shortcuts for bidirectional lookup. It validates shortcut uniqueness and refreshes grant mappings for dynamically deployed factories. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-8fe59160659bc8bfedc40b389177d9012587e877839599d369a1ef74f8539623'>services/src/main/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProviderFactory.java</a> </details> <details> <summary>TokenContextEncoderProvider.java<code>Define the token context encoder provider contract</code> <code>+38/-0</code></summary> <br/> >Define the token context encoder provider contract > ><pre> >• Adds provider methods for deriving context, decoding token IDs, and encoding contextual identifiers. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-28a32bb57fdb452dcdc01b71a78a9de76f25f24996abedfa44d31de22c40ebff'>services/src/main/java/org/keycloak/protocol/oidc/encode/TokenContextEncoderProvider.java</a> </details> <details> <summary>TokenContextEncoderProviderFactory.java<code>Define the token encoder factory contract</code> <code>+28/-0</code></summary> <br/> >Define the token encoder factory contract > ><pre> >• Introduces the provider factory interface for token context encoder implementations. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-d3f91989ee6843211c67a8e0d3cd2513bb65a86d0641217603a562bad3e95de5'>services/src/main/java/org/keycloak/protocol/oidc/encode/TokenContextEncoderProviderFactory.java</a> </details> <details> <summary>TokenContextEncoderSpi.java<code>Declare the internal token encoder SPI</code> <code>+51/-0</code></summary> <br/> >Declare the internal token encoder SPI > ><pre> >• Registers token context encoding as an internal Keycloak SPI and identifies its provider and factory contracts. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-70c29be17d24bda139a38421aab2939e03a6416d958a77893c114570b97ccfa7'>services/src/main/java/org/keycloak/protocol/oidc/encode/TokenContextEncoderSpi.java</a> </details> <details> <summary>AuthorizationCodeGrantTypeFactory.java<code>Assign authorization-code grant shortcut</code> <code>+7/-0</code></summary> <br/> >Assign authorization-code grant shortcut > ><pre> >• Registers &#x27;ac&#x27; as the compact authorization-code grant identifier. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-6134bc2028bd5e7c12304c989287e93fb201a994857fac8f257f129973ed529d'>services/src/main/java/org/keycloak/protocol/oidc/grants/AuthorizationCodeGrantTypeFactory.java</a> </details> <details> <summary>ClientCredentialsGrantTypeFactory.java<code>Assign client-credentials grant shortcut</code> <code>+5/-0</code></summary> <br/> >Assign client-credentials grant shortcut > ><pre> >• Registers &#x27;cc&#x27; as the compact client-credentials grant identifier. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-5ab7decff66a3c0c7e0b623020fe58f87708104a135a65269b4df2032604a8a4'>services/src/main/java/org/keycloak/protocol/oidc/grants/ClientCredentialsGrantTypeFactory.java</a> </details> <details> <summary>OAuth2GrantTypeBase.java<code>Propagate grant type before token creation</code> <code>+2/-0</code></summary> <br/> >Propagate grant type before token creation > ><pre> >• Stores the current grant type in client session context before generating access tokens. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-c9a17e9374330293b1896247be23f8a890d260cf90c5833d57ad7da8bdec4b56'>services/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeBase.java</a> </details> <details> <summary>PermissionGrantTypeFactory.java<code>Assign UMA permission grant shortcut</code> <code>+5/-0</code></summary> <br/> >Assign UMA permission grant shortcut > ><pre> >• Registers &#x27;pg&#x27; as the compact UMA permission grant identifier. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-0c3414a609531ef8ba8f4e7ba79065a1ccf1b1611eaf51914f5061324fbf352c'>services/src/main/java/org/keycloak/protocol/oidc/grants/PermissionGrantTypeFactory.java</a> </details> <details> <summary>PreAuthorizedCodeGrantType.java<code>Propagate pre-authorized code grant context</code> <code>+2/-1</code></summary> <br/> >Propagate pre-authorized code grant context > ><pre> >• Adds the pre-authorized code grant type to the client session context before credential issuance. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-47d9719120c056cf8fcfcfcd3c7cad871088a3372a1a4fb36cfd1b4bc26ad618'>services/src/main/java/org/keycloak/protocol/oidc/grants/PreAuthorizedCodeGrantType.java</a> </details> <details> <summary>PreAuthorizedCodeGrantTypeFactory.java<code>Assign pre-authorized code grant shortcut</code> <code>+5/-0</code></summary> <br/> >Assign pre-authorized code grant shortcut > ><pre> >• Registers &#x27;pc&#x27; as the compact pre-authorized code grant identifier. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-40ec52d8cfae590db8c0290f2003e89aff6d228dd2f1f2fdeaa4636d47013810'>services/src/main/java/org/keycloak/protocol/oidc/grants/PreAuthorizedCodeGrantTypeFactory.java</a> </details> <details> <summary>RefreshTokenGrantTypeFactory.java<code>Assign refresh-token grant shortcut</code> <code>+7/-0</code></summary> <br/> >Assign refresh-token grant shortcut > ><pre> >• Registers &#x27;rt&#x27; as the compact refresh-token grant identifier. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-8f5b16267e02f8f5f33ea21ad1dabdf1868058fef9f9ddb472c28499c8ca7b8a'>services/src/main/java/org/keycloak/protocol/oidc/grants/RefreshTokenGrantTypeFactory.java</a> </details> <details> <summary>ResourceOwnerPasswordCredentialsGrantType.java<code>Propagate password grant context</code> <code>+2/-0</code></summary> <br/> >Propagate password grant context > ><pre> >• Stores the resource-owner password grant type after attaching the authenticated client session. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-ce17c940444ef1b21fe4b46297a1441cbebdc36fc3ad708b5bb7805fa3760576'>services/src/main/java/org/keycloak/protocol/oidc/grants/ResourceOwnerPasswordCredentialsGrantType.java</a> </details> <details> <summary>ResourceOwnerPasswordCredentialsGrantTypeFactory.java<code>Assign password grant shortcut</code> <code>+5/-0</code></summary> <br/> >Assign password grant shortcut > ><pre> >• Registers &#x27;ro&#x27; as the compact resource-owner password grant identifier. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-5111259dc6ba0c57ae4477542bf07d5c2f36d6984534dd4f78857f316d983c00'>services/src/main/java/org/keycloak/protocol/oidc/grants/ResourceOwnerPasswordCredentialsGrantTypeFactory.java</a> </details> <details> <summary>TokenExchangeGrantTypeFactory.java<code>Assign token-exchange grant shortcut</code> <code>+5/-0</code></summary> <br/> >Assign token-exchange grant shortcut > ><pre> >• Registers &#x27;te&#x27; as the compact token-exchange grant identifier. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-332b399dbe5dc57400143f270b304a0b0ce57668a74fe827e3c3729fc8297157'>services/src/main/java/org/keycloak/protocol/oidc/grants/TokenExchangeGrantTypeFactory.java</a> </details> <details> <summary>CibaGrantTypeFactory.java<code>Assign CIBA grant shortcut</code> <code>+7/-0</code></summary> <br/> >Assign CIBA grant shortcut > ><pre> >• Registers &#x27;ci&#x27; as the compact CIBA grant identifier. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-1e76a2e312febb1a5bfcf05308d8b0daabbe94b8ee0e3eca48f14f212ce330f5'>services/src/main/java/org/keycloak/protocol/oidc/grants/ciba/CibaGrantTypeFactory.java</a> </details> <details> <summary>DeviceGrantTypeFactory.java<code>Assign device grant shortcut</code> <code>+7/-0</code></summary> <br/> >Assign device grant shortcut > ><pre> >• Registers &#x27;dg&#x27; as the compact device-code grant identifier. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-b4b1a2bcc32bab089f5ea1d26c067a78ef182d7226ee533b9788b2814b3536f0'>services/src/main/java/org/keycloak/protocol/oidc/grants/device/DeviceGrantTypeFactory.java</a> </details> <details> <summary>StandardTokenExchangeProvider.java<code>Propagate standard token-exchange context</code> <code>+2/-0</code></summary> <br/> >Propagate standard token-exchange context > ><pre> >• Marks exchanged access tokens with the token-exchange grant type before building the response. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-d6af3e4db00e3f2e9ce210ddbd14152aab83f0dd584411ae918110e9e1912c5a'>services/src/main/java/org/keycloak/protocol/oidc/tokenexchange/StandardTokenExchangeProvider.java</a> </details> </dd> </dl> </details> <details> <summary>Refactor (1) <code> +1 / -1 </code></summary> <dl> <dd> <details> <summary>AbstractOIDCProtocolMapper.java<code>Expose lightweight-token selection logic</code> <code>+1/-1</code></summary> <br/> >Expose lightweight-token selection logic > ><pre> >• Makes lightweight-token detection publicly accessible as a static utility so the encoder can classify generated access tokens. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-0b03cf408cc686bd517475bd221492980793c1586fc3d3596515ed7dc52e0600'>services/src/main/java/org/keycloak/protocol/oidc/mappers/AbstractOIDCProtocolMapper.java</a> </details> </dd> </dl> </details> <details> <summary>Tests (2) <code> +140 / -4 </code></summary> <dl> <dd> <details> <summary>DefaultTokenContextEncoderProviderTest.java<code>Test contextual token-ID round trips</code> <code>+114/-0</code></summary> <br/> >Test contextual token-ID round trips > ><pre> >• Covers client-credentials, offline password, unknown grant, invalid grant, and legacy token identifiers. Successful cases verify decoding and re-encoding. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-c518aaff3f28a94506e58e594839a0124d61586d8d331a8880f5fa7c5851c552'>services/src/test/java/org/keycloak/protocol/oidc/encode/DefaultTokenContextEncoderProviderTest.java</a> </details> <details> <summary>AssertEvents.java<code>Adapt event assertions for contextual token IDs</code> <code>+26/-4</code></summary> <br/> >Adapt event assertions for contextual token IDs > ><pre> >• Replaces UUID-only access-token assertions for authorization code, device, refresh, and CIBA flows. Adds a matcher for the contextual prefix, expected grant shortcut, and trailing UUID. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-9429b8ef26d95d6413c63594ea0cc00cdfc416a8a1547cfc92e2f671302d784d'>testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java</a> </details> </dd> </dl> </details> <details> <summary>Other (2) <code> +21 / -0 </code></summary> <dl> <dd> <details> <summary>org.keycloak.protocol.oidc.encode.TokenContextEncoderProviderFactory<code>Register the default token encoder provider</code> <code>+20/-0</code></summary> <br/> >Register the default token encoder provider > ><pre> >• Adds the service-loader registration for the default token context encoder factory. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-55455d93acaff284e7122f9bae8a6cfa9d9d110b6cefd7219bb4318d42b2398c'>services/src/main/resources/META-INF/services/org.keycloak.protocol.oidc.encode.TokenContextEncoderProviderFactory</a> </details> <details> <summary>org.keycloak.provider.Spi<code>Register the token context encoder SPI</code> <code>+1/-0</code></summary> <br/> >Register the token context encoder SPI > ><pre> >• Adds the new internal token context encoder to Keycloak&#x27;s SPI service registry. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/53/files#diff-eedaf529e31ff2137fb1916545d3ca83dc8d0829907887177b6166f8ed567ce2'>services/src/main/resources/META-INF/services/org.keycloak.provider.Spi</a> </details> </dd> </dl> </details> </dd> </dl> </details>