KEYCLOAK-10964 Remove realm reimport in SAMLServletAdapterTest

This commit is contained in:
Hynek Mlnarik 2019-07-30 18:18:47 +02:00 committed by Hynek Mlnařík
parent c0f73c0df4
commit 9bca5c9968
6 changed files with 235 additions and 166 deletions

View file

@ -0,0 +1,77 @@
/*
* Copyright 2018 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.testsuite.updaters;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.resource.GroupResource;
import org.keycloak.admin.client.resource.GroupsResource;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.admin.client.resource.UserResource;
import org.keycloak.admin.client.resource.UsersResource;
import org.keycloak.representations.idm.GroupRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import javax.ws.rs.core.Response;
import static org.keycloak.testsuite.admin.ApiUtil.getCreatedId;
/**
* Creates a temporary realm object and makes sure it is removed when used within try-with-resources.
*/
public class Creator<T> implements AutoCloseable {
public static Creator<RealmResource> create(Keycloak adminClient, RealmRepresentation rep) {
adminClient.realms().create(rep);
final RealmResource r = adminClient.realm(rep.getRealm());
return new Creator(r, r::remove);
}
public static Creator<GroupResource> create(RealmResource realmResource, GroupRepresentation rep) {
final GroupsResource groups = realmResource.groups();
try (Response response = groups.add(rep)) {
String createdId = getCreatedId(response);
final GroupResource r = groups.group(createdId);
return new Creator(r, r::remove);
}
}
public static Creator<UserResource> create(RealmResource realmResource, UserRepresentation rep) {
final UsersResource users = realmResource.users();
try (Response response = users.create(rep)) {
String createdId = getCreatedId(response);
final UserResource r = users.get(createdId);
return new Creator(r, r::remove);
}
}
private final T resource;
private final Runnable closer;
private Creator(T resource, Runnable closer) {
this.resource = resource;
this.closer = closer;
}
public T resource() {
return this.resource;
}
@Override
public void close() {
closer.run();
}
}

View file

@ -1,50 +0,0 @@
/*
* Copyright 2018 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.testsuite.updaters;
import org.keycloak.admin.client.Keycloak;
import java.io.Closeable;
import javax.ws.rs.NotFoundException;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.representations.idm.RealmRepresentation;
import java.io.IOException;
/**
* Creates a temporary realm and makes sure it is removed.
*/
public class RealmCreator implements Closeable {
private final RealmResource realmResource;
public RealmCreator(Keycloak adminClient, RealmRepresentation rep) {
adminClient.realms().create(rep);
this.realmResource = adminClient.realm(rep.getRealm());
}
public RealmResource realm() {
return this.realmResource;
}
@Override
public void close() throws IOException {
try {
realmResource.remove();
} catch (NotFoundException e) {
// ignore
}
}
}

View file

@ -1,16 +1,21 @@
package org.keycloak.testsuite.updaters;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.admin.client.resource.UserResource;
import org.keycloak.admin.client.resource.UsersResource;
import org.keycloak.models.UserModel;
import org.keycloak.representations.idm.GroupRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat;
import static org.keycloak.testsuite.updaters.ServerResourceUpdater.updateViaAddRemove;
/**
* Updater for user attributes. See {@link ServerResourceUpdater} for further details.
@ -18,6 +23,8 @@ import static org.junit.Assert.assertThat;
*/
public class UserAttributeUpdater extends ServerResourceUpdater<UserAttributeUpdater, UserResource, UserRepresentation> {
private final RealmResource realmResource;
/**
* Creates a {@UserAttributeUpdater} for the given user. The user must exist.
* @param adminClient
@ -26,21 +33,54 @@ public class UserAttributeUpdater extends ServerResourceUpdater<UserAttributeUpd
* @return
*/
public static UserAttributeUpdater forUserByUsername(Keycloak adminClient, String realm, String userName) {
UsersResource users = adminClient.realm(realm).users();
return forUserByUsername(adminClient.realm(realm), userName);
}
public static UserAttributeUpdater forUserByUsername(RealmResource realm, String userName) {
UsersResource users = realm.users();
List<UserRepresentation> foundUsers = users.search(userName).stream()
.filter(ur -> userName.equalsIgnoreCase(ur.getUsername()))
.collect(Collectors.toList());
assertThat(foundUsers, hasSize(1));
UserResource userRes = users.get(foundUsers.get(0).getId());
return new UserAttributeUpdater(userRes);
return new UserAttributeUpdater(userRes, realm);
}
public UserAttributeUpdater(UserResource resource) {
super(resource, resource::toRepresentation, resource::update);
this(resource, null);
}
public UserAttributeUpdater(UserResource resource, RealmResource realmResource) {
super(resource,
() -> {
UserRepresentation r = resource.toRepresentation();
r.setGroups(resource.groups().stream().map(GroupRepresentation::getPath).collect(Collectors.toList()));
return r;
},
resource::update
);
if (this.rep.getAttributes() == null) {
this.rep.setAttributes(new HashMap<>());
}
this.realmResource = realmResource;
}
@Override
protected void performUpdate(UserRepresentation from, UserRepresentation to) {
super.performUpdate(from, to);
updateViaAddRemove(from.getGroups(), to.getGroups(), this::getConversionForGroupPathToId, resource::joinGroup, resource::leaveGroup);
}
private Function<String, String> getConversionForGroupPathToId() {
if (realmResource == null) {
return String::toString;
}
Map<String, String> humanIdToIdMap = realmResource.groups().groups().stream()
.collect(Collectors.toMap(GroupRepresentation::getPath, GroupRepresentation::getId));
return humanIdToIdMap::get;
}
public UserAttributeUpdater setAttribute(String name, List<String> value) {
@ -78,4 +118,13 @@ public class UserAttributeUpdater extends ServerResourceUpdater<UserAttributeUpd
public RoleScopeUpdater clientRoleScope(String clientUUID) {
return new RoleScopeUpdater(resource.roles().clientLevel(clientUUID));
}
/**
* @param groups List of expected group paths
* @return
*/
public UserAttributeUpdater setGroups(String... groups) {
rep.setGroups(Arrays.asList(groups));
return this;
}
}

View file

@ -25,6 +25,8 @@ import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.common.util.ConcurrentMultivaluedHashMap;
import org.keycloak.testsuite.arquillian.TestContext;
import java.util.LinkedList;
import java.util.function.Consumer;
/**
* Enlist resources to be cleaned after test method
@ -45,6 +47,7 @@ public class TestCleanup {
private final TestContext testContext;
private final String realmName;
private final List<Runnable> genericCleanups = new LinkedList<>();
// Key is kind of entity (eg. "client", "role", "user" etc), Values are all kind of entities of given type to cleanup
private ConcurrentMultivaluedHashMap<String, String> entities = new ConcurrentMultivaluedHashMap<>();
@ -56,6 +59,20 @@ public class TestCleanup {
}
public void addCleanup(Runnable r) {
genericCleanups.add(r);
}
public void addCleanup(AutoCloseable c) {
genericCleanups.add(() -> {
try {
c.close();
} catch (Exception ex) {
// ignore
}
});
}
public void addUserId(String userId) {
entities.add(USER_IDS, userId);
}
@ -80,7 +97,6 @@ public class TestCleanup {
entities.add(CLIENT_SCOPE_IDS, clientScopeId);
}
public void addRoleId(String roleId) {
entities.add(ROLE_IDS, roleId);
}
@ -104,6 +120,8 @@ public class TestCleanup {
public void executeCleanup() {
RealmResource realm = getAdminClient().realm(realmName);
this.genericCleanups.forEach(Runnable::run);
List<String> userIds = entities.get(USER_IDS);
if (userIds != null) {
for (String userId : userIds) {

View file

@ -18,10 +18,8 @@
package org.keycloak.testsuite.adapter.servlet;
import static javax.ws.rs.core.Response.Status.OK;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
import static org.keycloak.OAuth2Constants.PASSWORD;
import static org.keycloak.testsuite.admin.ApiUtil.createUserAndResetPasswordWithAdminClient;
import static org.keycloak.testsuite.admin.Users.setPasswordFor;
import static org.keycloak.testsuite.AbstractAuthTest.createUserRepresentation;
import static org.keycloak.testsuite.adapter.AbstractServletsAdapterTest.samlServletDeployment;
@ -51,8 +49,6 @@ import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.ws.rs.client.Client;
@ -136,7 +132,6 @@ import org.keycloak.saml.common.util.XmlKeyInfoKeyNameTransformer;
import org.keycloak.saml.processing.core.parsers.saml.SAMLParser;
import org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder;
import org.keycloak.services.resources.RealmsResource;
import org.keycloak.testsuite.adapter.AbstractServletsAdapterTest;
import org.keycloak.testsuite.adapter.page.*;
import org.keycloak.testsuite.admin.ApiUtil;
import org.keycloak.testsuite.arquillian.annotation.AppServerContainer;
@ -148,7 +143,8 @@ import org.keycloak.testsuite.auth.page.login.SAMLPostLoginTenant2;
import org.keycloak.testsuite.page.AbstractPage;
import org.keycloak.testsuite.saml.AbstractSamlTest;
import org.keycloak.testsuite.updaters.ClientAttributeUpdater;
import org.keycloak.testsuite.util.ProtocolMapperUtil;
import org.keycloak.testsuite.updaters.Creator;
import org.keycloak.testsuite.updaters.UserAttributeUpdater;
import org.keycloak.testsuite.util.SamlClient;
import org.keycloak.testsuite.util.SamlClient.Binding;
import org.keycloak.testsuite.util.SamlClientBuilder;
@ -165,6 +161,7 @@ import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import static org.keycloak.testsuite.admin.ApiUtil.getCreatedId;
/**
* @author mhajas
@ -435,6 +432,11 @@ public class SAMLServletAdapterTest extends AbstractSAMLServletAdapterTest {
SendUsernameServlet.class, SamlMultiTenantResolver.class);
}
@Override
protected boolean isImportAfterEachMethod() {
return false;
}
private void assertForbidden(AbstractPage page, String expectedNotContains) {
page.navigateTo();
waitUntilElement(By.xpath("//body")).text().not().contains(expectedNotContains);
@ -903,20 +905,22 @@ public class SAMLServletAdapterTest extends AbstractSAMLServletAdapterTest {
.edit(createUserRepresentation(username, "xyz@redhat.com", "ěščřžýáí", "RoàåéèíñòøöùüßÅÄÖÜ", true))
.addPassword(PASSWORD)
.build();
String userId = createUserAndResetPasswordWithAdminClient(testRealmResource(), user, PASSWORD);
final RoleScopeResource realmRoleRes = testRealmResource().users().get(userId).roles().realmLevel();
List<RoleRepresentation> availableRoles = realmRoleRes.listAvailable();
realmRoleRes.add(availableRoles.stream().filter(r -> r.getName().equalsIgnoreCase("manager")).collect(Collectors.toList()));
UserRepresentation storedUser = testRealmResource().users().get(userId).toRepresentation();
try (Creator<UserResource> u = Creator.create(testRealmResource(), user)) {
final RoleScopeResource realmRoleRes = u.resource().roles().realmLevel();
List<RoleRepresentation> availableRoles = realmRoleRes.listAvailable();
realmRoleRes.add(availableRoles.stream().filter(r -> r.getName().equalsIgnoreCase("manager")).collect(Collectors.toList()));
Assert.assertThat(storedUser, notNullValue());
Assert.assertThat("Database seems to be unable to store Unicode for username. Refer to KEYCLOAK-3439 and related issues.", storedUser.getUsername(), equalToIgnoringCase(username));
UserRepresentation storedUser = u.resource().toRepresentation();
assertSuccessfulLogin(salesPostSigServletPage, user, testRealmSAMLPostLoginPage, "principal=" + storedUser.getUsername());
Assert.assertThat(storedUser, notNullValue());
Assert.assertThat("Database seems to be unable to store Unicode for username. Refer to KEYCLOAK-3439 and related issues.", storedUser.getUsername(), equalToIgnoringCase(username));
salesPostSigServletPage.logout();
checkLoggedOut(salesPostSigServletPage, testRealmSAMLPostLoginPage);
assertSuccessfulLogin(salesPostSigServletPage, user, testRealmSAMLPostLoginPage, "principal=" + storedUser.getUsername());
salesPostSigServletPage.logout();
checkLoggedOut(salesPostSigServletPage, testRealmSAMLPostLoginPage);
}
}
@Test
@ -927,20 +931,21 @@ public class SAMLServletAdapterTest extends AbstractSAMLServletAdapterTest {
.edit(createUserRepresentation(username, "xyz@redhat.com", "ěščřžýáí", "RoàåéèíñòøöùüßÅÄÖÜ", true))
.addPassword(PASSWORD)
.build();
String userId = createUserAndResetPasswordWithAdminClient(testRealmResource(), user, PASSWORD);
final RoleScopeResource realmRoleRes = testRealmResource().users().get(userId).roles().realmLevel();
List<RoleRepresentation> availableRoles = realmRoleRes.listAvailable();
realmRoleRes.add(availableRoles.stream().filter(r -> r.getName().equalsIgnoreCase("manager")).collect(Collectors.toList()));
try (Creator<UserResource> u = Creator.create(testRealmResource(), user)) {
final RoleScopeResource realmRoleRes = u.resource().roles().realmLevel();
List<RoleRepresentation> availableRoles = realmRoleRes.listAvailable();
realmRoleRes.add(availableRoles.stream().filter(r -> r.getName().equalsIgnoreCase("manager")).collect(Collectors.toList()));
UserRepresentation storedUser = testRealmResource().users().get(userId).toRepresentation();
UserRepresentation storedUser = u.resource().toRepresentation();
Assert.assertThat(storedUser, notNullValue());
Assert.assertThat("Database seems to be unable to store Unicode for username. Refer to KEYCLOAK-3439 and related issues.", storedUser.getUsername(), equalToIgnoringCase(username));
Assert.assertThat(storedUser, notNullValue());
Assert.assertThat("Database seems to be unable to store Unicode for username. Refer to KEYCLOAK-3439 and related issues.", storedUser.getUsername(), equalToIgnoringCase(username));
assertSuccessfulLogin(employeeSigServletPage, user, testRealmSAMLRedirectLoginPage, "principal=" + storedUser.getUsername());
assertSuccessfulLogin(employeeSigServletPage, user, testRealmSAMLRedirectLoginPage, "principal=" + storedUser.getUsername());
employeeSigServletPage.logout();
checkLoggedOut(employeeSigServletPage, testRealmSAMLRedirectLoginPage);
employeeSigServletPage.logout();
checkLoggedOut(employeeSigServletPage, testRealmSAMLRedirectLoginPage);
}
}
@Test
@ -1184,18 +1189,10 @@ public class SAMLServletAdapterTest extends AbstractSAMLServletAdapterTest {
@Test
public void testUserAttributeStatementMapperUserGroupsAggregate() throws Exception {
UserResource userResource = ApiUtil.findUserByUsernameId(testRealmResource(), "bburke");
UserRepresentation user = userResource.toRepresentation();
user.setAttributes(new HashMap<>());
user.getAttributes().put("group-value", Arrays.asList("user-value1"));
userResource.update(user);
GroupRepresentation group1 = new GroupRepresentation();
group1.setName("group1");
group1.setAttributes(new HashMap<>());
group1.getAttributes().put("group-value", Arrays.asList("value1", "value2"));
testRealmResource().groups().add(group1);
group1 = testRealmResource().getGroupByPath("/group1");
userResource.joinGroup(group1.getId());
ClientResource clientResource = ApiUtil.findClientResourceByClientId(testRealmResource(), AbstractSamlTest.SAML_CLIENT_ID_EMPLOYEE_2);
ProtocolMappersResource protocolMappersResource = clientResource.getProtocolMappers();
@ -1205,9 +1202,14 @@ public class SAMLServletAdapterTest extends AbstractSAMLServletAdapterTest {
config.put("user.attribute", "group-value");
config.put("attribute.name", "group-attribute");
config.put("aggregate.attrs", "true");
createProtocolMapper(protocolMappersResource, "group-value", "saml", "saml-user-attribute-mapper", config);
try {
try (
AutoCloseable g1 = Creator.create(testRealmResource(), group1);
AutoCloseable uau = UserAttributeUpdater.forUserByUsername(testRealmResource(), "bburke")
.setAttribute("group-value", "user-value1")
.setGroups("/group1")
.update();
AutoCloseable c = createProtocolMapper(protocolMappersResource, "group-value", "saml", "saml-user-attribute-mapper", config)) {
employee2ServletPage.navigateTo();
assertCurrentUrlStartsWith(testRealmSAMLPostLoginPage);
testRealmSAMLPostLoginPage.form().login("bburke", "password");
@ -1224,31 +1226,15 @@ public class SAMLServletAdapterTest extends AbstractSAMLServletAdapterTest {
employee2ServletPage.logout();
checkLoggedOut(employee2ServletPage, testRealmSAMLPostLoginPage);
} finally {
// revert
user.getAttributes().remove("group-value");
userResource.update(user);
userResource.leaveGroup(group1.getId());
testRealmResource().groups().group(group1.getId()).remove();
ProtocolMapperRepresentation mapper = ProtocolMapperUtil.getMapperByNameAndProtocol(protocolMappersResource, "saml", "group-value");
protocolMappersResource.delete(mapper.getId());
}
}
@Test
public void testUserAttributeStatementMapperUserGroupsNoAggregate() throws Exception {
UserResource userResource = ApiUtil.findUserByUsernameId(testRealmResource(), "bburke");
UserRepresentation user = userResource.toRepresentation();
user.setAttributes(new HashMap<>());
user.getAttributes().put("group-value", Arrays.asList("user-value1"));
userResource.update(user);
GroupRepresentation group1 = new GroupRepresentation();
group1.setName("group1");
group1.setAttributes(new HashMap<>());
group1.getAttributes().put("group-value", Arrays.asList("value1", "value2"));
testRealmResource().groups().add(group1);
group1 = testRealmResource().getGroupByPath("/group1");
userResource.joinGroup(group1.getId());
ClientResource clientResource = ApiUtil.findClientResourceByClientId(testRealmResource(), AbstractSamlTest.SAML_CLIENT_ID_EMPLOYEE_2);
ProtocolMappersResource protocolMappersResource = clientResource.getProtocolMappers();
@ -1257,9 +1243,14 @@ public class SAMLServletAdapterTest extends AbstractSAMLServletAdapterTest {
config.put("attribute.nameformat", "Basic");
config.put("user.attribute", "group-value");
config.put("attribute.name", "group-attribute");
createProtocolMapper(protocolMappersResource, "group-value", "saml", "saml-user-attribute-mapper", config);
try {
try (
AutoCloseable g1 = Creator.create(testRealmResource(), group1);
AutoCloseable uau = UserAttributeUpdater.forUserByUsername(testRealmResource(), "bburke")
.setAttribute("group-value", "user-value1")
.setGroups("/group1")
.update();
AutoCloseable c = createProtocolMapper(protocolMappersResource, "group-value", "saml", "saml-user-attribute-mapper", config)) {
employee2ServletPage.navigateTo();
assertCurrentUrlStartsWith(testRealmSAMLPostLoginPage);
testRealmSAMLPostLoginPage.form().login("bburke", "password");
@ -1274,34 +1265,20 @@ public class SAMLServletAdapterTest extends AbstractSAMLServletAdapterTest {
employee2ServletPage.logout();
checkLoggedOut(employee2ServletPage, testRealmSAMLPostLoginPage);
} finally {
// revert
user.getAttributes().remove("group-value");
userResource.update(user);
userResource.leaveGroup(group1.getId());
testRealmResource().groups().group(group1.getId()).remove();
ProtocolMapperRepresentation mapper = ProtocolMapperUtil.getMapperByNameAndProtocol(protocolMappersResource, "saml", "group-value");
protocolMappersResource.delete(mapper.getId());
}
}
@Test
public void testUserAttributeStatementMapperGroupsAggregate() throws Exception {
UserResource userResource = ApiUtil.findUserByUsernameId(testRealmResource(), "bburke");
GroupRepresentation group1 = new GroupRepresentation();
group1.setName("group1");
group1.setAttributes(new HashMap<>());
group1.getAttributes().put("group-value", Arrays.asList("value1", "value2"));
testRealmResource().groups().add(group1);
group1 = testRealmResource().getGroupByPath("/group1");
userResource.joinGroup(group1.getId());
GroupRepresentation group2 = new GroupRepresentation();
group2.setName("group2");
group2.setAttributes(new HashMap<>());
group2.getAttributes().put("group-value", Arrays.asList("value2", "value3"));
testRealmResource().groups().add(group2);
group2 = testRealmResource().getGroupByPath("/group2");
userResource.joinGroup(group2.getId());
ClientResource clientResource = ApiUtil.findClientResourceByClientId(testRealmResource(), AbstractSamlTest.SAML_CLIENT_ID_EMPLOYEE_2);
ProtocolMappersResource protocolMappersResource = clientResource.getProtocolMappers();
@ -1311,9 +1288,14 @@ public class SAMLServletAdapterTest extends AbstractSAMLServletAdapterTest {
config.put("user.attribute", "group-value");
config.put("attribute.name", "group-attribute");
config.put("aggregate.attrs", "true");
createProtocolMapper(protocolMappersResource, "group-value", "saml", "saml-user-attribute-mapper", config);
try {
try (
AutoCloseable g1 = Creator.create(testRealmResource(), group1);
AutoCloseable g2 = Creator.create(testRealmResource(), group2);
AutoCloseable uau = UserAttributeUpdater.forUserByUsername(testRealmResource(), "bburke")
.setGroups("/group1", "/group2")
.update();
AutoCloseable c = createProtocolMapper(protocolMappersResource, "group-value", "saml", "saml-user-attribute-mapper", config)) {
employee2ServletPage.navigateTo();
assertCurrentUrlStartsWith(testRealmSAMLPostLoginPage);
testRealmSAMLPostLoginPage.form().login("bburke", "password");
@ -1330,34 +1312,20 @@ public class SAMLServletAdapterTest extends AbstractSAMLServletAdapterTest {
employee2ServletPage.logout();
checkLoggedOut(employee2ServletPage, testRealmSAMLPostLoginPage);
} finally {
// revert
userResource.leaveGroup(group1.getId());
testRealmResource().groups().group(group1.getId()).remove();
userResource.leaveGroup(group2.getId());
testRealmResource().groups().group(group2.getId()).remove();
ProtocolMapperRepresentation mapper = ProtocolMapperUtil.getMapperByNameAndProtocol(protocolMappersResource, "saml", "group-value");
protocolMappersResource.delete(mapper.getId());
}
}
@Test
public void testUserAttributeStatementMapperGroupsNoAggregate() throws Exception {
UserResource userResource = ApiUtil.findUserByUsernameId(testRealmResource(), "bburke");
GroupRepresentation group1 = new GroupRepresentation();
group1.setName("group1");
group1.setAttributes(new HashMap<>());
group1.getAttributes().put("group-value", Arrays.asList("value1", "value2"));
testRealmResource().groups().add(group1);
group1 = testRealmResource().getGroupByPath("/group1");
userResource.joinGroup(group1.getId());
GroupRepresentation group2 = new GroupRepresentation();
group2.setName("group2");
group2.setAttributes(new HashMap<>());
group2.getAttributes().put("group-value", Arrays.asList("value2", "value3"));
testRealmResource().groups().add(group2);
group2 = testRealmResource().getGroupByPath("/group2");
userResource.joinGroup(group2.getId());
ClientResource clientResource = ApiUtil.findClientResourceByClientId(testRealmResource(), AbstractSamlTest.SAML_CLIENT_ID_EMPLOYEE_2);
ProtocolMappersResource protocolMappersResource = clientResource.getProtocolMappers();
@ -1366,9 +1334,14 @@ public class SAMLServletAdapterTest extends AbstractSAMLServletAdapterTest {
config.put("attribute.nameformat", "Basic");
config.put("user.attribute", "group-value");
config.put("attribute.name", "group-attribute");
createProtocolMapper(protocolMappersResource, "group-value", "saml", "saml-user-attribute-mapper", config);
try {
try (
AutoCloseable g1 = Creator.create(testRealmResource(), group1);
AutoCloseable g2 = Creator.create(testRealmResource(), group2);
AutoCloseable uau = UserAttributeUpdater.forUserByUsername(testRealmResource(), "bburke")
.setGroups("/group1", "/group2")
.update();
AutoCloseable c = createProtocolMapper(protocolMappersResource, "group-value", "saml", "saml-user-attribute-mapper", config)) {
employee2ServletPage.navigateTo();
assertCurrentUrlStartsWith(testRealmSAMLPostLoginPage);
testRealmSAMLPostLoginPage.form().login("bburke", "password");
@ -1384,14 +1357,6 @@ public class SAMLServletAdapterTest extends AbstractSAMLServletAdapterTest {
employee2ServletPage.logout();
checkLoggedOut(employee2ServletPage, testRealmSAMLPostLoginPage);
} finally {
// revert
userResource.leaveGroup(group1.getId());
testRealmResource().groups().group(group1.getId()).remove();
userResource.leaveGroup(group2.getId());
testRealmResource().groups().group(group2.getId()).remove();
ProtocolMapperRepresentation mapper = ProtocolMapperUtil.getMapperByNameAndProtocol(protocolMappersResource, "saml", "group-value");
protocolMappersResource.delete(mapper.getId());
}
}
@ -1404,19 +1369,19 @@ public class SAMLServletAdapterTest extends AbstractSAMLServletAdapterTest {
config.put("attribute.nameformat", "Basic");
config.put("user.attribute", "topAttribute");
config.put("attribute.name", "topAttribute");
createProtocolMapper(protocolMappersResource, "topAttribute", "saml", "saml-user-attribute-mapper", config);
getCleanup().addCleanup(createProtocolMapper(protocolMappersResource, "topAttribute", "saml", "saml-user-attribute-mapper", config));
config = new LinkedHashMap<>();
config.put("attribute.nameformat", "Basic");
config.put("user.attribute", "level2Attribute");
config.put("attribute.name", "level2Attribute");
createProtocolMapper(protocolMappersResource, "level2Attribute", "saml", "saml-user-attribute-mapper", config);
getCleanup().addCleanup(createProtocolMapper(protocolMappersResource, "level2Attribute", "saml", "saml-user-attribute-mapper", config));
config = new LinkedHashMap<>();
config.put("attribute.nameformat", "Basic");
config.put("single", "true");
config.put("attribute.name", "group");
createProtocolMapper(protocolMappersResource, "groups", "saml", "saml-group-membership-mapper", config);
getCleanup().addCleanup(createProtocolMapper(protocolMappersResource, "groups", "saml", "saml-group-membership-mapper", config));
setRolesToCheck("manager,user");
@ -1454,25 +1419,34 @@ public class SAMLServletAdapterTest extends AbstractSAMLServletAdapterTest {
config.put("attribute.value", "hard");
config.put("attribute.nameformat", "Basic");
config.put("attribute.name", "hardcoded-attribute");
createProtocolMapper(protocolMappersResource, "hardcoded-attribute", "saml", "saml-hardcode-attribute-mapper", config);
getCleanup().addCleanup(createProtocolMapper(protocolMappersResource, "hardcoded-attribute", "saml", "saml-hardcode-attribute-mapper", config));
config = new LinkedHashMap<>();
config.put("role", "hardcoded-role");
createProtocolMapper(protocolMappersResource, "hardcoded-role", "saml", "saml-hardcode-role-mapper", config);
getCleanup().addCleanup(createProtocolMapper(protocolMappersResource, "hardcoded-role", "saml", "saml-hardcode-role-mapper", config));
config = new LinkedHashMap<>();
config.put("new.role.name", "pee-on");
config.put("role", "http://localhost:8280/employee/.employee");
createProtocolMapper(protocolMappersResource, "renamed-employee-role", "saml", "saml-role-name-mapper", config);
getCleanup().addCleanup(createProtocolMapper(protocolMappersResource, "renamed-employee-role", "saml", "saml-role-name-mapper", config));
for (ProtocolMapperRepresentation mapper : clientResource.toRepresentation().getProtocolMappers()) {
if (mapper.getName().equals("role-list")) {
protocolMappersResource.delete(mapper.getId());
Map<String, String> origConfig = new HashMap<>(mapper.getConfig());
mapper.setId(null);
mapper.getConfig().put(RoleListMapper.SINGLE_ROLE_ATTRIBUTE, "true");
mapper.getConfig().put(AttributeStatementHelper.SAML_ATTRIBUTE_NAME, "memberOf");
protocolMappersResource.createMapper(mapper);
try (Response response = protocolMappersResource.createMapper(mapper)) {
String createdId = getCreatedId(response);
getCleanup().addCleanup((Runnable) () -> {
protocolMappersResource.delete(createdId);
mapper.setConfig(origConfig);
protocolMappersResource.createMapper(mapper).close();
});
}
}
}
@ -1481,7 +1455,7 @@ public class SAMLServletAdapterTest extends AbstractSAMLServletAdapterTest {
config = new LinkedHashMap<>();
config.put("new.role.name", "el-jefe");
config.put("role", "user");
createProtocolMapper(protocolMappersResource, "renamed-role", "saml", "saml-role-name-mapper", config);
getCleanup().addCleanup(createProtocolMapper(protocolMappersResource, "renamed-role", "saml", "saml-role-name-mapper", config));
employee2ServletPage.navigateTo();
assertCurrentUrlStartsWith(testRealmSAMLPostLoginPage);
@ -1862,13 +1836,16 @@ public class SAMLServletAdapterTest extends AbstractSAMLServletAdapterTest {
}
}
private void createProtocolMapper(ProtocolMappersResource resource, String name, String protocol, String protocolMapper, Map<String, String> config) {
private AutoCloseable createProtocolMapper(ProtocolMappersResource resource, String name, String protocol, String protocolMapper, Map<String, String> config) {
ProtocolMapperRepresentation representation = new ProtocolMapperRepresentation();
representation.setName(name);
representation.setProtocol(protocol);
representation.setProtocolMapper(protocolMapper);
representation.setConfig(config);
resource.createMapper(representation);
try (Response response = resource.createMapper(representation)) {
String createdId = getCreatedId(response);
return () -> resource.delete(createdId);
}
}
private void setRolesToCheck(String roles) {

View file

@ -27,7 +27,6 @@ import org.junit.rules.ExpectedException;
import org.keycloak.OAuth2Constants;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.admin.client.resource.ServerInfoResource;
import org.keycloak.common.util.Time;
import org.keycloak.events.admin.OperationType;
import org.keycloak.events.admin.ResourceType;
@ -52,7 +51,6 @@ import org.keycloak.testsuite.auth.page.AuthRealm;
import org.keycloak.testsuite.client.KeycloakTestingClient;
import org.keycloak.testsuite.runonserver.RunOnServerDeployment;
import org.keycloak.testsuite.runonserver.RunHelpers;
import org.keycloak.testsuite.updaters.RealmCreator;
import org.keycloak.testsuite.util.AdminEventPaths;
import org.keycloak.testsuite.util.ClientBuilder;
import org.keycloak.testsuite.util.CredentialBuilder;
@ -64,7 +62,6 @@ import org.keycloak.util.JsonSerialization;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.Response;
import java.io.Closeable;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
@ -80,6 +77,7 @@ import org.keycloak.events.EventType;
import org.keycloak.events.log.JBossLoggingEventListenerProviderFactory;
import org.keycloak.representations.idm.RealmEventsConfigRepresentation;
import org.keycloak.testsuite.events.EventsListenerProviderFactory;
import org.keycloak.testsuite.updaters.Creator;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
@ -242,10 +240,10 @@ public class RealmTest extends AbstractAdminTest {
//KEYCLOAK-6146
@Test
public void createRealmWithPasswordPolicyFromJsonWithValidPasswords() throws IOException {
public void createRealmWithPasswordPolicyFromJsonWithValidPasswords() {
RealmRepresentation rep = loadJson(getClass().getResourceAsStream("/import/testrealm-keycloak-6146.json"), RealmRepresentation.class);
try (RealmCreator c = new RealmCreator(adminClient, rep)) {
RealmRepresentation created = c.realm().toRepresentation();
try (Creator<RealmResource> c = Creator.create(adminClient, rep)) {
RealmRepresentation created = c.resource().toRepresentation();
assertRealm(rep, created);
}
}