Skip to content

Commit

Permalink
Made AssertEvents work with @rule
Browse files Browse the repository at this point in the history
  • Loading branch information
stianst committed Apr 20, 2016
1 parent 974906d commit 890af8d
Show file tree
Hide file tree
Showing 5 changed files with 83 additions and 92 deletions.
Expand Up @@ -22,30 +22,28 @@
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Assert;
import org.junit.rules.TestRule;
import org.junit.runners.model.Statement;
import org.keycloak.OAuth2Constants;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.authentication.authenticators.client.ClientIdAndSecretAuthenticator;
import org.keycloak.common.util.PemUtils;
import org.keycloak.events.Details;
import org.keycloak.events.EventType;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.EventRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.representations.idm.UserSessionRepresentation;
import org.keycloak.testsuite.client.resources.TestingResource;
import org.keycloak.util.TokenUtil;

import javax.ws.rs.core.Response;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class AssertEvents {
public class AssertEvents implements TestRule {

public static final String DEFAULT_CLIENT_ID = "test-app";
public static final String DEFAULT_IP_ADDRESS = "127.0.0.1";
Expand All @@ -54,25 +52,22 @@ public class AssertEvents {

String defaultRedirectUri = "http://localhost:8180/auth/realms/master/app/auth";

private RealmResource realmResource;
private TestingResource testingResource;
private RealmRepresentation realmRep;
private AbstractKeycloakTest context;
private PublicKey realmPublicKey;

public AssertEvents(AbstractKeycloakTest ctx) throws Exception {
public AssertEvents(AbstractKeycloakTest ctx) {
context = ctx;
}

realmResource = context.adminClient.realms().realm(DEFAULT_REALM);
realmRep = realmResource.toRepresentation();
String pubKeyString = realmRep.getPublicKey();
realmPublicKey = PemUtils.decodePublicKey(pubKeyString);

UserRepresentation defaultUser = getUser(DEFAULT_USERNAME);
if (defaultUser == null) {
throw new RuntimeException("Default user does not exist: " + DEFAULT_USERNAME + ". Make sure to add it to your test realm.");
}
testingResource = context.testingClient.testing();
@Override
public Statement apply(final Statement base, org.junit.runner.Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
base.evaluate();
// TODO Test should fail if there are leftover events
context.testingClient.testing().clearQueue();
}
};
}

public EventRepresentation poll() {
Expand All @@ -83,7 +78,7 @@ public EventRepresentation poll() {
}

public void clear() {
Response res = testingResource.clearQueue();
Response res = context.testingClient.testing().clearQueue();
try {
Assert.assertEquals("clear-event-queue success", res.getStatus(), 200);
} finally {
Expand Down Expand Up @@ -166,37 +161,32 @@ public ExpectedEvent expectAccount(EventType event) {

public ExpectedEvent expect(EventType event) {
return new ExpectedEvent()
.realm(realmRep.getId())
.realm(defaultRealmId())
.client(DEFAULT_CLIENT_ID)
.user(defaultUserId())
.ipAddress(DEFAULT_IP_ADDRESS)
.session((String) null)
.event(event);
}

UserRepresentation getUser(String username) {
List<UserRepresentation> result = realmResource.users().search(username, null, null, null, 0, 1);
return result.size() > 0 ? result.get(0) : null;
}

public PublicKey getRealmPublicKey() {
return realmPublicKey;
}

public class ExpectedEvent {
private EventRepresentation expected = new EventRepresentation();
private Matcher<String> realmId;
private Matcher<String> userId;
private Matcher<String> sessionId;
private HashMap<String, Matcher<String>> details;

public ExpectedEvent realm(RealmRepresentation realm) {
expected.setRealmId(realm.getId());
public ExpectedEvent realm(Matcher<String> realmId) {
this.realmId = realmId;
return this;
}

public ExpectedEvent realm(RealmRepresentation realm) {
return realm(CoreMatchers.equalTo(realm.getId()));
}

public ExpectedEvent realm(String realmId) {
expected.setRealmId(realmId);
return this;
return realm(CoreMatchers.equalTo(realmId));
}

public ExpectedEvent client(ClientRepresentation client) {
Expand Down Expand Up @@ -283,7 +273,7 @@ public EventRepresentation assertEvent(EventRepresentation actual) {
expected.setType(expected.getType() + "_ERROR");
}
Assert.assertEquals(expected.getType(), actual.getType());
Assert.assertEquals(expected.getRealmId(), actual.getRealmId());
Assert.assertThat(actual.getRealmId(), realmId);
Assert.assertEquals(expected.getClientId(), actual.getClientId());
Assert.assertEquals(expected.getError(), actual.getError());
Assert.assertEquals(expected.getIpAddress(), actual.getIpAddress());
Expand Down Expand Up @@ -333,6 +323,34 @@ public void describeTo(Description description) {
};
}

public Matcher<String> defaultRealmId() {
return new TypeSafeMatcher<String>() {
private String realmId;

@Override
protected boolean matchesSafely(String item) {
return item.equals(getRealmId());
}

@Override
public void describeTo(Description description) {
description.appendText(getRealmId());
}

private String getRealmId() {
if (realmId == null) {
RealmRepresentation realm = context.adminClient.realm(DEFAULT_REALM).toRepresentation();
if (realm == null) {
throw new RuntimeException("Default user does not exist: " + DEFAULT_USERNAME + ". Make sure to add it to your test realm.");
}
realmId = realm.getId();
}
return realmId;
}

};
}

public Matcher<String> defaultUserId() {
return new TypeSafeMatcher<String>() {
private String userId;
Expand Down Expand Up @@ -361,7 +379,12 @@ private String getUserId() {
};
}

private UserRepresentation getUser(String username) {
List<UserRepresentation> users = context.adminClient.realm(DEFAULT_REALM).users().search(username, null, null, null, 0, 1);
return users.isEmpty() ? null : users.get(0);
}

private EventRepresentation fetchNextEvent() {
return testingResource.pollEvent();
return context.testingClient.testing().pollEvent();
}
}
Expand Up @@ -41,6 +41,7 @@
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.keycloak.adapters.HttpClientBuilder;
import org.keycloak.admin.client.resource.RealmResource;
Expand Down Expand Up @@ -77,8 +78,9 @@ public abstract class AbstractKerberosAdapterTest extends AbstractServletsAdapte
protected ResteasyClient client;

protected static LDAPEmbeddedServer ldapEmbeddedServer;

protected AssertEvents events;

@Rule
public AssertEvents events = new AssertEvents(this);

@Page
protected ChangePassword changePasswordPage;
Expand Down Expand Up @@ -115,7 +117,6 @@ public void before() throws Exception {
String krb5ConfPath = LDAPTestConfiguration.getResource("test-krb5.conf");
log.info("Krb5.conf file location is: " + krb5ConfPath);
System.setProperty("java.security.krb5.conf", krb5ConfPath);
events = new AssertEvents(this);
UserFederationProviderModel model = new UserFederationProviderModel();
model.setConfig(ldapTestConfiguration.getLDAPConfig());
spnegoSchemeFactory = new KeycloakSPNegoSchemeFactory(getKerberosConfig(model));
Expand Down
Expand Up @@ -18,6 +18,7 @@
package org.keycloak.testsuite.admin;

import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.keycloak.Config;
import org.keycloak.admin.client.resource.ClientResource;
Expand Down Expand Up @@ -58,14 +59,14 @@
*/
public class ImpersonationTest extends AbstractKeycloakTest {

private AssertEvents events;
@Rule
public AssertEvents events = new AssertEvents(this);

private String impersonatedUserId;

@Override
public void beforeAbstractKeycloakTest() throws Exception {
super.beforeAbstractKeycloakTest();
events = new AssertEvents(this);
}

@Override
Expand Down
Expand Up @@ -18,8 +18,10 @@
package org.keycloak.testsuite.admin.group;

import org.junit.Before;
import org.junit.Rule;
import org.keycloak.OAuth2Constants;
import org.keycloak.RSATokenVerifier;
import org.keycloak.common.util.PemUtils;
import org.keycloak.events.Details;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.crypto.RSAProvider;
Expand All @@ -31,6 +33,7 @@
import org.keycloak.testsuite.AssertEvents;
import org.keycloak.testsuite.arquillian.AuthServerTestEnricher;

import java.security.PublicKey;
import java.util.List;

import static org.keycloak.testsuite.util.IOUtil.loadRealm;
Expand All @@ -40,13 +43,8 @@
*/
public abstract class AbstractGroupTest extends AbstractKeycloakTest {

AssertEvents events;

@Before
public void initAssertEvents() throws Exception {
events = new AssertEvents(this);
events.clear();
}
@Rule
public AssertEvents events = new AssertEvents(this);

AccessToken login(String login, String clientId, String clientSecret, String userId) throws Exception {

Expand All @@ -55,10 +53,12 @@ AccessToken login(String login, String clientId, String clientSecret, String use
String accessToken = tokenResponse.getToken();
String refreshToken = tokenResponse.getRefreshToken();

AccessToken accessTokenRepresentation = RSATokenVerifier.verifyToken(accessToken, events.getRealmPublicKey(), AuthServerTestEnricher.getAuthServerContextRoot() + "/auth/realms/test");
PublicKey publicKey = PemUtils.decodePublicKey(adminClient.realm("test").toRepresentation().getPublicKey());

AccessToken accessTokenRepresentation = RSATokenVerifier.verifyToken(accessToken, publicKey, AuthServerTestEnricher.getAuthServerContextRoot() + "/auth/realms/test");

JWSInput jws = new JWSInput(refreshToken);
if (!RSAProvider.verify(jws, events.getRealmPublicKey())) {
if (!RSAProvider.verify(jws, publicKey)) {
throw new RuntimeException("Invalid refresh token");
}
RefreshToken refreshTokenRepresentation = jws.readJsonContent(RefreshToken.class);
Expand Down
Expand Up @@ -18,13 +18,10 @@

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.keycloak.OAuth2Constants;
import org.keycloak.common.util.Time;
import org.keycloak.testsuite.util.KeycloakModelUtils;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.representations.idm.EventRepresentation;
Expand All @@ -33,13 +30,13 @@
import org.keycloak.representations.oidc.TokenMetadataRepresentation;
import org.keycloak.testsuite.AssertEvents;
import org.keycloak.testsuite.TestRealmKeycloakTest;
import org.keycloak.testsuite.util.KeycloakModelUtils;
import org.keycloak.testsuite.util.OAuthClient.AccessTokenResponse;
//import org.adminClient.testsuite.pages.LoginPage;
//import org.adminClient.testsuite.rule.KeycloakRule;
//import org.adminClient.testsuite.rule.WebResource;
//import org.adminClient.testsuite.rule.WebRule;
import org.keycloak.util.JsonSerialization;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.*;

/**
Expand All @@ -48,34 +45,8 @@
*/
public class TokenIntrospectionTest extends TestRealmKeycloakTest {

private AssertEvents events;

/* @ClassRule >>> now implemented in configureTestRealm()
public static KeycloakRule keycloakRule = new KeycloakRule(new KeycloakRule.KeycloakSetup() {
@Override
vvv "test" realm
public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
vvv Done in TestRealmKeycloakTest vvv
appRealm.getClientByClientId("test-app").setDirectAccessGrantsEnabled(true);
ClientModel confApp = KeycloakModelUtils.createClient(appRealm, "confidential-cli");
confApp.setSecret("secret1");
new ClientManager(manager).enableServiceAccount(confApp);
ClientModel pubApp = KeycloakModelUtils.createClient(appRealm, "public-cli");
pubApp.setPublicClient(true);
{
UserModel user = manager.getSession().users().addUser(appRealm, KeycloakModelUtils.generateId(), "no-permissions", false, false);
user.updateCredential(UserCredentialModel.password("password"));
user.setEnabled(true);
RoleModel role = appRealm.getRole("user");
user.grantRole(role);
}
adminClient = Keycloak.getInstance("http://localhost:8081/auth", "master", "admin", "admin", Constants.ADMIN_CLI_CLIENT_ID);
}
}); */
@Rule
public AssertEvents events = new AssertEvents(this);

@Override
public void configureTestRealm(RealmRepresentation testRealm) {
Expand All @@ -101,11 +72,6 @@ public void configureTestRealm(RealmRepresentation testRealm) {
testRealm.getUsers().add(user);
}

@Before
public void setUpAssertEvents() throws Exception {
events = new AssertEvents(this);
}

@Test
public void testConfidentialClientCredentialsBasicAuthentication() throws Exception {
oauth.doLogin("test-user@localhost", "password");
Expand Down

0 comments on commit 890af8d

Please sign in to comment.