From 263161ff6690318078eb123f92eaa48ed80940b4 Mon Sep 17 00:00:00 2001 From: Takashi Norimatsu Date: Thu, 14 Oct 2021 10:04:38 +0900 Subject: [PATCH] KEYCLOAK-19540 FAPI 2.0 Baseline : Reject Resource Owner Password Credentials Grant --- .../clientpolicy/ClientPolicyEvent.java | 3 +- .../oidc/endpoints/TokenEndpoint.java | 9 ++ ...sourceOwnerPasswordCredentialsContext.java | 45 ++++++++ ...OwnerPasswordCredentialsGrantExecutor.java | 108 ++++++++++++++++++ ...sswordCredentialsGrantExecutorFactory.java | 72 ++++++++++++ ...ecutor.ClientPolicyExecutorProviderFactory | 3 +- .../testsuite/client/ClientPoliciesTest.java | 43 +++++++ .../testsuite/util/ClientPoliciesUtil.java | 7 ++ 8 files changed, 288 insertions(+), 2 deletions(-) create mode 100644 services/src/main/java/org/keycloak/services/clientpolicy/context/ResourceOwnerPasswordCredentialsContext.java create mode 100644 services/src/main/java/org/keycloak/services/clientpolicy/executor/RejectResourceOwnerPasswordCredentialsGrantExecutor.java create mode 100644 services/src/main/java/org/keycloak/services/clientpolicy/executor/RejectResourceOwnerPasswordCredentialsGrantExecutorFactory.java diff --git a/server-spi/src/main/java/org/keycloak/services/clientpolicy/ClientPolicyEvent.java b/server-spi/src/main/java/org/keycloak/services/clientpolicy/ClientPolicyEvent.java index a59bf4721d..4093f95e67 100644 --- a/server-spi/src/main/java/org/keycloak/services/clientpolicy/ClientPolicyEvent.java +++ b/server-spi/src/main/java/org/keycloak/services/clientpolicy/ClientPolicyEvent.java @@ -42,6 +42,7 @@ public enum ClientPolicyEvent { BACKCHANNEL_TOKEN_REQUEST, PUSHED_AUTHORIZATION_REQUEST, DEVICE_AUTHORIZATION_REQUEST, - DEVICE_TOKEN_REQUEST + DEVICE_TOKEN_REQUEST, + RESOURCE_OWNER_PASSWORD_CREDENTIALS_REQUEST } diff --git a/services/src/main/java/org/keycloak/protocol/oidc/endpoints/TokenEndpoint.java b/services/src/main/java/org/keycloak/protocol/oidc/endpoints/TokenEndpoint.java index 0a5c08ced4..fc8d52c7b9 100644 --- a/services/src/main/java/org/keycloak/protocol/oidc/endpoints/TokenEndpoint.java +++ b/services/src/main/java/org/keycloak/protocol/oidc/endpoints/TokenEndpoint.java @@ -74,6 +74,7 @@ import org.keycloak.services.CorsErrorResponseException; import org.keycloak.services.ServicesLogger; import org.keycloak.services.Urls; import org.keycloak.services.clientpolicy.ClientPolicyException; +import org.keycloak.services.clientpolicy.context.ResourceOwnerPasswordCredentialsContext; import org.keycloak.services.clientpolicy.context.ServiceAccountTokenRequestContext; import org.keycloak.services.clientpolicy.context.TokenRefreshContext; import org.keycloak.services.clientpolicy.context.TokenRequestContext; @@ -630,6 +631,14 @@ public class TokenEndpoint { event.error(Errors.CONSENT_DENIED); throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_CLIENT, "Client requires user consent", Response.Status.BAD_REQUEST); } + + try { + session.clientPolicy().triggerOnEvent(new ResourceOwnerPasswordCredentialsContext(formParams)); + } catch (ClientPolicyException cpe) { + event.error(cpe.getError()); + throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), cpe.getErrorStatus()); + } + String scope = getRequestedScopes(); RootAuthenticationSessionModel rootAuthSession = new AuthenticationSessionManager(session).createAuthenticationSession(realm, false); diff --git a/services/src/main/java/org/keycloak/services/clientpolicy/context/ResourceOwnerPasswordCredentialsContext.java b/services/src/main/java/org/keycloak/services/clientpolicy/context/ResourceOwnerPasswordCredentialsContext.java new file mode 100644 index 0000000000..e6ad76a482 --- /dev/null +++ b/services/src/main/java/org/keycloak/services/clientpolicy/context/ResourceOwnerPasswordCredentialsContext.java @@ -0,0 +1,45 @@ +/* + * Copyright 2021 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.context; + +import javax.ws.rs.core.MultivaluedMap; + +import org.keycloak.services.clientpolicy.ClientPolicyContext; +import org.keycloak.services.clientpolicy.ClientPolicyEvent; + +/** + * @author Takashi Norimatsu + */ +public class ResourceOwnerPasswordCredentialsContext implements ClientPolicyContext { + + private final MultivaluedMap params; + + public ResourceOwnerPasswordCredentialsContext(MultivaluedMap params) { + this.params = params; + } + + @Override + public ClientPolicyEvent getEvent() { + return ClientPolicyEvent.RESOURCE_OWNER_PASSWORD_CREDENTIALS_REQUEST; + } + + public MultivaluedMap getParams() { + return params; + } + +} diff --git a/services/src/main/java/org/keycloak/services/clientpolicy/executor/RejectResourceOwnerPasswordCredentialsGrantExecutor.java b/services/src/main/java/org/keycloak/services/clientpolicy/executor/RejectResourceOwnerPasswordCredentialsGrantExecutor.java new file mode 100644 index 0000000000..d0d3042fca --- /dev/null +++ b/services/src/main/java/org/keycloak/services/clientpolicy/executor/RejectResourceOwnerPasswordCredentialsGrantExecutor.java @@ -0,0 +1,108 @@ +/* + * Copyright 2021 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 javax.ws.rs.core.MultivaluedMap; + +import org.keycloak.OAuthErrorException; +import org.keycloak.models.KeycloakSession; +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; +import org.keycloak.services.clientpolicy.context.ResourceOwnerPasswordCredentialsContext; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @author Takashi Norimatsu + */ +public class RejectResourceOwnerPasswordCredentialsGrantExecutor implements ClientPolicyExecutorProvider { + + private final KeycloakSession session; + private Configuration configuration; + + public RejectResourceOwnerPasswordCredentialsGrantExecutor(KeycloakSession session) { + this.session = session; + } + + @Override + public void setupConfiguration(Configuration config) { + this.configuration = config; + } + + @Override + public Class getExecutorConfigurationClass() { + return Configuration.class; + } + + public static class Configuration extends ClientPolicyExecutorConfigurationRepresentation { + @JsonProperty("auto-configure") + protected Boolean autoConfigure; + + public Boolean isAutoConfigure() { + return autoConfigure; + } + + public void setAutoConfigure(Boolean autoConfigure) { + this.autoConfigure = autoConfigure; + } + } + + @Override + public String getProviderId() { + return RejectResourceOwnerPasswordCredentialsGrantExecutorFactory.PROVIDER_ID; + } + + @Override + public void executeOnEvent(ClientPolicyContext context) throws ClientPolicyException { + switch (context.getEvent()) { + case REGISTER: + case UPDATE: + ClientCRUDContext clientUpdateContext = (ClientCRUDContext)context; + autoConfigure(clientUpdateContext.getProposedClientRepresentation()); + validate(clientUpdateContext.getProposedClientRepresentation()); + break; + case RESOURCE_OWNER_PASSWORD_CREDENTIALS_REQUEST: + ResourceOwnerPasswordCredentialsContext ropcContext = (ResourceOwnerPasswordCredentialsContext)context; + executeOnAuthorizationRequest(ropcContext.getParams()); + return; + default: + return; + } + } + + private void autoConfigure(ClientRepresentation rep) { + if (configuration.isAutoConfigure()) + rep.setDirectAccessGrantsEnabled(Boolean.FALSE); + } + + private void validate(ClientRepresentation rep) throws ClientPolicyException { + boolean isResourceOwnerPasswordCredentialsGrantEnabled = rep.isDirectAccessGrantsEnabled().booleanValue(); + if (!isResourceOwnerPasswordCredentialsGrantEnabled) return; + throw new ClientPolicyException(OAuthErrorException.INVALID_CLIENT_METADATA, "Invalid client metadata: resource owner password credentials grant enabled"); + } + + private void executeOnAuthorizationRequest(MultivaluedMap params) throws ClientPolicyException { + // Before client policies operation, Token Endpoint logic has already checked whether resource owner password credentials grant is activated for a client. + // This method rejects resource owner password credentials grant regardless of client setting for allowing resource owner password credentials grant. + throw new ClientPolicyException(OAuthErrorException.INVALID_GRANT, "resource owner password credentials grant is prohibited."); + } + +} \ No newline at end of file diff --git a/services/src/main/java/org/keycloak/services/clientpolicy/executor/RejectResourceOwnerPasswordCredentialsGrantExecutorFactory.java b/services/src/main/java/org/keycloak/services/clientpolicy/executor/RejectResourceOwnerPasswordCredentialsGrantExecutorFactory.java new file mode 100644 index 0000000000..5673fb221f --- /dev/null +++ b/services/src/main/java/org/keycloak/services/clientpolicy/executor/RejectResourceOwnerPasswordCredentialsGrantExecutorFactory.java @@ -0,0 +1,72 @@ +/* + * Copyright 2021 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; + +/** + * @author Takashi Norimatsu + */ +public class RejectResourceOwnerPasswordCredentialsGrantExecutorFactory implements ClientPolicyExecutorProviderFactory { + + public static final String PROVIDER_ID = "reject-ropc-grant"; + + public static final String AUTO_CONFIGURE = "auto-configure"; + + private static final ProviderConfigProperty AUTO_CONFIGURE_PROPERTY = new ProviderConfigProperty( + AUTO_CONFIGURE, "Auto-configure", "If On, then the during client creation or update, the configuration of the client will be auto-configured to reject a resource owner password credentials grant.", ProviderConfigProperty.BOOLEAN_TYPE, false); + + @Override + public ClientPolicyExecutorProvider create(KeycloakSession session) { + return new RejectResourceOwnerPasswordCredentialsGrantExecutor(session); + } + + @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 makes keycloak to reject a resource owner password credentials grant."; + } + + @Override + public List getConfigProperties() { + return Collections.singletonList(AUTO_CONFIGURE_PROPERTY); + } + +} \ No newline at end of file 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 3d92a09420..adae5d1654 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 @@ -13,4 +13,5 @@ org.keycloak.services.clientpolicy.executor.FullScopeDisabledExecutorFactory org.keycloak.protocol.oidc.grants.ciba.clientpolicy.executor.SecureCibaSessionEnforceExecutorFactory org.keycloak.protocol.oidc.grants.ciba.clientpolicy.executor.SecureCibaSignedAuthenticationRequestExecutorFactory org.keycloak.protocol.oidc.grants.ciba.clientpolicy.executor.SecureCibaAuthenticationRequestSigningAlgorithmExecutorFactory -org.keycloak.services.clientpolicy.executor.SecureLogoutExecutorFactory \ No newline at end of file +org.keycloak.services.clientpolicy.executor.SecureLogoutExecutorFactory +org.keycloak.services.clientpolicy.executor.RejectResourceOwnerPasswordCredentialsGrantExecutorFactory \ No newline at end of file diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientPoliciesTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientPoliciesTest.java index bbaa37ca83..fdc8df1377 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientPoliciesTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientPoliciesTest.java @@ -79,6 +79,7 @@ import org.keycloak.services.clientpolicy.executor.ConsentRequiredExecutorFactor import org.keycloak.services.clientpolicy.executor.FullScopeDisabledExecutorFactory; import org.keycloak.services.clientpolicy.executor.HolderOfKeyEnforcerExecutorFactory; import org.keycloak.services.clientpolicy.executor.PKCEEnforcerExecutorFactory; +import org.keycloak.services.clientpolicy.executor.RejectResourceOwnerPasswordCredentialsGrantExecutorFactory; import org.keycloak.services.clientpolicy.executor.SecureClientAuthenticatorExecutorFactory; import org.keycloak.services.clientpolicy.executor.SecureClientUrisExecutorFactory; import org.keycloak.services.clientpolicy.executor.SecureLogoutExecutorFactory; @@ -148,6 +149,7 @@ import static org.keycloak.testsuite.util.ClientPoliciesUtil.createSecureSigning import static org.keycloak.testsuite.util.ClientPoliciesUtil.createSecureSigningAlgorithmForSignedJwtEnforceExecutorConfig; import static org.keycloak.testsuite.util.ClientPoliciesUtil.createTestRaiseExeptionConditionConfig; import static org.keycloak.testsuite.util.ClientPoliciesUtil.createFullScopeDisabledExecutorConfig; +import static org.keycloak.testsuite.util.ClientPoliciesUtil.createRejectisResourceOwnerPasswordCredentialsGrantExecutorConfig; import javax.ws.rs.BadRequestException; @@ -2695,6 +2697,47 @@ public class ClientPoliciesTest extends AbstractClientPoliciesTest { assertTrue(driver.getPageSource().contains("Front-channel logout is not allowed for this client")); } + @Test + public void testRejectResourceOwnerCredentialsGrantExecutor() throws Exception { + + String clientId = generateSuffixedName(CLIENT_NAME); + String clientSecret = "secret"; + + createClientByAdmin(clientId, (ClientRepresentation clientRep) -> { + clientRep.setSecret(clientSecret); + clientRep.setStandardFlowEnabled(Boolean.TRUE); + clientRep.setDirectAccessGrantsEnabled(Boolean.TRUE); + clientRep.setPublicClient(Boolean.FALSE); + }); + + // register profiles + String json = (new ClientProfilesBuilder()).addProfile( + (new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Purofairu desu") + .addExecutor(RejectResourceOwnerPasswordCredentialsGrantExecutorFactory.PROVIDER_ID, + createRejectisResourceOwnerPasswordCredentialsGrantExecutorConfig(Boolean.TRUE)) + .toRepresentation() + ).toString(); + updateProfiles(json); + + // register policies + json = (new ClientPoliciesBuilder()).addPolicy( + (new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "Porisii desu", Boolean.TRUE) + .addCondition(AnyClientConditionFactory.PROVIDER_ID, + createAnyClientConditionConfig()) + .addProfile(PROFILE_NAME) + .toRepresentation() + ).toString(); + updatePolicies(json); + + oauth.clientId(clientId); + OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest(clientSecret, TEST_USER_NAME, TEST_USER_PASSWORD, null); + + assertEquals(400, response.getStatusCode()); + assertEquals(OAuthErrorException.INVALID_GRANT, response.getError()); + assertEquals("resource owner password credentials grant is prohibited.", response.getErrorDescription()); + + } + private void openVerificationPage(String verificationUri) { driver.navigate().to(verificationUri); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/ClientPoliciesUtil.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/ClientPoliciesUtil.java index 96629c2364..c99eedc29e 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/ClientPoliciesUtil.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/ClientPoliciesUtil.java @@ -41,6 +41,7 @@ import org.keycloak.services.clientpolicy.executor.ConsentRequiredExecutor; import org.keycloak.services.clientpolicy.executor.FullScopeDisabledExecutor; import org.keycloak.services.clientpolicy.executor.HolderOfKeyEnforcerExecutor; import org.keycloak.services.clientpolicy.executor.PKCEEnforcerExecutor; +import org.keycloak.services.clientpolicy.executor.RejectResourceOwnerPasswordCredentialsGrantExecutor; import org.keycloak.services.clientpolicy.executor.SecureClientAuthenticatorExecutor; import org.keycloak.services.clientpolicy.executor.SecureRequestObjectExecutor; import org.keycloak.services.clientpolicy.executor.SecureResponseTypeExecutor; @@ -211,6 +212,12 @@ public final class ClientPoliciesUtil { return config; } + public static RejectResourceOwnerPasswordCredentialsGrantExecutor.Configuration createRejectisResourceOwnerPasswordCredentialsGrantExecutorConfig(Boolean autoConfigure) { + RejectResourceOwnerPasswordCredentialsGrantExecutor.Configuration config = new RejectResourceOwnerPasswordCredentialsGrantExecutor.Configuration(); + config.setAutoConfigure(autoConfigure); + return config; + } + public static class ClientPoliciesBuilder { private final ClientPoliciesRepresentation policiesRep;