Skip to content

Fix #51137: Add TOKEN_EXCHANGE_REQUEST and JWT_AUTHORIZATION_GRANT to… - #51912

Merged
mposolda merged 1 commit into
keycloak:mainfrom
amaan0408:fix/51137-lightweight-token-exchange
Sep 8, 2026
Merged

mposolda merged 1 commit into
keycloak:mainfrom
amaan0408:fix/51137-lightweight-token-exchange

Conversation

@amaan0408

@amaan0408 amaan0408 commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #51137

Problem

Token exchange and JWT authorization grant flows were ignoring the use-lightweight-access-token client policy because UseLightweightAccessTokenExecutor was missing case labels for TOKEN_EXCHANGE_REQUEST and JWT_AUTHORIZATION_GRANT.

Solution

Added the missing case labels to the switch statement in UseLightweightAccessTokenExecutor.executeOnEvent(), so both grant types now respect the lightweight access token policy.

Testing

Added a regression test:

  • testPolicyLightWeightTokenExchangeTest: Verifies token exchange returns lightweight tokens when policy is enabled with GrantTypeCondition.

Reproduction

Manual testing on 999.0.0-SNAPSHOT:

  • Password grant with policy: lightweight token ✅
  • Token exchange with policy: lightweight token ✅ (now fixed)
  • JWT bearer grant with policy: lightweight token ✅ (now fixed)

Copilot AI balanced review requested due to automatic review settings August 20, 2026 20:35
@amaan0408
amaan0408 requested review from a team as code owners August 20, 2026 20:35

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Adds lightweight access-token policy support for token exchange and JWT authorization grants.

Changes:

  • Handles both missing client-policy events.
  • Adds regression coverage for both grant types.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
UseLightweightAccessTokenExecutor.java Enables lightweight tokens for both events.
LightWeightAccessTokenTest.java Adds grant-specific regression tests.
Suppressed comments (1)

testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/LightWeightAccessTokenTest.java:459

  • New integration tests must use the current test framework under tests; adding this regression to the deprecated Arquillian suite conflicts with the repository testing strategy. The existing JWT authorization-grant fixtures under tests/base/src/test/java/org/keycloak/tests/oauth can host this case.
    @Test
    public void testPolicyLightWeightJwtAuthorizationGrantTest() throws Exception {

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +425 to +427
@Test
@EnableFeature(value = Profile.Feature.TOKEN_EXCHANGE, skipRestart = true)
public void testPolicyLightWeightTokenExchangeTest() throws Exception {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the review. I added the tests to the existing LightWeightAccessTokenTest.java file to follow the pattern for lightweight-token regression coverage. I'm open to moving them to the current test framework if the maintainers prefer, awaiting feedback.

@graziang graziang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@amaan0408 Thanks for the PR, added some inline comments, could you please check? Also I see the DCO is failing, please check also the signature of the commit. https://github.com/keycloak/keycloak/blob/228dfb4ee87a8820f5909eaaee7db220f5866561/CONTRIBUTING.md for details.

@@ -17,24 +17,37 @@

package org.keycloak.testsuite.oidc;

import java.io.IOException;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

use the spotless script to fix the unused imports and the orders, check https://github.com/keycloak/keycloak/blob/228dfb4ee87a8820f5909eaaee7db220f5866561/CONTRIBUTING.md

@@ -405,6 +422,111 @@ public void testPolicyLightWeightTrueTest() throws Exception {
}
}

@Test
@EnableFeature(value = Profile.Feature.TOKEN_EXCHANGE, skipRestart = true)
public void testPolicyLightWeightTokenExchangeTest() throws Exception {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

this should be tested with the standard token exchange v2, the token exchange v1 feature you enabled on this method is deprecated.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the feedback! I've updated testPolicyLightWeightTokenExchangeTest to use Standard Token Exchange V2 (oauth.tokenExchangeRequest(accessToken).send()), removed the deprecated @EnableFeature annotation, and formatted the imports using Spotless.

@amaan0408
amaan0408 force-pushed the fix/51137-lightweight-token-exchange branch from 4cf8603 to 2b4eaf8 Compare August 21, 2026 09:02
Copilot AI review requested due to automatic review settings August 21, 2026 09:17
@amaan0408
amaan0408 force-pushed the fix/51137-lightweight-token-exchange branch from 2b4eaf8 to b558bcf Compare August 21, 2026 09:17

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 2 out of 3 changed files in this pull request and generated no new comments.

Suppressed comments (2)

testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/LightWeightAccessTokenTest.java:454

  • This setup also uses the helper's AnyClientConditionFactory, so it does not cover the JWT-authorization-grant-specific policy requested by #51137. Configure GrantTypeConditionFactory with OAuth2Constants.JWT_AUTHORIZATION_GRANT for this test.
        setUseLightweightAccessTokenExecutor();

testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/LightWeightAccessTokenTest.java:422

  • This setup calls a helper that hard-codes AnyClientConditionFactory, so the test does not cover the grant-specific policy required by #51137. Configure this policy with GrantTypeConditionFactory for OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE so the regression exercises the intended condition path.
        setUseLightweightAccessTokenExecutor();

Copilot AI review requested due to automatic review settings August 21, 2026 09:22
@amaan0408
amaan0408 force-pushed the fix/51137-lightweight-token-exchange branch from b558bcf to 08fad2d Compare August 21, 2026 09:22

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

Suppressed comments (2)

testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/LightWeightAccessTokenTest.java:454

  • This test also uses the helper's AnyClientCondition rather than the grant-specific policy required by the issue. Configure the policy with GrantTypeCondition for JWT_AUTHORIZATION_GRANT so the regression covers the reported configuration.
        setUseLightweightAccessTokenExecutor();

testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/LightWeightAccessTokenTest.java:422

  • The issue requires regression coverage for a grant-specific policy, but this helper installs an AnyClientCondition, so the test uses a blanket policy that also makes the source login token lightweight. Configure this test's policy with GrantTypeCondition for TOKEN_EXCHANGE_GRANT_TYPE so it exercises the reported policy shape.

This issue also appears on line 454 of the same file.

        setUseLightweightAccessTokenExecutor();

@amaan0408
amaan0408 force-pushed the fix/51137-lightweight-token-exchange branch from 08fad2d to fb1d181 Compare August 21, 2026 09:25
Copilot AI review requested due to automatic review settings August 21, 2026 09:31
@amaan0408
amaan0408 force-pushed the fix/51137-lightweight-token-exchange branch from fb1d181 to dd67c57 Compare August 21, 2026 09:31

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

Suppressed comments (2)

testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/LightWeightAccessTokenTest.java:520

  • The cleanup removes the identity provider but leaves JWT_AUTHORIZATION_GRANT_ENABLED and JWT_AUTHORIZATION_GRANT_IDP on the shared TEST_CLIENT; the superclass teardown does not restore client attributes, so later tests inherit this configuration. Preserve and restore these attributes (for example with ClientAttributeUpdater) in the test scope.
        } finally {
            deleteProtocolMappers(protocolMappers);
            try {
                adminClient.realm(REALM_NAME).identityProviders().get(idpAlias).remove();
            } catch (Exception ignored) {}

testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/LightWeightAccessTokenTest.java:494

  • This admin-client call returns a Response, but it is never closed, which can leak the underlying HTTP connection during the test suite. Use try-with-resources and assert the expected 204 response.
            adminClient.realm(REALM_NAME).users().get(userRep.getId()).addFederatedIdentity(idpAlias, fedIdentity);

Copilot AI review requested due to automatic review settings August 21, 2026 09:40
@amaan0408
amaan0408 force-pushed the fix/51137-lightweight-token-exchange branch from dd67c57 to d26e5f0 Compare August 21, 2026 09:40
@amaan0408
amaan0408 force-pushed the fix/51137-lightweight-token-exchange branch 2 times, most recently from d73ae1c to da40b4f Compare August 21, 2026 09:44

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

Suppressed comments (2)

testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/LightWeightAccessTokenTest.java:494

  • addFederatedIdentity returns a JAX-RS Response, but this result is discarded without being closed, leaking the underlying client connection. Close it and assert the expected status before continuing.
            adminClient.realm(REALM_NAME).users().get(userRep.getId()).addFederatedIdentity(idpAlias, fedIdentity);

testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/LightWeightAccessTokenTest.java:487

  • These attributes are written to the shared TEST_CLIENT but never restored; the inherited teardown only resets client policies/profiles, leaving later tests with JWT grants enabled and an IDP alias that this test deletes. Use the existing ClientAttributeUpdater pattern so both attributes are restored when the test exits.
            org.keycloak.admin.client.resource.ClientResource clientResource = AdminApiUtil.findClientResourceByClientId(adminClient.realm(REALM_NAME), TEST_CLIENT);
            ClientRepresentation clientRep = clientResource.toRepresentation();
            clientRep.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_ENABLED, "true");
            clientRep.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP, idpAlias);
            clientResource.update(clientRep);

Copilot AI review requested due to automatic review settings August 21, 2026 09:44
@amaan0408
amaan0408 force-pushed the fix/51137-lightweight-token-exchange branch from 230287d to e3a7240 Compare August 22, 2026 10:59

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

Suppressed comments (1)

services/src/main/java/org/keycloak/services/clientpolicy/executor/UseLightweightAccessTokenExecutor.java:48

  • The new JWT_AUTHORIZATION_GRANT behavior has no regression coverage; the added test exercises only token exchange. Add a current-framework JWT authorization-grant test with a grant-type condition and assert that the issued token context is LIGHTWEIGHT, so this branch cannot regress independently.
            case JWT_AUTHORIZATION_GRANT:

Comment on lines +1124 to +1131
String json = (new ClientPoliciesUtil.ClientPolicyBuilder())
.createPolicy("Lightweight-Token-Exchange-Policy")
.addCondition(ClientPoliciesUtil.GrantTypeConditionFactory.PROVIDER_ID,
(new ClientPoliciesUtil.GrantTypeConditionBuilder())
.setGrantTypes(java.util.Collections.singletonList(OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE)))
.addExecutor(UseLightweightAccessTokenExecutorFactory.PROVIDER_ID, null)
.build();
updatePolicies(json);
@amaan0408

Copy link
Copy Markdown
Contributor Author

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
Suppressed comments (1)

services/src/main/java/org/keycloak/services/clientpolicy/executor/UseLightweightAccessTokenExecutor.java:48

* The new `JWT_AUTHORIZATION_GRANT` behavior has no regression coverage; the added test exercises only token exchange. Add a current-framework JWT authorization-grant test with a grant-type condition and assert that the issued token context is `LIGHTWEIGHT`, so this branch cannot regress independently.
            case JWT_AUTHORIZATION_GRANT:

The JWT authorization grant test was omitted intentionally to keep the overall test class diff well under the 100-line Arquillian deprecation limit (Testsuite Deprecation Check). Both grant types use the exact same switch handling in UseLightweightAccessTokenExecutor, and manual verification on 999.0.0-SNAPSHOT confirmed both behave identically

Copilot AI review requested due to automatic review settings August 22, 2026 11:17
@amaan0408
amaan0408 force-pushed the fix/51137-lightweight-token-exchange branch from e3a7240 to c3a2c0f Compare August 22, 2026 11:17

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

Suppressed comments (1)

services/src/main/java/org/keycloak/services/clientpolicy/executor/UseLightweightAccessTokenExecutor.java:48

  • This newly handled grant has no regression coverage, while the added test exercises only token exchange. Add a JWT authorization grant policy test that verifies the issued access token is lightweight; otherwise this half of the fix can regress unnoticed.
            case JWT_AUTHORIZATION_GRANT:


@Test
public void testPolicyLightWeightTokenExchangeTest() throws Exception {
setUseLightweightAccessTokenExecutor();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Using setUseLightweightAccessTokenExecutor() is the established pattern across LightWeightAccessTokenTest for validating lightweight token behavior. The test explicitly asserts that the token exchange response returns a lightweight token context (TokenType.LIGHTWEIGHT), successfully covering the new event mapping in UseLightweightAccessTokenExecutor while keeping the diff within testsuite limits

@amaan0408

Copy link
Copy Markdown
Contributor Author

Hi @mposolda @vmuzikar Hi team, this PR is ready for review.

Summary of Changes:
Core Fix: Added the missing TOKEN_EXCHANGE_REQUEST and JWT_AUTHORIZATION_GRANT event cases to UseLightweightAccessTokenExecutor.executeOnEvent() so both grant types properly evaluate lightweight token policies (#51137).
Testing: Added testPolicyLightWeightTokenExchangeTest() in LightWeightAccessTokenTest to verify that token exchange issues a token with TokenType.LIGHTWEIGHT.
Note: Maintained a compact test layout to keep the diff well under the Arquillian testsuite line limit while aligning with existing patterns in LightWeightAccessTokenTest. Local Arquillian execution passed cleanly (BUILD SUCCESS).

Whenever you get a chance, please take a look!

@keycloak-github-bot keycloak-github-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unreported flaky test detected, please review

@keycloak-github-bot

Copy link
Copy Markdown

Unreported flaky test detected

If the flaky tests below are affected by the changes, please review and update the changes accordingly. Otherwise, a maintainer should report the flaky tests prior to merging the PR.

org.keycloak.testsuite.federation.ldap.LDAPGroupMapperTest#test06_addingUserToNewKeycloakGroup

Keycloak CI - Base IT (5)

java.lang.AssertionError: 

Expected: a collection with size <4>
     but: collection size was <3>
	at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
...

Report flaky test

@keycloak-github-bot keycloak-github-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unreported flaky test detected, please review

@keycloak-github-bot

Copy link
Copy Markdown

Unreported flaky test detected

If the flaky tests below are affected by the changes, please review and update the changes accordingly. Otherwise, a maintainer should report the flaky tests prior to merging the PR.

org.keycloak.testsuite.federation.ldap.LDAPGroupMapperTest#test06_addingUserToNewKeycloakGroup

Keycloak CI - Base IT (5)

java.lang.AssertionError: 

Expected: a collection with size <4>
     but: collection size was <3>
	at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
...

Report flaky test

@keycloak-github-bot keycloak-github-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unreported flaky test detected, please review

@keycloak-github-bot

Copy link
Copy Markdown

Unreported flaky test detected

If the flaky tests below are affected by the changes, please review and update the changes accordingly. Otherwise, a maintainer should report the flaky tests prior to merging the PR.

org.keycloak.testsuite.federation.ldap.LDAPGroupMapperTest#test06_addingUserToNewKeycloakGroup

Keycloak CI - Base IT (5)

java.lang.AssertionError: 

Expected: a collection with size <4>
     but: collection size was <3>
	at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
...

Report flaky test

1 similar comment
@keycloak-github-bot

Copy link
Copy Markdown

Unreported flaky test detected

If the flaky tests below are affected by the changes, please review and update the changes accordingly. Otherwise, a maintainer should report the flaky tests prior to merging the PR.

org.keycloak.testsuite.federation.ldap.LDAPGroupMapperTest#test06_addingUserToNewKeycloakGroup

Keycloak CI - Base IT (5)

java.lang.AssertionError: 

Expected: a collection with size <4>
     but: collection size was <3>
	at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
...

Report flaky test

@keycloak-github-bot keycloak-github-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unreported flaky test detected, please review

@amaan0408

Copy link
Copy Markdown
Contributor Author

Hi @mposolda @vmuzikar,

Just following up on this PR. The CI failure appears to be caused by a known upstream flaky test (LDAPGroupMapperTest#test06_addingUserToNewKeycloakGroup as flagged by keycloak-github-bot) and a pipeline artifact download error (keycloak-dist).

The local test suite for LightWeightAccessTokenTest passed cleanly. Could someone with write access please trigger a re-run of the failed CI jobs when you get a chance? Thanks!

Copilot AI review requested due to automatic review settings September 7, 2026 06:38
@mposolda
mposolda force-pushed the fix/51137-lightweight-token-exchange branch from c3a2c0f to 6611ae7 Compare September 7, 2026 06:38

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

The JWT authorization grant path lacks regression coverage.

Review details

Suppressed comments (1)

services/src/main/java/org/keycloak/services/clientpolicy/executor/UseLightweightAccessTokenExecutor.java:48

  • The new JWT_AUTHORIZATION_GRANT branch has no regression coverage: the added test only emits TOKEN_EXCHANGE_REQUEST, so this path could remain broken without failing the suite. Add a JWT bearer grant policy test that asserts the issued token context is LIGHTWEIGHT.
            case JWT_AUTHORIZATION_GRANT:
  • Files reviewed: 2/2 changed files
  • Comments generated: 0 new
  • Review effort level: Balanced

@keycloak-github-bot keycloak-github-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unreported flaky test detected, please review

@keycloak-github-bot

Copy link
Copy Markdown

Unreported flaky test detected

If the flaky tests below are affected by the changes, please review and update the changes accordingly. Otherwise, a maintainer should report the flaky tests prior to merging the PR.

org.keycloak.testsuite.federation.ldap.LDAPUserLoginTest#loginLDAPUserCredentialVaultAuthenticationNoneEncryptionStartTLS

Keycloak CI - Java Distribution IT (windows-latest - temurin - 17)

org.openqa.selenium.TimeoutException: 
java.net.SocketTimeoutException: Read timed out
Build info: version: '4.46.0', revision: 'df5a634 df5a6341cbb5f8f06b836bd595752775627c80dc'
System info: os.name: 'Windows Server 2025', os.arch: 'amd64', os.version: '10.0', java.version: '17.0.20.1'
Driver info: driver.version: HtmlUnitDriver
...

Report flaky test

@mposolda
mposolda merged commit 79f577f into keycloak:main Sep 8, 2026
93 of 94 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Token exchange and JWT grants ignore use-lightweight-access-token policy

5 participants