diff --git a/integration/admin-client/src/main/java/org/keycloak/admin/client/Keycloak.java b/integration/admin-client/src/main/java/org/keycloak/admin/client/Keycloak.java index 2b12225573..7b79074ace 100755 --- a/integration/admin-client/src/main/java/org/keycloak/admin/client/Keycloak.java +++ b/integration/admin-client/src/main/java/org/keycloak/admin/client/Keycloak.java @@ -28,8 +28,6 @@ import org.keycloak.admin.client.resource.ServerInfoResource; import org.keycloak.admin.client.token.TokenManager; import javax.net.ssl.SSLContext; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLSession; import java.net.URI; @@ -45,14 +43,13 @@ import static org.keycloak.OAuth2Constants.PASSWORD; * @author rodrigo.sasaki@icarros.com.br * @see KeycloakBuilder */ -public class Keycloak { +public class Keycloak implements AutoCloseable { private final Config config; private final TokenManager tokenManager; - private String authToken; + private final String authToken; private final ResteasyWebTarget target; private final ResteasyClient client; - private static final boolean authServerSslRequired = Boolean.parseBoolean(System.getProperty("auth.server.ssl.required")); - + Keycloak(String serverUrl, String realm, String username, String password, String clientId, String clientSecret, String grantType, ResteasyClient resteasyClient, String authtoken) { config = new Config(serverUrl, realm, username, password, clientId, clientSecret, grantType); client = resteasyClient != null ? resteasyClient : new ResteasyClientBuilder().connectionPoolSize(10).build(); @@ -84,20 +81,6 @@ public class Keycloak { return new Keycloak(serverUrl, realm, username, password, clientId, clientSecret, PASSWORD, clientBuilder.build(), null); } - private static ResteasyClientBuilder newResteasyClientBuilder() { - if (authServerSslRequired) { - // Disable PKIX path validation errors when running tests using SSL - HostnameVerifier hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostName, SSLSession session) { - return true; - } - }; - return new ResteasyClientBuilder().disableTrustManager().hostnameVerifier(hostnameVerifier); - } - return new ResteasyClientBuilder(); - } - public static Keycloak getInstance(String serverUrl, String realm, String username, String password, String clientId, String clientSecret) { return new Keycloak(serverUrl, realm, username, password, clientId, clientSecret, PASSWORD, null, null); } @@ -142,6 +125,7 @@ public class Keycloak { /** * Closes the underlying client. After calling this method, this Keycloak instance cannot be reused. */ + @Override public void close() { client.close(); } diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java index 96802df690..d0b5f5964f 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java @@ -66,6 +66,8 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; +import javax.persistence.criteria.Expression; +import javax.persistence.criteria.Path; /** * @author Bill Burke @@ -752,8 +754,9 @@ public class JpaUserProvider implements UserProvider, UserCredentialStore { Root from1 = subquery1.from(ResourceEntity.class); List subs = new ArrayList<>(); - - subs.add(builder.like(from1.get("name"), builder.concat("group.resource.", from.get("groupId")))); + + Expression groupId = from.get("groupId"); + subs.add(builder.like(from1.get("name"), builder.concat("group.resource.", groupId))); subquery1.where(subs.toArray(new Predicate[subs.size()])); diff --git a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/rest/TestingResourceProvider.java b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/rest/TestingResourceProvider.java index 7e936278d8..c6a7aa6bc8 100644 --- a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/rest/TestingResourceProvider.java +++ b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/rest/TestingResourceProvider.java @@ -439,7 +439,7 @@ public class TestingResourceProvider implements RealmResourceProvider { if (realmId != null) { query.realm(realmId); - }; + } if (authRealm != null) { query.authRealm(authRealm); @@ -548,7 +548,9 @@ public class TestingResourceProvider implements RealmResourceProvider { @Produces(MediaType.APPLICATION_JSON) public String getSSOCookieValue() { Map cookies = request.getHttpHeaders().getCookies(); - return cookies.get(AuthenticationManager.KEYCLOAK_IDENTITY_COOKIE).getValue(); + Cookie cookie = cookies.get(AuthenticationManager.KEYCLOAK_IDENTITY_COOKIE); + if (cookie == null) return null; + return cookie.getValue(); } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/ProfileAssume.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/ProfileAssume.java index 3aaf443756..f0e79d27b3 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/ProfileAssume.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/ProfileAssume.java @@ -42,13 +42,11 @@ public class ProfileAssume { boolean adapterCompatTesting = Boolean.parseBoolean(System.getProperty("testsuite.adapter.compat.testing")); String authServerContextRoot = "http://" + host + ":" + port; - try { - Keycloak adminClient = AdminClientUtil.createAdminClient(adapterCompatTesting, authServerContextRoot); + try (Keycloak adminClient = AdminClientUtil.createAdminClient(adapterCompatTesting, authServerContextRoot)) { ProfileInfoRepresentation profileInfo = adminClient.serverInfo().getInfo().getProfileInfo(); profile = profileInfo.getName(); List disabled = profileInfo.getDisabledFeatures(); disabledFeatures = Collections.unmodifiableSet(new HashSet<>(disabled)); - adminClient.close(); } catch (Exception e) { throw new RuntimeException("Failed to obtain profile / features info from serverinfo endpoint of " + authServerContextRoot, e); } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/ModelTestExecutor.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/ModelTestExecutor.java index 30f6bf53f7..145233ba2f 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/ModelTestExecutor.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/ModelTestExecutor.java @@ -54,8 +54,8 @@ public class ModelTestExecutor extends LocalTestExecuter { // Model test - wrap the call inside the TestContext ctx = testContext.get(); KeycloakTestingClient testingClient = ctx.getTestingClient(); - testingClient.server().runModelTest(testMethod.getDeclaringClass().getName(), testMethod.getName()); + result.setStatus(TestResult.Status.PASSED); } catch (Throwable e) { result.setStatus(TestResult.Status.FAILED); diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/client/KeycloakTestingClient.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/client/KeycloakTestingClient.java index aa6cc0d707..e9254de0a8 100755 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/client/KeycloakTestingClient.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/client/KeycloakTestingClient.java @@ -25,31 +25,27 @@ import org.keycloak.testsuite.client.resources.TestExampleCompanyResource; import org.keycloak.testsuite.client.resources.TestSamlApplicationResource; import org.keycloak.testsuite.client.resources.TestingResource; import org.keycloak.testsuite.runonserver.*; +import org.keycloak.testsuite.util.AdminClientUtil; import org.keycloak.util.JsonSerialization; -import javax.net.ssl.HostnameVerifier; - /** * @author Marko Strukelj */ -public class KeycloakTestingClient { +public class KeycloakTestingClient implements AutoCloseable { private final ResteasyWebTarget target; private final ResteasyClient client; - private static final boolean authServerSslRequired = Boolean.parseBoolean(System.getProperty("auth.server.ssl.required")); KeycloakTestingClient(String serverUrl, ResteasyClient resteasyClient) { - client = resteasyClient != null ? resteasyClient : newResteasyClientBuilder().connectionPoolSize(10).build(); - target = client.target(serverUrl); - } - - private static ResteasyClientBuilder newResteasyClientBuilder() { - if (authServerSslRequired) { - // Disable PKIX path validation errors when running tests using SSL - HostnameVerifier hostnameVerifier = (hostName, session) -> true; - return new ResteasyClientBuilder().disableTrustManager().hostnameVerifier(hostnameVerifier); + if (resteasyClient != null) { + client = resteasyClient; + } else { + ResteasyClientBuilder resteasyClientBuilder = new ResteasyClientBuilder(); + resteasyClientBuilder.connectionPoolSize(10); + resteasyClientBuilder.httpEngine(AdminClientUtil.getCustomClientHttpEngine(resteasyClientBuilder, 10)); + client = resteasyClientBuilder.build(); } - return new ResteasyClientBuilder(); + target = client.target(serverUrl); } public static KeycloakTestingClient getInstance(String serverUrl) { @@ -84,7 +80,7 @@ public class KeycloakTestingClient { public class Server { - private String realm; + private final String realm; public Server(String realm) { this.realm = realm; @@ -150,6 +146,7 @@ public class KeycloakTestingClient { } + @Override public void close() { client.close(); } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/AdminClientUtil.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/AdminClientUtil.java index d18905a27a..cdb9044266 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/AdminClientUtil.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/AdminClientUtil.java @@ -28,12 +28,20 @@ import javax.net.ssl.SSLContext; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; +import javax.net.ssl.HostnameVerifier; +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.conn.HttpClientConnectionManager; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.ssl.SSLContexts; +import org.jboss.resteasy.client.jaxrs.ClientHttpEngine; +import org.jboss.resteasy.client.jaxrs.ClientHttpEngineBuilder43; +import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.plugins.providers.jackson.ResteasyJackson2Provider; import org.keycloak.admin.client.Keycloak; +import org.keycloak.admin.client.KeycloakBuilder; import org.keycloak.models.Constants; import org.keycloak.testsuite.arquillian.AuthServerTestEnricher; -import org.keycloak.testsuite.arquillian.SuiteContext; import static org.keycloak.testsuite.auth.page.AuthRealm.ADMIN; import static org.keycloak.testsuite.auth.page.AuthRealm.MASTER; @@ -51,29 +59,40 @@ public class AdminClientUtil { } public static Keycloak createAdminClient(boolean ignoreUnknownProperties, String authServerContextRoot, String realmName, String username, String password, String clientId, String clientSecret) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException { - SSLContext ssl = null; + ResteasyClientBuilder resteasyClientBuilder = new ResteasyClientBuilder(); + if ("true".equals(System.getProperty("auth.server.ssl.required"))) { File trustore = new File(PROJECT_BUILD_DIRECTORY, "dependency/keystore/keycloak.truststore"); - ssl = getSSLContextWithTrustore(trustore, "secret"); + resteasyClientBuilder.sslContext(getSSLContextWithTrustore(trustore, "secret")); System.setProperty("javax.net.ssl.trustStore", trustore.getAbsolutePath()); } - ResteasyJackson2Provider jacksonProvider = null; - // We need to ignore unknown JSON properties e.g. in the adapter configuration representation // during adapter backward compatibility testing if (ignoreUnknownProperties) { // We need to use anonymous class to avoid the following error from RESTEasy: // Provider class org.jboss.resteasy.plugins.providers.jackson.ResteasyJackson2Provider is already registered. 2nd registration is being ignored. - jacksonProvider = new ResteasyJackson2Provider() {}; + ResteasyJackson2Provider jacksonProvider = new ResteasyJackson2Provider() {}; ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); jacksonProvider.setMapper(objectMapper); + resteasyClientBuilder.register(jacksonProvider, 100); } - return Keycloak.getInstance(authServerContextRoot + "/auth", - realmName, username, password, clientId, clientSecret, ssl, jacksonProvider); + resteasyClientBuilder + .hostnameVerification(ResteasyClientBuilder.HostnameVerificationPolicy.WILDCARD) + .connectionPoolSize(10) + .httpEngine(getCustomClientHttpEngine(resteasyClientBuilder, 1)); + + return KeycloakBuilder.builder() + .serverUrl(authServerContextRoot + "/auth") + .realm(realmName) + .username(username) + .password(password) + .clientId(clientId) + .clientSecret(clientSecret) + .resteasyClient(resteasyClientBuilder.build()).build(); } public static Keycloak createAdminClient() throws Exception { @@ -95,4 +114,35 @@ public class AdminClientUtil { return theContext; } + public static ClientHttpEngine getCustomClientHttpEngine(ResteasyClientBuilder resteasyClientBuilder, int validateAfterInactivity) { + return new CustomClientHttpEngineBuilder43(validateAfterInactivity).resteasyClientBuilder(resteasyClientBuilder).build(); + } + + /** + * Adds a possibility to pass validateAfterInactivity parameter into underlying ConnectionManager. The parameter affects how + * long the connection is being used without testing if it became stale, default value is 2000ms + */ + private static class CustomClientHttpEngineBuilder43 extends ClientHttpEngineBuilder43 { + + private final int validateAfterInactivity; + + private CustomClientHttpEngineBuilder43(int validateAfterInactivity) { + this.validateAfterInactivity = validateAfterInactivity; + } + + @Override + protected ClientHttpEngine createEngine(final HttpClientConnectionManager cm, final RequestConfig.Builder rcBuilder, + final HttpHost defaultProxy, final int responseBufferSize, final HostnameVerifier verifier, final SSLContext theContext) { + + if (cm instanceof PoolingHttpClientConnectionManager) { + PoolingHttpClientConnectionManager pcm = (PoolingHttpClientConnectionManager) cm; + pcm.setValidateAfterInactivity(validateAfterInactivity); + + return super.createEngine(pcm, rcBuilder, defaultProxy, responseBufferSize, verifier, theContext); + } else { + return super.createEngine(cm, rcBuilder, defaultProxy, responseBufferSize, verifier, theContext); + } + } + } + } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/ContainerAssume.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/ContainerAssume.java index c5f069458e..af4a38bf56 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/ContainerAssume.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/ContainerAssume.java @@ -38,16 +38,6 @@ public class ContainerAssume { AuthServerTestEnricher.AUTH_SERVER_CLUSTER_PROPERTY), AuthServerTestEnricher.AUTH_SERVER_CLUSTER); } - public static void assumeNotAppServerUndertow() { - log.warn("TODO: Not stable on app-server-undertow. " - + "It throws: KC-SERVICES0057: Logout for client '${CLIENT_NAME}' failed\n" - + "org.apache.http.NoHttpResponseException: localhost:8280 failed to respond"); - Assume.assumeFalse("Not stable on app-server-undertow. " - + "It throws: KC-SERVICES0057: Logout for client '${CLIENT_NAME}' failed\n" - + "org.apache.http.NoHttpResponseException: localhost:8280 failed to respond", - System.getProperty("app.server", "undertow").equals("undertow")); - } - public static void assumeNotAppServerFuse6() { Assume.assumeFalse("The test doesn't work on " + fuse6, fuse6.equals(System.getProperty("app.server"))); } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/OAuthClient.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/OAuthClient.java index 296448eb75..d0f83cc58f 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/OAuthClient.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/OAuthClient.java @@ -71,6 +71,7 @@ import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.security.KeyStore; import java.security.PublicKey; import java.util.Collections; @@ -725,7 +726,7 @@ public class OAuthClient { public Map getCurrentQuery() { Map m = new HashMap<>(); - List pairs = URLEncodedUtils.parse(getCurrentUri(), Charset.forName("UTF-8")); + List pairs = URLEncodedUtils.parse(getCurrentUri(), "UTF-8"); for (NameValuePair p : pairs) { m.put(p.getName(), p.getValue()); } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/SamlClient.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/SamlClient.java index 7256be9ab7..5a663993be 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/SamlClient.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/SamlClient.java @@ -49,7 +49,6 @@ import javax.ws.rs.core.Response; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; -import java.nio.charset.Charset; import java.security.PrivateKey; import java.security.PublicKey; import java.util.Arrays; @@ -296,7 +295,7 @@ public class SamlClient { * @return */ public static SAMLDocumentHolder extractSamlResponseFromRedirect(String responseUri) { - List params = URLEncodedUtils.parse(URI.create(responseUri), Charset.forName("UTF-8")); + List params = URLEncodedUtils.parse(URI.create(responseUri), "UTF-8"); String samlDoc = null; for (NameValuePair param : params) { diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/TokenSignatureUtil.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/TokenSignatureUtil.java index 087b9a2d8c..ee436ddb4f 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/TokenSignatureUtil.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/TokenSignatureUtil.java @@ -100,10 +100,10 @@ public class TokenSignatureUtil { rep.getConfig().putSingle("priority", Long.toString(priority)); rep.getConfig().putSingle(ECDSA_ELLIPTIC_CURVE_KEY, ecNistRep); - Response response = adminClient.realm(realm).components().add(rep); - String id = ApiUtil.getCreatedId(response); - testContext.getOrCreateCleanup(realm).addComponentId(id); - response.close(); + try (Response response = adminClient.realm(realm).components().add(rep)) { + String id = ApiUtil.getCreatedId(response); + testContext.getOrCreateCleanup(realm).addComponentId(id); + } } private static ComponentRepresentation createKeyRep(String name, String providerId) { diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/saml/ModifySamlResponseStepBuilder.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/saml/ModifySamlResponseStepBuilder.java index d97f057a01..5c80786416 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/saml/ModifySamlResponseStepBuilder.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/saml/ModifySamlResponseStepBuilder.java @@ -26,7 +26,6 @@ import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; -import java.nio.charset.Charset; import java.util.Iterator; import java.util.LinkedList; import java.util.List; @@ -126,7 +125,7 @@ public class ModifySamlResponseStepBuilder extends SamlDocumentStepBuilder params = URLEncodedUtils.parse(locationUri, Charset.forName("UTF-8")); + List params = URLEncodedUtils.parse(locationUri, "UTF-8"); for (Iterator it = params.iterator(); it.hasNext();) { NameValuePair param = it.next(); if ("SAMLResponse".equals(param.getName()) || "SAMLRequest".equals(param.getName())) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/example/authorization/AbstractPhotozExampleAdapterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/example/authorization/AbstractPhotozExampleAdapterTest.java index 894d6b391c..85b927250e 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/example/authorization/AbstractPhotozExampleAdapterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/example/authorization/AbstractPhotozExampleAdapterTest.java @@ -20,7 +20,6 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.LaxRedirectStrategy; -import org.hamcrest.CoreMatchers; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.graphene.page.Page; import org.jboss.arquillian.test.api.ArquillianResource; @@ -52,7 +51,6 @@ import org.keycloak.testsuite.adapter.page.PhotozClientAuthzTestApp; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.arquillian.AppServerTestEnricher; import org.keycloak.testsuite.auth.page.login.OAuthGrant; -import org.keycloak.testsuite.util.ContainerAssume; import org.keycloak.testsuite.util.DroneUtils; import org.keycloak.testsuite.util.JavascriptBrowser; import org.keycloak.testsuite.util.javascript.JavascriptTestExecutorWithAuthorization; @@ -227,8 +225,6 @@ public abstract class AbstractPhotozExampleAdapterTest extends AbstractPhotozJav @Test public void testOnlyOwnerCanDeleteAlbum() throws Exception { - ContainerAssume.assumeNotAppServerUndertow(); - loginToClientPage(aliceUser); clientPage.createAlbum(ALICE_ALBUM_NAME); @@ -301,8 +297,6 @@ public abstract class AbstractPhotozExampleAdapterTest extends AbstractPhotozJav @Test public void testAdminWithoutPermissionsToTypedResource() throws Exception { - ContainerAssume.assumeNotAppServerUndertow(); - loginToClientPage(aliceUser); clientPage.createAlbum(ALICE_ALBUM_NAME); @@ -538,8 +532,6 @@ public abstract class AbstractPhotozExampleAdapterTest extends AbstractPhotozJav @Test public void testInheritPermissionFromResourceParent() throws Exception { - ContainerAssume.assumeNotAppServerUndertow(); - loginToClientPage(aliceUser); final String RESOURCE_NAME = "My-Resource-Instance"; diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/DemoServletsAdapterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/DemoServletsAdapterTest.java index 1292d30370..b2ac9abae1 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/DemoServletsAdapterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/DemoServletsAdapterTest.java @@ -20,14 +20,11 @@ import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; -import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.ws.rs.client.Client; @@ -783,7 +780,7 @@ public class DemoServletsAdapterTest extends AbstractServletsAdapterTest { private static Map getQueryFromUrl(String url) { try { - return URLEncodedUtils.parse(new URI(url), StandardCharsets.UTF_8).stream() + return URLEncodedUtils.parse(new URI(url), "UTF-8").stream() .collect(Collectors.toMap(p -> p.getName(), p -> p.getValue())); } catch (URISyntaxException e) { return null; diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SessionServletAdapterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SessionServletAdapterTest.java index 20cadaebb6..c70c74c158 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SessionServletAdapterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SessionServletAdapterTest.java @@ -35,7 +35,6 @@ import org.keycloak.testsuite.auth.page.account.Sessions; import org.keycloak.testsuite.auth.page.login.Login; import org.keycloak.testsuite.arquillian.annotation.AppServerContainer; import org.keycloak.testsuite.arquillian.containers.ContainerConstants; -import org.keycloak.testsuite.util.ContainerAssume; import org.keycloak.testsuite.util.SecondBrowser; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; @@ -129,7 +128,6 @@ public class SessionServletAdapterTest extends AbstractServletsAdapterTest { //KEYCLOAK-741 @Test public void testSessionInvalidatedAfterFailedRefresh() { - ContainerAssume.assumeNotAppServerUndertow(); RealmRepresentation testRealmRep = testRealmResource().toRepresentation(); ClientResource sessionPortalRes = null; for (ClientRepresentation clientRep : testRealmResource().clients().findAll()) { @@ -187,7 +185,6 @@ public class SessionServletAdapterTest extends AbstractServletsAdapterTest { //KEYCLOAK-1216 @Test public void testAccountManagementSessionsLogout() { - ContainerAssume.assumeNotAppServerUndertow(); // login as bburke loginAndCheckSession(testRealmLoginPage); testRealmSessions.navigateTo(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/UserStorageConsentTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/UserStorageConsentTest.java index 788587656e..ffdc027823 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/UserStorageConsentTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/UserStorageConsentTest.java @@ -55,7 +55,6 @@ import org.keycloak.testsuite.auth.page.login.PageWithLoginUrl; import org.keycloak.testsuite.federation.UserMapStorageFactory; import org.keycloak.testsuite.pages.ConsentPage; import org.keycloak.testsuite.runonserver.RunOnServerDeployment; -import org.keycloak.testsuite.util.ContainerAssume; import static org.keycloak.testsuite.arquillian.DeploymentTargetModifier.AUTH_SERVER_CURRENT; import static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlEquals; @@ -150,8 +149,6 @@ public class UserStorageConsentTest extends AbstractServletsAdapterTest { */ @Test public void testLogin() throws Exception { - ContainerAssume.assumeNotAppServerUndertow(); - testingClient.server().run(UserStorageConsentTest::setupConsent); UserRepresentation memuser = new UserRepresentation(); memuser.setUsername("memuser"); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/AdminSignatureAlgorithmTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/AdminSignatureAlgorithmTest.java index be7b7d0846..5b065ee0f0 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/AdminSignatureAlgorithmTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/AdminSignatureAlgorithmTest.java @@ -50,19 +50,19 @@ public class AdminSignatureAlgorithmTest extends AbstractKeycloakTest { TokenSignatureUtil.registerKeyProvider("master", "P-256", adminClient, testContext); TokenSignatureUtil.changeRealmTokenSignatureProvider("master", adminClient, Algorithm.ES256); - Keycloak adminClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), suiteContext.getAuthServerInfo().getContextRoot().toString()); + try (Keycloak adminClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), suiteContext.getAuthServerInfo().getContextRoot().toString())) { + AccessTokenResponse accessToken = adminClient.tokenManager().getAccessToken(); + TokenVerifier verifier = TokenVerifier.create(accessToken.getToken(), AccessToken.class); + assertEquals(Algorithm.ES256, verifier.getHeader().getAlgorithm().name()); - AccessTokenResponse accessToken = adminClient.tokenManager().getAccessToken(); - TokenVerifier verifier = TokenVerifier.create(accessToken.getToken(), AccessToken.class); - assertEquals(Algorithm.ES256, verifier.getHeader().getAlgorithm().name()); + assertNotNull(adminClient.realms().findAll()); + + String whoAmiUrl = suiteContext.getAuthServerInfo().getContextRoot().toString() + "/auth/admin/master/console/whoami"; - assertNotNull(adminClient.realms().findAll()); - - String whoAmiUrl = suiteContext.getAuthServerInfo().getContextRoot().toString() + "/auth/admin/master/console/whoami"; - - JsonNode jsonNode = SimpleHttp.doGet(whoAmiUrl, client).auth(accessToken.getToken()).asJson(); - assertNotNull(jsonNode.get("realm")); - assertNotNull(jsonNode.get("userId")); + JsonNode jsonNode = SimpleHttp.doGet(whoAmiUrl, client).auth(accessToken.getToken()).asJson(); + assertNotNull(jsonNode.get("realm")); + assertNotNull(jsonNode.get("userId")); + } } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/FineGrainAdminUnitTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/FineGrainAdminUnitTest.java index 9c18c28db3..ec48d451f2 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/FineGrainAdminUnitTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/FineGrainAdminUnitTest.java @@ -427,35 +427,36 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest { // test configure client { - Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), - TEST, "clientConfigurer", "password", Constants.ADMIN_CLI_CLIENT_ID, null); - client.setAdminUrl("http://nowhere"); - realmClient.realm(TEST).clients().get(client.getId()).update(client); - client.setFullScopeAllowed(true); - try { + try (Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), + TEST, "clientConfigurer", "password", Constants.ADMIN_CLI_CLIENT_ID, null)) { + client.setAdminUrl("http://nowhere"); realmClient.realm(TEST).clients().get(client.getId()).update(client); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(403, e.getResponse().getStatus()); + client.setFullScopeAllowed(true); + try { + realmClient.realm(TEST).clients().get(client.getId()).update(client); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertEquals(403, e.getResponse().getStatus()); - } - client.setFullScopeAllowed(false); - realmClient.realm(TEST).clients().get(client.getId()).update(client); + } + client.setFullScopeAllowed(false); + realmClient.realm(TEST).clients().get(client.getId()).update(client); - try { - realmClient.realm(TEST).clients().get(client.getId()).addDefaultClientScope(scope.getId()); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(403, e.getResponse().getStatus()); + try { + realmClient.realm(TEST).clients().get(client.getId()).addDefaultClientScope(scope.getId()); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertEquals(403, e.getResponse().getStatus()); - } + } - try { - realmClient.realm(TEST).clients().get(client.getId()).getScopeMappings().realmLevel().add(realmRoleSet); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(403, e.getResponse().getStatus()); + try { + realmClient.realm(TEST).clients().get(client.getId()).getScopeMappings().realmLevel().add(realmRoleSet); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertEquals(403, e.getResponse().getStatus()); + } } } @@ -463,163 +464,159 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest { if (!IMPERSONATION_DISABLED) { Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), TEST, "nomap-admin", "password", Constants.ADMIN_CLI_CLIENT_ID, null); - realmClient.realm(TEST).users().get(user1.getId()).impersonate(); - realmClient.close(); // just in case of cookie settings - realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), - TEST, "nomap-admin", "password", Constants.ADMIN_CLI_CLIENT_ID, null); try { - realmClient.realm(TEST).users().get(anotherAdmin.getId()).impersonate(); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(403, e.getResponse().getStatus()); - + realmClient.realm(TEST).users().get(user1.getId()).impersonate(); + realmClient.close(); // just in case of cookie settings + realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), + TEST, "nomap-admin", "password", Constants.ADMIN_CLI_CLIENT_ID, null); + try { + realmClient.realm(TEST).users().get(anotherAdmin.getId()).impersonate(); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertEquals(403, e.getResponse().getStatus()); + } + } finally { + realmClient.close(); } - } { - Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), - TEST, "authorized", "password", Constants.ADMIN_CLI_CLIENT_ID, null); - realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().add(realmRoleSet); - List roles = adminClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().listAll(); - Assert.assertTrue(roles.stream().anyMatch((r) -> { - return r.getName().equals("realm-role"); - })); - realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().remove(realmRoleSet); - roles = adminClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().listAll(); - Assert.assertTrue(roles.stream().noneMatch((r) -> { - return r.getName().equals("realm-role"); - })); + try (Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), + TEST, "authorized", "password", Constants.ADMIN_CLI_CLIENT_ID, null)) { + realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().add(realmRoleSet); + List roles = adminClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().listAll(); + Assert.assertTrue(roles.stream().anyMatch((r) -> { + return r.getName().equals("realm-role"); + })); + realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().remove(realmRoleSet); + roles = adminClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().listAll(); + Assert.assertTrue(roles.stream().noneMatch((r) -> { + return r.getName().equals("realm-role"); + })); - realmClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).add(clientRoleSet); - roles = adminClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).listAll(); - Assert.assertTrue(roles.stream().anyMatch((r) -> { - return r.getName().equals("client-role"); - })); - realmClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).remove(clientRoleSet); - roles = adminClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).listAll(); - Assert.assertTrue(roles.stream().noneMatch((r) -> { - return r.getName().equals("client-role"); - })); - realmClient.close(); + realmClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).add(clientRoleSet); + roles = adminClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).listAll(); + Assert.assertTrue(roles.stream().anyMatch((r) -> { + return r.getName().equals("client-role"); + })); + realmClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).remove(clientRoleSet); + roles = adminClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).listAll(); + Assert.assertTrue(roles.stream().noneMatch((r) -> { + return r.getName().equals("client-role"); + })); + } } { - Keycloak realmClient= AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), - TEST, "authorizedComposite", "password", Constants.ADMIN_CLI_CLIENT_ID, null); - realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().add(realmRoleSet); - List roles = adminClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().listAll(); - Assert.assertTrue(roles.stream().anyMatch((r) -> { - return r.getName().equals("realm-role"); - })); - realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().remove(realmRoleSet); - roles = adminClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().listAll(); - Assert.assertTrue(roles.stream().noneMatch((r) -> { - return r.getName().equals("realm-role"); - })); + try (Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), + TEST, "authorizedComposite", "password", Constants.ADMIN_CLI_CLIENT_ID, null)) { + realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().add(realmRoleSet); + List roles = adminClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().listAll(); + Assert.assertTrue(roles.stream().anyMatch((r) -> { + return r.getName().equals("realm-role"); + })); + realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().remove(realmRoleSet); + roles = adminClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().listAll(); + Assert.assertTrue(roles.stream().noneMatch((r) -> { + return r.getName().equals("realm-role"); + })); - realmClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).add(clientRoleSet); - roles = adminClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).listAll(); - Assert.assertTrue(roles.stream().anyMatch((r) -> { - return r.getName().equals("client-role"); - })); - realmClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).remove(clientRoleSet); - roles = adminClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).listAll(); - Assert.assertTrue(roles.stream().noneMatch((r) -> { - return r.getName().equals("client-role"); - })); + realmClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).add(clientRoleSet); + roles = adminClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).listAll(); + Assert.assertTrue(roles.stream().anyMatch((r) -> { + return r.getName().equals("client-role"); + })); + realmClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).remove(clientRoleSet); + roles = adminClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).listAll(); + Assert.assertTrue(roles.stream().noneMatch((r) -> { + return r.getName().equals("client-role"); + })); + } } { - Keycloak realmClient= AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), - TEST, "unauthorized", "password", Constants.ADMIN_CLI_CLIENT_ID, null); - try { + try (Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), + TEST, "unauthorized", "password", Constants.ADMIN_CLI_CLIENT_ID, null)) { realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().add(realmRoleSet); Assert.fail("should fail with forbidden exception"); } catch (ClientErrorException e) { Assert.assertEquals(403, e.getResponse().getStatus()); - } } { - Keycloak realmClient= AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), - TEST, "unauthorizedMapper", "password", Constants.ADMIN_CLI_CLIENT_ID, null); - try { + try (Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), + TEST, "unauthorizedMapper", "password", Constants.ADMIN_CLI_CLIENT_ID, null)) { realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().add(realmRoleSet); Assert.fail("should fail with forbidden exception"); } catch (ClientErrorException e) { Assert.assertEquals(403, e.getResponse().getStatus()); - } } { - Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), - TEST, "groupManager", "password", Constants.ADMIN_CLI_CLIENT_ID, null); - List roles = null; - realmClient.realm(TEST).users().get(groupMember.getId()).roles().clientLevel(client.getId()).add(clientRoleSet); - roles = realmClient.realm(TEST).users().get(groupMember.getId()).roles().clientLevel(client.getId()).listAll(); - Assert.assertTrue(roles.stream().anyMatch((r) -> { - return r.getName().equals("client-role"); - })); - realmClient.realm(TEST).users().get(groupMember.getId()).roles().clientLevel(client.getId()).remove(clientRoleSet); - - roles = realmClient.realm(TEST).users().get(groupMember.getId()).roles().realmLevel().listAvailable(); - Assert.assertEquals(1, roles.size()); - realmClient.realm(TEST).users().get(groupMember.getId()).roles().realmLevel().add(realmRoleSet); - realmClient.realm(TEST).users().get(groupMember.getId()).roles().realmLevel().remove(realmRoleSet); - try { - realmClient.realm(TEST).users().get(groupMember.getId()).roles().realmLevel().add(realmRole2Set); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(403, e.getResponse().getStatus()); + try (Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), + TEST, "groupManager", "password", Constants.ADMIN_CLI_CLIENT_ID, null)) { + realmClient.realm(TEST).users().get(groupMember.getId()).roles().clientLevel(client.getId()).add(clientRoleSet); + List roles = realmClient.realm(TEST).users().get(groupMember.getId()).roles().clientLevel(client.getId()).listAll(); + Assert.assertTrue(roles.stream().anyMatch((r) -> { + return r.getName().equals("client-role"); + })); + realmClient.realm(TEST).users().get(groupMember.getId()).roles().clientLevel(client.getId()).remove(clientRoleSet); + roles = realmClient.realm(TEST).users().get(groupMember.getId()).roles().realmLevel().listAvailable(); + Assert.assertEquals(1, roles.size()); + realmClient.realm(TEST).users().get(groupMember.getId()).roles().realmLevel().add(realmRoleSet); + realmClient.realm(TEST).users().get(groupMember.getId()).roles().realmLevel().remove(realmRoleSet); + try { + realmClient.realm(TEST).users().get(groupMember.getId()).roles().realmLevel().add(realmRole2Set); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertEquals(403, e.getResponse().getStatus()); + } + try { + realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().add(realmRoleSet); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertEquals(403, e.getResponse().getStatus()); + } } - try { - realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().add(realmRoleSet); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(403, e.getResponse().getStatus()); - - } - } // test client.mapRoles { - Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), - TEST, "clientMapper", "password", Constants.ADMIN_CLI_CLIENT_ID, null); - List roles = null; - roles = realmClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).listAll(); - Assert.assertTrue(roles.isEmpty()); - realmClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).add(clientRoleSet); - roles = realmClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).listAll(); - Assert.assertTrue(roles.stream().anyMatch((r) -> { - return r.getName().equals("client-role"); - })); - roles = realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().listAvailable(); - Assert.assertTrue(roles.isEmpty()); - try { - realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().add(realmRoleSet); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(403, e.getResponse().getStatus()); - + try (Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), + TEST, "clientMapper", "password", Constants.ADMIN_CLI_CLIENT_ID, null)) { + List roles = realmClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).listAll(); + Assert.assertTrue(roles.isEmpty()); + realmClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).add(clientRoleSet); + roles = realmClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).listAll(); + Assert.assertTrue(roles.stream().anyMatch((r) -> { + return r.getName().equals("client-role"); + })); + roles = realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().listAvailable(); + Assert.assertTrue(roles.isEmpty()); + try { + realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().add(realmRoleSet); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertEquals(403, e.getResponse().getStatus()); + } } } // KEYCLOAK-5878 { - Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), - TEST, "groupViewer", "password", Constants.ADMIN_CLI_CLIENT_ID, null); - // Should only return the list of users that belong to "top" group - List queryUsers = realmClient.realm(TEST).users().list(); - Assert.assertEquals(queryUsers.size(), 1); - Assert.assertEquals("groupmember", queryUsers.get(0).getUsername()); - for (UserRepresentation user : queryUsers) { - System.out.println(user.getUsername()); + try (Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), + TEST, "groupViewer", "password", Constants.ADMIN_CLI_CLIENT_ID, null)) { + // Should only return the list of users that belong to "top" group + List queryUsers = realmClient.realm(TEST).users().list(); + Assert.assertEquals(queryUsers.size(), 1); + Assert.assertEquals("groupmember", queryUsers.get(0).getUsername()); + for (UserRepresentation user : queryUsers) { + System.out.println(user.getUsername()); + } } } } @@ -645,29 +642,29 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest { { - Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting()); - realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().add(realmRoleSet); - List roles = adminClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().listAll(); - Assert.assertTrue(roles.stream().anyMatch((r) -> { - return r.getName().equals("realm-role"); - })); - realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().remove(realmRoleSet); - roles = adminClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().listAll(); - Assert.assertTrue(roles.stream().noneMatch((r) -> { - return r.getName().equals("realm-role"); - })); + try (Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting())) { + realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().add(realmRoleSet); + List roles = adminClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().listAll(); + Assert.assertTrue(roles.stream().anyMatch((r) -> { + return r.getName().equals("realm-role"); + })); + realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().remove(realmRoleSet); + roles = adminClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().listAll(); + Assert.assertTrue(roles.stream().noneMatch((r) -> { + return r.getName().equals("realm-role"); + })); - realmClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).add(clientRoleSet); - roles = adminClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).listAll(); - Assert.assertTrue(roles.stream().anyMatch((r) -> { - return r.getName().equals("client-role"); - })); - realmClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).remove(clientRoleSet); - roles = adminClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).listAll(); - Assert.assertTrue(roles.stream().noneMatch((r) -> { - return r.getName().equals("client-role"); - })); - realmClient.close(); + realmClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).add(clientRoleSet); + roles = adminClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).listAll(); + Assert.assertTrue(roles.stream().anyMatch((r) -> { + return r.getName().equals("client-role"); + })); + realmClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).remove(clientRoleSet); + roles = adminClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).listAll(); + Assert.assertTrue(roles.stream().noneMatch((r) -> { + return r.getName().equals("client-role"); + })); + } } } @@ -706,21 +703,21 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest { public void testRealmWithComposites() throws Exception { testingClient.server().run(FineGrainAdminUnitTest::setup5152); - Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), - TEST, "realm-admin", "password", Constants.ADMIN_CLI_CLIENT_ID, null); + try (Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), + TEST, "realm-admin", "password", Constants.ADMIN_CLI_CLIENT_ID, null)) { + RoleRepresentation composite = new RoleRepresentation(); + composite.setName("composite"); + composite.setComposite(true); + realmClient.realm(TEST).roles().create(composite); + composite = adminClient.realm(TEST).roles().get("composite").toRepresentation(); - RoleRepresentation composite = new RoleRepresentation(); - composite.setName("composite"); - composite.setComposite(true); - realmClient.realm(TEST).roles().create(composite); - composite = adminClient.realm(TEST).roles().get("composite").toRepresentation(); + ClientRepresentation client = adminClient.realm(TEST).clients().findByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID).get(0); + RoleRepresentation viewUsers = adminClient.realm(TEST).clients().get(client.getId()).roles().get(AdminRoles.CREATE_CLIENT).toRepresentation(); - ClientRepresentation client = adminClient.realm(TEST).clients().findByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID).get(0); - RoleRepresentation viewUsers = adminClient.realm(TEST).clients().get(client.getId()).roles().get(AdminRoles.CREATE_CLIENT).toRepresentation(); - - List composites = new LinkedList<>(); - composites.add(viewUsers); - realmClient.realm(TEST).rolesById().addComposites(composite.getId(), composites); + List composites = new LinkedList<>(); + composites.add(viewUsers); + realmClient.realm(TEST).rolesById().addComposites(composite.getId(), composites); + } } // testRestEvaluationMasterRealm // testRestEvaluationMasterAdminTestRealm @@ -785,16 +782,15 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest { Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), "master", "admin", "admin", "fullScopedClient", "618268aa-51e6-4e64-93c4-3c0bc65b8171"); - - RealmRepresentation newRealm=new RealmRepresentation(); - newRealm.setRealm("anotherRealm"); - newRealm.setId("anotherRealm"); - newRealm.setEnabled(true); - realmClient.realms().create(newRealm); - - ClientRepresentation newClient = new ClientRepresentation(); - try { + RealmRepresentation newRealm=new RealmRepresentation(); + newRealm.setRealm("anotherRealm"); + newRealm.setId("anotherRealm"); + newRealm.setEnabled(true); + realmClient.realms().create(newRealm); + + ClientRepresentation newClient = new ClientRepresentation(); + newClient.setName("newClient"); newClient.setClientId("newClient"); newClient.setFullScopeAllowed(true); @@ -812,7 +808,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest { Assert.assertEquals(201, response.getStatus()); } finally { adminClient.realm("anotherRealm").remove(); - + realmClient.close(); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/IllegalAdminUpgradeTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/IllegalAdminUpgradeTest.java index e155cb5076..ee25d064f0 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/IllegalAdminUpgradeTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/IllegalAdminUpgradeTest.java @@ -21,37 +21,30 @@ import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.keycloak.admin.client.Keycloak; -import org.keycloak.admin.client.resource.ClientResource; -import org.keycloak.authorization.model.Policy; -import org.keycloak.authorization.model.ResourceServer; import org.keycloak.models.AdminRoles; import org.keycloak.models.ClientModel; import org.keycloak.models.Constants; -import org.keycloak.models.GroupModel; import org.keycloak.models.ImpersonationConstants; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.RoleModel; import org.keycloak.models.UserCredentialModel; import org.keycloak.models.UserModel; -import org.keycloak.models.utils.KeycloakModelUtils; import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.RoleRepresentation; import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.representations.idm.authorization.UserPolicyRepresentation; -import org.keycloak.services.resources.admin.permissions.AdminPermissionManagement; -import org.keycloak.services.resources.admin.permissions.AdminPermissions; import org.keycloak.testsuite.AbstractKeycloakTest; import org.keycloak.testsuite.runonserver.RunOnServerDeployment; import org.keycloak.testsuite.util.AdminClientUtil; import javax.ws.rs.ClientErrorException; -import java.util.HashSet; +import javax.ws.rs.core.Response; import java.util.LinkedList; import java.util.List; -import java.util.Set; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; import static org.keycloak.testsuite.auth.page.AuthRealm.TEST; /** @@ -76,6 +69,7 @@ public class IllegalAdminUpgradeTest extends AbstractKeycloakTest { testRealms.add(testRealmRep); } + @Override protected boolean isImportAfterEachMethod() { return true; } @@ -172,651 +166,631 @@ public class IllegalAdminUpgradeTest extends AbstractKeycloakTest { { ClientRepresentation client = realmAdminClient; - Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), - TEST, "userAdmin", "password", Constants.ADMIN_CLI_CLIENT_ID, null); - roles.clear(); - roles.add(realmManageAuthorization); - try { + try (Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), + TEST, "userAdmin", "password", Constants.ADMIN_CLI_CLIENT_ID, null)) { + roles.clear(); + roles.add(realmManageAuthorization); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmViewAuthorization); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmAdmin); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmManageClients); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmViewClients); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmManageEvents); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmViewEvents); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmManageIdentityProviders); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmViewIdentityProviders); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmManageRealm); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmViewRealm); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmImpersonate); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmManageUsers); realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - } - - roles.clear(); - roles.add(realmViewAuthorization); - try { + roles.clear(); + roles.add(realmViewUsers); realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - } - - roles.clear(); - roles.add(realmAdmin); - try { + roles.clear(); + roles.add(realmQueryUsers); realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - } - - roles.clear(); - roles.add(realmManageClients); - try { + roles.clear(); + roles.add(realmQueryGroups); realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - } - - roles.clear(); - roles.add(realmViewClients); - try { + roles.clear(); + roles.add(realmQueryClients); realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); } - - roles.clear(); - roles.add(realmManageEvents); - try { - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(realmViewEvents); - try { - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(realmManageIdentityProviders); - try { - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(realmViewIdentityProviders); - try { - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(realmManageRealm); - try { - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(realmViewRealm); - try { - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(realmImpersonate); - try { - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(realmManageUsers); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(realmViewUsers); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(realmQueryUsers); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(realmQueryGroups); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(realmQueryClients); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - realmClient.close(); } // test master user with manage_users can't assign realm's admin roles { ClientRepresentation client = realmAdminClient; - Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), - "master", "userAdmin", "password", Constants.ADMIN_CLI_CLIENT_ID, null); - roles.clear(); - roles.add(realmManageAuthorization); - try { + try (Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), + "master", "userAdmin", "password", Constants.ADMIN_CLI_CLIENT_ID, null)) { + roles.clear(); + roles.add(realmManageAuthorization); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmViewAuthorization); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmAdmin); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmManageClients); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmViewClients); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmManageEvents); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmViewEvents); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmManageIdentityProviders); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmViewIdentityProviders); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmManageRealm); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmViewRealm); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmImpersonate); + try { + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + + roles.clear(); + roles.add(realmManageUsers); realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - } - - roles.clear(); - roles.add(realmViewAuthorization); - try { + roles.clear(); + roles.add(realmViewUsers); realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - } - - roles.clear(); - roles.add(realmAdmin); - try { + roles.clear(); + roles.add(realmQueryUsers); realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - } - - roles.clear(); - roles.add(realmManageClients); - try { + roles.clear(); + roles.add(realmQueryGroups); realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - } - - roles.clear(); - roles.add(realmViewClients); - try { + roles.clear(); + roles.add(realmQueryClients); realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); } - - roles.clear(); - roles.add(realmManageEvents); - try { - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(realmViewEvents); - try { - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(realmManageIdentityProviders); - try { - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(realmViewIdentityProviders); - try { - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(realmManageRealm); - try { - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(realmViewRealm); - try { - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(realmImpersonate); - try { - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(realmManageUsers); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(realmViewUsers); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(realmQueryUsers); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(realmQueryGroups); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(realmQueryClients); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - realmClient.close(); } // test master manageUsers only admin can do with master realm admin roles { ClientRepresentation client = masterClient; - Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), - "master", "masterAdmin", "password", Constants.ADMIN_CLI_CLIENT_ID, null); - roles.clear(); - roles.add(masterManageAuthorization); - try { - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - + try (Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), + "master", "masterAdmin", "password", Constants.ADMIN_CLI_CLIENT_ID, null)) { + roles.clear(); + roles.add(masterManageAuthorization); + try { + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + roles.clear(); + roles.add(masterViewAuthorization); + try { + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + roles.clear(); + roles.add(masterManageClients); + try { + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + roles.clear(); + roles.add(masterViewClients); + try { + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + roles.clear(); + roles.add(masterManageEvents); + try { + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + roles.clear(); + roles.add(masterViewEvents); + try { + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + roles.clear(); + roles.add(masterManageIdentityProviders); + try { + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + roles.clear(); + roles.add(masterViewIdentityProviders); + try { + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + roles.clear(); + roles.add(masterManageRealm); + try { + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + roles.clear(); + roles.add(masterViewRealm); + try { + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + roles.clear(); + roles.add(masterImpersonate); + try { + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + roles.clear(); + roles.add(masterManageUsers); + try { + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + roles.clear(); + roles.add(masterViewUsers); + try { + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + roles.clear(); + roles.add(masterQueryUsers); + try { + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + roles.clear(); + roles.add(masterQueryGroups); + try { + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } + roles.clear(); + roles.add(masterQueryClients); + try { + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + Assert.fail("should fail with forbidden exception"); + } catch (ClientErrorException e) { + Assert.assertThat(Response.Status.fromStatusCode(e.getResponse().getStatus()), + is(equalTo(Response.Status.FORBIDDEN))); + } } - - roles.clear(); - roles.add(masterViewAuthorization); - try { - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(masterManageClients); - try { - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(masterViewClients); - try { - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(masterManageEvents); - try { - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(masterViewEvents); - try { - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(masterManageIdentityProviders); - try { - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(masterViewIdentityProviders); - try { - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(masterManageRealm); - try { - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(masterViewRealm); - try { - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(masterImpersonate); - try { - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(masterManageUsers); - try { - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(masterViewUsers); - try { - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(masterQueryUsers); - try { - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(masterQueryGroups); - try { - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - roles.clear(); - roles.add(masterQueryClients); - try { - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - Assert.fail("should fail with forbidden exception"); - } catch (ClientErrorException e) { - Assert.assertEquals(e.getResponse().getStatus(), 403); - - } - - realmClient.close(); } // test master admin can add all admin roles in realm { ClientRepresentation client = realmAdminClient; - Keycloak realmClient = AdminClientUtil.createAdminClient(); - roles.clear(); - roles.add(realmManageAuthorization); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(realmViewAuthorization); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(realmManageClients); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(realmViewClients); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(realmManageEvents); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(realmViewEvents); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(realmManageIdentityProviders); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(realmViewIdentityProviders); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(realmManageRealm); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(realmViewRealm); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(realmImpersonate); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(realmManageUsers); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - - roles.clear(); - roles.add(realmViewUsers); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - - roles.clear(); - roles.add(realmQueryUsers); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - - roles.clear(); - roles.add(realmQueryGroups); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(realmQueryClients); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - realmClient.close(); + try (Keycloak realmClient = AdminClientUtil.createAdminClient()) { + roles.clear(); + roles.add(realmManageAuthorization); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(realmViewAuthorization); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(realmManageClients); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(realmViewClients); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(realmManageEvents); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(realmViewEvents); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(realmManageIdentityProviders); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(realmViewIdentityProviders); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(realmManageRealm); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(realmViewRealm); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(realmImpersonate); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(realmManageUsers); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + + roles.clear(); + roles.add(realmViewUsers); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + + roles.clear(); + roles.add(realmQueryUsers); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + + roles.clear(); + roles.add(realmQueryGroups); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(realmQueryClients); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm(TEST).users().get(realmUser.getId()).roles().clientLevel(client.getId()).remove(roles); + } } // test that "admin" in master realm can assign all roles of master realm realm client admin roles { ClientRepresentation client = masterClient; - Keycloak realmClient = AdminClientUtil.createAdminClient(); - roles.clear(); - roles.add(masterManageAuthorization); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(masterViewAuthorization); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(masterManageClients); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(masterViewClients); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(masterManageEvents); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(masterViewEvents); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(masterManageIdentityProviders); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(masterViewIdentityProviders); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(masterManageRealm); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(masterViewRealm); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(masterImpersonate); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(masterManageUsers); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - - roles.clear(); - roles.add(masterViewUsers); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - - roles.clear(); - roles.add(masterQueryUsers); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - - roles.clear(); - roles.add(masterQueryGroups); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - roles.clear(); - roles.add(masterQueryClients); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); - realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); - - realmClient.close(); + try (Keycloak realmClient = AdminClientUtil.createAdminClient()) { + roles.clear(); + roles.add(masterManageAuthorization); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(masterViewAuthorization); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(masterManageClients); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(masterViewClients); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(masterManageEvents); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(masterViewEvents); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(masterManageIdentityProviders); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(masterViewIdentityProviders); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(masterManageRealm); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(masterViewRealm); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(masterImpersonate); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(masterManageUsers); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + + roles.clear(); + roles.add(masterViewUsers); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + + roles.clear(); + roles.add(masterQueryUsers); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + + roles.clear(); + roles.add(masterQueryGroups); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); + + roles.clear(); + roles.add(masterQueryClients); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).add(roles); + realmClient.realm("master").users().get(masterUser.getId()).roles().clientLevel(client.getId()).remove(roles); + } } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/ImpersonationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/ImpersonationTest.java index c1e0f493a3..1089c3f6a2 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/ImpersonationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/ImpersonationTest.java @@ -44,9 +44,9 @@ import org.keycloak.testsuite.AbstractKeycloakTest; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.arquillian.AuthServerTestEnricher; import org.keycloak.testsuite.auth.page.AuthRealm; -import org.keycloak.testsuite.client.KeycloakTestingClient; import org.keycloak.testsuite.pages.AppPage; import org.keycloak.testsuite.pages.LoginPage; +import org.keycloak.testsuite.util.AdminClientUtil; import org.keycloak.testsuite.util.ClientBuilder; import org.keycloak.testsuite.util.CredentialBuilder; import org.keycloak.testsuite.util.OAuthClient; @@ -54,6 +54,9 @@ import org.keycloak.testsuite.util.RealmBuilder; import org.keycloak.testsuite.util.UserBuilder; import javax.ws.rs.ClientErrorException; +import javax.ws.rs.client.Client; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.NewCookie; import javax.ws.rs.core.Response; import java.util.LinkedList; import java.util.List; @@ -62,6 +65,8 @@ import org.junit.Assume; import org.junit.BeforeClass; import org.openqa.selenium.Cookie; +import static org.hamcrest.Matchers.containsString; + /** * Tests Undertow Adapter * @@ -115,9 +120,10 @@ public class ImpersonationTest extends AbstractKeycloakTest { @Test public void testImpersonateByMasterImpersonator() { - Response response = adminClient.realm("master").users().create(UserBuilder.create().username("master-impersonator").build()); - String userId = ApiUtil.getCreatedId(response); - response.close(); + String userId; + try (Response response = adminClient.realm("master").users().create(UserBuilder.create().username("master-impersonator").build())) { + userId = ApiUtil.getCreatedId(response); + } UserResource user = adminClient.realm("master").users().get(userId); user.resetPassword(CredentialBuilder.create().password("password").build()); @@ -153,9 +159,10 @@ public class ImpersonationTest extends AbstractKeycloakTest { @Test public void testImpersonateByMastertBadImpersonator() { - Response response = adminClient.realm("master").users().create(UserBuilder.create().username("master-bad-impersonator").build()); - String userId = ApiUtil.getCreatedId(response); - response.close(); + String userId; + try (Response response = adminClient.realm("master").users().create(UserBuilder.create().username("master-bad-impersonator").build())) { + userId = ApiUtil.getCreatedId(response); + } adminClient.realm("master").users().get(userId).resetPassword(CredentialBuilder.create().password("password").build()); testForbiddenImpersonation("master-bad-impersonator", Config.getAdminRealm()); @@ -178,8 +185,7 @@ public class ImpersonationTest extends AbstractKeycloakTest { loginPage.assertCurrent(); // Impersonate and get SSO cookie. Setup that cookie for webDriver - String ssoCookie = testSuccessfulImpersonation("realm-admin", "test"); - driver.manage().addCookie(new Cookie(AuthenticationManager.KEYCLOAK_IDENTITY_COOKIE, ssoCookie)); + driver.manage().addCookie(testSuccessfulImpersonation("realm-admin", "test")); // Open the URL again - should be directly redirected to the app due the SSO login driver.navigate().to(loginFormUrl); @@ -191,47 +197,57 @@ public class ImpersonationTest extends AbstractKeycloakTest { // Return the SSO cookie from the impersonated session - protected String testSuccessfulImpersonation(String admin, String adminRealm) { - ResteasyClient resteasyClient = new ResteasyClientBuilder().connectionPoolSize(10).build(); + protected Cookie testSuccessfulImpersonation(String admin, String adminRealm) { + ResteasyClientBuilder resteasyClientBuilder = new ResteasyClientBuilder(); + resteasyClientBuilder.connectionPoolSize(10); + resteasyClientBuilder.httpEngine(AdminClientUtil.getCustomClientHttpEngine(resteasyClientBuilder, 10)); + ResteasyClient resteasyClient = resteasyClientBuilder.build(); // Login adminClient - Keycloak client = login(admin, adminRealm, resteasyClient); - try { + try (Keycloak client = login(admin, adminRealm, resteasyClient)) { // Impersonate - impersonate(client, admin, adminRealm); - - // Get the SSO cookie. Needs to use same RestEasyClient used by adminClient to be able to see the cookies - KeycloakTestingClient testingClient = KeycloakTestingClient.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth", resteasyClient); - String kcIdentity = testingClient.testing("test").getSSOCookieValue(); - Assert.assertNotNull(kcIdentity); - - return kcIdentity; - } finally { - resteasyClient.close(); + return impersonate(client, admin, adminRealm); } } - private void impersonate(Keycloak adminClient, String admin, String adminRealm) { - Map data = adminClient.realms().realm("test").users().get(impersonatedUserId).impersonate(); - Assert.assertNotNull(data); - Assert.assertNotNull(data.get("redirect")); + private Cookie impersonate(Keycloak adminClient, String admin, String adminRealm) { + Client httpClient = javax.ws.rs.client.ClientBuilder.newClient(); - events.expect(EventType.IMPERSONATE) - .session(AssertEvents.isUUID()) - .user(impersonatedUserId) - .detail(Details.IMPERSONATOR, admin) - .detail(Details.IMPERSONATOR_REALM, adminRealm) - .client((String) null).assertEvent(); + try (Response response = httpClient.target(OAuthClient.AUTH_SERVER_ROOT) + .path("admin") + .path("realms") + .path("test") + .path("users/" + impersonatedUserId + "/impersonation") + .request() + .header(HttpHeaders.AUTHORIZATION, "Bearer " + adminClient.tokenManager().getAccessTokenString()) + .post(null)) { + + Map data = response.readEntity(Map.class); + + Assert.assertNotNull(data); + Assert.assertNotNull(data.get("redirect")); + + events.expect(EventType.IMPERSONATE) + .session(AssertEvents.isUUID()) + .user(impersonatedUserId) + .detail(Details.IMPERSONATOR, admin) + .detail(Details.IMPERSONATOR_REALM, adminRealm) + .client((String) null).assertEvent(); + + NewCookie cookie = response.getCookies().get(AuthenticationManager.KEYCLOAK_IDENTITY_COOKIE); + + Assert.assertNotNull(cookie); + + return new Cookie(cookie.getName(), cookie.getValue(), cookie.getDomain(), cookie.getPath(), cookie.getExpiry(), cookie.isSecure(), cookie.isHttpOnly()); + } } protected void testForbiddenImpersonation(String admin, String adminRealm) { - Keycloak client = createAdminClient(adminRealm, establishClientId(adminRealm), admin); - try { + try (Keycloak client = createAdminClient(adminRealm, establishClientId(adminRealm), admin)) { client.realms().realm("test").users().get(impersonatedUserId).impersonate(); + Assert.fail("Expected ClientErrorException wasn't thrown."); } catch (ClientErrorException e) { - Assert.assertTrue(e.getMessage().indexOf("403 Forbidden") != -1); - } finally { - client.close(); + Assert.assertThat(e.getMessage(), containsString("403 Forbidden")); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/PermissionsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/PermissionsTest.java index e061d1906b..a086208ed9 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/PermissionsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/PermissionsTest.java @@ -170,13 +170,10 @@ public class PermissionsTest extends AbstractKeycloakTest { @AfterClass public static void removeTestUsers() throws Exception { - Keycloak adminClient = AdminClientUtil.createAdminClient(); - try { + try (Keycloak adminClient = AdminClientUtil.createAdminClient()) { for (UserRepresentation u : adminClient.realm("master").users().search("permissions-test-master-", 0, 100)) { adminClient.realm("master").users().get(u.getId()).remove(); } - } finally { - adminClient.close(); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/concurrency/ConcurrentLoginTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/concurrency/ConcurrentLoginTest.java index c67944bf71..4a5aadaa7b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/concurrency/ConcurrentLoginTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/concurrency/ConcurrentLoginTest.java @@ -21,7 +21,6 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; -import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -312,7 +311,7 @@ public class ConcurrentLoginTest extends AbstractConcurrencyTest { } private static Map getQueryFromUrl(String url) throws URISyntaxException { - return URLEncodedUtils.parse(new URI(url), Charset.forName("UTF-8")).stream() + return URLEncodedUtils.parse(new URI(url), "UTF-8").stream() .collect(Collectors.toMap(p -> p.getName(), p -> p.getValue())); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/event/AdminEventAuthDetailsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/event/AdminEventAuthDetailsTest.java index 3c388bb354..f08dea8059 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/event/AdminEventAuthDetailsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/event/AdminEventAuthDetailsTest.java @@ -127,9 +127,8 @@ public class AdminEventAuthDetailsTest extends AbstractAuthTest { } private void testClient(String realmName, String username, String password, String clientId, String expectedRealmId, String expectedClientUuid, String expectedUserId) { - Keycloak keycloak = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth", - realmName, username, password, clientId); - try { + try (Keycloak keycloak = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth", + realmName, username, password, clientId)) { UserRepresentation rep = UserBuilder.create().id(appUserId).username("app-user").email("foo@email.org").build(); keycloak.realm("test").users().get(appUserId).update(rep); @@ -141,8 +140,6 @@ public class AdminEventAuthDetailsTest extends AbstractAuthTest { .representation(rep) .authDetails(expectedRealmId, expectedClientUuid, expectedUserId) .assertEvent(); - } finally { - keycloak.close(); } } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/group/GroupTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/group/GroupTest.java index 085b04d3b5..a74903bb06 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/group/GroupTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/group/GroupTest.java @@ -141,16 +141,16 @@ public class GroupTest extends AbstractGroupTest { } private GroupRepresentation createGroup(RealmResource realm, GroupRepresentation group) { - Response response = realm.groups().add(group); - String groupId = ApiUtil.getCreatedId(response); - getCleanup().addGroupId(groupId); - response.close(); + try (Response response = realm.groups().add(group)) { + String groupId = ApiUtil.getCreatedId(response); + getCleanup().addGroupId(groupId); - assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.groupPath(groupId), group, ResourceType.GROUP); + assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.groupPath(groupId), group, ResourceType.GROUP); - // Set ID to the original rep - group.setId(groupId); - return group; + // Set ID to the original rep + group.setId(groupId); + return group; + } } @Test @@ -420,13 +420,12 @@ public class GroupTest extends AbstractGroupTest { UserRepresentation user = UserBuilder.create().username("user" + i).build(); usernames.add(user.getUsername()); - Response create = realm.users().create(user); - assertEquals(Status.CREATED, create.getStatusInfo()); - - String userAId = ApiUtil.getCreatedId(create); - realm.users().get(userAId).joinGroup(groupId); - - create.close(); + try (Response create = realm.users().create(user)) { + assertEquals(Status.CREATED, create.getStatusInfo()); + + String userAId = ApiUtil.getCreatedId(create); + realm.users().get(userAId).joinGroup(groupId); + } } List memberUsernames = new ArrayList<>(); @@ -463,69 +462,69 @@ public class GroupTest extends AbstractGroupTest { realm.roles().create(RoleBuilder.create().name("realm-child").build()); realm.roles().get("realm-composite").addComposites(Collections.singletonList(realm.roles().get("realm-child").toRepresentation())); - Response response = realm.clients().create(ClientBuilder.create().clientId("myclient").build()); - String clientId = ApiUtil.getCreatedId(response); - response.close(); + try (Response response = realm.clients().create(ClientBuilder.create().clientId("myclient").build())) { + String clientId = ApiUtil.getCreatedId(response); - realm.clients().get(clientId).roles().create(RoleBuilder.create().name("client-role").build()); - realm.clients().get(clientId).roles().create(RoleBuilder.create().name("client-role2").build()); - realm.clients().get(clientId).roles().create(RoleBuilder.create().name("client-composite").build()); - realm.clients().get(clientId).roles().create(RoleBuilder.create().name("client-child").build()); - realm.clients().get(clientId).roles().get("client-composite").addComposites(Collections.singletonList(realm.clients().get(clientId).roles().get("client-child").toRepresentation())); + realm.clients().get(clientId).roles().create(RoleBuilder.create().name("client-role").build()); + realm.clients().get(clientId).roles().create(RoleBuilder.create().name("client-role2").build()); + realm.clients().get(clientId).roles().create(RoleBuilder.create().name("client-composite").build()); + realm.clients().get(clientId).roles().create(RoleBuilder.create().name("client-child").build()); + realm.clients().get(clientId).roles().get("client-composite").addComposites(Collections.singletonList(realm.clients().get(clientId).roles().get("client-child").toRepresentation())); - // Roles+clients tested elsewhere - assertAdminEvents.clear(); + // Roles+clients tested elsewhere + assertAdminEvents.clear(); - GroupRepresentation group = new GroupRepresentation(); - group.setName("group"); - String groupId = createGroup(realm, group).getId(); + GroupRepresentation group = new GroupRepresentation(); + group.setName("group"); + String groupId = createGroup(realm, group).getId(); - RoleMappingResource roles = realm.groups().group(groupId).roles(); - assertEquals(0, roles.realmLevel().listAll().size()); + RoleMappingResource roles = realm.groups().group(groupId).roles(); + assertEquals(0, roles.realmLevel().listAll().size()); - // Add realm roles - List l = new LinkedList<>(); - l.add(realm.roles().get("realm-role").toRepresentation()); - l.add(realm.roles().get("realm-composite").toRepresentation()); - roles.realmLevel().add(l); - assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.groupRolesRealmRolesPath(group.getId()), l, ResourceType.REALM_ROLE_MAPPING); + // Add realm roles + List l = new LinkedList<>(); + l.add(realm.roles().get("realm-role").toRepresentation()); + l.add(realm.roles().get("realm-composite").toRepresentation()); + roles.realmLevel().add(l); + assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.groupRolesRealmRolesPath(group.getId()), l, ResourceType.REALM_ROLE_MAPPING); - // Add client roles - RoleRepresentation clientRole = realm.clients().get(clientId).roles().get("client-role").toRepresentation(); - RoleRepresentation clientComposite = realm.clients().get(clientId).roles().get("client-composite").toRepresentation(); - roles.clientLevel(clientId).add(Collections.singletonList(clientRole)); - roles.clientLevel(clientId).add(Collections.singletonList(clientComposite)); - assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.groupRolesClientRolesPath(group.getId(), clientId), Collections.singletonList(clientRole), ResourceType.CLIENT_ROLE_MAPPING); - assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.groupRolesClientRolesPath(group.getId(), clientId), Collections.singletonList(clientComposite), ResourceType.CLIENT_ROLE_MAPPING); + // Add client roles + RoleRepresentation clientRole = realm.clients().get(clientId).roles().get("client-role").toRepresentation(); + RoleRepresentation clientComposite = realm.clients().get(clientId).roles().get("client-composite").toRepresentation(); + roles.clientLevel(clientId).add(Collections.singletonList(clientRole)); + roles.clientLevel(clientId).add(Collections.singletonList(clientComposite)); + assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.groupRolesClientRolesPath(group.getId(), clientId), Collections.singletonList(clientRole), ResourceType.CLIENT_ROLE_MAPPING); + assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.groupRolesClientRolesPath(group.getId(), clientId), Collections.singletonList(clientComposite), ResourceType.CLIENT_ROLE_MAPPING); - // List realm roles - assertNames(roles.realmLevel().listAll(), "realm-role", "realm-composite"); - assertNames(roles.realmLevel().listAvailable(), "admin", "offline_access", Constants.AUTHZ_UMA_AUTHORIZATION, "user", "customer-user-premium", "realm-composite-role", "sample-realm-role", "attribute-role"); - assertNames(roles.realmLevel().listEffective(), "realm-role", "realm-composite", "realm-child"); + // List realm roles + assertNames(roles.realmLevel().listAll(), "realm-role", "realm-composite"); + assertNames(roles.realmLevel().listAvailable(), "admin", "offline_access", Constants.AUTHZ_UMA_AUTHORIZATION, "user", "customer-user-premium", "realm-composite-role", "sample-realm-role", "attribute-role"); + assertNames(roles.realmLevel().listEffective(), "realm-role", "realm-composite", "realm-child"); - // List client roles - assertNames(roles.clientLevel(clientId).listAll(), "client-role", "client-composite"); - assertNames(roles.clientLevel(clientId).listAvailable(), "client-role2"); - assertNames(roles.clientLevel(clientId).listEffective(), "client-role", "client-composite", "client-child"); + // List client roles + assertNames(roles.clientLevel(clientId).listAll(), "client-role", "client-composite"); + assertNames(roles.clientLevel(clientId).listAvailable(), "client-role2"); + assertNames(roles.clientLevel(clientId).listEffective(), "client-role", "client-composite", "client-child"); - // Get mapping representation - MappingsRepresentation all = roles.getAll(); - assertNames(all.getRealmMappings(), "realm-role", "realm-composite"); - assertEquals(1, all.getClientMappings().size()); - assertNames(all.getClientMappings().get("myclient").getMappings(), "client-role", "client-composite"); + // Get mapping representation + MappingsRepresentation all = roles.getAll(); + assertNames(all.getRealmMappings(), "realm-role", "realm-composite"); + assertEquals(1, all.getClientMappings().size()); + assertNames(all.getClientMappings().get("myclient").getMappings(), "client-role", "client-composite"); - // Remove realm role - RoleRepresentation realmRoleRep = realm.roles().get("realm-role").toRepresentation(); - roles.realmLevel().remove(Collections.singletonList(realmRoleRep)); - assertAdminEvents.assertEvent("test", OperationType.DELETE, AdminEventPaths.groupRolesRealmRolesPath(group.getId()), Collections.singletonList(realmRoleRep), ResourceType.REALM_ROLE_MAPPING); - assertNames(roles.realmLevel().listAll(), "realm-composite"); + // Remove realm role + RoleRepresentation realmRoleRep = realm.roles().get("realm-role").toRepresentation(); + roles.realmLevel().remove(Collections.singletonList(realmRoleRep)); + assertAdminEvents.assertEvent("test", OperationType.DELETE, AdminEventPaths.groupRolesRealmRolesPath(group.getId()), Collections.singletonList(realmRoleRep), ResourceType.REALM_ROLE_MAPPING); + assertNames(roles.realmLevel().listAll(), "realm-composite"); - // Remove client role - RoleRepresentation clientRoleRep = realm.clients().get(clientId).roles().get("client-role").toRepresentation(); - roles.clientLevel(clientId).remove(Collections.singletonList(clientRoleRep)); - assertAdminEvents.assertEvent("test", OperationType.DELETE, AdminEventPaths.groupRolesClientRolesPath(group.getId(), clientId), Collections.singletonList(clientRoleRep), ResourceType.CLIENT_ROLE_MAPPING); - assertNames(roles.clientLevel(clientId).listAll(), "client-composite"); + // Remove client role + RoleRepresentation clientRoleRep = realm.clients().get(clientId).roles().get("client-role").toRepresentation(); + roles.clientLevel(clientId).remove(Collections.singletonList(clientRoleRep)); + assertAdminEvents.assertEvent("test", OperationType.DELETE, AdminEventPaths.groupRolesClientRolesPath(group.getId(), clientId), Collections.singletonList(clientRoleRep), ResourceType.CLIENT_ROLE_MAPPING); + assertNames(roles.clientLevel(clientId).listAll(), "client-composite"); + } } @@ -540,12 +539,13 @@ public class GroupTest extends AbstractGroupTest { final String realmName = AuthRealm.MASTER; createUser(realmName, userName, "pwd"); - Keycloak userClient = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth", - realmName, userName, "pwd", Constants.ADMIN_CLI_CLIENT_ID); + try (Keycloak userClient = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth", + realmName, userName, "pwd", Constants.ADMIN_CLI_CLIENT_ID)) { - expectedException.expect(ClientErrorException.class); - expectedException.expectMessage(String.valueOf(Response.Status.FORBIDDEN.getStatusCode())); - userClient.realms().findAll(); // Any admin operation will do + expectedException.expect(ClientErrorException.class); + expectedException.expectMessage(String.valueOf(Response.Status.FORBIDDEN.getStatusCode())); + userClient.realms().findAll(); // Any admin operation will do + } } /** @@ -592,20 +592,20 @@ public class GroupTest extends AbstractGroupTest { String userId = createUser(realmName, userName, "pwd"); GroupRepresentation group = GroupBuilder.create().name(groupName).build(); - Response response = realm.groups().add(group); - String groupId = ApiUtil.getCreatedId(response); - response.close(); + try (Response response = realm.groups().add(group)) { + String groupId = ApiUtil.getCreatedId(response); + + RoleMappingResource mappings = realm.groups().group(groupId).roles(); + mappings.realmLevel().add(Collections.singletonList(adminRole)); - RoleMappingResource mappings = realm.groups().group(groupId).roles(); - mappings.realmLevel().add(Collections.singletonList(adminRole)); + realm.users().get(userId).joinGroup(groupId); + } + try (Keycloak userClient = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth", + realmName, userName, "pwd", Constants.ADMIN_CLI_CLIENT_ID)) { - realm.users().get(userId).joinGroup(groupId); - - Keycloak userClient = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth", - realmName, userName, "pwd", Constants.ADMIN_CLI_CLIENT_ID); - - assertThat(userClient.realms().findAll(), // Any admin operation will do - not(empty())); + assertThat(userClient.realms().findAll(), // Any admin operation will do + not(empty())); + } } @@ -626,46 +626,45 @@ public class GroupTest extends AbstractGroupTest { String userId = createUser(realmName, userName, "pwd"); GroupRepresentation group = GroupBuilder.create().name(groupName).build(); - Response response = realm.groups().add(group); - String groupId = ApiUtil.getCreatedId(response); - response.close(); + try (Response response = realm.groups().add(group)) { + String groupId = ApiUtil.getCreatedId(response); - realm.users().get(userId).joinGroup(groupId); + realm.users().get(userId).joinGroup(groupId); - RoleMappingResource mappings = realm.groups().group(groupId).roles(); - mappings.realmLevel().add(Collections.singletonList(adminRole)); + RoleMappingResource mappings = realm.groups().group(groupId).roles(); - Keycloak userClient = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth", - realmName, userName, "pwd", Constants.ADMIN_CLI_CLIENT_ID); + mappings.realmLevel().add(Collections.singletonList(adminRole)); + } + try (Keycloak userClient = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth", + realmName, userName, "pwd", Constants.ADMIN_CLI_CLIENT_ID)) { - assertThat(userClient.realms().findAll(), // Any admin operation will do - not(empty())); + assertThat(userClient.realms().findAll(), // Any admin operation will do + not(empty())); + } } @Test public void defaultMaxResults() { GroupsResource groups = adminClient.realms().realm("test").groups(); - Response response = groups.add(GroupBuilder.create().name("test").build()); - String groupId = ApiUtil.getCreatedId(response); - response.close(); + try (Response response = groups.add(GroupBuilder.create().name("test").build())) { + String groupId = ApiUtil.getCreatedId(response); - GroupResource group = groups.group(groupId); + GroupResource group = groups.group(groupId); - UsersResource users = adminClient.realms().realm("test").users(); + UsersResource users = adminClient.realms().realm("test").users(); - for (int i = 0; i < 110; i++) { - Response r = users.create(UserBuilder.create().username("test-" + i).build()); - String userId = ApiUtil.getCreatedId(r); - r.close(); + for (int i = 0; i < 110; i++) { + try (Response r = users.create(UserBuilder.create().username("test-" + i).build())) { + users.get(ApiUtil.getCreatedId(r)).joinGroup(groupId); + } + } - users.get(userId).joinGroup(groupId); + assertEquals(100, group.members(null, null).size()); + assertEquals(100, group.members().size()); + assertEquals(105, group.members(0, 105).size()); + assertEquals(110, group.members(0, 1000).size()); + assertEquals(110, group.members(-1, -2).size()); } - - assertEquals(100, group.members(null, null).size()); - assertEquals(100, group.members().size()); - assertEquals(105, group.members(0, 105).size()); - assertEquals(110, group.members(0, 1000).size()); - assertEquals(110, group.members(-1, -2).size()); } @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/realm/RealmTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/realm/RealmTest.java index 40cf19c54a..b441591343 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/realm/RealmTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/realm/RealmTest.java @@ -271,8 +271,9 @@ public class RealmTest extends AbstractAdminTest { public void loginAfterRemoveRealm() { realm.remove(); - ServerInfoResource serverInfoResource = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth", "master", "admin", "admin", Constants.ADMIN_CLI_CLIENT_ID).serverInfo(); - serverInfoResource.getInfo(); + try (Keycloak client = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth", "master", "admin", "admin", Constants.ADMIN_CLI_CLIENT_ID)) { + client.serverInfo().getInfo(); + } reCreateRealm(); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AuthzClientCredentialsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AuthzClientCredentialsTest.java index 84f0cc17a9..b24915d0e5 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AuthzClientCredentialsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AuthzClientCredentialsTest.java @@ -80,6 +80,7 @@ public class AuthzClientCredentialsTest extends AbstractAuthzTest { } @Before + @Override public void beforeAbstractKeycloakTest() throws Exception { super.beforeAbstractKeycloakTest(); testContext.getTestRealmReps().forEach(realmRepresentation -> { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/EntitlementAPITest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/EntitlementAPITest.java index c19376b6f0..8263928221 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/EntitlementAPITest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/EntitlementAPITest.java @@ -1170,8 +1170,6 @@ public class EntitlementAPITest extends AbstractAuthzTest { @Test public void testOfflineRequestingPartyToken() throws Exception { - ContainerAssume.assumeNotAuthServerUndertow(); - ClientResource client = getClient(getRealm(), RESOURCE_SERVER_TEST); AuthorizationResource authorization = client.authorization(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cookies/CookiesPathTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cookies/CookiesPathTest.java index f736bd38cf..f0cb0c9e8c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cookies/CookiesPathTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cookies/CookiesPathTest.java @@ -37,6 +37,10 @@ import java.util.Calendar; import java.util.LinkedList; import java.util.List; import java.util.Set; +import java.util.stream.Collectors; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import org.junit.After; /** * @author Martin Kanis @@ -54,6 +58,13 @@ public class CookiesPathTest extends AbstractKeycloakTest { public static final String KC_RESTART = "KC_RESTART"; + private CloseableHttpClient httpClient = null; + + @After + public void closeHttpClient() throws IOException { + if (httpClient != null) httpClient.close(); + } + @Test public void testCookiesPath() { // navigate to "/realms/foo/account" and remove cookies in the browser for the current path @@ -88,7 +99,7 @@ public class CookiesPathTest extends AbstractKeycloakTest { cookies.stream().forEach(cookie -> Assert.assertThat(cookie.getPath(), Matchers.endsWith("/auth/realms/foobar/"))); // lets back to "/realms/foo/account" to test the cookies for "foo" realm are still there and haven't been (correctly) sent to "foobar" - URLUtils.navigateToUri( oauth.AUTH_SERVER_ROOT + "/realms/foo/account"); + URLUtils.navigateToUri(OAuthClient.AUTH_SERVER_ROOT + "/realms/foo/account"); cookies = driver.manage().getCookies(); Assert.assertTrue("There should be cookies sent!", cookies.size() > 0); @@ -97,7 +108,7 @@ public class CookiesPathTest extends AbstractKeycloakTest { @Test public void testMultipleCookies() throws IOException { - String requestURI = oauth.AUTH_SERVER_ROOT + "/realms/foo/account"; + String requestURI = OAuthClient.AUTH_SERVER_ROOT + "/realms/foo/account"; Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, 1); @@ -113,16 +124,15 @@ public class CookiesPathTest extends AbstractKeycloakTest { Assert.assertThat(cookieStore.getCookies(), Matchers.hasSize(3)); - CloseableHttpResponse response = login(requestURI, cookieStore); - response.close(); + login(requestURI, cookieStore); // old cookie has been removed - // now we have AUTH_SESSION_ID, KEYCLOAK_IDENTITY, KEYCLOAK_SESSION, OAuth_Token_Request_State - Assert.assertThat(cookieStore.getCookies(), Matchers.hasSize(4)); + // now we have AUTH_SESSION_ID, KEYCLOAK_IDENTITY, KEYCLOAK_SESSION + Assert.assertThat(cookieStore.getCookies().stream().map(org.apache.http.cookie.Cookie::getName).collect(Collectors.toList()), + Matchers.containsInAnyOrder("AUTH_SESSION_ID", "KEYCLOAK_IDENTITY", "KEYCLOAK_SESSION")); // does each cookie's path end with "/" - cookieStore.getCookies().stream().filter(c -> !"OAuth_Token_Request_State".equals(c.getName())) - .map(c -> c.getPath()).forEach(path ->Assert.assertThat(path, Matchers.endsWith("/"))); + cookieStore.getCookies().stream().map(org.apache.http.cookie.Cookie::getPath).forEach(path ->Assert.assertThat(path, Matchers.endsWith("/"))); // KEYCLOAK_SESSION should end by AUTH_SESSION_ID value String authSessionId = cookieStore.getCookies().stream().filter(c -> "AUTH_SESSION_ID".equals(c.getName())).findFirst().get().getValue(); @@ -152,8 +162,7 @@ public class CookiesPathTest extends AbstractKeycloakTest { Assert.assertThat(cookies, Matchers.hasSize(3)); // does each cookie's path end with "/" - cookies.stream().map(c -> c.getPath()).forEach(path -> - Assert.assertThat(path, Matchers.endsWith("/"))); + cookies.stream().map(Cookie::getPath).forEach(path -> Assert.assertThat(path, Matchers.endsWith("/"))); // KEYCLOAK_SESSION should end by AUTH_SESSION_ID value String authSessionId = cookies.stream().filter(c -> "AUTH_SESSION_ID".equals(c.getName())).findFirst().get().getValue(); @@ -164,7 +173,7 @@ public class CookiesPathTest extends AbstractKeycloakTest { @Test public void testOldCookieWithNodeInValue() throws IOException { - String requestURI = oauth.AUTH_SERVER_ROOT + "/realms/foo/account"; + String requestURI = OAuthClient.AUTH_SERVER_ROOT + "/realms/foo/account"; Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, 1); @@ -180,16 +189,15 @@ public class CookiesPathTest extends AbstractKeycloakTest { Assert.assertThat(cookieStore.getCookies(), Matchers.hasSize(3)); - CloseableHttpResponse response = login(requestURI, cookieStore); - response.close(); + login(requestURI, cookieStore); // old cookie has been removed // now we have AUTH_SESSION_ID, KEYCLOAK_IDENTITY, KEYCLOAK_SESSION, OAuth_Token_Request_State - Assert.assertThat(cookieStore.getCookies(), Matchers.hasSize(4)); + Assert.assertThat(cookieStore.getCookies().stream().map(org.apache.http.cookie.Cookie::getName).collect(Collectors.toList()), + Matchers.containsInAnyOrder("AUTH_SESSION_ID", "KEYCLOAK_IDENTITY", "KEYCLOAK_SESSION")); // does each cookie's path end with "/" - cookieStore.getCookies().stream().filter(c -> !"OAuth_Token_Request_State".equals(c.getName())) - .map(c -> c.getPath()).forEach(path ->Assert.assertThat(path, Matchers.endsWith("/"))); + cookieStore.getCookies().stream().map(org.apache.http.cookie.Cookie::getPath).forEach(path ->Assert.assertThat(path, Matchers.endsWith("/"))); // KEYCLOAK_SESSION should end by AUTH_SESSION_ID value String authSessionId = cookieStore.getCookies().stream().filter(c -> "AUTH_SESSION_ID".equals(c.getName())).findFirst().get().getValue(); @@ -215,30 +223,29 @@ public class CookiesPathTest extends AbstractKeycloakTest { testRealms.add(foobar.build()); } + // if the client is closed before the response is read, it throws + // org.apache.http.ConnectionClosedException: Premature end of Content-Length delimited message body + // that's why the this.httpClient is introduced, the client is closed either here or after test method private CloseableHttpResponse sendRequest(HttpRequestBase request, CookieStore cookieStore, HttpCoreContext localContext) throws IOException { - CloseableHttpClient c = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).setRedirectStrategy(new LaxRedirectStrategy()).build(); - - CloseableHttpResponse response = c.execute(request, localContext); - - return response; + if (httpClient != null) httpClient.close(); + httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).setRedirectStrategy(new LaxRedirectStrategy()).build(); + return httpClient.execute(request, localContext); } private CookieStore getCorrectCookies(String uri) throws IOException { CookieStore cookieStore = new BasicCookieStore(); HttpGet request = new HttpGet(uri); - CloseableHttpResponse response = sendRequest(request, new BasicCookieStore(), new HttpCoreContext()); - - for (org.apache.http.Header h: response.getHeaders("Set-Cookie")) { - if (h.getValue().contains(AuthenticationSessionManager.AUTH_SESSION_ID)) { - cookieStore.addCookie(parseCookie(h.getValue(), AuthenticationSessionManager.AUTH_SESSION_ID)); - } else if (h.getValue().contains(KC_RESTART)) { - cookieStore.addCookie(parseCookie(h.getValue(), KC_RESTART)); + try (CloseableHttpResponse response = sendRequest(request, new BasicCookieStore(), new HttpCoreContext())) { + for (org.apache.http.Header h: response.getHeaders("Set-Cookie")) { + if (h.getValue().contains(AuthenticationSessionManager.AUTH_SESSION_ID)) { + cookieStore.addCookie(parseCookie(h.getValue(), AuthenticationSessionManager.AUTH_SESSION_ID)); + } else if (h.getValue().contains(KC_RESTART)) { + cookieStore.addCookie(parseCookie(h.getValue(), KC_RESTART)); + } } } - response.close(); - return cookieStore; } @@ -267,18 +274,18 @@ public class CookiesPathTest extends AbstractKeycloakTest { return c; } - private CloseableHttpResponse login(String requestURI, CookieStore cookieStore) throws IOException { + private void login(String requestURI, CookieStore cookieStore) throws IOException { HttpCoreContext httpContext = new HttpCoreContext(); HttpGet request = new HttpGet(requestURI); // send an initial request, we are redirected to login page - CloseableHttpResponse response = sendRequest(request, cookieStore, httpContext); - String s = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); - response.close(); - String action = ActionURIUtils.getActionURIFromPageSource(s); + String entityContent; + try (CloseableHttpResponse response = sendRequest(request, cookieStore, httpContext)) { + entityContent = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); + } // send credentials to login form - HttpPost post = new HttpPost(action); + HttpPost post = new HttpPost(ActionURIUtils.getActionURIFromPageSource(entityContent)); List params = new LinkedList<>(); params.add(new BasicNameValuePair("username", "foo")); params.add(new BasicNameValuePair("password", "password")); @@ -286,6 +293,8 @@ public class CookiesPathTest extends AbstractKeycloakTest { post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(new UrlEncodedFormEntity(params)); - return sendRequest(post, cookieStore, httpContext); + try (CloseableHttpResponse response = sendRequest(post, cookieStore, httpContext)) { + Assert.assertThat("Expected successful login.", response.getStatusLine().getStatusCode(), is(equalTo(200))); + } } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/AbstractKerberosTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/AbstractKerberosTest.java index 64f70dd25e..8b176f8a4f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/AbstractKerberosTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/AbstractKerberosTest.java @@ -20,7 +20,6 @@ package org.keycloak.testsuite.federation.kerberos; import static org.keycloak.testsuite.admin.AbstractAdminTest.loadJson; import java.net.URI; -import java.nio.charset.Charset; import java.security.Principal; import java.util.Hashtable; import java.util.List; @@ -315,7 +314,7 @@ public abstract class AbstractKerberosTest extends AbstractAuthTest { protected OAuthClient.AccessTokenResponse assertAuthenticationSuccess(String codeUrl) throws Exception { - List pairs = URLEncodedUtils.parse(new URI(codeUrl), Charset.forName("UTF-8")); + List pairs = URLEncodedUtils.parse(new URI(codeUrl), "UTF-8"); String code = null; String state = null; for (NameValuePair pair : pairs) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/PasswordHashingTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/PasswordHashingTest.java index 837c41314f..88877197db 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/PasswordHashingTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/PasswordHashingTest.java @@ -19,61 +19,33 @@ package org.keycloak.testsuite.forms; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.graphene.page.Page; import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.junit.Assert; -import org.junit.Rule; import org.junit.Test; -import org.keycloak.OAuth2Constants; -import org.keycloak.admin.client.resource.UserResource; import org.keycloak.common.util.Base64; import org.keycloak.credential.CredentialModel; import org.keycloak.credential.hash.Pbkdf2PasswordHashProvider; import org.keycloak.credential.hash.Pbkdf2PasswordHashProviderFactory; import org.keycloak.credential.hash.Pbkdf2Sha256PasswordHashProviderFactory; import org.keycloak.credential.hash.Pbkdf2Sha512PasswordHashProviderFactory; -import org.keycloak.events.Details; -import org.keycloak.events.EventType; -import org.keycloak.models.BrowserSecurityHeaders; import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; -import org.keycloak.models.utils.ModelToRepresentation; -import org.keycloak.models.utils.RepresentationToModel; import org.keycloak.representations.idm.CredentialRepresentation; import org.keycloak.representations.idm.ErrorRepresentation; -import org.keycloak.representations.idm.EventRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; -import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.ApiUtil; -import org.keycloak.testsuite.client.KeycloakTestingClient; import org.keycloak.testsuite.pages.AccountUpdateProfilePage; -import org.keycloak.testsuite.pages.AppPage; -import org.keycloak.testsuite.pages.AppPage.RequestType; -import org.keycloak.testsuite.pages.ErrorPage; import org.keycloak.testsuite.pages.LoginPage; -import org.keycloak.testsuite.pages.LoginPasswordUpdatePage; import org.keycloak.testsuite.runonserver.RunOnServerDeployment; -import org.keycloak.testsuite.util.RealmBuilder; import org.keycloak.testsuite.util.UserBuilder; -import org.keycloak.util.JsonSerialization; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.ws.rs.BadRequestException; -import javax.ws.rs.InternalServerErrorException; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.core.Response; -import java.io.IOException; -import java.security.NoSuchAlgorithmException; import java.security.spec.KeySpec; -import java.util.Map; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CacheTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CacheTest.java index 5270039890..21b9e68cc1 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CacheTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CacheTest.java @@ -21,22 +21,17 @@ package org.keycloak.testsuite.model; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.TargetsContainer; import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.junit.ClassRule; import org.junit.Test; import org.keycloak.admin.client.resource.UserResource; import org.keycloak.models.ClientModel; -import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.RoleModel; import org.keycloak.models.UserModel; import org.keycloak.models.UserSessionModel; import org.keycloak.models.cache.infinispan.ClientAdapter; import org.keycloak.models.cache.infinispan.RealmAdapter; -import org.keycloak.testsuite.federation.ldap.AbstractLDAPTest; -import org.keycloak.testsuite.pages.AppPage; import org.keycloak.testsuite.runonserver.RunOnServerDeployment; -import java.util.List; import java.util.List; import java.util.Set; @@ -47,10 +42,7 @@ import static org.keycloak.testsuite.arquillian.DeploymentTargetModifier.AUTH_SE import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; import org.keycloak.testsuite.Assert; -import org.keycloak.models.utils.ModelToRepresentation; import org.keycloak.representations.idm.RealmRepresentation; -import org.keycloak.testsuite.client.KeycloakTestingClient; -import org.keycloak.testsuite.arquillian.TestContext; /** * @author Bill Burke diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionInitializerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionInitializerTest.java index 81d9d0e4ac..2934dcaea9 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionInitializerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionInitializerTest.java @@ -24,7 +24,6 @@ import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import org.keycloak.admin.client.Keycloak; import org.keycloak.admin.client.resource.UserResource; import org.keycloak.common.util.Time; import org.keycloak.connections.infinispan.InfinispanConnectionProvider; diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OfflineTokenTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OfflineTokenTest.java index 02288e5d53..c53fdd72db 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OfflineTokenTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OfflineTokenTest.java @@ -513,10 +513,11 @@ public class OfflineTokenTest extends AbstractKeycloakTest { tokenResponse = oauth.doRefreshTokenRequest(tokenResponse.getRefreshToken(), "secret1"); // Use accessToken to admin REST request - Keycloak offlineTokenAdmin = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth", - AuthRealm.MASTER, Constants.ADMIN_CLI_CLIENT_ID, tokenResponse.getAccessToken()); - RealmRepresentation testRealm = offlineTokenAdmin.realm("test").toRepresentation(); - Assert.assertNotNull(testRealm); + try (Keycloak offlineTokenAdmin = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth", + AuthRealm.MASTER, Constants.ADMIN_CLI_CLIENT_ID, tokenResponse.getAccessToken())) { + RealmRepresentation testRealm = offlineTokenAdmin.realm("test").toRepresentation(); + Assert.assertNotNull(testRealm); + } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/resources/openshift/client-storage/openshift-version.json b/testsuite/integration-arquillian/tests/base/src/test/resources/openshift/client-storage/openshift-version.json index aa6cd2776e..374e2e7dca 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/resources/openshift/client-storage/openshift-version.json +++ b/testsuite/integration-arquillian/tests/base/src/test/resources/openshift/client-storage/openshift-version.json @@ -8,4 +8,4 @@ "goVersion": "", "compiler": "", "platform": "" -}ssss \ No newline at end of file +} \ No newline at end of file diff --git a/testsuite/integration-arquillian/tests/pom.xml b/testsuite/integration-arquillian/tests/pom.xml index 1ba0227ce5..423e0d9fff 100755 --- a/testsuite/integration-arquillian/tests/pom.xml +++ b/testsuite/integration-arquillian/tests/pom.xml @@ -1438,11 +1438,21 @@ ${appium.client.version} + org.apache.httpcomponents httpclient - 4.5.3 + + org.apache.httpcomponents + httpcore + + jfree jfreechart diff --git a/testsuite/integration-deprecated/src/test/java/org/keycloak/testsuite/broker/OIDCKeyCloakServerBrokerBasicTest.java b/testsuite/integration-deprecated/src/test/java/org/keycloak/testsuite/broker/OIDCKeyCloakServerBrokerBasicTest.java index c8e9d9bb37..c12f73297d 100755 --- a/testsuite/integration-deprecated/src/test/java/org/keycloak/testsuite/broker/OIDCKeyCloakServerBrokerBasicTest.java +++ b/testsuite/integration-deprecated/src/test/java/org/keycloak/testsuite/broker/OIDCKeyCloakServerBrokerBasicTest.java @@ -127,22 +127,23 @@ public class OIDCKeyCloakServerBrokerBasicTest extends AbstractKeycloakIdentityP @Test public void testLogoutWorksWithTokenTimeout() { - Keycloak keycloak = Keycloak.getInstance("http://localhost:8081/auth", "master", "admin", "admin", org.keycloak.models.Constants.ADMIN_CLI_CLIENT_ID); - RealmRepresentation realm = keycloak.realm("realm-with-oidc-identity-provider").toRepresentation(); - assertNotNull(realm); - int oldLifespan = realm.getAccessTokenLifespan(); - realm.setAccessTokenLifespan(1); - keycloak.realm("realm-with-oidc-identity-provider").update(realm); - IdentityProviderRepresentation idp = keycloak.realm("realm-with-broker").identityProviders().get("kc-oidc-idp").toRepresentation(); - idp.getConfig().put("backchannelSupported", "false"); - keycloak.realm("realm-with-broker").identityProviders().get("kc-oidc-idp").update(idp); - logoutTimeOffset = 2; - super.testSuccessfulAuthentication(); - logoutTimeOffset = 0; - realm.setAccessTokenLifespan(oldLifespan); - keycloak.realm("realm-with-oidc-identity-provider").update(realm); - idp.getConfig().put("backchannelSupported", "true"); - keycloak.realm("realm-with-broker").identityProviders().get("kc-oidc-idp").update(idp); + try (Keycloak keycloak = Keycloak.getInstance("http://localhost:8081/auth", "master", "admin", "admin", org.keycloak.models.Constants.ADMIN_CLI_CLIENT_ID)) { + RealmRepresentation realm = keycloak.realm("realm-with-oidc-identity-provider").toRepresentation(); + assertNotNull(realm); + int oldLifespan = realm.getAccessTokenLifespan(); + realm.setAccessTokenLifespan(1); + keycloak.realm("realm-with-oidc-identity-provider").update(realm); + IdentityProviderRepresentation idp = keycloak.realm("realm-with-broker").identityProviders().get("kc-oidc-idp").toRepresentation(); + idp.getConfig().put("backchannelSupported", "false"); + keycloak.realm("realm-with-broker").identityProviders().get("kc-oidc-idp").update(idp); + logoutTimeOffset = 2; + super.testSuccessfulAuthentication(); + logoutTimeOffset = 0; + realm.setAccessTokenLifespan(oldLifespan); + keycloak.realm("realm-with-oidc-identity-provider").update(realm); + idp.getConfig().put("backchannelSupported", "true"); + keycloak.realm("realm-with-broker").identityProviders().get("kc-oidc-idp").update(idp); + } } @Test