Skip to content

Automated Test: feature-token-context-implementation #310

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;

}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
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;
Expand Down Expand Up @@ -81,6 +82,7 @@ public static class Context {
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) {
Expand All @@ -97,22 +99,7 @@ public Context(KeycloakSession session, Object clientConfig, Map<String, String>
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) {
Expand Down Expand Up @@ -182,6 +169,10 @@ public KeycloakSession getSession() {
public Object getTokenManager() {
return tokenManager;
}

public String getGrantType() {
return grantType;
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,9 @@
*/
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();
Comment on lines +29 to +33

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find implementations of OAuth2GrantTypeFactory
rg "implements OAuth2GrantTypeFactory" -A 10 --max-count=20

Repository: admin-coderabbit/coderabbit-keycloak-mirror

Length of output: 12172


🏁 Script executed:

#!/bin/bash
# Find all shortcut implementations to verify 2-letter vs 3-letter claim
rg "getShortcut\(\)" -A 2 -B 2 | head -50

Repository: admin-coderabbit/coderabbit-keycloak-mirror

Length of output: 6162


🏁 Script executed:

#!/bin/bash
# Check the full interface definition to understand getId() method
cat -n server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java

Repository: admin-coderabbit/coderabbit-keycloak-mirror

Length of output: 1599


🏁 Script executed:

#!/bin/bash
# Check PreAuthorizedCodeGrantTypeFactory for getShortcut implementation
rg "class PreAuthorizedCodeGrantTypeFactory" -A 30 | grep -A 5 "getShortcut"

Repository: admin-coderabbit/coderabbit-keycloak-mirror

Length of output: 435


🏁 Script executed:

#!/bin/bash
# Verify getId() implementation to understand why the proposed fix is wrong
rg "getId\(\)" services/src/main/java/org/keycloak/protocol/oidc/grants/ -A 1 | head -30

Repository: admin-coderabbit/coderabbit-keycloak-mirror

Length of output: 3350


🏁 Script executed:

#!/bin/bash
# Check if there are any comments about Private SPI backward compatibility
rg -i "private.*spi|spi.*private" server-spi-private/ | head -10

Repository: admin-coderabbit/coderabbit-keycloak-mirror

Length of output: 415


Update Javadoc to reflect 2-letter shortcut length, not 3-letter.

The documentation states "3-letters shortcut" but all 10 implementations use exactly 2-letter shortcuts (e.g., "cc", "te", "ci", "dg", "ro", "rt", "pc", "pg", "ac"). Update the Javadoc to say "2-letter shortcut" for accuracy.

Note: The concern about adding a method without a default is not applicable here—this is a Private SPI where backward compatibility for external implementations is not guaranteed, and all bundled implementations already include the getShortcut() method. The proposed default implementation of returning getId() is incorrect, as getId() returns full grant type names (not 2-letter shortcuts) and would violate the shortcut contract.

🤖 Prompt for AI Agents
In
`@server-spi-private/src/main/java/org/keycloak/protocol/oidc/grants/OAuth2GrantTypeFactory.java`
around lines 29 - 33, Update the Javadoc on OAuth2GrantTypeFactory#getShortcut()
to state that shortcuts are 2-letter (not 3-letter) identifiers and must be
unique across grants; mention examples such as "cc", "te", "ci", etc., and keep
the contract that this method returns a short (2-character) shortcut distinct
from getId().

}
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@
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;
Expand Down Expand Up @@ -243,6 +245,7 @@ public TokenValidation validateToken(KeycloakSession session, UriInfo uriInfo, C
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);
Expand Down Expand Up @@ -861,9 +864,9 @@ protected AccessToken applyMapper(AccessToken token, Map.Entry<ProtocolMapperMod
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()));
}
Expand Down Expand Up @@ -1045,7 +1048,11 @@ protected IDToken applyMapper(IDToken token, Map.Entry<ProtocolMapperModel, Prot
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());
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
}
Comment on lines +69 to +78

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Copy-paste bug: rawTokenId is never null-checked.

Line 73 validates grantType a second time instead of rawTokenId. A null rawTokenId will be silently stored and cause NPEs later (e.g., when encoding the token ID).

🐛 Proposed fix
         Objects.requireNonNull(grantType, "Null grantType not allowed");
-        Objects.requireNonNull(grantType, "Null rawTokenId not allowed");
+        Objects.requireNonNull(rawTokenId, "Null rawTokenId not allowed");
🤖 Prompt for AI Agents
In
`@services/src/main/java/org/keycloak/protocol/oidc/encode/AccessTokenContext.java`
around lines 69 - 78, The constructor AccessTokenContext currently calls
Objects.requireNonNull(grantType, ...) twice and never null-checks rawTokenId;
replace the duplicate Objects.requireNonNull(grantType, "Null grantType not
allowed") with Objects.requireNonNull(rawTokenId, "Null rawTokenId not allowed")
so rawTokenId is validated before assignment to this.rawTokenId (ensure the four
requireNonNull calls validate sessionType, tokenType, grantType, and rawTokenId
respectively).


public SessionType getSessionType() {
return sessionType;
}

public TokenType getTokenType() {
return tokenType;
}

public String getGrantType() {
return grantType;
}

public String getRawTokenId() {
return rawTokenId;
}
}
Original file line number Diff line number Diff line change
@@ -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() {

}
}
Loading