From f58d46c399cc31eb5fed4310bdae7388437a2bfe Mon Sep 17 00:00:00 2001 From: mahdi-al-hakim Date: Fri, 14 Aug 2026 02:45:20 +0300 Subject: [PATCH] Add a client policy executor for the JWT authorization grant settings The identity provider allow list and the token audience allow list decide which assertions the JWT authorization grant accepts for a client, so a deployment may not want client administrators to change them. The new executor rejects a request that sets or changes either attribute, on both dynamic client registration and the admin REST API, and only where a client policy puts it. Only a change is rejected, so an existing configuration is preserved and an unrelated edit that sends the whole client representation back is still allowed. Closes #51718 Signed-off-by: mahdi-al-hakim --- .../topics/clients/client-policies.adoc | 1 + .../jwt-authorization-grant.adoc | 9 +- ...rizationGrantSettingsDisabledExecutor.java | 154 +++++++ ...nGrantSettingsDisabledExecutorFactory.java | 76 ++++ ...ecutor.ClientPolicyExecutorProviderFactory | 1 + ...tionGrantSettingsDisabledExecutorTest.java | 424 ++++++++++++++++++ 6 files changed, 664 insertions(+), 1 deletion(-) create mode 100644 services/src/main/java/org/keycloak/services/clientpolicy/executor/JWTAuthorizationGrantSettingsDisabledExecutor.java create mode 100644 services/src/main/java/org/keycloak/services/clientpolicy/executor/JWTAuthorizationGrantSettingsDisabledExecutorFactory.java create mode 100644 tests/base/src/test/java/org/keycloak/tests/client/policies/JWTAuthorizationGrantSettingsDisabledExecutorTest.java diff --git a/docs/documentation/server_admin/topics/clients/client-policies.adoc b/docs/documentation/server_admin/topics/clients/client-policies.adoc index ef7cc4d7a71..226db6d0b8c 100644 --- a/docs/documentation/server_admin/topics/clients/client-policies.adoc +++ b/docs/documentation/server_admin/topics/clients/client-policies.adoc @@ -159,6 +159,7 @@ One of several purposes for this executor is to realize the security requirement * Enforce scopes granted in link:{securing_apps_token_exchange_link}#_standard-token-exchange[Standard token exchange] or in JWT Authorization Grant are restricted to the ones present in the initial `subject_token` or `assertion` JWT. This executor only allows downscoping of the presented assertion. An error is returned if any extra scope, not originally granted to the JWT, is requested. * Enforce claims for assertion grants (`subject_token` in Token Exchange and `assertion` in JWT Authorization Grant). The executor enforces the presence and specific values of a claim in a JWT. It uses a Java regex so it is quite versatile. * Enforce that only configured protocol mapper types can be created or updated on clients through the dedicated Admin REST API protocol mapper endpoints using the `allowed-protocol-mappers` executor. Existing mapper types that are not configured can only be preserved with an unchanged type and configuration. +* Enforce that the JWT Authorization Grant settings of a client, its allowed identity providers and its custom audience mapping, are not set or changed by the request. Those settings decide which assertions the grant accepts for the client. Combined with the `client-updater-context` condition the restriction can be limited to requests the client makes itself, leaving administrators free to configure the client. A request that repeats the value the client already has is allowed, so existing configuration is preserved. * Add default **Certificate Authority subject DN** for the client registration service when TLS client authentication (`tls_client_auth`) is configured (see *Using the client registration service* in the link:{securing_apps_link}[securing apps] section for more information). The `tls-client-auth-ca-subject-dn` executor can be used to provide the new compulsory attribute in client registration interface. It can also enforce the configured CA name to reject unwanted values. Another available executor is the `auth-flow-enforce`, which can be used to enforce an authentication flow during an authentication request. For instance, it can be used to select a flow based on certain conditions, such as a specific scope or an ACR value. For more details, see the <<_client-policy-auth-flow, related documentation>>. diff --git a/docs/guides/securing-apps/jwt-authorization-grant.adoc b/docs/guides/securing-apps/jwt-authorization-grant.adoc index 813563d8e10..4ea8a7730c9 100644 --- a/docs/guides/securing-apps/jwt-authorization-grant.adoc +++ b/docs/guides/securing-apps/jwt-authorization-grant.adoc @@ -50,7 +50,7 @@ Only confidential clients can request a JWT authorization grant. In order to all .Client configuration for JWT Authorization Grant image::jwt-authorization-grant-client-config.png[Client configuration for JWT Authorization Grant] -NOTE: In the **Advanced** tab, section **OpenID Connect Compatibility Modes**, the configuration option **Custom audience mapping** allows to configure specific custom valid audiences for individual Identity Providers. The map key is the Identity Provider alias, and the value is the custom audience that will be accepted for that provider. Note this behavior is not covered by the standard and can have major security implications. +NOTE: In the **Advanced** tab, section **OpenID Connect Compatibility Modes**, the configuration option **Custom audience mapping** allows to configure specific custom valid audiences for individual Identity Providers. The map key is the Identity Provider alias, and the value is the custom audience that will be accepted for that provider. Note this behavior is not covered by the standard and can have major security implications. In deployments where client administrators should not be allowed to edit this option, see the **jwt-authorization-grant-settings-disabled** executor below. The Identity Provider (both types commented in the introduction) needs to also be configured to establish the relationship that will validate the assertion. In **Identity providers** -> select your OIDC or JWT provider -> **Settings** tab -> **Authorization Grant Settings** section. @@ -157,6 +157,13 @@ The enforcer can be used for any request that uses an assertion parameter. Curre * Executor **jwt-claim-enforcer**. This executor allows to configure extra requirements for claims in the JWT assertion token. For example, if we want the assertion to contain an `iat` claim or a custom claim with a specific value. The configuration allows us to set any claim name and any claim value (using a java regex). If the claim in the JWT assertion does not match the regex, the request does not proceed and an error is returned. + As the previous executor, for the moment this enforcer can be used for JWT Authorization Grant and the Standard Token exchange. +* Executor **jwt-authorization-grant-settings-disabled**. This executor rejects any request that sets or changes the JWT Authorization Grant settings of a client, which are the **Allowed Identity Providers for JWT Authorization Grant** and the **Custom audience mapping** options. Those options decide which assertions the grant accepts for the client, so the executor is intended for deployments where client administrators should not be allowed to edit them. It applies to client creation and update, so it covers both the admin REST API and dynamic client registration. ++ +Enabling the grant on a client that already exists is rejected as well, because the allow lists configured earlier are still on the client and the flag on its own would be enough to make the grant work again. Turning the grant off stays permitted. ++ +Only a change is rejected. A request that carries the value a client already has is permitted, so applying the executor preserves the existing configuration of a client and leaves the rest of the client editable. ++ +The executor applies to whoever the policy matches. To allow administrators to keep configuring these settings while refusing the clients themselves, combine it with the **client-updater-context** condition and select the `ByRegistrationAccessToken`, `ByInitialAccessToken` and `ByAnonymous` sources. == JWT Authorization Grant for Google Identity Provider diff --git a/services/src/main/java/org/keycloak/services/clientpolicy/executor/JWTAuthorizationGrantSettingsDisabledExecutor.java b/services/src/main/java/org/keycloak/services/clientpolicy/executor/JWTAuthorizationGrantSettingsDisabledExecutor.java new file mode 100644 index 00000000000..9c4edab4973 --- /dev/null +++ b/services/src/main/java/org/keycloak/services/clientpolicy/executor/JWTAuthorizationGrantSettingsDisabledExecutor.java @@ -0,0 +1,154 @@ +/* + * Copyright 2026 Red Hat, Inc. and/or its affiliates + * and other contributors as indicated by the @author tags. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.keycloak.services.clientpolicy.executor; + +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +import org.keycloak.events.Errors; +import org.keycloak.models.ClientModel; +import org.keycloak.protocol.oidc.OIDCConfigAttributes; +import org.keycloak.representations.idm.ClientPolicyExecutorConfigurationRepresentation; +import org.keycloak.representations.idm.ClientRepresentation; +import org.keycloak.services.clientpolicy.ClientPolicyContext; +import org.keycloak.services.clientpolicy.ClientPolicyException; +import org.keycloak.services.clientpolicy.context.ClientCRUDContext; + +/** + * Check that the JWT authorization grant settings of a client are not set or changed by the request. + * + *

The identity provider allow list and the token audience allow list decide which assertions the + * JWT authorization grant accepts for a client, so they are trust decisions rather than ordinary + * client metadata. This executor lets a deployment keep those decisions away from whoever the policy + * applies to. Combined with the client-updater-context condition it can be limited to + * requests that the client itself makes, leaving administrators free to configure the client.

+ * + *

Only a change is rejected. A request that carries the value the client already has is allowed, + * so an existing configuration is preserved and a read-modify-write of the whole client keeps + * working.

+ * + * @author Mahdi Alhakim + */ +public class JWTAuthorizationGrantSettingsDisabledExecutor implements ClientPolicyExecutorProvider { + + private static final Set PROTECTED_ATTRIBUTES = Set.of( + OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP, + OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_AUDIENCE); + + @Override + public String getProviderId() { + return JWTAuthorizationGrantSettingsDisabledExecutorFactory.PROVIDER_ID; + } + + @Override + public void executeOnEvent(ClientPolicyContext context) throws ClientPolicyException { + switch (context.getEvent()) { + case REGISTER: + case UPDATE: + ClientCRUDContext clientContext = (ClientCRUDContext) context; + validate(clientContext.getProposedClientRepresentation(), clientContext.getTargetClient()); + break; + default: + return; + } + } + + private void validate(ClientRepresentation proposedClient, ClientModel existingClient) throws ClientPolicyException { + if (proposedClient == null) { + return; + } + + Map attributes = proposedClient.getAttributes(); + if (attributes == null) { + return; + } + + for (String attribute : PROTECTED_ATTRIBUTES) { + if (!attributes.containsKey(attribute)) { + continue; + } + + String proposed = attributes.get(attribute); + // On REGISTER there is no existing client, so any value is a new setting. + String current = existingClient == null ? null : existingClient.getAttribute(attribute); + + // A value that storage treats as undefined and an absent attribute are the same thing, so + // clearing an attribute that is not set is not a change. The test has to match storage, + // which treats a value as undefined with String.trim (see ClientAdapter.setAttribute). + // Character.isWhitespace, used by ObjectUtil.isBlank, instead counts characters such as the + // em space U+2003 as blank, and trim keeps those, so reading such a value as a clear here + // would let storage keep it and set the attribute this executor is meant to lock. + if (isUndefined(proposed) && isUndefined(current)) { + continue; + } + + // Deliberately an exact comparison of the stored form. Both attributes are serialized, + // the identity provider list with a separator and the audience map as JSON, so a + // re-serialization that means the same thing is still rejected. That errs towards + // refusing a request rather than letting a change through. + if (!Objects.equals(proposed, current)) { + throw new ClientPolicyException(Errors.INVALID_REGISTRATION, + "Not permitted to set, change or remove the client attribute " + attribute); + } + } + + validateGrantNotEnabled(attributes, existingClient); + } + + /** + * The enabled flag is not one of the protected attributes, because {@code DescriptionConverter} + * writes it from the standard {@code grant_types} field of an OpenID Connect registration + * request, so rejecting every write of it would reject a spec compliant registration. Turning it + * on for a client that already exists is rejected all the same: the allow lists an administrator + * configured earlier are still on the client, so the flag on its own is enough to make the grant + * work again. Turning it off stays allowed. + */ + private void validateGrantNotEnabled(Map attributes, ClientModel existingClient) throws ClientPolicyException { + if (existingClient == null) { + // A REGISTER that gets this far carries no allow list, the loop above rejects one, + // so the flag on its own grants nothing. + return; + } + + String attribute = OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_ENABLED; + if (!Boolean.parseBoolean(attributes.get(attribute))) { + // Absent, or the grant is being turned off. + return; + } + + if (Boolean.parseBoolean(existingClient.getAttribute(attribute))) { + // Already enabled, so this is not a change. + return; + } + + throw new ClientPolicyException(Errors.INVALID_REGISTRATION, + "Not permitted to enable the JWT authorization grant on an existing client, attribute " + attribute); + } + + /** + * Whether storage keeps the value, matching {@code ClientAdapter.setAttribute}. A value is kept + * unless it is null or empty once {@link String#trim()} has run, so this is deliberately not + * {@code ObjectUtil.isBlank}: that treats whitespace such as the em space U+2003 as blank while + * {@code trim} does not strip it, which would let such a value through the check and into storage. + */ + private static boolean isUndefined(String value) { + return value == null || value.trim().isEmpty(); + } +} diff --git a/services/src/main/java/org/keycloak/services/clientpolicy/executor/JWTAuthorizationGrantSettingsDisabledExecutorFactory.java b/services/src/main/java/org/keycloak/services/clientpolicy/executor/JWTAuthorizationGrantSettingsDisabledExecutorFactory.java new file mode 100644 index 00000000000..249d862ff6f --- /dev/null +++ b/services/src/main/java/org/keycloak/services/clientpolicy/executor/JWTAuthorizationGrantSettingsDisabledExecutorFactory.java @@ -0,0 +1,76 @@ +/* + * Copyright 2026 Red Hat, Inc. and/or its affiliates + * and other contributors as indicated by the @author tags. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.keycloak.services.clientpolicy.executor; + +import java.util.Collections; +import java.util.List; + +import org.keycloak.Config.Scope; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.KeycloakSessionFactory; +import org.keycloak.provider.ProviderConfigProperty; + +/** + * Factory for the executor that keeps the JWT authorization grant settings of a client out of + * client requests, so only a realm administrator with the policy disabled can change them. + * + * @author Mahdi Alhakim + */ +public class JWTAuthorizationGrantSettingsDisabledExecutorFactory implements ClientPolicyExecutorProviderFactory { + + public static final String PROVIDER_ID = "jwt-authorization-grant-settings-disabled"; + + @Override + public ClientPolicyExecutorProvider create(KeycloakSession session) { + return new JWTAuthorizationGrantSettingsDisabledExecutor(); + } + + @Override + public void init(Scope config) { + } + + @Override + public void postInit(KeycloakSessionFactory factory) { + } + + @Override + public void close() { + } + + @Override + public String getId() { + return PROVIDER_ID; + } + + @Override + public String getHelpText() { + return """ + It rejects a request that sets or changes the JWT authorization grant settings of a client, which are + the identity provider allow list and the token audience allow list. Enabling the grant on a client + that already exists is rejected as well, while turning it off stays allowed. A request that repeats + the value the client already has is permitted, so existing configuration is preserved. Combine it + with the client-updater-context condition to restrict it to requests that the client itself makes. + """; + } + + @Override + public List getConfigProperties() { + return Collections.emptyList(); + } +} diff --git a/services/src/main/resources/META-INF/services/org.keycloak.services.clientpolicy.executor.ClientPolicyExecutorProviderFactory b/services/src/main/resources/META-INF/services/org.keycloak.services.clientpolicy.executor.ClientPolicyExecutorProviderFactory index 8cd8fb6e74e..f7f937bd211 100644 --- a/services/src/main/resources/META-INF/services/org.keycloak.services.clientpolicy.executor.ClientPolicyExecutorProviderFactory +++ b/services/src/main/resources/META-INF/services/org.keycloak.services.clientpolicy.executor.ClientPolicyExecutorProviderFactory @@ -39,3 +39,4 @@ org.keycloak.services.clientpolicy.executor.AllowedProtocolMappersExecutorFactor org.keycloak.services.clientpolicy.executor.RejectMayActClaimExecutorFactory org.keycloak.protocol.oauth2.cimd.clientpolicy.executor.ClientIdMetadataDocumentExecutorFactory org.keycloak.services.clientpolicy.executor.SecureClientNodeExecutorFactory +org.keycloak.services.clientpolicy.executor.JWTAuthorizationGrantSettingsDisabledExecutorFactory diff --git a/tests/base/src/test/java/org/keycloak/tests/client/policies/JWTAuthorizationGrantSettingsDisabledExecutorTest.java b/tests/base/src/test/java/org/keycloak/tests/client/policies/JWTAuthorizationGrantSettingsDisabledExecutorTest.java new file mode 100644 index 00000000000..04cf4f3f2b5 --- /dev/null +++ b/tests/base/src/test/java/org/keycloak/tests/client/policies/JWTAuthorizationGrantSettingsDisabledExecutorTest.java @@ -0,0 +1,424 @@ +/* + * Copyright 2026 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.tests.client.policies; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.keycloak.OAuth2Constants; +import org.keycloak.client.registration.Auth; +import org.keycloak.client.registration.ClientRegistration; +import org.keycloak.client.registration.ClientRegistrationException; +import org.keycloak.client.registration.HttpErrorException; +import org.keycloak.events.Errors; +import org.keycloak.protocol.oidc.OIDCConfigAttributes; +import org.keycloak.protocol.oidc.OIDCLoginProtocol; +import org.keycloak.representations.idm.ClientInitialAccessCreatePresentation; +import org.keycloak.representations.idm.ClientPolicyConditionConfigurationRepresentation; +import org.keycloak.representations.idm.ClientPolicyExecutorConfigurationRepresentation; +import org.keycloak.representations.idm.ClientRepresentation; +import org.keycloak.representations.oidc.OIDCClientRepresentation; +import org.keycloak.services.clientpolicy.ClientPolicyException; +import org.keycloak.services.clientpolicy.condition.AnyClientConditionFactory; +import org.keycloak.services.clientpolicy.condition.ClientUpdaterContextCondition; +import org.keycloak.services.clientpolicy.condition.ClientUpdaterContextConditionFactory; +import org.keycloak.services.clientpolicy.executor.JWTAuthorizationGrantSettingsDisabledExecutorFactory; +import org.keycloak.testframework.annotations.InjectKeycloakUrls; +import org.keycloak.testframework.annotations.InjectRealm; +import org.keycloak.testframework.annotations.KeycloakIntegrationTest; +import org.keycloak.testframework.realm.ManagedRealm; +import org.keycloak.testframework.server.KeycloakUrls; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +/** + * @author Mahdi Alhakim + */ +@KeycloakIntegrationTest +public class JWTAuthorizationGrantSettingsDisabledExecutorTest extends AbstractClientPoliciesTest { + + private static final String IDP_ALIAS = "my-idp"; + private static final String AUDIENCE = "[{\"key\":\"my-idp\",\"value\":\"my-audience\"}]"; + private static final String OTHER_AUDIENCE = "[{\"key\":\"my-idp\",\"value\":\"other-audience\"}]"; + + @InjectRealm + protected ManagedRealm realm; + + @InjectKeycloakUrls + KeycloakUrls keycloakUrls; + + @Test + public void testSettingsRejectedOnCreate() throws Exception { + setupPolicy(); + + // a client that does not carry the settings is unaffected + createClientByAdmin(realm, generateSuffixedName("no-settings"), OIDCLoginProtocol.LOGIN_PROTOCOL, c -> { + }); + + ClientPolicyException cpe = Assertions.assertThrows(ClientPolicyException.class, + () -> createClientByAdmin(realm, generateSuffixedName("with-idp"), OIDCLoginProtocol.LOGIN_PROTOCOL, + c -> c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP, IDP_ALIAS))); + assertNamesAttribute(cpe, OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP); + + cpe = Assertions.assertThrows(ClientPolicyException.class, + () -> createClientByAdmin(realm, generateSuffixedName("with-audience"), OIDCLoginProtocol.LOGIN_PROTOCOL, + c -> c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_AUDIENCE, AUDIENCE))); + assertNamesAttribute(cpe, OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_AUDIENCE); + } + + @Test + public void testSettingsRejectedOnUpdate() throws Exception { + setupPolicy(); + + String cId = createClientByAdmin(realm, generateSuffixedName("update-target"), OIDCLoginProtocol.LOGIN_PROTOCOL, c -> { + }); + + ClientPolicyException cpe = Assertions.assertThrows(ClientPolicyException.class, + () -> updateClientByAdmin(realm, cId, + c -> c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP, IDP_ALIAS))); + assertNamesAttribute(cpe, OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP); + + cpe = Assertions.assertThrows(ClientPolicyException.class, + () -> updateClientByAdmin(realm, cId, + c -> c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_AUDIENCE, AUDIENCE))); + assertNamesAttribute(cpe, OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_AUDIENCE); + } + + /** + * The settings a client already has must survive the policy being enabled, and the rest of the + * client must stay editable. An update sends the whole representation back, so the existing + * value is repeated on every unrelated change and must not be treated as a new setting. + */ + @Test + public void testExistingSettingsPreservedAndClientStillEditable() throws Exception { + String cId = createClientByAdmin(realm, generateSuffixedName("preexisting"), OIDCLoginProtocol.LOGIN_PROTOCOL, c -> { + c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP, IDP_ALIAS); + c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_AUDIENCE, AUDIENCE); + }); + + setupPolicy(); + + // an unrelated change repeats both settings unchanged and must be allowed + updateClientByAdmin(realm, cId, c -> c.setDescription("edited while the policy is active")); + + ClientRepresentation stored = realm.admin().clients().get(cId).toRepresentation(); + Assertions.assertEquals("edited while the policy is active", stored.getDescription()); + Assertions.assertEquals(IDP_ALIAS, stored.getAttributes().get(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP)); + Assertions.assertEquals(AUDIENCE, stored.getAttributes().get(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_AUDIENCE)); + + // changing one of them is still rejected + ClientPolicyException cpe = Assertions.assertThrows(ClientPolicyException.class, + () -> updateClientByAdmin(realm, cId, + c -> c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_AUDIENCE, OTHER_AUDIENCE))); + assertNamesAttribute(cpe, OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_AUDIENCE); + + // and removing one of them is rejected too + cpe = Assertions.assertThrows(ClientPolicyException.class, + () -> updateClientByAdmin(realm, cId, + c -> c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP, ""))); + assertNamesAttribute(cpe, OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP); + } + + /** + * Without the executor in a policy the behaviour is unchanged, which is what makes the + * assertions above attributable to the executor rather than to something else. + */ + @Test + public void testSettingsAllowedWithoutThePolicy() throws Exception { + String cId = createClientByAdmin(realm, generateSuffixedName("no-policy"), OIDCLoginProtocol.LOGIN_PROTOCOL, + c -> c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP, IDP_ALIAS)); + + updateClientByAdmin(realm, cId, + c -> c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_AUDIENCE, AUDIENCE)); + + ClientRepresentation stored = realm.admin().clients().get(cId).toRepresentation(); + Assertions.assertEquals(IDP_ALIAS, stored.getAttributes().get(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP)); + Assertions.assertEquals(AUDIENCE, stored.getAttributes().get(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_AUDIENCE)); + } + + /** + * The same rule has to hold for dynamic client registration, which is the path where the client + * itself authors the request rather than an administrator. + */ + @Test + public void testSettingsRejectedThroughDynamicClientRegistration() throws Exception { + setupPolicy(); + + ClientRegistration reg = ClientRegistration.create().url(keycloakUrls.getBase(), realm.getName()).build(); + reg.auth(Auth.token(newInitialAccessToken())); + + ClientRepresentation withSettings = new ClientRepresentation(); + withSettings.setClientId(generateSuffixedName("dcr-with-idp")); + withSettings.setAttributes(Map.of(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP, IDP_ALIAS)); + assertRegistrationRefused(Assertions.assertThrows(ClientRegistrationException.class, () -> reg.create(withSettings))); + + // a registration that does not carry the settings still works, so the refusal above is the + // executor rather than the registration being broken + reg.auth(Auth.token(newInitialAccessToken())); + ClientRepresentation clean = new ClientRepresentation(); + clean.setClientId(generateSuffixedName("dcr-clean")); + ClientRepresentation created = reg.create(clean); + realm.cleanup().add(r -> r.clients().delete(created.getId())); + + // and the client cannot add them afterwards with its own registration access token + reg.auth(Auth.token(created.getRegistrationAccessToken())); + ClientRepresentation update = new ClientRepresentation(); + update.setClientId(created.getClientId()); + update.setAttributes(Map.of(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_AUDIENCE, AUDIENCE)); + assertRegistrationRefused(Assertions.assertThrows(ClientRegistrationException.class, () -> reg.update(update))); + } + + /** + * The point of doing this with a client policy is that a deployment can decide who it applies + * to. Scoped to the token based sources with the client-updater-context condition, a client is + * refused and an administrator is not, which is the case for a deployment that trusts its + * client administrators with these settings but not the clients themselves. + */ + @Test + public void testCanBeScopedToClientRequestsOnly() throws Exception { + ClientUpdaterContextCondition.Configuration conditionConfig = new ClientUpdaterContextCondition.Configuration(); + conditionConfig.setUpdateClientSource(List.of( + ClientUpdaterContextConditionFactory.BY_REGISTRATION_ACCESS_TOKEN, + ClientUpdaterContextConditionFactory.BY_INITIAL_ACCESS_TOKEN, + ClientUpdaterContextConditionFactory.BY_ANONYMOUS)); + setupPolicy(realm, JWTAuthorizationGrantSettingsDisabledExecutorFactory.PROVIDER_ID, + new ClientPolicyExecutorConfigurationRepresentation(), + ClientUpdaterContextConditionFactory.PROVIDER_ID, conditionConfig); + + // the administrator is outside the condition, so this is allowed + String cId = createClientByAdmin(realm, generateSuffixedName("scoped-admin"), OIDCLoginProtocol.LOGIN_PROTOCOL, + c -> c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP, IDP_ALIAS)); + ClientRepresentation stored = realm.admin().clients().get(cId).toRepresentation(); + Assertions.assertEquals(IDP_ALIAS, stored.getAttributes().get(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP)); + + // the client is inside it, so the same attribute is refused + ClientRegistration reg = ClientRegistration.create().url(keycloakUrls.getBase(), realm.getName()).build(); + reg.auth(Auth.token(newInitialAccessToken())); + ClientRepresentation byClient = new ClientRepresentation(); + byClient.setClientId(generateSuffixedName("scoped-client")); + byClient.setAttributes(Map.of(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP, IDP_ALIAS)); + assertRegistrationRefused(Assertions.assertThrows(ClientRegistrationException.class, () -> reg.create(byClient))); + } + + /** + * Enabling the grant on an existing client is refused, because the allow lists an administrator + * configured earlier are still there and the flag alone would make the grant work again. + * Turning it off has to stay allowed, since a client drops the grant type that way. + */ + @Test + public void testEnablingTheGrantOnAnExistingClientIsRejected() throws Exception { + String cId = createClientByAdmin(realm, generateSuffixedName("enable-target"), OIDCLoginProtocol.LOGIN_PROTOCOL, c -> { + c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP, IDP_ALIAS); + c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_ENABLED, "false"); + }); + + setupPolicy(); + + ClientPolicyException cpe = Assertions.assertThrows(ClientPolicyException.class, + () -> updateClientByAdmin(realm, cId, + c -> c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_ENABLED, "true"))); + Assertions.assertTrue(cpe.getErrorDetail().contains("enable the JWT authorization grant"), cpe.getErrorDetail()); + + // turning it off is still permitted + updateClientByAdmin(realm, cId, + c -> c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_ENABLED, "false")); + } + + /** + * The enabled flag is written from the standard OpenID Connect {@code grant_types} field, so a + * registration that asks for the grant has to keep working while the policy is active, and so + * does the read modify write that an update of an OpenID Connect client goes through. + */ + @Test + public void testGrantTypeAcceptedThroughOIDCDynamicClientRegistration() throws Exception { + setupPolicy(); + + ClientRegistration reg = newClientRegistration(); + OIDCClientRepresentation created = registerWithTheGrantType(reg, generateSuffixedName("oidc-with-grant")); + String clientId = created.getClientId(); + + // the response advertises the grant, so an update sends it back + Assertions.assertTrue(created.getGrantTypes().contains(OAuth2Constants.JWT_AUTHORIZATION_GRANT)); + Assertions.assertEquals("true", storedAttribute(clientId, OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_ENABLED)); + + // an unrelated edit repeats grant_types unchanged, which is not a change + updateClientDynamically(reg, clientId, c -> c.setClientName("edited while the policy is active")); + Assertions.assertEquals("true", storedAttribute(clientId, OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_ENABLED)); + } + + /** + * A client drops the grant by leaving it out of grant_types and that stays allowed, but it + * cannot put it back once the grant is off. The allow lists an administrator configured are + * untouched throughout, since an OpenID Connect request cannot carry them. + */ + @Test + public void testClientCanDropTheGrantTypeButNotAddItBack() throws Exception { + ClientRegistration reg = newClientRegistration(); + String clientId = registerWithTheGrantType(reg, generateSuffixedName("oidc-drop-grant")).getClientId(); + + // the administrator adds the allow lists the grant needs + updateClientByAdmin(realm, findByClientIdByAdmin(realm, clientId).getId(), c -> { + c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP, IDP_ALIAS); + c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_AUDIENCE, AUDIENCE); + }); + + setupPolicy(); + + // the client leaves the grant out of its own registration + updateClientDynamically(reg, clientId, c -> c.setGrantTypes(List.of(OAuth2Constants.AUTHORIZATION_CODE))); + Assertions.assertEquals("false", storedAttribute(clientId, OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_ENABLED)); + + // and cannot put it back + assertRegistrationRefused(Assertions.assertThrows(ClientRegistrationException.class, + () -> updateClientDynamically(reg, clientId, c -> c.setGrantTypes( + List.of(OAuth2Constants.AUTHORIZATION_CODE, OAuth2Constants.JWT_AUTHORIZATION_GRANT))))); + + ClientRepresentation stored = findByClientIdByAdmin(realm, clientId); + Assertions.assertEquals("false", stored.getAttributes().get(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_ENABLED)); + Assertions.assertEquals(IDP_ALIAS, stored.getAttributes().get(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP)); + Assertions.assertEquals(AUDIENCE, stored.getAttributes().get(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_AUDIENCE)); + } + + /** + * The compatibility branch the executor keeps open: a grant that an administrator enabled is turned + * off by the client itself through its registration access token, by dropping the grant type from + * the OpenID Connect grant_types. That update succeeds, the grant stays disabled, and the allow + * lists the administrator configured are left in place. Re-enabling it stays refused by + * {@link #testEnablingTheGrantOnAnExistingClientIsRejected()}. + */ + @Test + public void testClientCanDisableAnAdminEnabledGrantThroughRegistrationAccessToken() throws Exception { + // the administrator enables the grant and sets the allow lists it relies on + String cId = createClientByAdmin(realm, generateSuffixedName("admin-enabled"), OIDCLoginProtocol.LOGIN_PROTOCOL, c -> { + c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP, IDP_ALIAS); + c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_AUDIENCE, AUDIENCE); + c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_ENABLED, "true"); + }); + + setupPolicy(); + + // the client turns it off through its own registration access token by dropping the grant type + String clientId = realm.admin().clients().get(cId).toRepresentation().getClientId(); + ClientRepresentation withRegistrationToken = realm.admin().clients().get(cId).regenerateRegistrationAccessToken(); + ClientRegistration reg = ClientRegistration.create().url(keycloakUrls.getBase(), realm.getName()).build(); + reg.auth(Auth.token(withRegistrationToken)); + // drop only the JWT grant, so the service account and the other flows the client has are kept + // and the registration guard against disabling them is not triggered + updateClientDynamically(reg, clientId, c -> { + List grantTypes = new ArrayList<>(c.getGrantTypes()); + grantTypes.remove(OAuth2Constants.JWT_AUTHORIZATION_GRANT); + c.setGrantTypes(grantTypes); + }); + + // the grant is disabled and stays disabled, and the allow lists are untouched + ClientRepresentation stored = realm.admin().clients().get(cId).toRepresentation(); + Assertions.assertEquals("false", stored.getAttributes().get(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_ENABLED)); + Assertions.assertEquals(IDP_ALIAS, stored.getAttributes().get(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP)); + Assertions.assertEquals(AUDIENCE, stored.getAttributes().get(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_AUDIENCE)); + } + + /** + * A protected attribute set to whitespace that {@link String#trim()} does not strip, such as the + * em space U+2003, is rejected on a client that does not already have it. ObjectUtil.isBlank reads + * such a value as blank, but storage keeps it (see ClientAdapter.setAttribute), so unless the + * executor uses the same notion of blank as storage it reads the value as a no-op clear and lets + * the request set the attribute it is meant to lock. + */ + @Test + public void testWhitespaceSettingStorageKeepsIsRejected() throws Exception { + // U+2003 EM SPACE: whitespace to Character.isWhitespace but not stripped by String.trim + String emSpace = new String(new int[] {0x2003}, 0, 1); + + setupPolicy(); + + // REGISTER: a client created with a protected attribute set to such whitespace is refused + ClientPolicyException cpe = Assertions.assertThrows(ClientPolicyException.class, + () -> createClientByAdmin(realm, generateSuffixedName("ws-create"), OIDCLoginProtocol.LOGIN_PROTOCOL, + c -> c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP, emSpace))); + assertNamesAttribute(cpe, OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP); + + // UPDATE: the same on a client that does not have the attribute is refused, and nothing is stored + String cId = createClientByAdmin(realm, generateSuffixedName("ws-update"), OIDCLoginProtocol.LOGIN_PROTOCOL, c -> { + }); + cpe = Assertions.assertThrows(ClientPolicyException.class, + () -> updateClientByAdmin(realm, cId, + c -> c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP, emSpace))); + assertNamesAttribute(cpe, OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP); + Assertions.assertNull(realm.admin().clients().get(cId).toRepresentation().getAttributes() + .get(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP), + "the rejected whitespace value must not have been stored"); + + // a value storage also drops stays a no-op clear, so the fix does not start rejecting the + // read-modify-write of a client that never had the attribute + updateClientByAdmin(realm, cId, + c -> c.getAttributes().put(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP, " ")); + Assertions.assertNull(realm.admin().clients().get(cId).toRepresentation().getAttributes() + .get(OIDCConfigAttributes.JWT_AUTHORIZATION_GRANT_IDP)); + } + + private void assertNamesAttribute(ClientPolicyException cpe, String attribute) { + Assertions.assertTrue(cpe.getErrorDetail().contains(attribute), + "the refusal should name the attribute that failed, was: " + cpe.getErrorDetail()); + } + + private void assertRegistrationRefused(ClientRegistrationException cre) { + HttpErrorException cause = (HttpErrorException) cre.getCause(); + Assertions.assertEquals(403, cause.getStatusLine().getStatusCode()); + // the refusal is the client policy, not the request being unauthorized + Assertions.assertEquals(Errors.INVALID_REGISTRATION, cause.toErrorRepresentation().getErrorDescription()); + } + + private ClientRegistration newClientRegistration() { + ClientRegistration reg = ClientRegistration.create().url(keycloakUrls.getBase(), realm.getName()).build(); + reg.auth(Auth.token(newInitialAccessToken())); + return reg; + } + + private OIDCClientRepresentation registerWithTheGrantType(ClientRegistration reg, String clientName) throws Exception { + OIDCClientRepresentation request = new OIDCClientRepresentation(); + request.setClientName(clientName); + request.setClientUri(realm.getBaseUrl()); + request.setRedirectUris(List.of(realm.getBaseUrl() + "/app/auth")); + request.setGrantTypes(List.of(OAuth2Constants.AUTHORIZATION_CODE, OAuth2Constants.JWT_AUTHORIZATION_GRANT)); + + OIDCClientRepresentation created = reg.oidc().create(request); + reg.auth(Auth.token(created)); + + String cId = findByClientIdByAdmin(realm, created.getClientId()).getId(); + realm.cleanup().add(r -> r.clients().delete(cId)); + return created; + } + + private String storedAttribute(String clientId, String attribute) throws Exception { + return findByClientIdByAdmin(realm, clientId).getAttributes().get(attribute); + } + + private String newInitialAccessToken() { + ClientInitialAccessCreatePresentation rep = new ClientInitialAccessCreatePresentation(); + rep.setCount(1); + rep.setExpiration(10000); + return realm.admin().clientInitialAccess().create(rep).getToken(); + } + + private void setupPolicy() throws Exception { + setupPolicy(realm, JWTAuthorizationGrantSettingsDisabledExecutorFactory.PROVIDER_ID, + new ClientPolicyExecutorConfigurationRepresentation(), + AnyClientConditionFactory.PROVIDER_ID, new ClientPolicyConditionConfigurationRepresentation()); + } +}