parent
09ff572ef6
commit
cc6597967a
14 changed files with 4386 additions and 3782 deletions
|
@ -124,6 +124,7 @@ import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfileBuilder;
|
|||
import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfilesBuilder;
|
||||
import org.keycloak.testsuite.util.OAuthClient.AuthenticationRequestAcknowledgement;
|
||||
import org.keycloak.util.JsonSerialization;
|
||||
import org.keycloak.testsuite.client.policies.AbstractClientPoliciesTest;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -73,6 +73,7 @@ import org.keycloak.testsuite.rest.resource.TestingOIDCEndpointsApplicationResou
|
|||
import org.keycloak.testsuite.util.MutualTLSUtils;
|
||||
import org.keycloak.testsuite.util.OAuthClient;
|
||||
import org.keycloak.testsuite.util.ServerURLs;
|
||||
import org.keycloak.testsuite.client.policies.AbstractClientPoliciesTest;
|
||||
|
||||
import java.security.KeyPair;
|
||||
import java.security.PrivateKey;
|
||||
|
|
|
@ -99,6 +99,7 @@ import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPoliciesBuilder;
|
|||
import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPolicyBuilder;
|
||||
import org.keycloak.testsuite.util.OAuthClient.AuthenticationRequestAcknowledgement;
|
||||
import org.keycloak.util.JsonSerialization;
|
||||
import org.keycloak.testsuite.client.policies.AbstractClientPoliciesTest;
|
||||
|
||||
/**
|
||||
* Test for the FAPI CIBA specifications (still implementer's draft):
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
* Copyright 2021 Red Hat, Inc. and/or its affiliates
|
||||
* Copyright 2023 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");
|
||||
|
@ -15,7 +15,25 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.keycloak.testsuite.client;
|
||||
package org.keycloak.testsuite.client.policies;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.fail;
|
||||
import static org.keycloak.testsuite.admin.ApiUtil.findUserByUsername;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientAccessTypeConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientRolesConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientScopesConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientUpdateContextConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientUpdateSourceGroupsConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientUpdateSourceHostsConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientUpdateSourceRolesConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createHolderOfKeyEnforceExecutorConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createPKCEEnforceExecutorConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createSecureClientAuthenticatorExecutorConfig;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
|
@ -37,6 +55,7 @@ import java.util.HashSet;
|
|||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
|
@ -46,9 +65,6 @@ import java.util.stream.Collectors;
|
|||
import javax.ws.rs.BadRequestException;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
|
@ -58,7 +74,9 @@ import org.apache.http.impl.client.CloseableHttpClient;
|
|||
import org.apache.http.impl.client.DefaultHttpClient;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.jboss.arquillian.graphene.page.Page;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
|
@ -66,7 +84,10 @@ import org.keycloak.OAuth2Constants;
|
|||
import org.keycloak.OAuthErrorException;
|
||||
import org.keycloak.adapters.AdapterUtils;
|
||||
import org.keycloak.admin.client.resource.ClientResource;
|
||||
import org.keycloak.authentication.authenticators.client.ClientIdAndSecretAuthenticator;
|
||||
import org.keycloak.authentication.authenticators.client.JWTClientAuthenticator;
|
||||
import org.keycloak.authentication.authenticators.client.JWTClientSecretAuthenticator;
|
||||
import org.keycloak.authentication.authenticators.client.X509ClientAuthenticator;
|
||||
import org.keycloak.client.registration.Auth;
|
||||
import org.keycloak.client.registration.ClientRegistration;
|
||||
import org.keycloak.client.registration.ClientRegistrationException;
|
||||
|
@ -81,13 +102,17 @@ import org.keycloak.constants.ServiceUrlConstants;
|
|||
import org.keycloak.crypto.Algorithm;
|
||||
import org.keycloak.crypto.KeyType;
|
||||
import org.keycloak.crypto.SignatureSignerContext;
|
||||
import org.keycloak.events.Details;
|
||||
import org.keycloak.events.Errors;
|
||||
import org.keycloak.events.EventType;
|
||||
import org.keycloak.jose.jws.JWSBuilder;
|
||||
import org.keycloak.models.AdminRoles;
|
||||
import org.keycloak.models.Constants;
|
||||
import org.keycloak.models.utils.KeycloakModelUtils;
|
||||
import org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper;
|
||||
import org.keycloak.representations.AccessToken;
|
||||
import org.keycloak.representations.JsonWebToken;
|
||||
import org.keycloak.representations.RefreshToken;
|
||||
import org.keycloak.representations.idm.ClientInitialAccessCreatePresentation;
|
||||
import org.keycloak.representations.idm.ClientInitialAccessPresentation;
|
||||
import org.keycloak.representations.idm.ClientPoliciesRepresentation;
|
||||
|
@ -98,6 +123,7 @@ import org.keycloak.representations.idm.ClientPolicyRepresentation;
|
|||
import org.keycloak.representations.idm.ClientProfileRepresentation;
|
||||
import org.keycloak.representations.idm.ClientProfilesRepresentation;
|
||||
import org.keycloak.representations.idm.ClientRepresentation;
|
||||
import org.keycloak.representations.idm.EventRepresentation;
|
||||
import org.keycloak.representations.oidc.OIDCClientRepresentation;
|
||||
import org.keycloak.representations.oidc.TokenMetadataRepresentation;
|
||||
import org.keycloak.services.Urls;
|
||||
|
@ -117,6 +143,8 @@ import org.keycloak.services.clientpolicy.condition.ClientUpdaterSourceHostsCond
|
|||
import org.keycloak.services.clientpolicy.condition.ClientUpdaterSourceHostsConditionFactory;
|
||||
import org.keycloak.services.clientpolicy.condition.ClientUpdaterSourceRolesCondition;
|
||||
import org.keycloak.services.clientpolicy.condition.ClientUpdaterSourceRolesConditionFactory;
|
||||
import org.keycloak.services.clientpolicy.executor.ClientSecretRotationExecutor;
|
||||
import org.keycloak.services.clientpolicy.executor.ClientSecretRotationExecutorFactory;
|
||||
import org.keycloak.services.clientpolicy.executor.ConsentRequiredExecutorFactory;
|
||||
import org.keycloak.services.clientpolicy.executor.FullScopeDisabledExecutorFactory;
|
||||
import org.keycloak.services.clientpolicy.executor.HolderOfKeyEnforcerExecutorFactory;
|
||||
|
@ -134,30 +162,25 @@ import org.keycloak.testsuite.AssertEvents;
|
|||
import org.keycloak.testsuite.admin.ApiUtil;
|
||||
import org.keycloak.testsuite.client.resources.TestApplicationResourceUrls;
|
||||
import org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource;
|
||||
import org.keycloak.testsuite.pages.ErrorPage;
|
||||
import org.keycloak.testsuite.pages.LogoutConfirmPage;
|
||||
import org.keycloak.testsuite.pages.OAuth2DeviceVerificationPage;
|
||||
import org.keycloak.testsuite.pages.OAuthGrantPage;
|
||||
import org.keycloak.testsuite.rest.resource.TestingOIDCEndpointsApplicationResource;
|
||||
import org.keycloak.testsuite.rest.resource.TestingOIDCEndpointsApplicationResource.AuthorizationEndpointRequestObject;
|
||||
import org.keycloak.testsuite.util.ClientPoliciesUtil;
|
||||
import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPoliciesBuilder;
|
||||
import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPolicyBuilder;
|
||||
import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfileBuilder;
|
||||
import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfilesBuilder;
|
||||
import org.keycloak.testsuite.util.MutualTLSUtils;
|
||||
import org.keycloak.testsuite.util.OAuthClient;
|
||||
import org.keycloak.testsuite.util.ServerURLs;
|
||||
import org.keycloak.util.JsonSerialization;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.fail;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientAccessTypeConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientRolesConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientScopesConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientUpdateContextConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientUpdateSourceGroupsConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientUpdateSourceHostsConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientUpdateSourceRolesConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createHolderOfKeyEnforceExecutorConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createSecureClientAuthenticatorExecutorConfig;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
/**
|
||||
* @author <a href="mailto:takashi.norimatsu.ws@hitachi.com">Takashi Norimatsu</a>
|
||||
|
@ -187,6 +210,29 @@ public abstract class AbstractClientPoliciesTest extends AbstractKeycloakTest {
|
|||
|
||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
protected static final String CLIENT_NAME = "Zahlungs-App";
|
||||
protected static final String TEST_USER_NAME = "test-user@localhost";
|
||||
protected static final String TEST_USER_PASSWORD = "password";
|
||||
|
||||
protected static final String DEVICE_APP = "test-device";
|
||||
protected static final String DEVICE_APP_PUBLIC = "test-device-public";
|
||||
protected static String userId;
|
||||
|
||||
protected static final String SECRET_ROTATION_PROFILE = "ClientSecretRotationProfile";
|
||||
protected static final String SECRET_ROTATION_POLICY = "ClientSecretRotationPolicy";
|
||||
|
||||
@Page
|
||||
protected OAuth2DeviceVerificationPage verificationPage;
|
||||
|
||||
@Page
|
||||
protected OAuthGrantPage grantPage;
|
||||
|
||||
@Page
|
||||
protected ErrorPage errorPage;
|
||||
|
||||
@Page
|
||||
protected LogoutConfirmPage logoutConfirmPage;
|
||||
|
||||
@Rule
|
||||
public AssertEvents events = new AssertEvents(this);
|
||||
|
||||
|
@ -1207,4 +1253,363 @@ public abstract class AbstractClientPoliciesTest extends AbstractKeycloakTest {
|
|||
Assert.assertTrue("Expected empty configuration for provider " + executorProviderId, config.isEmpty());
|
||||
}
|
||||
|
||||
protected String signRequestObject(AuthorizationEndpointRequestObject requestObject) throws IOException {
|
||||
byte[] contentBytes = JsonSerialization.writeValueAsBytes(requestObject);
|
||||
String encodedRequestObject = Base64Url.encode(contentBytes);
|
||||
TestOIDCEndpointsApplicationResource client = testingClient.testApp().oidcClientEndpoints();
|
||||
|
||||
// use and set jwks_url
|
||||
ClientResource clientResource = ApiUtil.findClientByClientId(adminClient.realm(oauth.getRealm()), oauth.getClientId());
|
||||
ClientRepresentation clientRep = clientResource.toRepresentation();
|
||||
OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setUseJwksUrl(true);
|
||||
OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setJwksUrl(TestApplicationResourceUrls.clientJwksUri());
|
||||
clientResource.update(clientRep);
|
||||
client.generateKeys(Algorithm.PS256);
|
||||
client.registerOIDCRequest(encodedRequestObject, Algorithm.PS256);
|
||||
|
||||
// do not send any other parameter but the request request parameter
|
||||
String oidcRequest = client.getOIDCRequest();
|
||||
return oidcRequest;
|
||||
}
|
||||
|
||||
protected List<String> getAttributeMultivalued(ClientRepresentation clientRep, String attrKey) {
|
||||
String attrValue = Optional.ofNullable(clientRep.getAttributes()).orElse(Collections.emptyMap()).get(attrKey);
|
||||
if (attrValue == null) return Collections.emptyList();
|
||||
return Arrays.asList(Constants.CFG_DELIMITER_PATTERN.split(attrValue));
|
||||
}
|
||||
|
||||
protected void setAttributeMultivalued(ClientRepresentation clientRep, String attrKey, List<String> attrValues) {
|
||||
String attrValueFull = String.join(Constants.CFG_DELIMITER, attrValues);
|
||||
clientRep.getAttributes().put(attrKey, attrValueFull);
|
||||
}
|
||||
|
||||
protected void openVerificationPage(String verificationUri) {
|
||||
driver.navigate().to(verificationUri);
|
||||
}
|
||||
|
||||
protected void checkMtlsFlow() throws IOException {
|
||||
// Check login.
|
||||
OAuthClient.AuthorizationEndpointResponse loginResponse = oauth.doLogin(TEST_USER_NAME, TEST_USER_PASSWORD);
|
||||
Assert.assertNull(loginResponse.getError());
|
||||
|
||||
String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
|
||||
|
||||
// Check token obtaining.
|
||||
OAuthClient.AccessTokenResponse accessTokenResponse;
|
||||
try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithDefaultKeyStoreAndTrustStore()) {
|
||||
accessTokenResponse = oauth.doAccessTokenRequest(code, TEST_CLIENT_SECRET, client);
|
||||
} catch (IOException ioe) {
|
||||
throw new RuntimeException(ioe);
|
||||
}
|
||||
assertEquals(200, accessTokenResponse.getStatusCode());
|
||||
|
||||
// Check token refresh.
|
||||
OAuthClient.AccessTokenResponse accessTokenResponseRefreshed;
|
||||
try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithDefaultKeyStoreAndTrustStore()) {
|
||||
accessTokenResponseRefreshed = oauth.doRefreshTokenRequest(accessTokenResponse.getRefreshToken(), TEST_CLIENT_SECRET, client);
|
||||
} catch (IOException ioe) {
|
||||
throw new RuntimeException(ioe);
|
||||
}
|
||||
assertEquals(200, accessTokenResponseRefreshed.getStatusCode());
|
||||
|
||||
// Check token introspection.
|
||||
String tokenResponse;
|
||||
try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithDefaultKeyStoreAndTrustStore()) {
|
||||
tokenResponse = oauth.introspectTokenWithClientCredential(TEST_CLIENT, TEST_CLIENT_SECRET, "access_token", accessTokenResponse.getAccessToken(), client);
|
||||
} catch (IOException ioe) {
|
||||
throw new RuntimeException(ioe);
|
||||
}
|
||||
Assert.assertNotNull(tokenResponse);
|
||||
TokenMetadataRepresentation tokenMetadataRepresentation = JsonSerialization.readValue(tokenResponse, TokenMetadataRepresentation.class);
|
||||
Assert.assertTrue(tokenMetadataRepresentation.isActive());
|
||||
|
||||
// Check token revoke.
|
||||
CloseableHttpResponse tokenRevokeResponse;
|
||||
try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithDefaultKeyStoreAndTrustStore()) {
|
||||
tokenRevokeResponse = oauth.doTokenRevoke(accessTokenResponse.getRefreshToken(), "refresh_token", TEST_CLIENT_SECRET, client);
|
||||
} catch (IOException ioe) {
|
||||
throw new RuntimeException(ioe);
|
||||
}
|
||||
assertEquals(200, tokenRevokeResponse.getStatusLine().getStatusCode());
|
||||
|
||||
// Check logout.
|
||||
CloseableHttpResponse logoutResponse;
|
||||
try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithDefaultKeyStoreAndTrustStore()) {
|
||||
logoutResponse = oauth.doLogout(accessTokenResponse.getRefreshToken(), TEST_CLIENT_SECRET, client);
|
||||
} catch (IOException ioe) {
|
||||
throw new RuntimeException(ioe);
|
||||
}
|
||||
assertEquals(204, logoutResponse.getStatusLine().getStatusCode());
|
||||
|
||||
// Check login.
|
||||
loginResponse = oauth.doLogin(TEST_USER_NAME, TEST_USER_PASSWORD);
|
||||
Assert.assertNull(loginResponse.getError());
|
||||
|
||||
code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
|
||||
|
||||
// Check token obtaining without certificate
|
||||
try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithoutKeyStoreAndTrustStore()) {
|
||||
accessTokenResponse = oauth.doAccessTokenRequest(code, TEST_CLIENT_SECRET, client);
|
||||
} catch (IOException ioe) {
|
||||
throw new RuntimeException(ioe);
|
||||
}
|
||||
assertEquals(400, accessTokenResponse.getStatusCode());
|
||||
assertEquals(OAuthErrorException.INVALID_GRANT, accessTokenResponse.getError());
|
||||
|
||||
// Check frontchannel logout and login.
|
||||
driver.navigate().to(oauth.getLogoutUrl().build());
|
||||
logoutConfirmPage.assertCurrent();
|
||||
logoutConfirmPage.confirmLogout();
|
||||
loginResponse = oauth.doLogin(TEST_USER_NAME, TEST_USER_PASSWORD);
|
||||
Assert.assertNull(loginResponse.getError());
|
||||
|
||||
code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
|
||||
|
||||
// Check token obtaining.
|
||||
try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithDefaultKeyStoreAndTrustStore()) {
|
||||
accessTokenResponse = oauth.doAccessTokenRequest(code, TEST_CLIENT_SECRET, client);
|
||||
} catch (IOException ioe) {
|
||||
throw new RuntimeException(ioe);
|
||||
}
|
||||
assertEquals(200, accessTokenResponse.getStatusCode());
|
||||
|
||||
// Check token refresh with other certificate
|
||||
try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithOtherKeyStoreAndTrustStore()) {
|
||||
accessTokenResponseRefreshed = oauth.doRefreshTokenRequest(accessTokenResponse.getRefreshToken(), TEST_CLIENT_SECRET, client);
|
||||
} catch (IOException ioe) {
|
||||
throw new RuntimeException(ioe);
|
||||
}
|
||||
assertEquals(400, accessTokenResponseRefreshed.getStatusCode());
|
||||
assertEquals(OAuthErrorException.INVALID_GRANT, accessTokenResponseRefreshed.getError());
|
||||
|
||||
// Check token revoke with other certificate
|
||||
try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithOtherKeyStoreAndTrustStore()) {
|
||||
tokenRevokeResponse = oauth.doTokenRevoke(accessTokenResponse.getRefreshToken(), "refresh_token", TEST_CLIENT_SECRET, client);
|
||||
} catch (IOException ioe) {
|
||||
throw new RuntimeException(ioe);
|
||||
}
|
||||
assertEquals(401, tokenRevokeResponse.getStatusLine().getStatusCode());
|
||||
|
||||
// Check logout without certificate
|
||||
try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithoutKeyStoreAndTrustStore()) {
|
||||
logoutResponse = oauth.doLogout(accessTokenResponse.getRefreshToken(), TEST_CLIENT_SECRET, client);
|
||||
} catch (IOException ioe) {
|
||||
throw new RuntimeException(ioe);
|
||||
}
|
||||
assertEquals(401, logoutResponse.getStatusLine().getStatusCode());
|
||||
|
||||
// Check logout.
|
||||
try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithDefaultKeyStoreAndTrustStore()) {
|
||||
logoutResponse = oauth.doLogout(accessTokenResponse.getRefreshToken(), TEST_CLIENT_SECRET, client);
|
||||
} catch (IOException ioe) {
|
||||
throw new RuntimeException(ioe);
|
||||
}
|
||||
}
|
||||
|
||||
protected void setupPolicyClientIdAndSecretNotAcceptableAuthType(String policyName) throws Exception {
|
||||
// register profiles
|
||||
String profileName = "MyProfile";
|
||||
String json = (new ClientProfilesBuilder()).addProfile(
|
||||
(new ClientProfileBuilder()).createProfile(profileName, "Primum Profile")
|
||||
.addExecutor(SecureClientAuthenticatorExecutorFactory.PROVIDER_ID,
|
||||
createSecureClientAuthenticatorExecutorConfig(
|
||||
Arrays.asList(JWTClientAuthenticator.PROVIDER_ID, JWTClientSecretAuthenticator.PROVIDER_ID, X509ClientAuthenticator.PROVIDER_ID),
|
||||
null))
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
// register policies
|
||||
json = (new ClientPoliciesBuilder()).addPolicy(
|
||||
(new ClientPolicyBuilder()).createPolicy(policyName, "Primum Consilium", Boolean.TRUE)
|
||||
.addCondition(ClientUpdaterContextConditionFactory.PROVIDER_ID,
|
||||
createClientUpdateContextConditionConfig(Arrays.asList(ClientUpdaterContextConditionFactory.BY_AUTHENTICATED_USER)))
|
||||
.addProfile(profileName)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updatePolicies(json);
|
||||
}
|
||||
|
||||
protected void setupPolicyAuthzCodeFlowUnderMultiPhasePolicy(String policyName) throws Exception {
|
||||
// register profiles
|
||||
String profileName = "MyProfile";
|
||||
String json = (new ClientProfilesBuilder()).addProfile(
|
||||
(new ClientProfileBuilder()).createProfile(profileName, "Primul Profil")
|
||||
.addExecutor(SecureClientAuthenticatorExecutorFactory.PROVIDER_ID,
|
||||
createSecureClientAuthenticatorExecutorConfig(
|
||||
Arrays.asList(ClientIdAndSecretAuthenticator.PROVIDER_ID, JWTClientAuthenticator.PROVIDER_ID),
|
||||
ClientIdAndSecretAuthenticator.PROVIDER_ID))
|
||||
.addExecutor(PKCEEnforcerExecutorFactory.PROVIDER_ID,
|
||||
createPKCEEnforceExecutorConfig(Boolean.TRUE))
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
// register policies
|
||||
json = (new ClientPoliciesBuilder()).addPolicy(
|
||||
(new ClientPolicyBuilder()).createPolicy(policyName, "Prima Politica", Boolean.TRUE)
|
||||
.addCondition(ClientRolesConditionFactory.PROVIDER_ID,
|
||||
createClientRolesConditionConfig(Arrays.asList(SAMPLE_CLIENT_ROLE)))
|
||||
.addCondition(ClientUpdaterContextConditionFactory.PROVIDER_ID,
|
||||
createClientUpdateContextConditionConfig(Arrays.asList(ClientUpdaterContextConditionFactory.BY_INITIAL_ACCESS_TOKEN)))
|
||||
.addProfile(profileName)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updatePolicies(json);
|
||||
}
|
||||
|
||||
protected void successfulLoginAndLogout(String clientId, String clientSecret) {
|
||||
OAuthClient.AccessTokenResponse res = successfulLogin(clientId, clientSecret);
|
||||
oauth.doLogout(res.getRefreshToken(), clientSecret);
|
||||
events.expectLogout(res.getSessionState()).client(clientId).clearDetails().assertEvent();
|
||||
}
|
||||
|
||||
protected OAuthClient.AccessTokenResponse successfulLogin(String clientId, String clientSecret) {
|
||||
oauth.clientId(clientId);
|
||||
oauth.doLogin(TEST_USER_NAME, TEST_USER_PASSWORD);
|
||||
|
||||
EventRepresentation loginEvent = events.expectLogin().client(clientId).assertEvent();
|
||||
String sessionId = loginEvent.getSessionId();
|
||||
String codeId = loginEvent.getDetails().get(Details.CODE_ID);
|
||||
String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
|
||||
OAuthClient.AccessTokenResponse res = oauth.doAccessTokenRequest(code, clientSecret);
|
||||
assertEquals(200, res.getStatusCode());
|
||||
events.expectCodeToToken(codeId, sessionId).client(clientId).assertEvent();
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
protected void successfulLoginAndLogoutWithPKCE(String clientId, String clientSecret, String userName, String userPassword) throws Exception {
|
||||
oauth.clientId(clientId);
|
||||
String codeVerifier = "1a345A7890123456r8901c3456789012b45K7890l23"; // 43
|
||||
String codeChallenge = generateS256CodeChallenge(codeVerifier);
|
||||
oauth.codeChallenge(codeChallenge);
|
||||
oauth.codeChallengeMethod(OAuth2Constants.PKCE_METHOD_S256);
|
||||
oauth.nonce("bjapewiziIE083d");
|
||||
|
||||
oauth.doLogin(userName, userPassword);
|
||||
|
||||
EventRepresentation loginEvent = events.expectLogin().client(clientId).assertEvent();
|
||||
String sessionId = loginEvent.getSessionId();
|
||||
String codeId = loginEvent.getDetails().get(Details.CODE_ID);
|
||||
String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
|
||||
|
||||
oauth.codeVerifier(codeVerifier);
|
||||
OAuthClient.AccessTokenResponse res = oauth.doAccessTokenRequest(code, clientSecret);
|
||||
assertEquals(200, res.getStatusCode());
|
||||
events.expectCodeToToken(codeId, sessionId).client(clientId).assertEvent();
|
||||
|
||||
AccessToken token = oauth.verifyToken(res.getAccessToken());
|
||||
String userId = findUserByUsername(adminClient.realm(REALM_NAME), userName).getId();
|
||||
assertEquals(userId, token.getSubject());
|
||||
Assert.assertNotEquals(userName, token.getSubject());
|
||||
assertEquals(sessionId, token.getSessionState());
|
||||
assertEquals(clientId, token.getIssuedFor());
|
||||
|
||||
String refreshTokenString = res.getRefreshToken();
|
||||
RefreshToken refreshToken = oauth.parseRefreshToken(refreshTokenString);
|
||||
assertEquals(sessionId, refreshToken.getSessionState());
|
||||
assertEquals(clientId, refreshToken.getIssuedFor());
|
||||
|
||||
OAuthClient.AccessTokenResponse refreshResponse = oauth.doRefreshTokenRequest(refreshTokenString, clientSecret);
|
||||
assertEquals(200, refreshResponse.getStatusCode());
|
||||
events.expectRefresh(refreshToken.getId(), sessionId).client(clientId).assertEvent();
|
||||
|
||||
AccessToken refreshedToken = oauth.verifyToken(refreshResponse.getAccessToken());
|
||||
RefreshToken refreshedRefreshToken = oauth.parseRefreshToken(refreshResponse.getRefreshToken());
|
||||
assertEquals(sessionId, refreshedToken.getSessionState());
|
||||
assertEquals(sessionId, refreshedRefreshToken.getSessionState());
|
||||
assertEquals(findUserByUsername(adminClient.realm(REALM_NAME), userName).getId(), refreshedToken.getSubject());
|
||||
|
||||
doIntrospectAccessToken(refreshResponse, userName, clientId, clientSecret);
|
||||
|
||||
doTokenRevoke(refreshResponse.getRefreshToken(), clientId, clientSecret, userId, false);
|
||||
}
|
||||
|
||||
protected void failLoginByNotFollowingPKCE(String clientId) {
|
||||
oauth.clientId(clientId);
|
||||
oauth.openLoginForm();
|
||||
assertEquals(OAuthErrorException.INVALID_REQUEST, oauth.getCurrentQuery().get(OAuth2Constants.ERROR));
|
||||
assertEquals("Missing parameter: code_challenge_method", oauth.getCurrentQuery().get(OAuth2Constants.ERROR_DESCRIPTION));
|
||||
}
|
||||
|
||||
protected void failTokenRequestByNotFollowingPKCE(String clientId, String clientSecret) {
|
||||
oauth.clientId(clientId);
|
||||
oauth.doLogin(TEST_USER_NAME, TEST_USER_PASSWORD);
|
||||
|
||||
EventRepresentation loginEvent = events.expectLogin().client(clientId).assertEvent();
|
||||
String sessionId = loginEvent.getSessionId();
|
||||
String codeId = loginEvent.getDetails().get(Details.CODE_ID);
|
||||
String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
|
||||
OAuthClient.AccessTokenResponse res = oauth.doAccessTokenRequest(code, clientSecret);
|
||||
|
||||
assertEquals(OAuthErrorException.INVALID_GRANT, res.getError());
|
||||
assertEquals("PKCE code verifier not specified", res.getErrorDescription());
|
||||
events.expect(EventType.CODE_TO_TOKEN_ERROR).client(clientId).session(sessionId).clearDetails().error(Errors.CODE_VERIFIER_MISSING).assertEvent();
|
||||
|
||||
oauth.idTokenHint(res.getIdToken()).openLogout();
|
||||
events.expectLogout(sessionId).clearDetails().assertEvent();
|
||||
}
|
||||
|
||||
protected void failLoginWithoutSecureSessionParameter(String clientId, String errorDescription) {
|
||||
oauth.clientId(clientId);
|
||||
oauth.openLoginForm();
|
||||
assertEquals(OAuthErrorException.INVALID_REQUEST, oauth.getCurrentQuery().get(OAuth2Constants.ERROR));
|
||||
assertEquals(errorDescription, oauth.getCurrentQuery().get(OAuth2Constants.ERROR_DESCRIPTION));
|
||||
}
|
||||
|
||||
protected void failLoginWithoutNonce(String clientId) {
|
||||
oauth.clientId(clientId);
|
||||
oauth.openLoginForm();
|
||||
assertEquals(OAuthErrorException.INVALID_REQUEST, oauth.getCurrentQuery().get(OAuth2Constants.ERROR));
|
||||
assertEquals(ERR_MSG_MISSING_NONCE, oauth.getCurrentQuery().get(OAuth2Constants.ERROR_DESCRIPTION));
|
||||
}
|
||||
|
||||
protected void doConfigProfileAndPolicy(ClientPoliciesUtil.ClientProfileBuilder profileBuilder,
|
||||
ClientSecretRotationExecutor.Configuration profileConfig) throws Exception {
|
||||
String json = (new ClientPoliciesUtil.ClientProfilesBuilder()).addProfile(
|
||||
profileBuilder.createProfile(SECRET_ROTATION_PROFILE, "Enable Client Secret Rotation")
|
||||
.addExecutor(ClientSecretRotationExecutorFactory.PROVIDER_ID, profileConfig)
|
||||
.toRepresentation()).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
// register policies
|
||||
ClientAccessTypeCondition.Configuration config = new ClientAccessTypeCondition.Configuration();
|
||||
config.setType(Arrays.asList(ClientAccessTypeConditionFactory.TYPE_CONFIDENTIAL));
|
||||
json = (new ClientPoliciesUtil.ClientPoliciesBuilder()).addPolicy(
|
||||
(new ClientPoliciesUtil.ClientPolicyBuilder()).createPolicy(SECRET_ROTATION_POLICY,
|
||||
"Policy for Client Secret Rotation",
|
||||
Boolean.TRUE).addCondition(ClientAccessTypeConditionFactory.PROVIDER_ID, config)
|
||||
.addProfile(SECRET_ROTATION_PROFILE).toRepresentation()).toString();
|
||||
updatePolicies(json);
|
||||
}
|
||||
|
||||
protected void configureCustomProfileAndPolicy(int secretExpiration, int rotatedExpiration,
|
||||
int remainingExpiration) throws Exception {
|
||||
ClientPoliciesUtil.ClientProfileBuilder profileBuilder = new ClientPoliciesUtil.ClientProfileBuilder();
|
||||
ClientSecretRotationExecutor.Configuration profileConfig = getClientProfileConfiguration(
|
||||
secretExpiration, rotatedExpiration, remainingExpiration);
|
||||
|
||||
doConfigProfileAndPolicy(profileBuilder, profileConfig);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
protected ClientSecretRotationExecutor.Configuration getClientProfileConfiguration(
|
||||
int expirationPeriod, int rotatedExpirationPeriod, int remainExpirationPeriod) {
|
||||
ClientSecretRotationExecutor.Configuration profileConfig = new ClientSecretRotationExecutor.Configuration();
|
||||
profileConfig.setExpirationPeriod(expirationPeriod);
|
||||
profileConfig.setRotatedExpirationPeriod(rotatedExpirationPeriod);
|
||||
profileConfig.setRemainExpirationPeriod(remainExpirationPeriod);
|
||||
return profileConfig;
|
||||
}
|
||||
|
||||
protected void assertLoginAndLogoutStatus(String clientId, String secret, Response.Status status) {
|
||||
oauth.clientId(clientId);
|
||||
OAuthClient.AuthorizationEndpointResponse loginResponse = oauth.doLogin(TEST_USER_NAME,
|
||||
TEST_USER_PASSWORD);
|
||||
String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
|
||||
OAuthClient.AccessTokenResponse res = oauth.doAccessTokenRequest(code, secret);
|
||||
assertThat(res.getStatusCode(), equalTo(status.getStatusCode()));
|
||||
oauth.doLogout(res.getRefreshToken(), secret);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,285 @@
|
|||
/*
|
||||
* Copyright 2023 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.testsuite.client.policies;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.fail;
|
||||
import static org.keycloak.testsuite.admin.AbstractAdminTest.loadJson;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientUpdateContextConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createSecureClientAuthenticatorExecutorConfig;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import org.jboss.arquillian.graphene.page.Page;
|
||||
import org.junit.Test;
|
||||
import org.keycloak.OAuthErrorException;
|
||||
import org.keycloak.authentication.authenticators.client.ClientIdAndSecretAuthenticator;
|
||||
import org.keycloak.authentication.authenticators.client.JWTClientAuthenticator;
|
||||
import org.keycloak.authentication.authenticators.client.JWTClientSecretAuthenticator;
|
||||
import org.keycloak.authentication.authenticators.client.X509ClientAuthenticator;
|
||||
import org.keycloak.common.Profile;
|
||||
import org.keycloak.models.AdminRoles;
|
||||
import org.keycloak.models.Constants;
|
||||
import org.keycloak.models.OAuth2DeviceConfig;
|
||||
import org.keycloak.models.utils.KeycloakModelUtils;
|
||||
import org.keycloak.protocol.oidc.OIDCConfigAttributes;
|
||||
import org.keycloak.representations.idm.ClientRepresentation;
|
||||
import org.keycloak.representations.idm.CredentialRepresentation;
|
||||
import org.keycloak.representations.idm.RealmRepresentation;
|
||||
import org.keycloak.representations.idm.UserRepresentation;
|
||||
import org.keycloak.services.clientpolicy.ClientPolicyException;
|
||||
import org.keycloak.services.clientpolicy.condition.ClientUpdaterContextConditionFactory;
|
||||
import org.keycloak.services.clientpolicy.executor.SecureClientAuthenticatorExecutorFactory;
|
||||
import org.keycloak.testsuite.arquillian.annotation.EnableFeature;
|
||||
import org.keycloak.testsuite.pages.ErrorPage;
|
||||
import org.keycloak.testsuite.pages.LogoutConfirmPage;
|
||||
import org.keycloak.testsuite.pages.OAuth2DeviceVerificationPage;
|
||||
import org.keycloak.testsuite.pages.OAuthGrantPage;
|
||||
import org.keycloak.testsuite.util.ClientBuilder;
|
||||
import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPoliciesBuilder;
|
||||
import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPolicyBuilder;
|
||||
import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfileBuilder;
|
||||
import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfilesBuilder;
|
||||
import org.keycloak.testsuite.util.UserBuilder;
|
||||
|
||||
/**
|
||||
* This test class is for testing client policies' related actions done through an admin console, admin CLI, and admin REST API.
|
||||
*
|
||||
* @author <a href="mailto:takashi.norimatsu.ws@hitachi.com">Takashi Norimatsu</a>
|
||||
*/
|
||||
@EnableFeature(value = Profile.Feature.CLIENT_SECRET_ROTATION)
|
||||
public class ClientPoliciesAdminTest extends AbstractClientPoliciesTest {
|
||||
|
||||
@Page
|
||||
protected OAuth2DeviceVerificationPage verificationPage;
|
||||
|
||||
@Page
|
||||
protected OAuthGrantPage grantPage;
|
||||
|
||||
@Page
|
||||
protected ErrorPage errorPage;
|
||||
|
||||
@Page
|
||||
protected LogoutConfirmPage logoutConfirmPage;
|
||||
|
||||
@Override
|
||||
public void addTestRealms(List<RealmRepresentation> testRealms) {
|
||||
RealmRepresentation realm = loadJson(getClass().getResourceAsStream("/testrealm.json"), RealmRepresentation.class);
|
||||
|
||||
List<UserRepresentation> users = realm.getUsers();
|
||||
|
||||
LinkedList<CredentialRepresentation> credentials = new LinkedList<>();
|
||||
CredentialRepresentation password = new CredentialRepresentation();
|
||||
password.setType(CredentialRepresentation.PASSWORD);
|
||||
password.setValue("password");
|
||||
credentials.add(password);
|
||||
|
||||
UserRepresentation user = new UserRepresentation();
|
||||
user.setEnabled(true);
|
||||
user.setUsername("manage-clients");
|
||||
user.setCredentials(credentials);
|
||||
user.setClientRoles(Collections.singletonMap(Constants.REALM_MANAGEMENT_CLIENT_ID, Collections.singletonList(AdminRoles.MANAGE_CLIENTS)));
|
||||
|
||||
users.add(user);
|
||||
|
||||
user = new UserRepresentation();
|
||||
user.setEnabled(true);
|
||||
user.setUsername("create-clients");
|
||||
user.setCredentials(credentials);
|
||||
user.setClientRoles(Collections.singletonMap(Constants.REALM_MANAGEMENT_CLIENT_ID, Collections.singletonList(AdminRoles.CREATE_CLIENT)));
|
||||
user.setGroups(Arrays.asList("topGroup")); // defined in testrealm.json
|
||||
|
||||
users.add(user);
|
||||
|
||||
realm.setUsers(users);
|
||||
|
||||
List<ClientRepresentation> clients = realm.getClients();
|
||||
|
||||
ClientRepresentation app = ClientBuilder.create()
|
||||
.id(KeycloakModelUtils.generateId())
|
||||
.clientId("test-device")
|
||||
.secret("secret")
|
||||
.attribute(OAuth2DeviceConfig.OAUTH2_DEVICE_AUTHORIZATION_GRANT_ENABLED, "true")
|
||||
.attribute(OIDCConfigAttributes.POST_LOGOUT_REDIRECT_URIS, "+")
|
||||
.build();
|
||||
clients.add(app);
|
||||
|
||||
ClientRepresentation appPublic = ClientBuilder.create().id(KeycloakModelUtils.generateId()).publicClient()
|
||||
.clientId(DEVICE_APP_PUBLIC)
|
||||
.attribute(OAuth2DeviceConfig.OAUTH2_DEVICE_AUTHORIZATION_GRANT_ENABLED, "true")
|
||||
.attribute(OIDCConfigAttributes.POST_LOGOUT_REDIRECT_URIS, "+")
|
||||
.build();
|
||||
clients.add(appPublic);
|
||||
|
||||
userId = KeycloakModelUtils.generateId();
|
||||
UserRepresentation deviceUser = UserBuilder.create()
|
||||
.id(userId)
|
||||
.username("device-login")
|
||||
.email("device-login@localhost")
|
||||
.password("password")
|
||||
.build();
|
||||
users.add(deviceUser);
|
||||
|
||||
testRealms.add(realm);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdminClientRegisterUnacceptableAuthType() throws Exception {
|
||||
setupPolicyClientIdAndSecretNotAcceptableAuthType(POLICY_NAME);
|
||||
try {
|
||||
createClientByAdmin(generateSuffixedName(CLIENT_NAME), (ClientRepresentation clientRep) -> {
|
||||
clientRep.setClientAuthenticatorType(ClientIdAndSecretAuthenticator.PROVIDER_ID);
|
||||
});
|
||||
fail();
|
||||
} catch (ClientPolicyException e) {
|
||||
assertEquals(OAuthErrorException.INVALID_CLIENT_METADATA, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdminClientRegisterAcceptableAuthType() throws Exception {
|
||||
setupPolicyClientIdAndSecretNotAcceptableAuthType(POLICY_NAME);
|
||||
String cId = createClientByAdmin(generateSuffixedName(CLIENT_NAME), (ClientRepresentation clientRep) -> {
|
||||
clientRep.setClientAuthenticatorType(JWTClientSecretAuthenticator.PROVIDER_ID);
|
||||
});
|
||||
assertEquals(JWTClientSecretAuthenticator.PROVIDER_ID, getClientByAdmin(cId).getClientAuthenticatorType());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdminClientRegisterDefaultAuthType() throws Exception {
|
||||
setupPolicyClientIdAndSecretNotAcceptableAuthType(POLICY_NAME);
|
||||
try {
|
||||
createClientByAdmin(generateSuffixedName(CLIENT_NAME), (ClientRepresentation clientRep) -> {
|
||||
});
|
||||
fail();
|
||||
} catch (ClientPolicyException e) {
|
||||
assertEquals(OAuthErrorException.INVALID_CLIENT_METADATA, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdminClientUpdateUnacceptableAuthType() throws Exception {
|
||||
setupPolicyClientIdAndSecretNotAcceptableAuthType(POLICY_NAME);
|
||||
String cId = createClientByAdmin(generateSuffixedName(CLIENT_NAME), (ClientRepresentation clientRep) -> {
|
||||
clientRep.setClientAuthenticatorType(JWTClientSecretAuthenticator.PROVIDER_ID);
|
||||
});
|
||||
assertEquals(JWTClientSecretAuthenticator.PROVIDER_ID, getClientByAdmin(cId).getClientAuthenticatorType());
|
||||
try {
|
||||
updateClientByAdmin(cId, (ClientRepresentation clientRep) -> {
|
||||
clientRep.setClientAuthenticatorType(ClientIdAndSecretAuthenticator.PROVIDER_ID);
|
||||
});
|
||||
fail();
|
||||
} catch (ClientPolicyException cpe) {
|
||||
assertEquals(OAuthErrorException.INVALID_CLIENT_METADATA, cpe.getError());
|
||||
}
|
||||
assertEquals(JWTClientSecretAuthenticator.PROVIDER_ID, getClientByAdmin(cId).getClientAuthenticatorType());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdminClientUpdateAcceptableAuthType() throws Exception {
|
||||
setupPolicyClientIdAndSecretNotAcceptableAuthType(POLICY_NAME);
|
||||
|
||||
String cId = createClientByAdmin(generateSuffixedName(CLIENT_NAME), (ClientRepresentation clientRep) -> {
|
||||
clientRep.setClientAuthenticatorType(JWTClientSecretAuthenticator.PROVIDER_ID);
|
||||
});
|
||||
|
||||
assertEquals(JWTClientSecretAuthenticator.PROVIDER_ID, getClientByAdmin(cId).getClientAuthenticatorType());
|
||||
|
||||
updateClientByAdmin(cId, (ClientRepresentation clientRep) -> {
|
||||
clientRep.setClientAuthenticatorType(JWTClientAuthenticator.PROVIDER_ID);
|
||||
});
|
||||
assertEquals(JWTClientAuthenticator.PROVIDER_ID, getClientByAdmin(cId).getClientAuthenticatorType());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdminClientUpdateDefaultAuthType() throws Exception {
|
||||
setupPolicyClientIdAndSecretNotAcceptableAuthType(POLICY_NAME);
|
||||
|
||||
String cId = createClientByAdmin(generateSuffixedName(CLIENT_NAME), (ClientRepresentation clientRep) -> {
|
||||
clientRep.setClientAuthenticatorType(JWTClientSecretAuthenticator.PROVIDER_ID);
|
||||
});
|
||||
|
||||
assertEquals(JWTClientSecretAuthenticator.PROVIDER_ID, getClientByAdmin(cId).getClientAuthenticatorType());
|
||||
|
||||
updateClientByAdmin(cId, (ClientRepresentation clientRep) -> {
|
||||
clientRep.setServiceAccountsEnabled(Boolean.FALSE);
|
||||
});
|
||||
assertEquals(JWTClientSecretAuthenticator.PROVIDER_ID, getClientByAdmin(cId).getClientAuthenticatorType());
|
||||
assertEquals(Boolean.FALSE, getClientByAdmin(cId).isServiceAccountsEnabled());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdminClientAutoConfiguredClientAuthType() throws Exception {
|
||||
// register profiles
|
||||
String json = (new ClientProfilesBuilder()).addProfile(
|
||||
(new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Pershyy Profil")
|
||||
.addExecutor(SecureClientAuthenticatorExecutorFactory.PROVIDER_ID,
|
||||
createSecureClientAuthenticatorExecutorConfig(
|
||||
Arrays.asList(JWTClientAuthenticator.PROVIDER_ID, JWTClientSecretAuthenticator.PROVIDER_ID, X509ClientAuthenticator.PROVIDER_ID),
|
||||
X509ClientAuthenticator.PROVIDER_ID))
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
// register policies
|
||||
json = (new ClientPoliciesBuilder()).addPolicy(
|
||||
(new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "Persha Polityka", Boolean.TRUE)
|
||||
.addCondition(ClientUpdaterContextConditionFactory.PROVIDER_ID,
|
||||
createClientUpdateContextConditionConfig(Arrays.asList(ClientUpdaterContextConditionFactory.BY_AUTHENTICATED_USER)))
|
||||
.addProfile(PROFILE_NAME)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updatePolicies(json);
|
||||
|
||||
// Attempt to create client with set authenticator to ClientIdAndSecretAuthenticator. Should fail
|
||||
try {
|
||||
createClientByAdmin(generateSuffixedName(CLIENT_NAME), (ClientRepresentation clientRep) -> {
|
||||
clientRep.setClientAuthenticatorType(ClientIdAndSecretAuthenticator.PROVIDER_ID);
|
||||
});
|
||||
fail();
|
||||
} catch (ClientPolicyException e) {
|
||||
assertEquals(OAuthErrorException.INVALID_CLIENT_METADATA, e.getMessage());
|
||||
}
|
||||
|
||||
// Attempt to create client without set authenticator. Default authenticator should be set
|
||||
String cId = createClientByAdmin(generateSuffixedName(CLIENT_NAME), (ClientRepresentation clientRep) -> {
|
||||
});
|
||||
|
||||
assertEquals(X509ClientAuthenticator.PROVIDER_ID, getClientByAdmin(cId).getClientAuthenticatorType());
|
||||
|
||||
// update profiles
|
||||
json = (new ClientProfilesBuilder()).addProfile(
|
||||
(new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Pershyy Profil")
|
||||
.addExecutor(SecureClientAuthenticatorExecutorFactory.PROVIDER_ID,
|
||||
createSecureClientAuthenticatorExecutorConfig(
|
||||
Arrays.asList(JWTClientAuthenticator.PROVIDER_ID, JWTClientSecretAuthenticator.PROVIDER_ID, X509ClientAuthenticator.PROVIDER_ID),
|
||||
JWTClientAuthenticator.PROVIDER_ID))
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
// It is allowed to update authenticator to one of allowed client authenticators. Default client authenticator is not explicitly set in this case
|
||||
updateClientByAdmin(cId, (ClientRepresentation clientRep) -> {
|
||||
clientRep.setClientAuthenticatorType(JWTClientSecretAuthenticator.PROVIDER_ID);
|
||||
});
|
||||
assertEquals(JWTClientSecretAuthenticator.PROVIDER_ID, getClientByAdmin(cId).getClientAuthenticatorType());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,526 @@
|
|||
/*
|
||||
* Copyright 2023 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.testsuite.client.policies;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.fail;
|
||||
import static org.keycloak.testsuite.admin.AbstractAdminTest.loadJson;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createAnyClientConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientAccessTypeConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientScopesConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientUpdateSourceGroupsConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientUpdateSourceHostsConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientUpdateSourceRolesConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createPKCEEnforceExecutorConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createSecureClientAuthenticatorExecutorConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createTestRaiseExeptionExecutorConfig;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import org.jboss.arquillian.graphene.page.Page;
|
||||
import org.junit.Test;
|
||||
import org.keycloak.OAuth2Constants;
|
||||
import org.keycloak.OAuthErrorException;
|
||||
import org.keycloak.authentication.authenticators.client.JWTClientAuthenticator;
|
||||
import org.keycloak.authentication.authenticators.client.JWTClientSecretAuthenticator;
|
||||
import org.keycloak.authentication.authenticators.client.X509ClientAuthenticator;
|
||||
import org.keycloak.client.registration.ClientRegistrationException;
|
||||
import org.keycloak.common.Profile;
|
||||
import org.keycloak.models.AdminRoles;
|
||||
import org.keycloak.models.Constants;
|
||||
import org.keycloak.models.OAuth2DeviceConfig;
|
||||
import org.keycloak.models.utils.KeycloakModelUtils;
|
||||
import org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper;
|
||||
import org.keycloak.protocol.oidc.OIDCConfigAttributes;
|
||||
import org.keycloak.representations.idm.ClientRepresentation;
|
||||
import org.keycloak.representations.idm.CredentialRepresentation;
|
||||
import org.keycloak.representations.idm.RealmRepresentation;
|
||||
import org.keycloak.representations.idm.UserRepresentation;
|
||||
import org.keycloak.representations.oidc.OIDCClientRepresentation;
|
||||
import org.keycloak.services.clientpolicy.ClientPolicyEvent;
|
||||
import org.keycloak.services.clientpolicy.ClientPolicyException;
|
||||
import org.keycloak.services.clientpolicy.condition.AnyClientConditionFactory;
|
||||
import org.keycloak.services.clientpolicy.condition.ClientAccessTypeConditionFactory;
|
||||
import org.keycloak.services.clientpolicy.condition.ClientScopesConditionFactory;
|
||||
import org.keycloak.services.clientpolicy.condition.ClientUpdaterSourceGroupsConditionFactory;
|
||||
import org.keycloak.services.clientpolicy.condition.ClientUpdaterSourceHostsConditionFactory;
|
||||
import org.keycloak.services.clientpolicy.condition.ClientUpdaterSourceRolesConditionFactory;
|
||||
import org.keycloak.services.clientpolicy.executor.PKCEEnforcerExecutorFactory;
|
||||
import org.keycloak.services.clientpolicy.executor.SecureClientAuthenticatorExecutorFactory;
|
||||
import org.keycloak.services.clientpolicy.executor.SecureSessionEnforceExecutorFactory;
|
||||
import org.keycloak.testsuite.arquillian.annotation.EnableFeature;
|
||||
import org.keycloak.testsuite.pages.ErrorPage;
|
||||
import org.keycloak.testsuite.pages.LogoutConfirmPage;
|
||||
import org.keycloak.testsuite.pages.OAuth2DeviceVerificationPage;
|
||||
import org.keycloak.testsuite.pages.OAuthGrantPage;
|
||||
import org.keycloak.testsuite.services.clientpolicy.executor.TestRaiseExceptionExecutorFactory;
|
||||
import org.keycloak.testsuite.util.ClientBuilder;
|
||||
import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPoliciesBuilder;
|
||||
import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPolicyBuilder;
|
||||
import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfileBuilder;
|
||||
import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfilesBuilder;
|
||||
import org.keycloak.testsuite.util.OAuthClient;
|
||||
import org.keycloak.testsuite.util.UserBuilder;
|
||||
|
||||
/**
|
||||
* This test class is for testing a condition of client policies.
|
||||
*
|
||||
* @author <a href="mailto:takashi.norimatsu.ws@hitachi.com">Takashi Norimatsu</a>
|
||||
*/
|
||||
@EnableFeature(value = Profile.Feature.CLIENT_SECRET_ROTATION)
|
||||
public class ClientPoliciesConditionTest extends AbstractClientPoliciesTest {
|
||||
|
||||
@Page
|
||||
protected OAuth2DeviceVerificationPage verificationPage;
|
||||
|
||||
@Page
|
||||
protected OAuthGrantPage grantPage;
|
||||
|
||||
@Page
|
||||
protected ErrorPage errorPage;
|
||||
|
||||
@Page
|
||||
protected LogoutConfirmPage logoutConfirmPage;
|
||||
|
||||
@Override
|
||||
public void addTestRealms(List<RealmRepresentation> testRealms) {
|
||||
RealmRepresentation realm = loadJson(getClass().getResourceAsStream("/testrealm.json"), RealmRepresentation.class);
|
||||
|
||||
List<UserRepresentation> users = realm.getUsers();
|
||||
|
||||
LinkedList<CredentialRepresentation> credentials = new LinkedList<>();
|
||||
CredentialRepresentation password = new CredentialRepresentation();
|
||||
password.setType(CredentialRepresentation.PASSWORD);
|
||||
password.setValue("password");
|
||||
credentials.add(password);
|
||||
|
||||
UserRepresentation user = new UserRepresentation();
|
||||
user.setEnabled(true);
|
||||
user.setUsername("manage-clients");
|
||||
user.setCredentials(credentials);
|
||||
user.setClientRoles(Collections.singletonMap(Constants.REALM_MANAGEMENT_CLIENT_ID, Collections.singletonList(AdminRoles.MANAGE_CLIENTS)));
|
||||
|
||||
users.add(user);
|
||||
|
||||
user = new UserRepresentation();
|
||||
user.setEnabled(true);
|
||||
user.setUsername("create-clients");
|
||||
user.setCredentials(credentials);
|
||||
user.setClientRoles(Collections.singletonMap(Constants.REALM_MANAGEMENT_CLIENT_ID, Collections.singletonList(AdminRoles.CREATE_CLIENT)));
|
||||
user.setGroups(Arrays.asList("topGroup")); // defined in testrealm.json
|
||||
|
||||
users.add(user);
|
||||
|
||||
realm.setUsers(users);
|
||||
|
||||
List<ClientRepresentation> clients = realm.getClients();
|
||||
|
||||
ClientRepresentation app = ClientBuilder.create()
|
||||
.id(KeycloakModelUtils.generateId())
|
||||
.clientId("test-device")
|
||||
.secret("secret")
|
||||
.attribute(OAuth2DeviceConfig.OAUTH2_DEVICE_AUTHORIZATION_GRANT_ENABLED, "true")
|
||||
.attribute(OIDCConfigAttributes.POST_LOGOUT_REDIRECT_URIS, "+")
|
||||
.build();
|
||||
clients.add(app);
|
||||
|
||||
ClientRepresentation appPublic = ClientBuilder.create().id(KeycloakModelUtils.generateId()).publicClient()
|
||||
.clientId(DEVICE_APP_PUBLIC)
|
||||
.attribute(OAuth2DeviceConfig.OAUTH2_DEVICE_AUTHORIZATION_GRANT_ENABLED, "true")
|
||||
.attribute(OIDCConfigAttributes.POST_LOGOUT_REDIRECT_URIS, "+")
|
||||
.build();
|
||||
clients.add(appPublic);
|
||||
|
||||
userId = KeycloakModelUtils.generateId();
|
||||
UserRepresentation deviceUser = UserBuilder.create()
|
||||
.id(userId)
|
||||
.username("device-login")
|
||||
.email("device-login@localhost")
|
||||
.password("password")
|
||||
.build();
|
||||
users.add(deviceUser);
|
||||
|
||||
testRealms.add(realm);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAnyClientCondition() throws Exception {
|
||||
// register profiles
|
||||
String json = (new ClientProfilesBuilder()).addProfile(
|
||||
(new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Le Premier Profil")
|
||||
.addExecutor(SecureSessionEnforceExecutorFactory.PROVIDER_ID, null)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
// register policies
|
||||
json = (new ClientPoliciesBuilder()).addPolicy(
|
||||
(new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "La Premiere Politique", Boolean.TRUE)
|
||||
.addCondition(AnyClientConditionFactory.PROVIDER_ID,
|
||||
createAnyClientConditionConfig())
|
||||
.addProfile(PROFILE_NAME)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updatePolicies(json);
|
||||
|
||||
String clientAlphaId = generateSuffixedName("Alpha-App");
|
||||
String clientAlphaSecret = "secretAlpha";
|
||||
createClientByAdmin(clientAlphaId, (ClientRepresentation clientRep) -> {
|
||||
clientRep.setDefaultRoles((String[]) Arrays.asList("sample-client-role-alpha").toArray(new String[1]));
|
||||
clientRep.setSecret(clientAlphaSecret);
|
||||
});
|
||||
|
||||
String clientBetaId = generateSuffixedName("Beta-App");
|
||||
createClientByAdmin(clientBetaId, (ClientRepresentation clientRep) -> {
|
||||
clientRep.setSecret("secretBeta");
|
||||
});
|
||||
|
||||
try {
|
||||
failLoginWithoutSecureSessionParameter(clientBetaId, ERR_MSG_MISSING_NONCE);
|
||||
oauth.nonce("yesitisnonce");
|
||||
successfulLoginAndLogout(clientAlphaId, clientAlphaSecret);
|
||||
} catch (Exception e) {
|
||||
fail();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClientUpdateSourceHostsCondition() throws Exception {
|
||||
// register profiles
|
||||
String json = (new ClientProfilesBuilder()).addProfile(
|
||||
(new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Prvni Profil")
|
||||
.addExecutor(SecureClientAuthenticatorExecutorFactory.PROVIDER_ID,
|
||||
createSecureClientAuthenticatorExecutorConfig(
|
||||
Arrays.asList(JWTClientAuthenticator.PROVIDER_ID, JWTClientSecretAuthenticator.PROVIDER_ID, X509ClientAuthenticator.PROVIDER_ID),
|
||||
null)
|
||||
)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
// register policies
|
||||
json = (new ClientPoliciesBuilder()).addPolicy(
|
||||
(new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "Prvni Politika", Boolean.TRUE)
|
||||
.addCondition(ClientUpdaterSourceHostsConditionFactory.PROVIDER_ID,
|
||||
createClientUpdateSourceHostsConditionConfig(Arrays.asList("localhost", "127.0.0.1")))
|
||||
.addProfile(PROFILE_NAME)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updatePolicies(json);
|
||||
|
||||
String clientId = generateSuffixedName(CLIENT_NAME);
|
||||
String clientSecret = "secret";
|
||||
try {
|
||||
createClientByAdmin(clientId, (ClientRepresentation clientRep) -> {
|
||||
clientRep.setSecret(clientSecret);
|
||||
});
|
||||
fail();
|
||||
} catch (ClientPolicyException e) {
|
||||
assertEquals(OAuthErrorException.INVALID_CLIENT_METADATA, e.getMessage());
|
||||
}
|
||||
|
||||
// update policies
|
||||
json = (new ClientPoliciesBuilder()).addPolicy(
|
||||
(new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "Aktualizovana Prvni Politika", Boolean.TRUE)
|
||||
.addCondition(ClientUpdaterSourceHostsConditionFactory.PROVIDER_ID,
|
||||
createClientUpdateSourceHostsConditionConfig(Arrays.asList("example.com")))
|
||||
.addProfile(PROFILE_NAME)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updatePolicies(json);
|
||||
|
||||
try {
|
||||
createClientByAdmin(clientId, (ClientRepresentation clientRep) -> {
|
||||
clientRep.setSecret(clientSecret);
|
||||
});
|
||||
} catch (Exception e) {
|
||||
fail();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClientUpdateSourceGroupsCondition() throws Exception {
|
||||
// register profiles
|
||||
String json = (new ClientProfilesBuilder()).addProfile(
|
||||
(new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Den Forste Profil")
|
||||
.addExecutor(SecureClientAuthenticatorExecutorFactory.PROVIDER_ID,
|
||||
createSecureClientAuthenticatorExecutorConfig(
|
||||
Arrays.asList(JWTClientAuthenticator.PROVIDER_ID),
|
||||
null)
|
||||
)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
// register policies
|
||||
json = (new ClientPoliciesBuilder()).addPolicy(
|
||||
(new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "Den Forste Politik", Boolean.TRUE)
|
||||
.addCondition(ClientUpdaterSourceGroupsConditionFactory.PROVIDER_ID,
|
||||
createClientUpdateSourceGroupsConditionConfig(Arrays.asList("topGroup")))
|
||||
.addProfile(PROFILE_NAME)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updatePolicies(json);
|
||||
|
||||
try {
|
||||
authCreateClients();
|
||||
createClientDynamically(generateSuffixedName(CLIENT_NAME), (OIDCClientRepresentation clientRep) -> {
|
||||
});
|
||||
fail();
|
||||
} catch (ClientRegistrationException e) {
|
||||
assertEquals(ERR_MSG_CLIENT_REG_FAIL, e.getMessage());
|
||||
}
|
||||
authManageClients();
|
||||
try {
|
||||
createClientDynamically(generateSuffixedName(CLIENT_NAME), (OIDCClientRepresentation clientRep) -> {
|
||||
});
|
||||
} catch (Exception e) {
|
||||
fail();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClientUpdateSourceRolesCondition() throws Exception {
|
||||
// register profiles
|
||||
String json = (new ClientProfilesBuilder()).addProfile(
|
||||
(new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Il Primo Profilo")
|
||||
.addExecutor(SecureClientAuthenticatorExecutorFactory.PROVIDER_ID,
|
||||
createSecureClientAuthenticatorExecutorConfig(
|
||||
Arrays.asList(JWTClientSecretAuthenticator.PROVIDER_ID),
|
||||
null)
|
||||
)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
// register policies
|
||||
json = (new ClientPoliciesBuilder()).addPolicy(
|
||||
(new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "La Prima Politica", Boolean.TRUE)
|
||||
.addCondition(ClientUpdaterSourceRolesConditionFactory.PROVIDER_ID,
|
||||
createClientUpdateSourceRolesConditionConfig(Arrays.asList(Constants.REALM_MANAGEMENT_CLIENT_ID + "." + AdminRoles.CREATE_CLIENT)))
|
||||
.addProfile(PROFILE_NAME)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updatePolicies(json);
|
||||
|
||||
try {
|
||||
authCreateClients();
|
||||
createClientDynamically(generateSuffixedName(CLIENT_NAME), (OIDCClientRepresentation clientRep) -> {
|
||||
});
|
||||
fail();
|
||||
} catch (ClientRegistrationException e) {
|
||||
assertEquals(ERR_MSG_CLIENT_REG_FAIL, e.getMessage());
|
||||
}
|
||||
authManageClients();
|
||||
try {
|
||||
createClientDynamically(generateSuffixedName(CLIENT_NAME), (OIDCClientRepresentation clientRep) -> {
|
||||
});
|
||||
} catch (Exception e) {
|
||||
fail();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClientScopesCondition() throws Exception {
|
||||
// register profiles
|
||||
String json = (new ClientProfilesBuilder()).addProfile(
|
||||
(new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Het Eerste Profiel")
|
||||
.addExecutor(PKCEEnforcerExecutorFactory.PROVIDER_ID,
|
||||
createPKCEEnforceExecutorConfig(Boolean.TRUE))
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
// register policies
|
||||
json = (new ClientPoliciesBuilder()).addPolicy(
|
||||
(new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "Het Eerste Beleid", Boolean.TRUE)
|
||||
.addCondition(ClientScopesConditionFactory.PROVIDER_ID,
|
||||
createClientScopesConditionConfig(ClientScopesConditionFactory.OPTIONAL, Arrays.asList("offline_access", "microprofile-jwt")))
|
||||
.addProfile(PROFILE_NAME)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updatePolicies(json);
|
||||
|
||||
String clientId = generateSuffixedName(CLIENT_NAME);
|
||||
String clientSecret = "secret";
|
||||
createClientByAdmin(clientId, (ClientRepresentation clientRep) -> {
|
||||
clientRep.setSecret(clientSecret);
|
||||
});
|
||||
|
||||
try {
|
||||
oauth.scope("address" + " " + "phone");
|
||||
successfulLoginAndLogout(clientId, clientSecret);
|
||||
|
||||
oauth.scope("microprofile-jwt" + " " + "profile");
|
||||
failLoginByNotFollowingPKCE(clientId);
|
||||
|
||||
oauth.scope("microprofile-jwt" + " " + "profile");
|
||||
failLoginByNotFollowingPKCE(clientId);
|
||||
|
||||
successfulLoginAndLogoutWithPKCE(clientId, clientSecret, TEST_USER_NAME, TEST_USER_PASSWORD);
|
||||
} catch (Exception e) {
|
||||
fail();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClientAccessTypeCondition() throws Exception {
|
||||
// register profiles
|
||||
String json = (new ClientProfilesBuilder()).addProfile(
|
||||
(new ClientProfileBuilder()).createProfile(PROFILE_NAME, "El Primer Perfil")
|
||||
.addExecutor(SecureSessionEnforceExecutorFactory.PROVIDER_ID, null)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
// register policies
|
||||
json = (new ClientPoliciesBuilder()).addPolicy(
|
||||
(new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "La Primera Plitica", Boolean.TRUE)
|
||||
.addCondition(ClientAccessTypeConditionFactory.PROVIDER_ID,
|
||||
createClientAccessTypeConditionConfig(Arrays.asList(ClientAccessTypeConditionFactory.TYPE_CONFIDENTIAL)))
|
||||
.addProfile(PROFILE_NAME)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updatePolicies(json);
|
||||
|
||||
// confidential client
|
||||
String clientAlphaId = generateSuffixedName("Alpha-App");
|
||||
createClientByAdmin(clientAlphaId, (ClientRepresentation clientRep) -> {
|
||||
clientRep.setSecret("secretAlpha");
|
||||
clientRep.setBearerOnly(Boolean.FALSE);
|
||||
clientRep.setPublicClient(Boolean.FALSE);
|
||||
});
|
||||
|
||||
// public client
|
||||
String clientBetaId = generateSuffixedName("Beta-App");
|
||||
createClientByAdmin(clientBetaId, (ClientRepresentation clientRep) -> {
|
||||
clientRep.setBearerOnly(Boolean.FALSE);
|
||||
clientRep.setPublicClient(Boolean.TRUE);
|
||||
});
|
||||
|
||||
successfulLoginAndLogout(clientBetaId, null);
|
||||
failLoginWithoutNonce(clientAlphaId);
|
||||
|
||||
// update profiles
|
||||
json = (new ClientProfilesBuilder()).addProfile(
|
||||
(new ClientProfileBuilder()).createProfile(PROFILE_NAME, "El Primer Perfil")
|
||||
.addExecutor(PKCEEnforcerExecutorFactory.PROVIDER_ID,
|
||||
createPKCEEnforceExecutorConfig(Boolean.FALSE)) // check only
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
// Attempt to create a confidential client without PKCE setting. Should fail
|
||||
try {
|
||||
createClientByAdmin(generateSuffixedName("Gamma-App"), (ClientRepresentation clientRep) -> {
|
||||
clientRep.setSecret("secretGamma");
|
||||
clientRep.setBearerOnly(Boolean.FALSE);
|
||||
clientRep.setPublicClient(Boolean.FALSE);
|
||||
});
|
||||
fail();
|
||||
} catch (ClientPolicyException e) {
|
||||
assertEquals(OAuthErrorException.INVALID_CLIENT_METADATA, e.getMessage());
|
||||
assertEquals("Invalid client metadata: code_challenge_method", e.getErrorDetail());
|
||||
}
|
||||
|
||||
json = (new ClientProfilesBuilder()).addProfile(
|
||||
(new ClientProfileBuilder()).createProfile(PROFILE_NAME, "El Primer Perfil")
|
||||
.addExecutor(PKCEEnforcerExecutorFactory.PROVIDER_ID,
|
||||
createPKCEEnforceExecutorConfig(Boolean.TRUE)) // enforce
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
authCreateClients();
|
||||
String clientGammaId = createClientDynamically(generateSuffixedName("Gamma-App"), (OIDCClientRepresentation clientRep) -> {
|
||||
clientRep.setClientSecret("secretGamma");
|
||||
});
|
||||
|
||||
ClientRepresentation clientRep = getClientByAdmin(clientGammaId);
|
||||
assertEquals(OAuth2Constants.PKCE_METHOD_S256, OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).getPkceCodeChallengeMethod());
|
||||
|
||||
json = (new ClientProfilesBuilder()).addProfile(
|
||||
(new ClientProfileBuilder()).createProfile(PROFILE_NAME, "El Primer Perfil")
|
||||
.addExecutor(PKCEEnforcerExecutorFactory.PROVIDER_ID,
|
||||
createPKCEEnforceExecutorConfig(Boolean.FALSE)) // check only
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
// Attempt to update the confidential client with not allowed PKCE setting. Should fail
|
||||
try {
|
||||
updateClientByAdmin(clientGammaId, (ClientRepresentation updatingClientRep) -> {
|
||||
updatingClientRep.setAttributes(new HashMap<>());
|
||||
updatingClientRep.getAttributes().put(OIDCConfigAttributes.PKCE_CODE_CHALLENGE_METHOD, OAuth2Constants.PKCE_METHOD_PLAIN);
|
||||
});
|
||||
} catch (ClientPolicyException e) {
|
||||
assertEquals(OAuthErrorException.INVALID_CLIENT_METADATA, e.getMessage());
|
||||
assertEquals("Invalid client metadata: code_challenge_method", e.getErrorDetail());
|
||||
}
|
||||
ClientRepresentation cRep = getClientByAdmin(clientGammaId);
|
||||
assertEquals(OAuth2Constants.PKCE_METHOD_S256, cRep.getAttributes().get(OIDCConfigAttributes.PKCE_CODE_CHALLENGE_METHOD));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClientPolicyTriggeredForServiceAccountRequest() throws Exception {
|
||||
String clientId = "service-account-app";
|
||||
String clientSecret = "app-secret";
|
||||
createClientByAdmin(clientId, (ClientRepresentation clientRep) -> {
|
||||
clientRep.setSecret(clientSecret);
|
||||
clientRep.setStandardFlowEnabled(Boolean.FALSE);
|
||||
clientRep.setImplicitFlowEnabled(Boolean.FALSE);
|
||||
clientRep.setServiceAccountsEnabled(Boolean.TRUE);
|
||||
clientRep.setPublicClient(Boolean.FALSE);
|
||||
clientRep.setBearerOnly(Boolean.FALSE);
|
||||
});
|
||||
|
||||
// register profiles
|
||||
String json = (new ClientProfilesBuilder()).addProfile(
|
||||
(new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Den Forste Profilen")
|
||||
.addExecutor(TestRaiseExceptionExecutorFactory.PROVIDER_ID,
|
||||
createTestRaiseExeptionExecutorConfig(Arrays.asList(ClientPolicyEvent.SERVICE_ACCOUNT_TOKEN_REQUEST)))
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
// register policies
|
||||
json = (new ClientPoliciesBuilder()).addPolicy(
|
||||
(new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "La Premiere Politique", Boolean.TRUE)
|
||||
.addCondition(AnyClientConditionFactory.PROVIDER_ID, createAnyClientConditionConfig())
|
||||
.addProfile(PROFILE_NAME)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updatePolicies(json);
|
||||
|
||||
String origClientId = oauth.getClientId();
|
||||
oauth.clientId("service-account-app");
|
||||
try {
|
||||
OAuthClient.AccessTokenResponse response = oauth.doClientCredentialsGrantAccessTokenRequest("app-secret");
|
||||
assertEquals(400, response.getStatusCode());
|
||||
assertEquals(ClientPolicyEvent.SERVICE_ACCOUNT_TOKEN_REQUEST.toString(), response.getError());
|
||||
assertEquals("Exception thrown intentionally", response.getErrorDescription());
|
||||
} finally {
|
||||
oauth.clientId(origClientId);
|
||||
}
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load diff
|
@ -0,0 +1,540 @@
|
|||
/*
|
||||
* Copyright 2023 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.testsuite.client.policies;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.fail;
|
||||
import static org.keycloak.testsuite.admin.AbstractAdminTest.loadJson;
|
||||
import static org.keycloak.testsuite.admin.ApiUtil.findUserByUsername;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createAnyClientConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientAccessTypeConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientRolesConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientScopesConditionConfig;
|
||||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createTestRaiseExeptionExecutorConfig;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import org.jboss.arquillian.graphene.page.Page;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.keycloak.OAuth2Constants;
|
||||
import org.keycloak.OAuthErrorException;
|
||||
import org.keycloak.common.Profile;
|
||||
import org.keycloak.events.Details;
|
||||
import org.keycloak.models.AdminRoles;
|
||||
import org.keycloak.models.Constants;
|
||||
import org.keycloak.models.OAuth2DeviceConfig;
|
||||
import org.keycloak.models.utils.KeycloakModelUtils;
|
||||
import org.keycloak.protocol.oidc.OIDCConfigAttributes;
|
||||
import org.keycloak.representations.RefreshToken;
|
||||
import org.keycloak.representations.idm.ClientRepresentation;
|
||||
import org.keycloak.representations.idm.CredentialRepresentation;
|
||||
import org.keycloak.representations.idm.EventRepresentation;
|
||||
import org.keycloak.representations.idm.RealmRepresentation;
|
||||
import org.keycloak.representations.idm.UserRepresentation;
|
||||
import org.keycloak.services.clientpolicy.ClientPolicyEvent;
|
||||
import org.keycloak.services.clientpolicy.ClientPolicyException;
|
||||
import org.keycloak.services.clientpolicy.condition.AnyClientConditionFactory;
|
||||
import org.keycloak.services.clientpolicy.condition.ClientAccessTypeConditionFactory;
|
||||
import org.keycloak.services.clientpolicy.condition.ClientRolesConditionFactory;
|
||||
import org.keycloak.services.clientpolicy.condition.ClientScopesConditionFactory;
|
||||
import org.keycloak.services.clientpolicy.executor.SuppressRefreshTokenRotationExecutorFactory;
|
||||
import org.keycloak.testsuite.arquillian.annotation.EnableFeature;
|
||||
import org.keycloak.testsuite.pages.ErrorPage;
|
||||
import org.keycloak.testsuite.pages.LogoutConfirmPage;
|
||||
import org.keycloak.testsuite.pages.OAuth2DeviceVerificationPage;
|
||||
import org.keycloak.testsuite.pages.OAuthGrantPage;
|
||||
import org.keycloak.testsuite.services.clientpolicy.executor.TestRaiseExceptionExecutorFactory;
|
||||
import org.keycloak.testsuite.util.ClientBuilder;
|
||||
import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPoliciesBuilder;
|
||||
import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPolicyBuilder;
|
||||
import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfileBuilder;
|
||||
import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfilesBuilder;
|
||||
import org.keycloak.testsuite.util.OAuthClient;
|
||||
import org.keycloak.testsuite.util.RoleBuilder;
|
||||
import org.keycloak.testsuite.util.UserBuilder;
|
||||
|
||||
/**
|
||||
* This test class is for testing a newly supported event for client policies.
|
||||
*
|
||||
* @author <a href="mailto:takashi.norimatsu.ws@hitachi.com">Takashi Norimatsu</a>
|
||||
*/
|
||||
@EnableFeature(value = Profile.Feature.CLIENT_SECRET_ROTATION)
|
||||
public class ClientPoliciesExtendedEventTest extends AbstractClientPoliciesTest {
|
||||
|
||||
@Page
|
||||
protected OAuth2DeviceVerificationPage verificationPage;
|
||||
|
||||
@Page
|
||||
protected OAuthGrantPage grantPage;
|
||||
|
||||
@Page
|
||||
protected ErrorPage errorPage;
|
||||
|
||||
@Page
|
||||
protected LogoutConfirmPage logoutConfirmPage;
|
||||
|
||||
@Override
|
||||
public void addTestRealms(List<RealmRepresentation> testRealms) {
|
||||
RealmRepresentation realm = loadJson(getClass().getResourceAsStream("/testrealm.json"), RealmRepresentation.class);
|
||||
|
||||
List<UserRepresentation> users = realm.getUsers();
|
||||
|
||||
LinkedList<CredentialRepresentation> credentials = new LinkedList<>();
|
||||
CredentialRepresentation password = new CredentialRepresentation();
|
||||
password.setType(CredentialRepresentation.PASSWORD);
|
||||
password.setValue("password");
|
||||
credentials.add(password);
|
||||
|
||||
UserRepresentation user = new UserRepresentation();
|
||||
user.setEnabled(true);
|
||||
user.setUsername("manage-clients");
|
||||
user.setCredentials(credentials);
|
||||
user.setClientRoles(Collections.singletonMap(Constants.REALM_MANAGEMENT_CLIENT_ID, Collections.singletonList(AdminRoles.MANAGE_CLIENTS)));
|
||||
|
||||
users.add(user);
|
||||
|
||||
user = new UserRepresentation();
|
||||
user.setEnabled(true);
|
||||
user.setUsername("create-clients");
|
||||
user.setCredentials(credentials);
|
||||
user.setClientRoles(Collections.singletonMap(Constants.REALM_MANAGEMENT_CLIENT_ID, Collections.singletonList(AdminRoles.CREATE_CLIENT)));
|
||||
user.setGroups(Arrays.asList("topGroup")); // defined in testrealm.json
|
||||
|
||||
users.add(user);
|
||||
|
||||
realm.setUsers(users);
|
||||
|
||||
List<ClientRepresentation> clients = realm.getClients();
|
||||
|
||||
ClientRepresentation app = ClientBuilder.create()
|
||||
.id(KeycloakModelUtils.generateId())
|
||||
.clientId("test-device")
|
||||
.secret("secret")
|
||||
.attribute(OAuth2DeviceConfig.OAUTH2_DEVICE_AUTHORIZATION_GRANT_ENABLED, "true")
|
||||
.attribute(OIDCConfigAttributes.POST_LOGOUT_REDIRECT_URIS, "+")
|
||||
.build();
|
||||
clients.add(app);
|
||||
|
||||
ClientRepresentation appPublic = ClientBuilder.create().id(KeycloakModelUtils.generateId()).publicClient()
|
||||
.clientId(DEVICE_APP_PUBLIC)
|
||||
.attribute(OAuth2DeviceConfig.OAUTH2_DEVICE_AUTHORIZATION_GRANT_ENABLED, "true")
|
||||
.attribute(OIDCConfigAttributes.POST_LOGOUT_REDIRECT_URIS, "+")
|
||||
.build();
|
||||
clients.add(appPublic);
|
||||
|
||||
userId = KeycloakModelUtils.generateId();
|
||||
UserRepresentation deviceUser = UserBuilder.create()
|
||||
.id(userId)
|
||||
.username("device-login")
|
||||
.email("device-login@localhost")
|
||||
.password("password")
|
||||
.build();
|
||||
users.add(deviceUser);
|
||||
|
||||
testRealms.add(realm);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExtendedClientPolicyIntefacesForClientRegistrationPolicyMigration() throws Exception {
|
||||
// register profiles
|
||||
String json = (new ClientProfilesBuilder()).addProfile(
|
||||
(new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Den Forste Profilen")
|
||||
.addExecutor(TestRaiseExceptionExecutorFactory.PROVIDER_ID,
|
||||
createTestRaiseExeptionExecutorConfig(Arrays.asList(
|
||||
ClientPolicyEvent.REGISTERED, ClientPolicyEvent.UPDATED, ClientPolicyEvent.UNREGISTER)))
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
// register policies
|
||||
json = (new ClientPoliciesBuilder()).addPolicy(
|
||||
(new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "La Premiere Politique", Boolean.TRUE)
|
||||
.addCondition(AnyClientConditionFactory.PROVIDER_ID, createAnyClientConditionConfig())
|
||||
.addProfile(PROFILE_NAME)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updatePolicies(json);
|
||||
|
||||
String clientName = "ByAdmin-App" + KeycloakModelUtils.generateId().substring(0, 7);
|
||||
String clientId = null;
|
||||
|
||||
try {
|
||||
createClientByAdmin(clientName, (ClientRepresentation clientRep) -> {
|
||||
});
|
||||
fail();
|
||||
} catch (ClientPolicyException cpe) {
|
||||
assertEquals(ClientPolicyEvent.REGISTERED.toString(), cpe.getError());
|
||||
}
|
||||
|
||||
clientId = getClientByAdminWithName(clientName).getId();
|
||||
assertEquals(true, getClientByAdmin(clientId).isEnabled());
|
||||
try {
|
||||
updateClientByAdmin(clientId, (ClientRepresentation clientRep) -> {
|
||||
clientRep.setEnabled(false);
|
||||
});
|
||||
fail();
|
||||
} catch (ClientPolicyException cpe) {
|
||||
assertEquals(ClientPolicyEvent.UPDATED.toString(), cpe.getError());
|
||||
}
|
||||
assertEquals(false, getClientByAdmin(clientId).isEnabled());
|
||||
|
||||
try {
|
||||
deleteClientByAdmin(clientId);
|
||||
fail();
|
||||
} catch (ClientPolicyException cpe) {
|
||||
assertEquals(ClientPolicyEvent.UNREGISTER.toString(), cpe.getError());
|
||||
}
|
||||
|
||||
// TODO : For dynamic client registration, the existing test scheme can not distinguish when the exception happens on which event so that the migrated client policy executors test them afterwards.
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExtendedClientPolicyIntefacesForDeviceAuthorizationRequest() throws Exception {
|
||||
// register profiles
|
||||
String json = (new ClientProfilesBuilder()).addProfile(
|
||||
(new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Den Forste Profilen")
|
||||
.addExecutor(TestRaiseExceptionExecutorFactory.PROVIDER_ID,
|
||||
createTestRaiseExeptionExecutorConfig(Arrays.asList(ClientPolicyEvent.DEVICE_AUTHORIZATION_REQUEST)))
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
// register policies
|
||||
json = (new ClientPoliciesBuilder()).addPolicy(
|
||||
(new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "La Premiere Politique", Boolean.TRUE)
|
||||
.addCondition(AnyClientConditionFactory.PROVIDER_ID, createAnyClientConditionConfig())
|
||||
.addProfile(PROFILE_NAME)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updatePolicies(json);
|
||||
|
||||
// Device Authorization Request from device
|
||||
oauth.realm(REALM_NAME);
|
||||
oauth.clientId(DEVICE_APP);
|
||||
OAuthClient.DeviceAuthorizationResponse response = oauth.doDeviceAuthorizationRequest(DEVICE_APP, "secret");
|
||||
assertEquals(400, response.getStatusCode());
|
||||
assertEquals(ClientPolicyEvent.DEVICE_AUTHORIZATION_REQUEST.toString(), response.getError());
|
||||
assertEquals("Exception thrown intentionally", response.getErrorDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExtendedClientPolicyIntefacesForDeviceTokenRequest() throws Exception {
|
||||
// Device Authorization Request from device
|
||||
oauth.realm(REALM_NAME);
|
||||
oauth.clientId(DEVICE_APP);
|
||||
OAuthClient.DeviceAuthorizationResponse response = oauth.doDeviceAuthorizationRequest(DEVICE_APP, "secret");
|
||||
|
||||
Assert.assertEquals(200, response.getStatusCode());
|
||||
assertNotNull(response.getDeviceCode());
|
||||
assertNotNull(response.getUserCode());
|
||||
assertNotNull(response.getVerificationUri());
|
||||
assertNotNull(response.getVerificationUriComplete());
|
||||
|
||||
// Verify user code from verification page using browser
|
||||
openVerificationPage(response.getVerificationUri());
|
||||
verificationPage.assertCurrent();
|
||||
verificationPage.submit(response.getUserCode());
|
||||
|
||||
loginPage.assertCurrent();
|
||||
|
||||
// Do Login
|
||||
oauth.fillLoginForm("device-login", "password");
|
||||
|
||||
// Consent
|
||||
grantPage.assertCurrent();
|
||||
grantPage.assertGrants(OAuthGrantPage.PROFILE_CONSENT_TEXT, OAuthGrantPage.EMAIL_CONSENT_TEXT, OAuthGrantPage.ROLES_CONSENT_TEXT);
|
||||
grantPage.accept();
|
||||
|
||||
verificationPage.assertApprovedPage();
|
||||
|
||||
// register profiles
|
||||
String json = (new ClientProfilesBuilder()).addProfile(
|
||||
(new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Den Forste Profilen")
|
||||
.addExecutor(TestRaiseExceptionExecutorFactory.PROVIDER_ID,
|
||||
createTestRaiseExeptionExecutorConfig(Arrays.asList(ClientPolicyEvent.DEVICE_TOKEN_REQUEST)))
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
// register policies
|
||||
json = (new ClientPoliciesBuilder()).addPolicy(
|
||||
(new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "La Premiere Politique", Boolean.TRUE)
|
||||
.addCondition(AnyClientConditionFactory.PROVIDER_ID, createAnyClientConditionConfig())
|
||||
.addProfile(PROFILE_NAME)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updatePolicies(json);
|
||||
|
||||
// Token request from device
|
||||
OAuthClient.AccessTokenResponse tokenResponse = oauth.doDeviceTokenRequest(DEVICE_APP, "secret", response.getDeviceCode());
|
||||
assertEquals(400, tokenResponse.getStatusCode());
|
||||
assertEquals(OAuthErrorException.INVALID_GRANT, tokenResponse.getError());
|
||||
assertEquals("Exception thrown intentionally", tokenResponse.getErrorDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExtendedClientPolicyIntefacesForDeviceTokenResponse() throws Exception {
|
||||
// Device Authorization Request from device
|
||||
oauth.realm(REALM_NAME);
|
||||
oauth.clientId(DEVICE_APP);
|
||||
OAuthClient.DeviceAuthorizationResponse response = oauth.doDeviceAuthorizationRequest(DEVICE_APP, "secret");
|
||||
|
||||
Assert.assertEquals(200, response.getStatusCode());
|
||||
assertNotNull(response.getDeviceCode());
|
||||
assertNotNull(response.getUserCode());
|
||||
assertNotNull(response.getVerificationUri());
|
||||
assertNotNull(response.getVerificationUriComplete());
|
||||
|
||||
// Verify user code from verification page using browser
|
||||
openVerificationPage(response.getVerificationUri());
|
||||
verificationPage.assertCurrent();
|
||||
verificationPage.submit(response.getUserCode());
|
||||
|
||||
loginPage.assertCurrent();
|
||||
|
||||
// Do Login
|
||||
oauth.fillLoginForm("device-login", "password");
|
||||
|
||||
// Consent
|
||||
grantPage.assertCurrent();
|
||||
grantPage.assertGrants(OAuthGrantPage.PROFILE_CONSENT_TEXT, OAuthGrantPage.EMAIL_CONSENT_TEXT, OAuthGrantPage.ROLES_CONSENT_TEXT);
|
||||
grantPage.accept();
|
||||
|
||||
verificationPage.assertApprovedPage();
|
||||
|
||||
// register profiles
|
||||
String json = (new ClientProfilesBuilder()).addProfile(
|
||||
(new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Den Forste Profilen")
|
||||
.addExecutor(TestRaiseExceptionExecutorFactory.PROVIDER_ID,
|
||||
createTestRaiseExeptionExecutorConfig(Arrays.asList(ClientPolicyEvent.DEVICE_TOKEN_RESPONSE)))
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
// register policies
|
||||
json = (new ClientPoliciesBuilder()).addPolicy(
|
||||
(new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "La Premiere Politique", Boolean.TRUE)
|
||||
.addCondition(AnyClientConditionFactory.PROVIDER_ID, createAnyClientConditionConfig())
|
||||
.addProfile(PROFILE_NAME)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updatePolicies(json);
|
||||
|
||||
// Token request from device
|
||||
OAuthClient.AccessTokenResponse tokenResponse = oauth.doDeviceTokenRequest(DEVICE_APP, "secret", response.getDeviceCode());
|
||||
assertEquals(400, tokenResponse.getStatusCode());
|
||||
assertEquals(ClientPolicyEvent.DEVICE_TOKEN_RESPONSE.toString(), tokenResponse.getError());
|
||||
assertEquals("Exception thrown intentionally", tokenResponse.getErrorDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExtendedClientPolicyIntefacesForTokenResponse() throws Exception {
|
||||
// register a confidential client
|
||||
String clientId = generateSuffixedName(CLIENT_NAME);
|
||||
String clientSecret = "secret";
|
||||
createClientByAdmin(clientId, (ClientRepresentation clientRep) -> {
|
||||
clientRep.setSecret(clientSecret);
|
||||
clientRep.setPublicClient(Boolean.FALSE);
|
||||
clientRep.setBearerOnly(Boolean.FALSE);
|
||||
});
|
||||
|
||||
// register profiles
|
||||
String json = (new ClientProfilesBuilder()).addProfile(
|
||||
(new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Den Forste Profilen")
|
||||
.addExecutor(TestRaiseExceptionExecutorFactory.PROVIDER_ID,
|
||||
createTestRaiseExeptionExecutorConfig(Arrays.asList(ClientPolicyEvent.TOKEN_RESPONSE)))
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
// register policies
|
||||
json = (new ClientPoliciesBuilder()).addPolicy(
|
||||
(new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "La Primera Plitica", Boolean.TRUE)
|
||||
.addCondition(ClientAccessTypeConditionFactory.PROVIDER_ID,
|
||||
createClientAccessTypeConditionConfig(Arrays.asList(ClientAccessTypeConditionFactory.TYPE_CONFIDENTIAL)))
|
||||
.addProfile(PROFILE_NAME)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updatePolicies(json);
|
||||
|
||||
oauth.clientId(clientId);
|
||||
oauth.doLogin(TEST_USER_NAME, TEST_USER_PASSWORD);
|
||||
|
||||
events.expectLogin().client(clientId).assertEvent();
|
||||
String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
|
||||
OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, clientSecret);
|
||||
assertEquals(400, response.getStatusCode());
|
||||
assertEquals(ClientPolicyEvent.TOKEN_RESPONSE.toString(), response.getError());
|
||||
assertEquals("Exception thrown intentionally", response.getErrorDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExtendedClientPolicyIntefacesForTokenRefreshResponse() throws Exception {
|
||||
String clientId = generateSuffixedName(CLIENT_NAME);
|
||||
String clientSecret = "secret";
|
||||
String cid = createClientByAdmin(clientId, (ClientRepresentation clientRep) -> {
|
||||
clientRep.setSecret(clientSecret);
|
||||
clientRep.setStandardFlowEnabled(Boolean.TRUE);
|
||||
clientRep.setImplicitFlowEnabled(Boolean.TRUE);
|
||||
clientRep.setPublicClient(Boolean.FALSE);
|
||||
});
|
||||
adminClient.realm(REALM_NAME).clients().get(cid).roles().create(RoleBuilder.create().name(SAMPLE_CLIENT_ROLE).build());
|
||||
|
||||
oauth.clientId(clientId);
|
||||
oauth.doLogin(TEST_USER_NAME, TEST_USER_PASSWORD);
|
||||
|
||||
EventRepresentation loginEvent = events.expectLogin().client(clientId).assertEvent();
|
||||
String sessionId = loginEvent.getSessionId();
|
||||
String codeId = loginEvent.getDetails().get(Details.CODE_ID);
|
||||
String code = new OAuthClient.AuthorizationEndpointResponse(oauth).getCode();
|
||||
|
||||
OAuthClient.AccessTokenResponse res = oauth.doAccessTokenRequest(code, clientSecret);
|
||||
assertEquals(200, res.getStatusCode());
|
||||
events.expectCodeToToken(codeId, sessionId).client(clientId).assertEvent();
|
||||
|
||||
// register profiles
|
||||
String json = (new ClientProfilesBuilder()).addProfile(
|
||||
(new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Le Premier Profil")
|
||||
.addExecutor(SuppressRefreshTokenRotationExecutorFactory.PROVIDER_ID, null)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
// register policies
|
||||
json = (new ClientPoliciesBuilder()).addPolicy(
|
||||
(new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "Den Forste Politikken", Boolean.TRUE)
|
||||
.addCondition(ClientRolesConditionFactory.PROVIDER_ID,
|
||||
createClientRolesConditionConfig(Arrays.asList(SAMPLE_CLIENT_ROLE)))
|
||||
.addProfile(PROFILE_NAME)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updatePolicies(json);
|
||||
|
||||
String refreshTokenString = res.getRefreshToken();
|
||||
OAuthClient.AccessTokenResponse accessTokenResponseRefreshed = oauth.doRefreshTokenRequest(refreshTokenString, clientSecret);
|
||||
assertEquals(200, accessTokenResponseRefreshed.getStatusCode());
|
||||
assertEquals(null, accessTokenResponseRefreshed.getRefreshToken());
|
||||
|
||||
json = (new ClientPoliciesBuilder()).addPolicy(
|
||||
(new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "Den Forste Politikken", Boolean.TRUE)
|
||||
.addCondition(ClientRolesConditionFactory.PROVIDER_ID,
|
||||
createClientRolesConditionConfig(Arrays.asList("other" + SAMPLE_CLIENT_ROLE)))
|
||||
.addProfile(PROFILE_NAME)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updatePolicies(json);
|
||||
|
||||
accessTokenResponseRefreshed = oauth.doRefreshTokenRequest(refreshTokenString, clientSecret);
|
||||
assertEquals(200, accessTokenResponseRefreshed.getStatusCode());
|
||||
RefreshToken refreshedRefreshToken = oauth.parseRefreshToken(accessTokenResponseRefreshed.getRefreshToken());
|
||||
assertEquals(sessionId, refreshedRefreshToken.getSessionState());
|
||||
assertEquals(sessionId, refreshedRefreshToken.getSessionState());
|
||||
assertEquals(findUserByUsername(adminClient.realm(REALM_NAME), TEST_USER_NAME).getId(), refreshedRefreshToken.getSubject());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExtendedClientPolicyIntefacesForServiceAccountTokenRequeponse() throws Exception {
|
||||
String clientId = "service-account-app";
|
||||
String clientSecret = "app-secret";
|
||||
createClientByAdmin(clientId, (ClientRepresentation clientRep) -> {
|
||||
clientRep.setSecret(clientSecret);
|
||||
clientRep.setStandardFlowEnabled(Boolean.FALSE);
|
||||
clientRep.setImplicitFlowEnabled(Boolean.FALSE);
|
||||
clientRep.setServiceAccountsEnabled(Boolean.TRUE);
|
||||
clientRep.setPublicClient(Boolean.FALSE);
|
||||
clientRep.setBearerOnly(Boolean.FALSE);
|
||||
});
|
||||
|
||||
// register profiles
|
||||
String json = (new ClientProfilesBuilder()).addProfile(
|
||||
(new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Den Forste Profilen")
|
||||
.addExecutor(TestRaiseExceptionExecutorFactory.PROVIDER_ID,
|
||||
createTestRaiseExeptionExecutorConfig(Arrays.asList(ClientPolicyEvent.SERVICE_ACCOUNT_TOKEN_RESPONSE)))
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updateProfiles(json);
|
||||
|
||||
// register policies
|
||||
json = (new ClientPoliciesBuilder()).addPolicy(
|
||||
(new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "Het Eerste Beleid", Boolean.TRUE)
|
||||
.addCondition(ClientScopesConditionFactory.PROVIDER_ID,
|
||||
createClientScopesConditionConfig(ClientScopesConditionFactory.OPTIONAL, Arrays.asList("offline_access", "microprofile-jwt")))
|
||||
.addProfile(PROFILE_NAME)
|
||||
.toRepresentation()
|
||||
).toString();
|
||||
updatePolicies(json);
|
||||
|
||||
|
||||
String origClientId = oauth.getClientId();
|
||||
oauth.clientId("service-account-app");
|
||||
oauth.scope("offline_access");
|
||||
try {
|
||||
OAuthClient.AccessTokenResponse response = oauth.doClientCredentialsGrantAccessTokenRequest("app-secret");
|
||||
assertEquals(400, response.getStatusCode());
|
||||
assertEquals(ClientPolicyEvent.SERVICE_ACCOUNT_TOKEN_RESPONSE.toString(), response.getError());
|
||||
assertEquals("Exception thrown intentionally", response.getErrorDescription());
|
||||
} finally {
|
||||
oauth.clientId(origClientId);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExtendedClientPolicyIntefacesForResourceOwnerPasswordCredentialsResponse() 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, "Den Forste Profilen")
|
||||
.addExecutor(TestRaiseExceptionExecutorFactory.PROVIDER_ID,
|
||||
createTestRaiseExeptionExecutorConfig(Arrays.asList(ClientPolicyEvent.RESOURCE_OWNER_PASSWORD_CREDENTIALS_RESPONSE)))
|
||||
.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(ClientPolicyEvent.RESOURCE_OWNER_PASSWORD_CREDENTIALS_RESPONSE.toString(), response.getError());
|
||||
assertEquals("Exception thrown intentionally", response.getErrorDescription());
|
||||
}
|
||||
}
|
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
* Copyright 2021 Red Hat, Inc. and/or its affiliates
|
||||
* Copyright 2023 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");
|
||||
|
@ -16,7 +16,7 @@
|
|||
*
|
||||
*/
|
||||
|
||||
package org.keycloak.testsuite.client;
|
||||
package org.keycloak.testsuite.client.policies;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
|
@ -37,6 +37,8 @@ import static org.junit.Assert.fail;
|
|||
import static org.keycloak.common.Profile.Feature.CLIENT_POLICIES;
|
||||
|
||||
/**
|
||||
* This test class is for enabling and disabling client policies by feature mechanism.
|
||||
*
|
||||
* @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
|
||||
*/
|
||||
public class ClientPoliciesFeatureTest extends AbstractTestRealmKeycloakTest {
|
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
* Copyright 2021 Red Hat, Inc. and/or its affiliates
|
||||
* Copyright 2023 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");
|
||||
|
@ -15,7 +15,7 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.keycloak.testsuite.client;
|
||||
package org.keycloak.testsuite.client.policies;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
|
@ -35,6 +35,8 @@ import java.util.List;
|
|||
import static org.keycloak.testsuite.admin.AbstractAdminTest.loadJson;
|
||||
|
||||
/**
|
||||
* This test class is for testing client policies that are applied when importing and exporting a realm setting file.
|
||||
*
|
||||
* @author <a href="mailto:takashi.norimatsu.ws@hitachi.com">Takashi Norimatsu</a>
|
||||
*/
|
||||
public class ClientPoliciesImportExportTest extends AbstractClientPoliciesTest {
|
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
* Copyright 2021 Red Hat, Inc. and/or its affiliates
|
||||
* Copyright 2023 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");
|
||||
|
@ -15,7 +15,7 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.keycloak.testsuite.client;
|
||||
package org.keycloak.testsuite.client.policies;
|
||||
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Test;
|
||||
|
@ -59,6 +59,8 @@ import static org.keycloak.testsuite.util.ClientPoliciesUtil.createPKCEEnforceEx
|
|||
import static org.keycloak.testsuite.util.ClientPoliciesUtil.createSecureClientAuthenticatorExecutorConfig;
|
||||
|
||||
/**
|
||||
* This test class is for testing loading and updating profiles and policies file of client policies.
|
||||
*
|
||||
* @author <a href="mailto:takashi.norimatsu.ws@hitachi.com">Takashi Norimatsu</a>
|
||||
*/
|
||||
public class ClientPoliciesLoadUpdateTest extends AbstractClientPoliciesTest {
|
File diff suppressed because it is too large
Load diff
|
@ -63,7 +63,7 @@ import org.keycloak.representations.oidc.OIDCClientRepresentation;
|
|||
import org.keycloak.services.clientpolicy.ClientPolicyEvent;
|
||||
import org.keycloak.services.clientpolicy.condition.ClientRolesConditionFactory;
|
||||
import org.keycloak.testsuite.admin.ApiUtil;
|
||||
import org.keycloak.testsuite.client.AbstractClientPoliciesTest;
|
||||
import org.keycloak.testsuite.client.policies.AbstractClientPoliciesTest;
|
||||
import org.keycloak.testsuite.client.resources.TestApplicationResourceUrls;
|
||||
import org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource;
|
||||
import org.keycloak.testsuite.rest.resource.TestingOIDCEndpointsApplicationResource;
|
||||
|
|
Loading…
Reference in a new issue