KEYCLOAK-7677 KEYCLOAK-7723 fix version collision of httpclient

Co-authored-by: Pedro Igor <psilva@redhat.com>
This commit is contained in:
vramik 2018-12-07 09:40:37 +01:00 committed by Pedro Igor
parent 7c9f15778a
commit c4a46a5591
36 changed files with 1128 additions and 1161 deletions

View file

@ -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 <code>Keycloak</code> instance cannot be reused.
*/
@Override
public void close() {
client.close();
}

View file

@ -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 <a href="mailto:bill@burkecentral.com">Bill Burke</a>
@ -752,8 +754,9 @@ public class JpaUserProvider implements UserProvider, UserCredentialStore {
Root from1 = subquery1.from(ResourceEntity.class);
List<Predicate> subs = new ArrayList<>();
subs.add(builder.like(from1.get("name"), builder.concat("group.resource.", from.get("groupId"))));
Expression<String> groupId = from.get("groupId");
subs.add(builder.like(from1.get("name"), builder.concat("group.resource.", groupId)));
subquery1.where(subs.toArray(new Predicate[subs.size()]));

View file

@ -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<String, Cookie> 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();
}

View file

@ -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<String> 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);
}

View file

@ -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);

View file

@ -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 <a href="mailto:mstrukel@redhat.com">Marko Strukelj</a>
*/
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();
}

View file

@ -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);
}
}
}
}

View file

@ -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")));
}

View file

@ -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<String, String> getCurrentQuery() {
Map<String, String> m = new HashMap<>();
List<NameValuePair> pairs = URLEncodedUtils.parse(getCurrentUri(), Charset.forName("UTF-8"));
List<NameValuePair> pairs = URLEncodedUtils.parse(getCurrentUri(), "UTF-8");
for (NameValuePair p : pairs) {
m.put(p.getName(), p.getValue());
}

View file

@ -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<NameValuePair> params = URLEncodedUtils.parse(URI.create(responseUri), Charset.forName("UTF-8"));
List<NameValuePair> params = URLEncodedUtils.parse(URI.create(responseUri), "UTF-8");
String samlDoc = null;
for (NameValuePair param : params) {

View file

@ -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) {

View file

@ -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<SAML2
String location = currentResponse.getFirstHeader("Location").getValue();
URI locationUri = URI.create(location);
List<NameValuePair> params = URLEncodedUtils.parse(locationUri, Charset.forName("UTF-8"));
List<NameValuePair> params = URLEncodedUtils.parse(locationUri, "UTF-8");
for (Iterator<NameValuePair> it = params.iterator(); it.hasNext();) {
NameValuePair param = it.next();
if ("SAMLResponse".equals(param.getName()) || "SAMLRequest".equals(param.getName())) {

View file

@ -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";

View file

@ -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<String, String> 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;

View file

@ -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();

View file

@ -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");

View file

@ -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<AccessToken> verifier = TokenVerifier.create(accessToken.getToken(), AccessToken.class);
assertEquals(Algorithm.ES256, verifier.getHeader().getAlgorithm().name());
AccessTokenResponse accessToken = adminClient.tokenManager().getAccessToken();
TokenVerifier<AccessToken> 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"));
}
}
}

View file

@ -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<RoleRepresentation> 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<RoleRepresentation> 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<RoleRepresentation> 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<RoleRepresentation> 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<RoleRepresentation> 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<RoleRepresentation> 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<RoleRepresentation> 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<RoleRepresentation> 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<UserRepresentation> 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<UserRepresentation> 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<RoleRepresentation> 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<RoleRepresentation> 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<RoleRepresentation> composites = new LinkedList<>();
composites.add(viewUsers);
realmClient.realm(TEST).rolesById().addComposites(composite.getId(), composites);
List<RoleRepresentation> 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();
}

View file

@ -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"));
}
}

View file

@ -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();
}
}

View file

@ -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<String, String> 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()));
}

View file

@ -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();
}
}
}

View file

@ -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<String> 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<RoleRepresentation> 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<RoleRepresentation> 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

View file

@ -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();
}

View file

@ -80,6 +80,7 @@ public class AuthzClientCredentialsTest extends AbstractAuthzTest {
}
@Before
@Override
public void beforeAbstractKeycloakTest() throws Exception {
super.beforeAbstractKeycloakTest();
testContext.getTestRealmReps().forEach(realmRepresentation -> {

View file

@ -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();

View file

@ -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 <a href="mailto:mkanis@redhat.com">Martin Kanis</a>
@ -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<NameValuePair> 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)));
}
}
}

View file

@ -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<NameValuePair> pairs = URLEncodedUtils.parse(new URI(codeUrl), Charset.forName("UTF-8"));
List<NameValuePair> pairs = URLEncodedUtils.parse(new URI(codeUrl), "UTF-8");
String code = null;
String state = null;
for (NameValuePair pair : pairs) {

View file

@ -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;
/**

View file

@ -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 <a href="mailto:bill@burkecentral.com">Bill Burke</a>

View file

@ -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;

View file

@ -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);
}
}

View file

@ -8,4 +8,4 @@
"goVersion": "",
"compiler": "",
"platform": ""
}ssss
}

View file

@ -1438,11 +1438,21 @@
<version>${appium.client.version}</version>
</dependency>
<!--
httpclient and httpcore are here to ensure we use the same version
as in keycloak/pom.xml and to prevent the other versions beeing present
on classpath during tests (as a transitive dependencies e.g.).
There has beeen issues due to this.
-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<dependency>
<groupId>jfree</groupId>
<artifactId>jfreechart</artifactId>

View file

@ -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