Ensure code does not rely on a particular format for the realm id or component id

This commit is contained in:
Stefan Guilhen 2022-03-28 18:37:18 -03:00 committed by Hynek Mlnařík
parent ae90b232ff
commit b29b27d731
84 changed files with 554 additions and 375 deletions

View file

@ -1039,7 +1039,7 @@ public class RealmAdapter implements CachedRealmModel {
@Override
public ClientModel getMasterAdminClient() {
return cached.getMasterAdminClient()==null ? null : cacheSession.getRealm(Config.getAdminRealm()).getClientById(cached.getMasterAdminClient());
return cached.getMasterAdminClient()==null ? null : cacheSession.getRealmByName(Config.getAdminRealm()).getClientById(cached.getMasterAdminClient());
}
@Override

View file

@ -1165,7 +1165,7 @@ public class RealmAdapter implements RealmModel, JpaModel<RealmEntity> {
}
RealmModel masterRealm = getName().equals(Config.getAdminRealm())
? this
: session.realms().getRealm(Config.getAdminRealm());
: session.realms().getRealmByName(Config.getAdminRealm());
return session.clients().getClientById(masterRealm, masterAdminClientId);
}

View file

@ -39,6 +39,8 @@ import org.keycloak.models.map.authSession.MapRootAuthenticationSessionEntity.Ab
import org.keycloak.models.map.common.DeepCloner;
import static org.keycloak.models.map.storage.jpa.Constants.CURRENT_SCHEMA_VERSION_AUTH_SESSION;
import static org.keycloak.models.map.storage.jpa.JpaMapStorageProviderFactory.CLONER;
import org.keycloak.models.map.common.UuidValidator;
import org.keycloak.models.map.storage.jpa.JpaRootVersionedEntity;
import org.keycloak.models.map.storage.jpa.hibernate.jsonb.JsonbType;
@ -143,7 +145,8 @@ public class JpaRootAuthenticationSessionEntity extends AbstractRootAuthenticati
@Override
public void setId(String id) {
this.id = id == null ? null : UUID.fromString(id);
String validatedId = UuidValidator.validateAndConvert(id);
this.id = UUID.fromString(validatedId);
}
@Override

View file

@ -43,6 +43,8 @@ import org.keycloak.models.map.client.MapClientEntity.AbstractClientEntity;
import org.keycloak.models.map.client.MapProtocolMapperEntity;
import org.keycloak.models.map.common.DeepCloner;
import static org.keycloak.models.map.storage.jpa.Constants.CURRENT_SCHEMA_VERSION_CLIENT;
import org.keycloak.models.map.common.UuidValidator;
import org.keycloak.models.map.storage.jpa.JpaRootVersionedEntity;
import org.keycloak.models.map.storage.jpa.hibernate.jsonb.JsonbType;
@ -156,7 +158,8 @@ public class JpaClientEntity extends AbstractClientEntity implements JpaRootVers
@Override
public void setId(String id) {
this.id = id == null ? null : UUID.fromString(id);
String validatedId = UuidValidator.validateAndConvert(id);
this.id = UUID.fromString(validatedId);
}
@Override

View file

@ -43,6 +43,8 @@ import org.keycloak.models.map.client.MapProtocolMapperEntity;
import org.keycloak.models.map.clientscope.MapClientScopeEntity.AbstractClientScopeEntity;
import org.keycloak.models.map.common.DeepCloner;
import static org.keycloak.models.map.storage.jpa.Constants.CURRENT_SCHEMA_VERSION_CLIENT_SCOPE;
import org.keycloak.models.map.common.UuidValidator;
import org.keycloak.models.map.storage.jpa.JpaRootVersionedEntity;
import org.keycloak.models.map.storage.jpa.hibernate.jsonb.JsonbType;
@ -140,7 +142,8 @@ public class JpaClientScopeEntity extends AbstractClientScopeEntity implements J
@Override
public void setId(String id) {
this.id = id == null ? null : UUID.fromString(id);
String validatedId = UuidValidator.validateAndConvert(id);
this.id = UUID.fromString(validatedId);
}
@Override

View file

@ -39,6 +39,7 @@ import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;
import org.keycloak.models.map.common.DeepCloner;
import org.keycloak.models.map.common.UuidValidator;
import org.keycloak.models.map.group.MapGroupEntity.AbstractGroupEntity;
import static org.keycloak.models.map.storage.jpa.Constants.CURRENT_SCHEMA_VERSION_GROUP;
import org.keycloak.models.map.storage.jpa.JpaRootVersionedEntity;
@ -144,7 +145,8 @@ public class JpaGroupEntity extends AbstractGroupEntity implements JpaRootVersio
@Override
public void setId(String id) {
this.id = id == null ? null : UUID.fromString(id);
String validatedId = UuidValidator.validateAndConvert(id);
this.id = UUID.fromString(validatedId);
}
@Override

View file

@ -59,13 +59,11 @@ public class JpaRealmDelegateProvider extends JpaDelegateProvider<JpaRealmEntity
return getDelegate();
case ATTRIBUTES:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<JpaRealmEntity> query = cb.createQuery(JpaRealmEntity.class);
Root<JpaRealmEntity> root = query.from(JpaRealmEntity.class);
root.fetch("attributes", JoinType.LEFT);
query.select(root).where(cb.equal(root.get("id"), UUID.fromString(getDelegate().getId())));
this.setDelegateWithAssociation("attributes");
break;
setDelegate(em.createQuery(query).getSingleResult());
case COMPONENTS:
this.setDelegateWithAssociation("components");
break;
default:
@ -77,5 +75,15 @@ public class JpaRealmDelegateProvider extends JpaDelegateProvider<JpaRealmEntity
} else {
setDelegate(em.find(JpaRealmEntity.class, UUID.fromString(getDelegate().getId())));
}
return getDelegate(); }
return getDelegate();
}
protected void setDelegateWithAssociation(final String associationName) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<JpaRealmEntity> query = cb.createQuery(JpaRealmEntity.class);
Root<JpaRealmEntity> root = query.from(JpaRealmEntity.class);
root.fetch(associationName, JoinType.LEFT);
query.select(root).where(cb.equal(root.get("id"), UUID.fromString(getDelegate().getId())));
setDelegate(em.createQuery(query).getSingleResult());
}
}

View file

@ -36,6 +36,7 @@ import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;
import org.keycloak.models.map.common.DeepCloner;
import org.keycloak.models.map.common.UpdatableEntity;
import org.keycloak.models.map.common.UuidValidator;
import org.keycloak.models.map.realm.entity.MapComponentEntity;
import org.keycloak.models.map.storage.jpa.JpaRootVersionedEntity;
import org.keycloak.models.map.storage.jpa.hibernate.jsonb.JsonbType;
@ -45,6 +46,16 @@ import static org.keycloak.models.map.storage.jpa.Constants.CURRENT_SCHEMA_VERSI
/**
* JPA {@link MapComponentEntity} implementation. Some fields are annotated with {@code @Column(insertable = false, updatable = false)}
* to indicate that they are automatically generated from json fields. As such, these fields are non-insertable and non-updatable.
* <p/>
* Components are independent (i.e. a component doesn't depend on another component) and can be manipulated directly via
* the component endpoints. Because of that, this entity implements {@link JpaRootVersionedEntity} instead of
* {@link org.keycloak.models.map.storage.jpa.JpaChildEntity}. This prevents {@link javax.persistence.OptimisticLockException}s
* when different components in the same realm are being manipulated at the same time - for example, when multiple components
* are being added to the realm by different threads.
* <p/>
* By implementing {@link JpaRootVersionedEntity}, this entity will enforce optimistic locking, which can lead to
* {@link javax.persistence.OptimisticLockException} if more than one thread attempts to modify the <b>same</b> component
* at the same time.
*
* @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a>
*/
@ -100,7 +111,8 @@ public class JpaComponentEntity extends UpdatableEntity.Impl implements MapCompo
@Override
public void setId(String id) {
this.id = id == null ? null : UUID.fromString(id);
String validatedId = UuidValidator.validateAndConvert(id);
this.id = UUID.fromString(validatedId);
}
@Override

View file

@ -42,6 +42,7 @@ import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;
import org.keycloak.models.map.common.DeepCloner;
import org.keycloak.models.map.common.UuidValidator;
import org.keycloak.models.map.realm.MapRealmEntity;
import org.keycloak.models.map.realm.entity.MapAuthenticationExecutionEntity;
import org.keycloak.models.map.realm.entity.MapAuthenticationFlowEntity;
@ -74,6 +75,7 @@ import static org.keycloak.models.map.storage.jpa.JpaMapStorageProviderFactory.C
)
})
@TypeDefs({@TypeDef(name = "jsonb", typeClass = JsonbType.class)})
@SuppressWarnings("ConstantConditions")
public class JpaRealmEntity extends MapRealmEntity.AbstractRealmEntity implements JpaRootVersionedEntity {
@Id
@ -174,7 +176,8 @@ public class JpaRealmEntity extends MapRealmEntity.AbstractRealmEntity implement
@Override
public void setId(String id) {
this.id = id == null ? null : UUID.fromString(id);
String validatedId = UuidValidator.validateAndConvert(id);
this.id = UUID.fromString(validatedId);
}
@Override
@ -190,7 +193,7 @@ public class JpaRealmEntity extends MapRealmEntity.AbstractRealmEntity implement
@Override
public String getDisplayName() {
if (isMetadataInitialized()) this.metadata.getDisplayName();
if (isMetadataInitialized()) return this.metadata.getDisplayName();
return this.displayName;
}
@ -482,12 +485,12 @@ public class JpaRealmEntity extends MapRealmEntity.AbstractRealmEntity implement
}
@Override
public Integer getNotBefore() {
public Long getNotBefore() {
return this.metadata.getNotBefore();
}
@Override
public void setNotBefore(Integer notBefore) {
public void setNotBefore(Long notBefore) {
this.metadata.setNotBefore(notBefore);
}

View file

@ -39,6 +39,7 @@ import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;
import org.keycloak.models.map.common.DeepCloner;
import org.keycloak.models.map.common.UuidValidator;
import org.keycloak.models.map.role.MapRoleEntity.AbstractRoleEntity;
import static org.keycloak.models.map.storage.jpa.Constants.CURRENT_SCHEMA_VERSION_ROLE;
import org.keycloak.models.map.storage.jpa.JpaRootVersionedEntity;
@ -148,7 +149,8 @@ public class JpaRoleEntity extends AbstractRoleEntity implements JpaRootVersione
@Override
public void setId(String id) {
this.id = id == null ? null : UUID.fromString(id);
String validatedId = UuidValidator.validateAndConvert(id);
this.id = UUID.fromString(validatedId);
}
@Override

View file

@ -0,0 +1,52 @@
/*
* Copyright 2022 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.models.map.common;
import java.util.regex.Pattern;
/**
* Utility class for validating and converting UUIDs.
*
* @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a>
*/
public class UuidValidator {
protected static final Pattern UUID_REGEX_PATTERN = Pattern.compile("^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$");
private UuidValidator() {}
/**
* Validates that the specified {@code id} is a {@code UUID}.
*
* @param id the {@code id} to be validated.
* @return {@code true} if the {@code id} is a {@code UUID}; {@code false} otherwise.
*/
public static boolean isValid(final String id) {
return (id == null) ? false : UUID_REGEX_PATTERN.matcher(id).matches();
}
/**
* Validates that the specified {@code id} is a {@code UUID}. If it is, the {@code id} itself is returned. Otherwise,
* it is discarded and a new {@code UUID} is created and returned.
*
* @param id the {@code id} to be validated.
* @return the {@code id} itself if it is a valid {@code UUID}, or a new generated {@code UUID}.
*/
public static String validateAndConvert(final String id) {
return isValid(id) ? id : StringKeyConverter.UUIDKey.INSTANCE.yieldNewUniqueKey().toString();
}
}

View file

@ -1313,7 +1313,7 @@ public class MapRealmAdapter extends AbstractRealmModel<MapRealmEntity> implemen
}
RealmModel masterRealm = getName().equals(Config.getAdminRealm())
? this
: session.realms().getRealm(Config.getAdminRealm());
: session.realms().getRealmByName(Config.getAdminRealm());
return session.clients().getClientById(masterRealm, masterAdminClientId);
}

View file

@ -45,7 +45,9 @@ public interface MapAuthenticatorConfigEntity extends UpdatableEntity, AbstractE
AuthenticatorConfigModel model = new AuthenticatorConfigModel();
model.setId(entity.getId());
model.setAlias(entity.getAlias());
model.setConfig(entity.getConfig());
Map<String, String> config = new HashMap<>();
if (entity.getConfig() != null) config.putAll(entity.getConfig());
model.setConfig(config);
return model;
}

View file

@ -34,7 +34,7 @@ public class MigrateTo1_9_0 implements Migration {
}
public void migrate(KeycloakSession session) {
RealmModel realm = session.realms().getRealm(Config.getAdminRealm());
RealmModel realm = session.realms().getRealmByName(Config.getAdminRealm());
if (realm != null && realm.getDisplayNameHtml() != null && realm.getDisplayNameHtml().equals("<strong>Keycloak</strong>")) {
realm.setDisplayNameHtml("<div class=\"kc-logo-text\"><span>Keycloak</span></div>");
}

View file

@ -36,7 +36,7 @@ public class ImpersonationConstants {
adminRealm = realm;
adminRole = realm.getRole(AdminRoles.ADMIN);
} else {
adminRealm = model.getRealm(Config.getAdminRealm());
adminRealm = model.getRealmByName(Config.getAdminRealm());
adminRole = adminRealm.getRole(AdminRoles.ADMIN);
}
ClientModel realmAdminApp = adminRealm.getClientByClientId(KeycloakModelUtils.getMasterRealmAdminApplicationClientId(realm.getName()));

View file

@ -40,7 +40,9 @@ public interface RealmProvider extends Provider /* TODO: Remove in future versio
/**
* Created new realm with given ID and name.
* @param id Internal ID of the realm or {@code null} if one is to be created by the underlying store
* @param id Internal ID of the realm or {@code null} if one is to be created by the underlying store. If the store
* expects the ID to have a certain format (for example {@code UUID}) and the supplied ID doesn't follow
* the expected format, the store may replace the {@code id} with a new one at its own discretion.
* @param name String name of the realm
* @return Model of the created realm.
*/

View file

@ -1352,7 +1352,7 @@ public class SamlService extends AuthorizationEndpointBase {
Resteasy.pushContext(ClientConnection.class, connection);
RealmManager realmManager = new RealmManager(session);
RealmModel realm = realmManager.getRealmByName(realmId);
RealmModel realm = realmManager.getRealm(realmId);
if (realm == null) {
throw new NotFoundException("Realm does not exist");
}

View file

@ -43,7 +43,7 @@ public class ApplianceBootstrap {
}
public boolean isNewInstall() {
if (session.realms().getRealm(Config.getAdminRealm()) != null) {
if (session.realms().getRealmByName(Config.getAdminRealm()) != null) {
return false;
} else {
return true;
@ -51,7 +51,7 @@ public class ApplianceBootstrap {
}
public boolean isNoMasterUser() {
RealmModel realm = session.realms().getRealm(Config.getAdminRealm());
RealmModel realm = session.realms().getRealmByName(Config.getAdminRealm());
return session.users().getUsersCount(realm) == 0;
}
@ -64,7 +64,7 @@ public class ApplianceBootstrap {
ServicesLogger.LOGGER.initializingAdminRealm(adminRealmName);
RealmManager manager = new RealmManager(session);
RealmModel realm = manager.createRealm(adminRealmName, adminRealmName);
RealmModel realm = manager.createRealm(adminRealmName);
realm.setName(adminRealmName);
realm.setDisplayName(Version.NAME);
realm.setDisplayNameHtml(Version.NAME_HTML);
@ -93,7 +93,7 @@ public class ApplianceBootstrap {
}
public void createMasterRealmUser(String username, String password) {
RealmModel realm = session.realms().getRealm(Config.getAdminRealm());
RealmModel realm = session.realms().getRealmByName(Config.getAdminRealm());
session.getContext().setRealm(realm);
if (session.users().getUsersCount(realm) > 0) {

View file

@ -81,7 +81,7 @@ public class RealmManager {
}
public RealmModel getKeycloakAdminstrationRealm() {
return getRealm(Config.getAdminRealm());
return getRealmByName(Config.getAdminRealm());
}
public RealmModel getRealm(String id) {
@ -93,11 +93,11 @@ public class RealmManager {
}
public RealmModel createRealm(String name) {
return createRealm(name, name);
return createRealm(null, name);
}
public RealmModel createRealm(String id, String name) {
if (id == null) {
if (id == null || id.trim().isEmpty()) {
id = KeycloakModelUtils.generateId();
}
else {
@ -299,8 +299,8 @@ public class RealmManager {
public void setupMasterAdminManagement(RealmModel realm) {
// Need to refresh masterApp for current realm
String adminRealmId = Config.getAdminRealm();
RealmModel adminRealm = model.getRealm(adminRealmId);
String adminRealmName = Config.getAdminRealm();
RealmModel adminRealm = model.getRealmByName(adminRealmName);
ClientModel masterApp = adminRealm.getClientByClientId(KeycloakModelUtils.getMasterRealmAdminApplicationClientId(realm.getName()));
if (masterApp == null) {
createMasterAdminManagement(realm);
@ -322,7 +322,7 @@ public class RealmManager {
adminRole.addCompositeRole(createRealmRole);
createRealmRole.setDescription("${role_" + AdminRoles.CREATE_REALM + "}");
} else {
adminRealm = model.getRealm(Config.getAdminRealm());
adminRealm = model.getRealmByName(Config.getAdminRealm());
adminRole = adminRealm.getRole(AdminRoles.ADMIN);
}
adminRole.setDescription("${role_"+AdminRoles.ADMIN+"}");

View file

@ -1,2 +0,0 @@
package org.keycloak.utils;public class UuidValidator {
}

View file

@ -613,7 +613,7 @@ public class TestingResourceProvider implements RealmResourceProvider {
@Path("/valid-credentials")
@Produces(MediaType.APPLICATION_JSON)
public boolean validCredentials(@QueryParam("realmName") String realmName, @QueryParam("userName") String userName, @QueryParam("password") String password) {
RealmModel realm = session.realms().getRealm(realmName);
RealmModel realm = session.realms().getRealmByName(realmName);
if (realm == null) return false;
UserProvider userProvider = session.getProvider(UserProvider.class);
UserModel user = userProvider.getUserByUsername(realm, userName);

View file

@ -136,7 +136,7 @@ public class TokenSignatureUtil {
private static void registerKeyProvider(String realm, String providerSpecificKey, String providerSpecificValue, String providerId, Keycloak adminClient, TestContext testContext) {
long priority = System.currentTimeMillis();
ComponentRepresentation rep = createKeyRep("valid", providerId);
ComponentRepresentation rep = createKeyRep("valid", providerId, adminClient);
rep.setConfig(new MultivaluedHashMap<>());
rep.getConfig().putSingle("priority", Long.toString(priority));
rep.getConfig().putSingle(providerSpecificKey, providerSpecificValue);
@ -147,10 +147,10 @@ public class TokenSignatureUtil {
}
}
private static ComponentRepresentation createKeyRep(String name, String providerId) {
private static ComponentRepresentation createKeyRep(String name, String providerId, Keycloak adminClient) {
ComponentRepresentation rep = new ComponentRepresentation();
rep.setName(name);
rep.setParentId(TEST_REALM_NAME);
rep.setParentId(adminClient.realm(TEST_REALM_NAME).toRepresentation().getId());
rep.setProviderId(providerId);
rep.setProviderType(KeyProvider.class.getName());
rep.setConfig(new MultivaluedHashMap<>());

View file

@ -658,7 +658,7 @@ public class SAMLServletAdapterTest extends AbstractSAMLServletAdapterTest {
ComponentRepresentation rep = new ComponentRepresentation();
rep.setName("mycomponent");
rep.setParentId("demo");
rep.setParentId(adminClient.realm(DEMO).toRepresentation().getId());
rep.setProviderId(ImportedRsaKeyProviderFactory.ID);
rep.setProviderType(KeyProvider.class.getName());
@ -673,7 +673,8 @@ public class SAMLServletAdapterTest extends AbstractSAMLServletAdapterTest {
}
private void dropKeys(String priority) {
for (ComponentRepresentation c : testRealmResource().components().query("demo", KeyProvider.class.getName())) {
String parentId = adminClient.realm(DEMO).toRepresentation().getId();
for (ComponentRepresentation c : testRealmResource().components().query(parentId, KeyProvider.class.getName())) {
if (c.getConfig().getFirst("priority").equals(priority)) {
testRealmResource().components().component(c.getId()).remove();
return;

View file

@ -31,6 +31,8 @@ import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.keycloak.testsuite.auth.page.AuthRealm.TEST;
import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;
import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer;
@ -54,7 +56,8 @@ public class AttackDetectionResourceTest extends AbstractAdminTest {
@Test
public void test() {
AttackDetectionResource detection = adminClient.realm("test").attackDetection();
AttackDetectionResource detection = adminClient.realm(TEST).attackDetection();
String realmId = adminClient.realm(TEST).toRepresentation().getId();
assertBruteForce(detection.bruteForceUserStatus(findUser("test-user@localhost").getId()), 0, false, false);
@ -71,13 +74,13 @@ public class AttackDetectionResourceTest extends AbstractAdminTest {
assertBruteForce(detection.bruteForceUserStatus("nosuchuser"), 0, false, false);
detection.clearBruteForceForUser(findUser("test-user@localhost").getId());
assertAdminEvents.assertEvent("test", OperationType.DELETE, AdminEventPaths.attackDetectionClearBruteForceForUserPath(findUser("test-user@localhost").getId()), ResourceType.USER_LOGIN_FAILURE);
assertAdminEvents.assertEvent(realmId, OperationType.DELETE, AdminEventPaths.attackDetectionClearBruteForceForUserPath(findUser("test-user@localhost").getId()), ResourceType.USER_LOGIN_FAILURE);
assertBruteForce(detection.bruteForceUserStatus(findUser("test-user@localhost").getId()), 0, false, false);
assertBruteForce(detection.bruteForceUserStatus(findUser("test-user2").getId()), 2, true, true);
detection.clearAllBruteForce();
assertAdminEvents.assertEvent("test", OperationType.DELETE, AdminEventPaths.attackDetectionClearAllBruteForcePath(), ResourceType.USER_LOGIN_FAILURE);
assertAdminEvents.assertEvent(realmId, OperationType.DELETE, AdminEventPaths.attackDetectionClearAllBruteForcePath(), ResourceType.USER_LOGIN_FAILURE);
assertBruteForce(detection.bruteForceUserStatus(findUser("test-user@localhost").getId()), 0, false, false);
assertBruteForce(detection.bruteForceUserStatus(findUser("test-user2").getId()), 0, false, false);

View file

@ -23,6 +23,7 @@ import org.junit.Test;
import org.keycloak.admin.client.resource.ComponentsResource;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.common.util.MultivaluedHashMap;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.representations.idm.*;
import org.keycloak.testsuite.components.TestProvider;
@ -166,10 +167,11 @@ public class ComponentsTest extends AbstractAdminTest {
public void testCreateWithGivenId() {
ComponentRepresentation rep = createComponentRepresentation("mycomponent");
rep.getConfig().addFirst("required", "foo");
rep.setId("fixed-id");
String componentId = KeycloakModelUtils.generateId();
rep.setId(componentId);
String id = createComponent(rep);
assertEquals("fixed-id", id);
assertEquals(componentId, id);
}
@Test

View file

@ -46,6 +46,7 @@ import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.UserModel;
import org.keycloak.models.credential.OTPCredentialModel;
import org.keycloak.models.credential.PasswordCredentialModel;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.models.utils.ModelToRepresentation;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.idm.ClientRepresentation;
@ -520,18 +521,19 @@ public class UserTest extends AbstractAdminTest {
// add a dummy federation provider
ComponentRepresentation dummyFederationProvider = new ComponentRepresentation();
dummyFederationProvider.setId(DummyUserFederationProviderFactory.PROVIDER_NAME);
String componentId = KeycloakModelUtils.generateId();
dummyFederationProvider.setId(componentId);
dummyFederationProvider.setName(DummyUserFederationProviderFactory.PROVIDER_NAME);
dummyFederationProvider.setProviderId(DummyUserFederationProviderFactory.PROVIDER_NAME);
dummyFederationProvider.setProviderType(UserStorageProvider.class.getName());
adminClient.realms().realm(REALM_NAME).components().add(dummyFederationProvider);
assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.componentPath(DummyUserFederationProviderFactory.PROVIDER_NAME), dummyFederationProvider, ResourceType.COMPONENT);
assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.componentPath(componentId), dummyFederationProvider, ResourceType.COMPONENT);
UserRepresentation user = new UserRepresentation();
user.setUsername("user1");
user.setEmail("user1@localhost");
user.setFederationLink(DummyUserFederationProviderFactory.PROVIDER_NAME);
user.setFederationLink(componentId);
String userId = createUser(user);
@ -2288,6 +2290,7 @@ public class UserTest extends AbstractAdminTest {
@Test
public void roleMappings() {
RealmResource realm = adminClient.realms().realm("test");
String realmId = realm.toRepresentation().getId();
// Enable events
RealmRepresentation realmRep = RealmBuilder.edit(realm.toRepresentation()).testEventListener().build();
@ -2331,16 +2334,16 @@ public class UserTest extends AbstractAdminTest {
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.userRealmRoleMappingsPath(userId), l, ResourceType.REALM_ROLE_MAPPING);
assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.userRealmRoleMappingsPath(userId), l, ResourceType.REALM_ROLE_MAPPING);
// Add client roles
List<RoleRepresentation> list = Collections.singletonList(realm.clients().get(clientUuid).roles().get("client-role").toRepresentation());
roles.clientLevel(clientUuid).add(list);
assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.userClientRoleMappingsPath(userId, clientUuid), list, ResourceType.CLIENT_ROLE_MAPPING);
assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.userClientRoleMappingsPath(userId, clientUuid), list, ResourceType.CLIENT_ROLE_MAPPING);
list = Collections.singletonList(realm.clients().get(clientUuid).roles().get("client-composite").toRepresentation());
roles.clientLevel(clientUuid).add(list);
assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.userClientRoleMappingsPath(userId, clientUuid), ResourceType.CLIENT_ROLE_MAPPING);
assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.userClientRoleMappingsPath(userId, clientUuid), ResourceType.CLIENT_ROLE_MAPPING);
// List realm roles
assertNames(roles.realmLevel().listAll(), "realm-role", "realm-composite", Constants.DEFAULT_ROLES_ROLE_PREFIX + "-test");
@ -2373,14 +2376,14 @@ public class UserTest extends AbstractAdminTest {
// Remove realm role
RoleRepresentation realmRoleRep = realm.roles().get("realm-role").toRepresentation();
roles.realmLevel().remove(Collections.singletonList(realmRoleRep));
assertAdminEvents.assertEvent("test", OperationType.DELETE, AdminEventPaths.userRealmRoleMappingsPath(userId), Collections.singletonList(realmRoleRep), ResourceType.REALM_ROLE_MAPPING);
assertAdminEvents.assertEvent(realmId, OperationType.DELETE, AdminEventPaths.userRealmRoleMappingsPath(userId), Collections.singletonList(realmRoleRep), ResourceType.REALM_ROLE_MAPPING);
assertNames(roles.realmLevel().listAll(), "realm-composite", Constants.DEFAULT_ROLES_ROLE_PREFIX + "-test");
// Remove client role
RoleRepresentation clientRoleRep = realm.clients().get(clientUuid).roles().get("client-role").toRepresentation();
roles.clientLevel(clientUuid).remove(Collections.singletonList(clientRoleRep));
assertAdminEvents.assertEvent("test", OperationType.DELETE, AdminEventPaths.userClientRoleMappingsPath(userId, clientUuid), Collections.singletonList(clientRoleRep), ResourceType.CLIENT_ROLE_MAPPING);
assertAdminEvents.assertEvent(realmId, OperationType.DELETE, AdminEventPaths.userClientRoleMappingsPath(userId, clientUuid), Collections.singletonList(clientRoleRep), ResourceType.CLIENT_ROLE_MAPPING);
assertNames(roles.clientLevel(clientUuid).listAll(), "client-composite");
}

View file

@ -66,8 +66,8 @@ public class UsersTest extends AbstractAdminTest {
@Test
public void findUsersByEmailVerifiedStatus() {
createUser(realmId, "user1", "password", "user1FirstName", "user1LastName", "user1@example.com", rep -> rep.setEmailVerified(true));
createUser(realmId, "user2", "password", "user2FirstName", "user2LastName", "user2@example.com", rep -> rep.setEmailVerified(false));
createUser(REALM_NAME, "user1", "password", "user1FirstName", "user1LastName", "user1@example.com", rep -> rep.setEmailVerified(true));
createUser(REALM_NAME, "user2", "password", "user2FirstName", "user2LastName", "user2@example.com", rep -> rep.setEmailVerified(false));
boolean emailVerified;
emailVerified = true;
@ -87,9 +87,9 @@ public class UsersTest extends AbstractAdminTest {
@Test
public void countUsersByEmailVerifiedStatus() {
createUser(realmId, "user1", "password", "user1FirstName", "user1LastName", "user1@example.com", rep -> rep.setEmailVerified(true));
createUser(realmId, "user2", "password", "user2FirstName", "user2LastName", "user2@example.com", rep -> rep.setEmailVerified(false));
createUser(realmId, "user3", "password", "user3FirstName", "user3LastName", "user3@example.com", rep -> rep.setEmailVerified(true));
createUser(REALM_NAME, "user1", "password", "user1FirstName", "user1LastName", "user1@example.com", rep -> rep.setEmailVerified(true));
createUser(REALM_NAME, "user2", "password", "user2FirstName", "user2LastName", "user2@example.com", rep -> rep.setEmailVerified(false));
createUser(REALM_NAME, "user3", "password", "user3FirstName", "user3LastName", "user3@example.com", rep -> rep.setEmailVerified(true));
boolean emailVerified;
emailVerified = true;
@ -103,16 +103,16 @@ public class UsersTest extends AbstractAdminTest {
@Test
public void countUsersWithViewPermission() {
createUser(realmId, "user1", "password", "user1FirstName", "user1LastName", "user1@example.com");
createUser(realmId, "user2", "password", "user2FirstName", "user2LastName", "user2@example.com");
createUser(REALM_NAME, "user1", "password", "user1FirstName", "user1LastName", "user1@example.com");
createUser(REALM_NAME, "user2", "password", "user2FirstName", "user2LastName", "user2@example.com");
assertThat(realm.users().count(), is(2));
}
@Test
public void countUsersBySearchWithViewPermission() {
createUser(realmId, "user1", "password", "user1FirstName", "user1LastName", "user1@example.com", rep -> rep.setEmailVerified(true));
createUser(realmId, "user2", "password", "user2FirstName", "user2LastName", "user2@example.com", rep -> rep.setEmailVerified(false));
createUser(realmId, "user3", "password", "user3FirstName", "user3LastName", "user3@example.com", rep -> rep.setEmailVerified(true));
createUser(REALM_NAME, "user1", "password", "user1FirstName", "user1LastName", "user1@example.com", rep -> rep.setEmailVerified(true));
createUser(REALM_NAME, "user2", "password", "user2FirstName", "user2LastName", "user2@example.com", rep -> rep.setEmailVerified(false));
createUser(REALM_NAME, "user3", "password", "user3FirstName", "user3LastName", "user3@example.com", rep -> rep.setEmailVerified(true));
// Prefix search count
Integer count = realm.users().count("user");
@ -189,8 +189,8 @@ public class UsersTest extends AbstractAdminTest {
@Test
public void countUsersByFiltersWithViewPermission() {
createUser(realmId, "user1", "password", "user1FirstName", "user1LastName", "user1@example.com");
createUser(realmId, "user2", "password", "user2FirstName", "user2LastName", "user2@example.com");
createUser(REALM_NAME, "user1", "password", "user1FirstName", "user1LastName", "user1@example.com");
createUser(REALM_NAME, "user2", "password", "user2FirstName", "user2LastName", "user2@example.com");
//search username
assertThat(realm.users().count(null, null, null, "user"), is(2));
assertThat(realm.users().count(null, null, null, "user1"), is(1));
@ -362,7 +362,7 @@ public class UsersTest extends AbstractAdminTest {
}
private RealmResource setupTestEnvironmentWithPermissions(boolean grp1ViewPermissions) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
String testUserId = createUser(realmId, "test-user", "password", "", "", "");
String testUserId = createUser(REALM_NAME, "test-user", "password", "", "", "");
//assign 'query-users' role to test user
ClientRepresentation clientRepresentation = realm.clients().findByClientId("realm-management").get(0);
String realmManagementId = clientRepresentation.getId();
@ -401,10 +401,10 @@ public class UsersTest extends AbstractAdminTest {
GroupRepresentation grp1 = createGroupWithPermissions("grp1");
GroupRepresentation grp2 = createGroupWithPermissions("grp2");
//create test users
String user1Id = createUser(realmId, "user1", "password", "user1FirstName", "user1LastName", "user1@example.com");
String user2Id = createUser(realmId, "user2", "password", "user2FirstName", "user2LastName", "user2@example.com");
String user3Id = createUser(realmId, "user3", "password", "user3FirstName", "user3LastName", "user3@example.com");
String user4Id = createUser(realmId, "user4", "password", "user4FirstName", "user4LastName", "user4@example.com");
String user1Id = createUser(REALM_NAME, "user1", "password", "user1FirstName", "user1LastName", "user1@example.com");
String user2Id = createUser(REALM_NAME, "user2", "password", "user2FirstName", "user2LastName", "user2@example.com");
String user3Id = createUser(REALM_NAME, "user3", "password", "user3FirstName", "user3LastName", "user3@example.com");
String user4Id = createUser(REALM_NAME, "user4", "password", "user4FirstName", "user4LastName", "user4@example.com");
//add users to groups
realm.users().get(user1Id).joinGroup(grp1.getId());
realm.users().get(user2Id).joinGroup(grp1.getId());

View file

@ -55,6 +55,7 @@ public abstract class AbstractAuthenticationTest extends AbstractKeycloakTest {
RealmResource realmResource;
AuthenticationManagementResource authMgmtResource;
protected String testRealmId;
@Rule
public AssertAdminEvents assertAdminEvents = new AssertAdminEvents(this);
@ -63,6 +64,7 @@ public abstract class AbstractAuthenticationTest extends AbstractKeycloakTest {
public void before() {
realmResource = adminClient.realms().realm(REALM_NAME);
authMgmtResource = realmResource.flows();
testRealmId = realmResource.toRepresentation().getId();
}
@Override
@ -199,6 +201,6 @@ public abstract class AbstractAuthenticationTest extends AbstractKeycloakTest {
response.close();
String flowId = ApiUtil.getCreatedId(response);
getCleanup().addAuthenticationFlowId(flowId);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AssertAdminEvents.isExpectedPrefixFollowedByUuid(AdminEventPaths.authFlowsPath()), flowRep, ResourceType.AUTH_FLOW);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AssertAdminEvents.isExpectedPrefixFollowedByUuid(AdminEventPaths.authFlowsPath()), flowRep, ResourceType.AUTH_FLOW);
}
}

View file

@ -52,7 +52,7 @@ public class AuthenticatorConfigTest extends AbstractAuthenticationTest {
HashMap<String, String> params = new HashMap<>();
params.put("provider", IdpCreateUserIfUniqueAuthenticatorFactory.PROVIDER_ID);
authMgmtResource.addExecution("firstBrokerLogin2", params);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authAddExecutionPath("firstBrokerLogin2"), params, ResourceType.AUTH_EXECUTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.authAddExecutionPath("firstBrokerLogin2"), params, ResourceType.AUTH_EXECUTION);
List<AuthenticationExecutionInfoRepresentation> executionReps = authMgmtResource.getExecutions("firstBrokerLogin2");
AuthenticationExecutionInfoRepresentation exec = findExecutionByProvider(IdpCreateUserIfUniqueAuthenticatorFactory.PROVIDER_ID, executionReps);
@ -85,7 +85,7 @@ public class AuthenticatorConfigTest extends AbstractAuthenticationTest {
// Cleanup
authMgmtResource.removeAuthenticatorConfig(cfgId);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.DELETE, AdminEventPaths.authExecutionConfigPath(cfgId), ResourceType.AUTHENTICATOR_CONFIG);
assertAdminEvents.assertEvent(testRealmId, OperationType.DELETE, AdminEventPaths.authExecutionConfigPath(cfgId), ResourceType.AUTHENTICATOR_CONFIG);
}
@Test (expected = BadRequestException.class)
@ -120,7 +120,7 @@ public class AuthenticatorConfigTest extends AbstractAuthenticationTest {
cfgRep.setAlias("foo2");
cfgRep.getConfig().put("configKey2", "configValue2");
authMgmtResource.updateAuthenticatorConfig(cfgRep.getId(), cfgRep);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.UPDATE, AdminEventPaths.authExecutionConfigPath(cfgId), cfgRep, ResourceType.AUTHENTICATOR_CONFIG);
assertAdminEvents.assertEvent(testRealmId, OperationType.UPDATE, AdminEventPaths.authExecutionConfigPath(cfgId), cfgRep, ResourceType.AUTHENTICATOR_CONFIG);
// Assert updated
cfgRep = authMgmtResource.getAuthenticatorConfig(cfgRep.getId());
@ -152,7 +152,7 @@ public class AuthenticatorConfigTest extends AbstractAuthenticationTest {
// Test remove our config
authMgmtResource.removeAuthenticatorConfig(cfgId);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.DELETE, AdminEventPaths.authExecutionConfigPath(cfgId), ResourceType.AUTHENTICATOR_CONFIG);
assertAdminEvents.assertEvent(testRealmId, OperationType.DELETE, AdminEventPaths.authExecutionConfigPath(cfgId), ResourceType.AUTHENTICATOR_CONFIG);
// Assert config not found
try {
@ -183,7 +183,7 @@ public class AuthenticatorConfigTest extends AbstractAuthenticationTest {
Assert.assertEquals(201, resp.getStatus());
String cfgId = ApiUtil.getCreatedId(resp);
Assert.assertNotNull(cfgId);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authAddExecutionConfigPath(executionId), cfg, ResourceType.AUTH_EXECUTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.authAddExecutionConfigPath(executionId), cfg, ResourceType.AUTH_EXECUTION);
return cfgId;
}

View file

@ -59,7 +59,7 @@ public class ExecutionTest extends AbstractAuthenticationTest {
HashMap<String, String> params = new HashMap<>();
params.put("newName", "new-browser-flow");
Response response = authMgmtResource.copy("browser", params);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authCopyFlowPath("browser"), params, ResourceType.AUTH_FLOW);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.authCopyFlowPath("browser"), params, ResourceType.AUTH_FLOW);
try {
Assert.assertEquals("Copy flow", 201, response.getStatus());
} finally {
@ -69,7 +69,7 @@ public class ExecutionTest extends AbstractAuthenticationTest {
// create Conditional OTP Form execution
params.put("provider", "auth-conditional-otp-form");
authMgmtResource.addExecution("new-browser-flow", params);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authAddExecutionPath("new-browser-flow"), params, ResourceType.AUTH_EXECUTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.authAddExecutionPath("new-browser-flow"), params, ResourceType.AUTH_EXECUTION);
List<AuthenticationExecutionInfoRepresentation> executionReps = authMgmtResource.getExecutions("new-browser-flow");
AuthenticationExecutionInfoRepresentation exec = findExecutionByProvider("auth-conditional-otp-form", executionReps);
@ -128,7 +128,7 @@ public class ExecutionTest extends AbstractAuthenticationTest {
// copy built-in flow so we get a new editable flow
params.put("newName", "Copy-of-browser");
Response response = authMgmtResource.copy("browser", params);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authCopyFlowPath("browser"), params, ResourceType.AUTH_FLOW);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.authCopyFlowPath("browser"), params, ResourceType.AUTH_FLOW);
try {
Assert.assertEquals("Copy flow", 201, response.getStatus());
} finally {
@ -147,7 +147,7 @@ public class ExecutionTest extends AbstractAuthenticationTest {
// add execution - should succeed
params.put("provider", "idp-review-profile");
authMgmtResource.addExecution("Copy-of-browser", params);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authAddExecutionPath("Copy-of-browser"), params, ResourceType.AUTH_EXECUTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.authAddExecutionPath("Copy-of-browser"), params, ResourceType.AUTH_EXECUTION);
// check execution was added
List<AuthenticationExecutionInfoRepresentation> executionReps = authMgmtResource.getExecutions("Copy-of-browser");
@ -161,7 +161,7 @@ public class ExecutionTest extends AbstractAuthenticationTest {
// remove execution
authMgmtResource.removeExecution(exec.getId());
assertAdminEvents.assertEvent(REALM_NAME, OperationType.DELETE, AdminEventPaths.authExecutionPath(exec.getId()), ResourceType.AUTH_EXECUTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.DELETE, AdminEventPaths.authExecutionPath(exec.getId()), ResourceType.AUTH_EXECUTION);
// check execution was removed
executionReps = authMgmtResource.getExecutions("Copy-of-browser");
@ -172,7 +172,7 @@ public class ExecutionTest extends AbstractAuthenticationTest {
// delete auth-cookie
authMgmtResource.removeExecution(authCookieExec.getId());
assertAdminEvents.assertEvent(REALM_NAME, OperationType.DELETE, AdminEventPaths.authExecutionPath(authCookieExec.getId()), ResourceType.AUTH_EXECUTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.DELETE, AdminEventPaths.authExecutionPath(authCookieExec.getId()), ResourceType.AUTH_EXECUTION);
AuthenticationExecutionRepresentation rep = new AuthenticationExecutionRepresentation();
rep.setPriority(10);
@ -213,7 +213,7 @@ public class ExecutionTest extends AbstractAuthenticationTest {
// add execution - should succeed
response = authMgmtResource.addExecution(rep);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AssertAdminEvents.isExpectedPrefixFollowedByUuid(AdminEventPaths.authMgmtBasePath() + "/executions"), rep, ResourceType.AUTH_EXECUTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AssertAdminEvents.isExpectedPrefixFollowedByUuid(AdminEventPaths.authMgmtBasePath() + "/executions"), rep, ResourceType.AUTH_EXECUTION);
try {
Assert.assertEquals("added execution", 201, response.getStatus());
} finally {
@ -242,7 +242,7 @@ public class ExecutionTest extends AbstractAuthenticationTest {
// switch from DISABLED to ALTERNATIVE
exec.setRequirement(DISABLED);
authMgmtResource.updateExecutions("browser", exec);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.UPDATE, AdminEventPaths.authUpdateExecutionPath("browser"), exec, ResourceType.AUTH_EXECUTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.UPDATE, AdminEventPaths.authUpdateExecutionPath("browser"), exec, ResourceType.AUTH_EXECUTION);
// make sure the change is visible
executionReps = authMgmtResource.getExecutions("browser");
@ -262,7 +262,7 @@ public class ExecutionTest extends AbstractAuthenticationTest {
Map<String, String> executionData = new HashMap<>();
executionData.put("provider", ClientIdAndSecretAuthenticator.PROVIDER_ID);
authMgmtResource.addExecution("new-client-flow", executionData);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authAddExecutionPath("new-client-flow"), executionData, ResourceType.AUTH_EXECUTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.authAddExecutionPath("new-client-flow"), executionData, ResourceType.AUTH_EXECUTION);
// Check executions of not-existent flow - SHOULD FAIL
try {
@ -298,7 +298,7 @@ public class ExecutionTest extends AbstractAuthenticationTest {
// Update success
executionRep.setRequirement(ALTERNATIVE);
authMgmtResource.updateExecutions("new-client-flow", executionRep);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.UPDATE, AdminEventPaths.authUpdateExecutionPath("new-client-flow"), executionRep, ResourceType.AUTH_EXECUTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.UPDATE, AdminEventPaths.authUpdateExecutionPath("new-client-flow"), executionRep, ResourceType.AUTH_EXECUTION);
// Check updated
executionRep = findExecutionByProvider(ClientIdAndSecretAuthenticator.PROVIDER_ID, authMgmtResource.getExecutions("new-client-flow"));
@ -314,11 +314,11 @@ public class ExecutionTest extends AbstractAuthenticationTest {
// Successfuly remove execution and flow
authMgmtResource.removeExecution(executionRep.getId());
assertAdminEvents.assertEvent(REALM_NAME, OperationType.DELETE, AdminEventPaths.authExecutionPath(executionRep.getId()), ResourceType.AUTH_EXECUTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.DELETE, AdminEventPaths.authExecutionPath(executionRep.getId()), ResourceType.AUTH_EXECUTION);
AuthenticationFlowRepresentation rep = findFlowByAlias("new-client-flow", authMgmtResource.getFlows());
authMgmtResource.deleteFlow(rep.getId());
assertAdminEvents.assertEvent(REALM_NAME, OperationType.DELETE, AdminEventPaths.authFlowPath(rep.getId()), ResourceType.AUTH_FLOW);
assertAdminEvents.assertEvent(testRealmId, OperationType.DELETE, AdminEventPaths.authFlowPath(rep.getId()), ResourceType.AUTH_FLOW);
}
@Test
@ -329,7 +329,7 @@ public class ExecutionTest extends AbstractAuthenticationTest {
params.put("newName", newBrowserFlow);
try (Response response = authMgmtResource.copy("browser", params)) {
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authCopyFlowPath("browser"), params, ResourceType.AUTH_FLOW);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.authCopyFlowPath("browser"), params, ResourceType.AUTH_FLOW);
Assert.assertEquals("Copy flow", 201, response.getStatus());
}
@ -340,13 +340,13 @@ public class ExecutionTest extends AbstractAuthenticationTest {
AuthenticationFlowRepresentation rep = findFlowByAlias(newBrowserFlow, authMgmtResource.getFlows());
Assert.assertNotNull(rep);
authMgmtResource.deleteFlow(rep.getId());
assertAdminEvents.assertEvent(REALM_NAME, OperationType.DELETE, AdminEventPaths.authFlowPath(rep.getId()), ResourceType.AUTH_FLOW);
assertAdminEvents.assertEvent(testRealmId, OperationType.DELETE, AdminEventPaths.authFlowPath(rep.getId()), ResourceType.AUTH_FLOW);
}
private void addExecutionCheckReq(String flow, String providerID, HashMap<String, String> params, String expectedRequirement) {
params.put("provider", providerID);
authMgmtResource.addExecution(flow, params);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authAddExecutionPath(flow), params, ResourceType.AUTH_EXECUTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.authAddExecutionPath(flow), params, ResourceType.AUTH_EXECUTION);
List<AuthenticationExecutionInfoRepresentation> executionReps = authMgmtResource.getExecutions(flow);
AuthenticationExecutionInfoRepresentation exec = findExecutionByProvider(providerID, executionReps);
@ -355,6 +355,6 @@ public class ExecutionTest extends AbstractAuthenticationTest {
Assert.assertEquals(expectedRequirement, exec.getRequirement());
authMgmtResource.removeExecution(exec.getId());
assertAdminEvents.assertEvent(REALM_NAME, OperationType.DELETE, AdminEventPaths.authExecutionPath(exec.getId()), ResourceType.AUTH_EXECUTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.DELETE, AdminEventPaths.authExecutionPath(exec.getId()), ResourceType.AUTH_EXECUTION);
}
}

View file

@ -181,8 +181,8 @@ public class FlowTest extends AbstractAuthenticationTest {
data.put("alias", "SomeFlow");
authMgmtResource.addExecutionFlow("browser-2", data);
authMgmtResource.addExecutionFlow("browser-2", data2);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authAddExecutionFlowPath("browser-2"), data, ResourceType.AUTH_EXECUTION_FLOW);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authAddExecutionFlowPath("browser-2"), data2, ResourceType.AUTH_EXECUTION_FLOW);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.authAddExecutionFlowPath("browser-2"), data, ResourceType.AUTH_EXECUTION_FLOW);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.authAddExecutionFlowPath("browser-2"), data2, ResourceType.AUTH_EXECUTION_FLOW);
// check that new flow is returned in a children list
flows = authMgmtResource.getFlows();
@ -212,7 +212,7 @@ public class FlowTest extends AbstractAuthenticationTest {
// delete non-built-in flow
authMgmtResource.deleteFlow(found.getId());
assertAdminEvents.assertEvent(REALM_NAME, OperationType.DELETE, AdminEventPaths.authFlowPath(found.getId()), ResourceType.AUTH_FLOW);
assertAdminEvents.assertEvent(testRealmId, OperationType.DELETE, AdminEventPaths.authFlowPath(found.getId()), ResourceType.AUTH_FLOW);
// check the deleted flow is no longer returned
flows = authMgmtResource.getFlows();
@ -257,7 +257,7 @@ public class FlowTest extends AbstractAuthenticationTest {
// copy that should succeed
params.put("newName", "Copy of browser");
response = authMgmtResource.copy("browser", params);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authCopyFlowPath("browser"), params, ResourceType.AUTH_FLOW);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.authCopyFlowPath("browser"), params, ResourceType.AUTH_FLOW);
try {
Assert.assertThat("Copy flow", response, statusCodeIs(Status.CREATED));
} finally {
@ -293,7 +293,7 @@ public class FlowTest extends AbstractAuthenticationTest {
Response response = authMgmtResource.copy("browser", params);
Assert.assertEquals(201, response.getStatus());
response.close();
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authCopyFlowPath("browser"), params, ResourceType.AUTH_FLOW);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.authCopyFlowPath("browser"), params, ResourceType.AUTH_FLOW);
params = new HashMap<>();
params.put("alias", "child");
@ -302,7 +302,7 @@ public class FlowTest extends AbstractAuthenticationTest {
params.put("type", "basic-flow");
authMgmtResource.addExecutionFlow("parent", params);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authAddExecutionFlowPath("parent"), params, ResourceType.AUTH_EXECUTION_FLOW);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.authAddExecutionFlowPath("parent"), params, ResourceType.AUTH_EXECUTION_FLOW);
}
@Test
@ -315,7 +315,7 @@ public class FlowTest extends AbstractAuthenticationTest {
HashMap<String, String> params = new HashMap<>();
params.put("newName", "Copy of browser");
Response response = authMgmtResource.copy("browser", params);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authCopyFlowPath("browser"), params, ResourceType.AUTH_FLOW);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.authCopyFlowPath("browser"), params, ResourceType.AUTH_FLOW);
try {
Assert.assertEquals("Copy flow", 201, response.getStatus());
} finally {
@ -328,7 +328,7 @@ public class FlowTest extends AbstractAuthenticationTest {
//Set a new unique name. Should succeed
testFlow.setAlias("Copy of browser2");
authMgmtResource.updateFlow(testFlow.getId(), testFlow);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.UPDATE, AdminEventPaths.authEditFlowPath(testFlow.getId()), ResourceType.AUTH_FLOW);
assertAdminEvents.assertEvent(testRealmId, OperationType.UPDATE, AdminEventPaths.authEditFlowPath(testFlow.getId()), ResourceType.AUTH_FLOW);
flows = authMgmtResource.getFlows();
Assert.assertEquals("Copy of browser2", findFlowByAlias("Copy of browser2", flows).getAlias());
@ -360,7 +360,7 @@ public class FlowTest extends AbstractAuthenticationTest {
flows = authMgmtResource.getFlows();
Assert.assertEquals("New description", findFlowByAlias("New Flow", flows).getDescription());
assertAdminEvents.assertEvent(REALM_NAME, OperationType.UPDATE, AdminEventPaths.authEditFlowPath(found.getId()), ResourceType.AUTH_FLOW);
assertAdminEvents.assertEvent(testRealmId, OperationType.UPDATE, AdminEventPaths.authEditFlowPath(found.getId()), ResourceType.AUTH_FLOW);
//Update name and description
found.setAlias("New Flow2");
@ -370,7 +370,7 @@ public class FlowTest extends AbstractAuthenticationTest {
Assert.assertEquals("New Flow2", findFlowByAlias("New Flow2", flows).getAlias());
Assert.assertEquals("New description2", findFlowByAlias("New Flow2", flows).getDescription());
assertAdminEvents.assertEvent(REALM_NAME, OperationType.UPDATE, AdminEventPaths.authEditFlowPath(found.getId()), ResourceType.AUTH_FLOW);
assertAdminEvents.assertEvent(testRealmId, OperationType.UPDATE, AdminEventPaths.authEditFlowPath(found.getId()), ResourceType.AUTH_FLOW);
Assert.assertNull(findFlowByAlias("New Flow", flows));
authMgmtResource.deleteFlow(testFlow.getId());
@ -392,7 +392,7 @@ public class FlowTest extends AbstractAuthenticationTest {
params.put("type", "basic-flow");
authMgmtResource.addExecutionFlow("Parent-Flow", params);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authAddExecutionFlowPath("Parent-Flow"), params, ResourceType.AUTH_EXECUTION_FLOW);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.authAddExecutionFlowPath("Parent-Flow"), params, ResourceType.AUTH_EXECUTION_FLOW);
executionReps = authMgmtResource.getExecutions("Parent-Flow");
@ -424,7 +424,7 @@ public class FlowTest extends AbstractAuthenticationTest {
found.setDescription("This is another child flow2");
authMgmtResource.updateExecutions("Parent-Flow", found);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.UPDATE, AdminEventPaths.authUpdateExecutionPath("Parent-Flow"), ResourceType.AUTH_EXECUTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.UPDATE, AdminEventPaths.authUpdateExecutionPath("Parent-Flow"), ResourceType.AUTH_EXECUTION);
executionReps = authMgmtResource.getExecutions("Parent-Flow");
Assert.assertEquals("Child-Flow2", executionReps.get(0).getDisplayName());
Assert.assertEquals("This is another child flow2", executionReps.get(0).getDescription());
@ -433,7 +433,7 @@ public class FlowTest extends AbstractAuthenticationTest {
found.setDescription("This is another child flow3");
authMgmtResource.updateExecutions("Parent-Flow", found);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.UPDATE, AdminEventPaths.authUpdateExecutionPath("Parent-Flow"), ResourceType.AUTH_EXECUTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.UPDATE, AdminEventPaths.authUpdateExecutionPath("Parent-Flow"), ResourceType.AUTH_EXECUTION);
executionReps = authMgmtResource.getExecutions("Parent-Flow");
Assert.assertEquals("Child-Flow2", executionReps.get(0).getDisplayName());
Assert.assertEquals("This is another child flow3", executionReps.get(0).getDescription());

View file

@ -46,7 +46,7 @@ public class RegistrationFlowTest extends AbstractAuthenticationTest {
data.put("description", "registrationForm2 flow");
data.put("provider", "registration-page-form");
authMgmtResource.addExecutionFlow("registration2", data);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authAddExecutionFlowPath("registration2"), data, ResourceType.AUTH_EXECUTION_FLOW);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.authAddExecutionFlowPath("registration2"), data, ResourceType.AUTH_EXECUTION_FLOW);
// Should fail to add execution under top level flow
Map<String, String> data2 = new HashMap<>();
@ -59,7 +59,7 @@ public class RegistrationFlowTest extends AbstractAuthenticationTest {
// Should success to add execution under form flow
authMgmtResource.addExecution("registrationForm2", data2);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authAddExecutionPath("registrationForm2"), data2, ResourceType.AUTH_EXECUTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.authAddExecutionPath("registrationForm2"), data2, ResourceType.AUTH_EXECUTION);
}
// TODO: More type-safety instead of passing generic maps

View file

@ -58,7 +58,7 @@ public class RequiredActionsTest extends AbstractAuthenticationTest {
RequiredActionProviderRepresentation forUpdate = newRequiredAction("VERIFY_EMAIL", "Verify Email", false, false, null);
authMgmtResource.updateRequiredAction(forUpdate.getAlias(), forUpdate);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.UPDATE, AdminEventPaths.authRequiredActionPath(forUpdate.getAlias()), ResourceType.REQUIRED_ACTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.UPDATE, AdminEventPaths.authRequiredActionPath(forUpdate.getAlias()), ResourceType.REQUIRED_ACTION);
result = authMgmtResource.getRequiredActions();
RequiredActionProviderRepresentation updated = findRequiredActionByAlias(forUpdate.getAlias(), result);
@ -68,7 +68,7 @@ public class RequiredActionsTest extends AbstractAuthenticationTest {
forUpdate.setConfig(Collections.<String, String>emptyMap());
authMgmtResource.updateRequiredAction(forUpdate.getAlias(), forUpdate);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.UPDATE, AdminEventPaths.authRequiredActionPath(forUpdate.getAlias()), ResourceType.REQUIRED_ACTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.UPDATE, AdminEventPaths.authRequiredActionPath(forUpdate.getAlias()), ResourceType.REQUIRED_ACTION);
result = authMgmtResource.getRequiredActions();
updated = findRequiredActionByAlias(forUpdate.getAlias(), result);
@ -92,7 +92,7 @@ public class RequiredActionsTest extends AbstractAuthenticationTest {
// Register it
authMgmtResource.registerRequiredAction(action);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authMgmtBasePath() + "/register-required-action", action, ResourceType.REQUIRED_ACTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.authMgmtBasePath() + "/register-required-action", action, ResourceType.REQUIRED_ACTION);
// Try to find not-existent action - should fail
try {
@ -121,7 +121,7 @@ public class RequiredActionsTest extends AbstractAuthenticationTest {
// Update (set it as defaultAction)
rep.setDefaultAction(true);
authMgmtResource.updateRequiredAction(DummyRequiredActionFactory.PROVIDER_ID, rep);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.UPDATE, AdminEventPaths.authRequiredActionPath(rep.getAlias()), rep, ResourceType.REQUIRED_ACTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.UPDATE, AdminEventPaths.authRequiredActionPath(rep.getAlias()), rep, ResourceType.REQUIRED_ACTION);
compareRequiredAction(rep, newRequiredAction(DummyRequiredActionFactory.PROVIDER_ID, "Dummy Action",
true, true, Collections.<String, String>emptyMap()));
@ -135,7 +135,7 @@ public class RequiredActionsTest extends AbstractAuthenticationTest {
// Remove success
authMgmtResource.removeRequiredAction(DummyRequiredActionFactory.PROVIDER_ID);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.DELETE, AdminEventPaths.authRequiredActionPath(rep.getAlias()), ResourceType.REQUIRED_ACTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.DELETE, AdminEventPaths.authRequiredActionPath(rep.getAlias()), ResourceType.REQUIRED_ACTION);
}

View file

@ -42,7 +42,7 @@ public class ShiftExecutionTest extends AbstractAuthenticationTest {
HashMap<String, String> params = new HashMap<>();
params.put("newName", "Copy of browser");
Response response = authMgmtResource.copy("browser", params);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authCopyFlowPath("browser"), params, ResourceType.AUTH_FLOW);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.authCopyFlowPath("browser"), params, ResourceType.AUTH_FLOW);
try {
Assert.assertEquals("Copy flow", 201, response.getStatus());
} finally {
@ -65,7 +65,7 @@ public class ShiftExecutionTest extends AbstractAuthenticationTest {
// shift last execution up
authMgmtResource.raisePriority(last.getId());
assertAdminEvents.assertEvent(REALM_NAME, OperationType.UPDATE, AdminEventPaths.authRaiseExecutionPath(last.getId()), ResourceType.AUTH_EXECUTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.UPDATE, AdminEventPaths.authRaiseExecutionPath(last.getId()), ResourceType.AUTH_EXECUTION);
List<AuthenticationExecutionInfoRepresentation> executions2 = authMgmtResource.getExecutions("Copy of browser");
@ -85,7 +85,7 @@ public class ShiftExecutionTest extends AbstractAuthenticationTest {
// shift one before last down
authMgmtResource.lowerPriority(oneButLast2.getId());
assertAdminEvents.assertEvent(REALM_NAME, OperationType.UPDATE, AdminEventPaths.authLowerExecutionPath(oneButLast2.getId()), ResourceType.AUTH_EXECUTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.UPDATE, AdminEventPaths.authLowerExecutionPath(oneButLast2.getId()), ResourceType.AUTH_EXECUTION);
executions2 = authMgmtResource.getExecutions("Copy of browser");

View file

@ -52,7 +52,7 @@ public class ShiftRequiredActionTest extends AbstractAuthenticationTest {
// shift last required action up
authMgmtResource.raiseRequiredActionPriority(last.getAlias());
assertAdminEvents.assertEvent(REALM_NAME, OperationType.UPDATE, AdminEventPaths.authRaiseRequiredActionPath(last.getAlias()), ResourceType.REQUIRED_ACTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.UPDATE, AdminEventPaths.authRaiseRequiredActionPath(last.getAlias()), ResourceType.REQUIRED_ACTION);
List<RequiredActionProviderRepresentation> actions2 = authMgmtResource.getRequiredActions();
@ -72,7 +72,7 @@ public class ShiftRequiredActionTest extends AbstractAuthenticationTest {
// shift one before last down
authMgmtResource.lowerRequiredActionPriority(oneButLast2.getAlias());
assertAdminEvents.assertEvent(REALM_NAME, OperationType.UPDATE, AdminEventPaths.authLowerRequiredActionPath(oneButLast2.getAlias()), ResourceType.REQUIRED_ACTION);
assertAdminEvents.assertEvent(testRealmId, OperationType.UPDATE, AdminEventPaths.authLowerRequiredActionPath(oneButLast2.getAlias()), ResourceType.REQUIRED_ACTION);
actions2 = authMgmtResource.getRequiredActions();

View file

@ -37,6 +37,8 @@ import org.keycloak.testsuite.util.RealmBuilder;
import javax.ws.rs.core.Response;
import java.util.List;
import static org.keycloak.testsuite.auth.page.AuthRealm.TEST;
/**
*
* @author Stan Silvert ssilvert@redhat.com (C) 2016 Red Hat Inc.
@ -73,7 +75,7 @@ public abstract class AbstractClientTest extends AbstractAuthTest {
}
protected String getRealmId() {
return "test";
return adminClient.realm(TEST).toRepresentation().getId();
}
// returns UserRepresentation retrieved from server, with all fields, including id

View file

@ -50,6 +50,8 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.keycloak.testsuite.auth.page.AuthRealm.TEST;
import org.keycloak.testsuite.util.RoleBuilder;
/**
@ -182,7 +184,7 @@ public class ClientRolesTest extends AbstractClientTest {
mainRoleRsc.addComposites(createdRoles);
mainRole = mainRoleRsc.toRepresentation();
RoleByIdResource roleByIdResource = adminClient.realm(getRealmId()).rolesById();
RoleByIdResource roleByIdResource = adminClient.realm(TEST).rolesById();
// Search for all composites
Set<RoleRepresentation> foundRoles = roleByIdResource.getRoleComposites(mainRole.getId());

View file

@ -48,6 +48,7 @@ import javax.ws.rs.NotFoundException;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.keycloak.common.Profile.Feature.AUTHORIZATION;
import static org.keycloak.testsuite.auth.page.AuthRealm.TEST;
import static org.keycloak.testsuite.util.ServerURLs.getAuthServerContextRoot;
import static org.keycloak.saml.common.constants.JBossSAMLURIConstants.METADATA_NSURI;
@ -214,7 +215,7 @@ public class InstallationTest extends AbstractClientTest {
@Test
public void testSamlMetadataSpDescriptorPost() throws Exception {
try (ClientAttributeUpdater updater = ClientAttributeUpdater.forClient(adminClient, getRealmId(), SAML_NAME)) {
try (ClientAttributeUpdater updater = ClientAttributeUpdater.forClient(adminClient, TEST, SAML_NAME)) {
assertThat(updater.getResource().toRepresentation().getAttributes().get(SamlConfigAttributes.SAML_FORCE_POST_BINDING), equalTo("true"));
@ -259,7 +260,7 @@ public class InstallationTest extends AbstractClientTest {
@Test
public void testSamlMetadataSpDescriptorRedirect() throws Exception {
try (ClientAttributeUpdater updater = ClientAttributeUpdater.forClient(adminClient, getRealmId(), SAML_NAME)
try (ClientAttributeUpdater updater = ClientAttributeUpdater.forClient(adminClient, TEST, SAML_NAME)
.setAttribute(SamlConfigAttributes.SAML_FORCE_POST_BINDING, "false")
.update()) {

View file

@ -27,6 +27,7 @@ import org.keycloak.events.admin.ResourceType;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.representations.idm.UserSessionRepresentation;
import org.keycloak.testsuite.arquillian.annotation.DisableFeature;
import org.keycloak.testsuite.auth.page.AuthRealm;
import org.keycloak.testsuite.auth.page.account.AccountManagement;
import org.keycloak.testsuite.util.AdminEventPaths;
@ -34,6 +35,7 @@ import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.keycloak.testsuite.auth.page.AuthRealm.TEST;
/**
*
@ -59,8 +61,8 @@ public class SessionTest extends AbstractClientTest {
@Override
public void setDefaultPageUriParameters() {
super.setDefaultPageUriParameters();
testRealmAccountManagementPage.setAuthRealm(getRealmId());
loginPage.setAuthRealm(getRealmId());
testRealmAccountManagementPage.setAuthRealm(TEST);
loginPage.setAuthRealm(TEST);
}
@Test

View file

@ -62,7 +62,8 @@ public class AdminEventAuthDetailsTest extends AbstractAuthTest {
private String masterAdminUserId;
private String masterAdminUser2Id;
private String realmUuid;
private String testRealmId;
private String masterRealmId;
private String client1Uuid;
private String adminCliUuid;
private String admin1Id;
@ -90,13 +91,14 @@ public class AdminEventAuthDetailsTest extends AbstractAuthTest {
@Before
public void initConfig() {
RealmResource masterRealm = adminClient.realm(MASTER);
masterRealmId = masterRealm.toRepresentation().getId();
masterAdminCliUuid = ApiUtil.findClientByClientId(masterRealm, Constants.ADMIN_CLI_CLIENT_ID).toRepresentation().getId();
masterAdminUserId = ApiUtil.findUserByUsername(masterRealm, "admin").getId();
masterAdminUser2Id = ApiUtil.createUserAndResetPasswordWithAdminClient(masterRealm, UserBuilder.create().username("admin2").build(), "password");
masterRealm.users().get(masterAdminUser2Id).roles().realmLevel().add(Collections.singletonList(masterRealm.roles().get("admin").toRepresentation()));
RealmResource testRealm = adminClient.realm("test");
realmUuid = testRealm.toRepresentation().getId();
testRealmId = testRealm.toRepresentation().getId();
adminCliUuid = ApiUtil.findClientByClientId(testRealm, Constants.ADMIN_CLI_CLIENT_ID).toRepresentation().getId();
}
@ -107,17 +109,17 @@ public class AdminEventAuthDetailsTest extends AbstractAuthTest {
@Test
public void testAuth() {
testClient(MASTER, ADMIN, ADMIN, Constants.ADMIN_CLI_CLIENT_ID, MASTER, masterAdminCliUuid, masterAdminUserId);
testClient(MASTER, "admin2", "password", Constants.ADMIN_CLI_CLIENT_ID, MASTER, masterAdminCliUuid, masterAdminUser2Id);
testClient(MASTER, ADMIN, ADMIN, Constants.ADMIN_CLI_CLIENT_ID, masterRealmId, masterAdminCliUuid, masterAdminUserId);
testClient(MASTER, "admin2", "password", Constants.ADMIN_CLI_CLIENT_ID, masterRealmId, masterAdminCliUuid, masterAdminUser2Id);
testClient("test", "admin1", "password", Constants.ADMIN_CLI_CLIENT_ID, realmUuid, adminCliUuid, admin1Id);
testClient("test", "admin2", "password", Constants.ADMIN_CLI_CLIENT_ID, realmUuid, adminCliUuid, admin2Id);
testClient("test", "admin1", "password", "client1", realmUuid, client1Uuid, admin1Id);
testClient("test", "admin2", "password", "client1", realmUuid, client1Uuid, admin2Id);
testClient("test", "admin1", "password", Constants.ADMIN_CLI_CLIENT_ID, testRealmId, adminCliUuid, admin1Id);
testClient("test", "admin2", "password", Constants.ADMIN_CLI_CLIENT_ID, testRealmId, adminCliUuid, admin2Id);
testClient("test", "admin1", "password", "client1", testRealmId, client1Uuid, admin1Id);
testClient("test", "admin2", "password", "client1", testRealmId, client1Uuid, admin2Id);
// Should fail due to different client UUID
try {
testClient("test", "admin1", "password", "client1", realmUuid, adminCliUuid, admin1Id);
testClient("test", "admin1", "password", "client1", testRealmId, adminCliUuid, admin1Id);
Assert.fail("Not expected to pass");
} catch (ComparisonFailure expected) {
// expected
@ -125,7 +127,7 @@ public class AdminEventAuthDetailsTest extends AbstractAuthTest {
// Should fail due to different user ID
try {
testClient("test", "admin1", "password", "client1", realmUuid, client1Uuid, admin2Id);
testClient("test", "admin1", "password", "client1", testRealmId, client1Uuid, admin2Id);
Assert.fail("Not expected to pass");
} catch (ComparisonFailure expected) {
// expected
@ -140,7 +142,7 @@ public class AdminEventAuthDetailsTest extends AbstractAuthTest {
keycloak.realm("test").users().get(appUserId).update(rep);
assertAdminEvents.expect()
.realmId(realmUuid)
.realmId(testRealmId)
.operationType(OperationType.UPDATE)
.resourcePath(AdminEventPaths.userResourcePath(appUserId))
.resourceType(ResourceType.USER)

View file

@ -40,6 +40,7 @@ import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.keycloak.testsuite.auth.page.AuthRealm.MASTER;
/**
* Test getting and filtering admin events.
@ -48,10 +49,13 @@ import static org.junit.Assert.assertThat;
*/
public class AdminEventTest extends AbstractEventTest {
private String masterRealmId;
@Before
public void initConfig() {
enableEvents();
testRealmResource().clearAdminEvents();
this.masterRealmId = adminClient.realm(MASTER).toRepresentation().getId();
}
private List<AdminEventRepresentation> events() {
@ -93,7 +97,7 @@ public class AdminEventTest extends AbstractEventTest {
assertThat(event.getError(), is(nullValue()));
AuthDetailsRepresentation details = event.getAuthDetails();
assertThat(details.getRealmId(), is(equalTo("master")));
assertThat(details.getRealmId(), is(equalTo(masterRealmId)));
assertThat(details.getClientId(), is(notNullValue()));
assertThat(details.getUserId(), is(notNullValue()));
assertThat(details.getIpAddress(), is(notNullValue()));
@ -109,7 +113,7 @@ public class AdminEventTest extends AbstractEventTest {
assertThat(event.getOperationType(), is(equalTo("CREATE")));
assertThat(event.getRealmId(), is(equalTo(realmName())));
assertThat(event.getAuthDetails().getRealmId(), is(equalTo("master")));
assertThat(event.getAuthDetails().getRealmId(), is(equalTo(masterRealmId)));
assertThat(event.getRepresentation(), is(nullValue()));
}
@ -164,7 +168,7 @@ public class AdminEventTest extends AbstractEventTest {
assertThat(event.getOperationType(), is(equalTo("UPDATE")));
assertThat(event.getRealmId(), is(equalTo(realmName())));
assertThat(event.getResourcePath(), is(equalTo("events/config")));
assertThat(event.getAuthDetails().getRealmId(), is(equalTo("master")));
assertThat(event.getAuthDetails().getRealmId(), is(equalTo(masterRealmId)));
assertThat(event.getRepresentation(), is(notNullValue()));
}

View file

@ -35,6 +35,7 @@ import org.keycloak.testsuite.util.OAuthClient.AccessTokenResponse;
import java.security.PublicKey;
import java.util.List;
import static org.keycloak.testsuite.auth.page.AuthRealm.TEST;
import static org.keycloak.testsuite.utils.io.IOUtil.loadRealm;
import static org.keycloak.testsuite.util.ServerURLs.getAuthServerContextRoot;
@ -43,12 +44,20 @@ import static org.keycloak.testsuite.util.ServerURLs.getAuthServerContextRoot;
*/
public abstract class AbstractGroupTest extends AbstractKeycloakTest {
protected String testRealmId;
@Rule
public AssertEvents events = new AssertEvents(this);
@Rule
public AssertAdminEvents assertAdminEvents = new AssertAdminEvents(this);
@Override
public void beforeAbstractKeycloakTest() throws Exception {
super.beforeAbstractKeycloakTest();
this.testRealmId = adminClient.realm(TEST).toRepresentation().getId();
}
AccessToken login(String login, String clientId, String clientSecret, String userId) throws Exception {
AccessTokenResponse tokenResponse = oauth.doGrantAccessTokenRequest("test", login, "password", null, clientId, clientSecret);

View file

@ -138,13 +138,13 @@ public class GroupTest extends AbstractGroupTest {
Response response = realm.clients().create(client);
response.close();
String clientUuid = ApiUtil.getCreatedId(response);
assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.clientResourcePath(clientUuid), client, ResourceType.CLIENT);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.clientResourcePath(clientUuid), client, ResourceType.CLIENT);
client = realm.clients().findByClientId("foo").get(0);
RoleRepresentation role = new RoleRepresentation();
role.setName("foo-role");
realm.clients().get(client.getId()).roles().create(role);
assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.clientRoleResourcePath(clientUuid, "foo-role"), role, ResourceType.CLIENT_ROLE);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.clientRoleResourcePath(clientUuid, "foo-role"), role, ResourceType.CLIENT_ROLE);
role = realm.clients().get(client.getId()).roles().get("foo-role").toRepresentation();
GroupRepresentation group = new GroupRepresentation();
@ -154,10 +154,10 @@ public class GroupTest extends AbstractGroupTest {
List<RoleRepresentation> list = new LinkedList<>();
list.add(role);
realm.groups().group(group.getId()).roles().clientLevel(client.getId()).add(list);
assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.groupRolesClientRolesPath(group.getId(), clientUuid), list, ResourceType.CLIENT_ROLE_MAPPING);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.groupRolesClientRolesPath(group.getId(), clientUuid), list, ResourceType.CLIENT_ROLE_MAPPING);
realm.clients().get(client.getId()).remove();
assertAdminEvents.assertEvent("test", OperationType.DELETE, AdminEventPaths.clientResourcePath(clientUuid), ResourceType.CLIENT);
assertAdminEvents.assertEvent(testRealmId, OperationType.DELETE, AdminEventPaths.clientResourcePath(clientUuid), ResourceType.CLIENT);
}
private GroupRepresentation createGroup(RealmResource realm, GroupRepresentation group) {
@ -165,7 +165,7 @@ public class GroupTest extends AbstractGroupTest {
String groupId = ApiUtil.getCreatedId(response);
getCleanup().addGroupId(groupId);
assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.groupPath(groupId), group, ResourceType.GROUP);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.groupPath(groupId), group, ResourceType.GROUP);
// Set ID to the original rep
group.setId(groupId);
@ -300,7 +300,7 @@ public class GroupTest extends AbstractGroupTest {
public void doNotAllowSameGroupNameAtTopLevelInDatabase() throws Exception {
final String id = KeycloakModelUtils.generateId();
testingClient.server().run(session -> {
RealmModel realm = session.realms().getRealm("test");
RealmModel realm = session.realms().getRealmByName("test");
realm.createGroup(id, "test-group");
});
getCleanup().addGroupId(id);
@ -308,7 +308,7 @@ public class GroupTest extends AbstractGroupTest {
expectedException.expect(RunOnServerException.class);
expectedException.expectMessage(ModelDuplicateException.class.getName());
testingClient.server().run(session -> {
RealmModel realm = session.realms().getRealm("test");
RealmModel realm = session.realms().getRealmByName("test");
realm.createGroup("test-group");
});
}
@ -388,13 +388,13 @@ public class GroupTest extends AbstractGroupTest {
List<RoleRepresentation> roles = new LinkedList<>();
roles.add(topRole);
realm.groups().group(topGroup.getId()).roles().realmLevel().add(roles);
assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.groupRolesRealmRolesPath(topGroup.getId()), roles, ResourceType.REALM_ROLE_MAPPING);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.groupRolesRealmRolesPath(topGroup.getId()), roles, ResourceType.REALM_ROLE_MAPPING);
GroupRepresentation level2Group = new GroupRepresentation();
level2Group.setName("level2");
Response response = realm.groups().group(topGroup.getId()).subGroup(level2Group);
response.close();
assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.groupSubgroupsPath(topGroup.getId()), level2Group, ResourceType.GROUP);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.groupSubgroupsPath(topGroup.getId()), level2Group, ResourceType.GROUP);
URI location = response.getLocation();
final String level2Id = ApiUtil.getCreatedId(response);
@ -415,20 +415,20 @@ public class GroupTest extends AbstractGroupTest {
roles.clear();
roles.add(level2Role);
realm.groups().group(level2Group.getId()).roles().realmLevel().add(roles);
assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.groupRolesRealmRolesPath(level2Group.getId()), roles, ResourceType.REALM_ROLE_MAPPING);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.groupRolesRealmRolesPath(level2Group.getId()), roles, ResourceType.REALM_ROLE_MAPPING);
GroupRepresentation level3Group = new GroupRepresentation();
level3Group.setName("level3");
response = realm.groups().group(level2Group.getId()).subGroup(level3Group);
response.close();
assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.groupSubgroupsPath(level2Group.getId()), level3Group, ResourceType.GROUP);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.groupSubgroupsPath(level2Group.getId()), level3Group, ResourceType.GROUP);
level3Group = realm.getGroupByPath("/top/level2/level3");
Assert.assertNotNull(level3Group);
roles.clear();
roles.add(level3Role);
realm.groups().group(level3Group.getId()).roles().realmLevel().add(roles);
assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.groupRolesRealmRolesPath(level3Group.getId()), roles, ResourceType.REALM_ROLE_MAPPING);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.groupRolesRealmRolesPath(level3Group.getId()), roles, ResourceType.REALM_ROLE_MAPPING);
topGroup = realm.getGroupByPath("/top");
assertEquals(1, topGroup.getRealmRoles().size());
@ -448,7 +448,7 @@ public class GroupTest extends AbstractGroupTest {
UserRepresentation user = realm.users().search("direct-login", -1, -1).get(0);
realm.users().get(user.getId()).joinGroup(level3Group.getId());
assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.userGroupPath(user.getId(), level3Group.getId()), ResourceType.GROUP_MEMBERSHIP);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.userGroupPath(user.getId(), level3Group.getId()), ResourceType.GROUP_MEMBERSHIP);
List<GroupRepresentation> membership = realm.users().get(user.getId()).groups();
assertEquals(1, membership.size());
@ -460,7 +460,7 @@ public class GroupTest extends AbstractGroupTest {
assertTrue(token.getRealmAccess().getRoles().contains("level3Role"));
realm.addDefaultGroup(level3Group.getId());
assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.defaultGroupPath(level3Group.getId()), ResourceType.GROUP);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.defaultGroupPath(level3Group.getId()), ResourceType.GROUP);
List<GroupRepresentation> defaultGroups = realm.getDefaultGroups();
assertEquals(1, defaultGroups.size());
@ -472,20 +472,20 @@ public class GroupTest extends AbstractGroupTest {
response = realm.users().create(newUser);
String userId = ApiUtil.getCreatedId(response);
response.close();
assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.userResourcePath(userId), newUser, ResourceType.USER);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.userResourcePath(userId), newUser, ResourceType.USER);
membership = realm.users().get(userId).groups();
assertEquals(1, membership.size());
assertEquals("level3", membership.get(0).getName());
realm.removeDefaultGroup(level3Group.getId());
assertAdminEvents.assertEvent("test", OperationType.DELETE, AdminEventPaths.defaultGroupPath(level3Group.getId()), ResourceType.GROUP);
assertAdminEvents.assertEvent(testRealmId, OperationType.DELETE, AdminEventPaths.defaultGroupPath(level3Group.getId()), ResourceType.GROUP);
defaultGroups = realm.getDefaultGroups();
assertEquals(0, defaultGroups.size());
realm.groups().group(topGroup.getId()).remove();
assertAdminEvents.assertEvent("test", OperationType.DELETE, AdminEventPaths.groupPath(topGroup.getId()), ResourceType.GROUP);
assertAdminEvents.assertEvent(testRealmId, OperationType.DELETE, AdminEventPaths.groupPath(topGroup.getId()), ResourceType.GROUP);
try {
realm.getGroupByPath("/top/level2/level3");
@ -535,7 +535,7 @@ public class GroupTest extends AbstractGroupTest {
group.getAttributes().put("attr3", Collections.singletonList("attrval2"));
realm.groups().group(group.getId()).update(group);
assertAdminEvents.assertEvent("test", OperationType.UPDATE, AdminEventPaths.groupPath(group.getId()), group, ResourceType.GROUP);
assertAdminEvents.assertEvent(testRealmId, OperationType.UPDATE, AdminEventPaths.groupPath(group.getId()), group, ResourceType.GROUP);
group = realm.getGroupByPath("/" + groupNewName);
@ -607,27 +607,27 @@ public class GroupTest extends AbstractGroupTest {
Response response = realm.users().create(UserBuilder.create().username("user-a").build());
String userAId = ApiUtil.getCreatedId(response);
response.close();
assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.userResourcePath(userAId), ResourceType.USER);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.userResourcePath(userAId), ResourceType.USER);
response = realm.users().create(UserBuilder.create().username("user-b").build());
String userBId = ApiUtil.getCreatedId(response);
response.close();
assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.userResourcePath(userBId), ResourceType.USER);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.userResourcePath(userBId), ResourceType.USER);
realm.users().get(userAId).joinGroup(groupId);
assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.userGroupPath(userAId, groupId), group, ResourceType.GROUP_MEMBERSHIP);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.userGroupPath(userAId, groupId), group, ResourceType.GROUP_MEMBERSHIP);
List<UserRepresentation> members = realm.groups().group(groupId).members(0, 10);
assertNames(members, "user-a");
realm.users().get(userBId).joinGroup(groupId);
assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.userGroupPath(userBId, groupId), group, ResourceType.GROUP_MEMBERSHIP);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.userGroupPath(userBId, groupId), group, ResourceType.GROUP_MEMBERSHIP);
members = realm.groups().group(groupId).members(0, 10);
assertNames(members, "user-a", "user-b");
realm.users().get(userAId).leaveGroup(groupId);
assertAdminEvents.assertEvent("test", OperationType.DELETE, AdminEventPaths.userGroupPath(userAId, groupId), group, ResourceType.GROUP_MEMBERSHIP);
assertAdminEvents.assertEvent(testRealmId, OperationType.DELETE, AdminEventPaths.userGroupPath(userAId, groupId), group, ResourceType.GROUP_MEMBERSHIP);
members = realm.groups().group(groupId).members(0, 10);
assertNames(members, "user-b");
@ -716,15 +716,15 @@ public class GroupTest extends AbstractGroupTest {
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);
assertAdminEvents.assertEvent(testRealmId, 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);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.groupRolesClientRolesPath(group.getId(), clientId), Collections.singletonList(clientRole), ResourceType.CLIENT_ROLE_MAPPING);
assertAdminEvents.assertEvent(testRealmId, 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");
@ -745,13 +745,13 @@ public class GroupTest extends AbstractGroupTest {
// 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);
assertAdminEvents.assertEvent(testRealmId, 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);
assertAdminEvents.assertEvent(testRealmId, OperationType.DELETE, AdminEventPaths.groupRolesClientRolesPath(group.getId(), clientId), Collections.singletonList(clientRoleRep), ResourceType.CLIENT_ROLE_MAPPING);
assertNames(roles.clientLevel(clientId).listAll(), "client-composite");
}
}
@ -1077,7 +1077,7 @@ public class GroupTest extends AbstractGroupTest {
for (GroupRepresentation group : realm.groups().groups()) {
GroupResource resource = realm.groups().group(group.getId());
resource.remove();
assertAdminEvents.assertEvent("test", OperationType.DELETE, AdminEventPaths.groupPath(group.getId()), ResourceType.GROUP);
assertAdminEvents.assertEvent(testRealmId, OperationType.DELETE, AdminEventPaths.groupPath(group.getId()), ResourceType.GROUP);
}
// Add 20 new groups with known names
@ -1116,7 +1116,7 @@ public class GroupTest extends AbstractGroupTest {
level2Group.setName("group1111");
Response response = realm.groups().group(firstGroupId).subGroup(level2Group);
response.close();
assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.groupSubgroupsPath(firstGroupId), level2Group, ResourceType.GROUP);
assertAdminEvents.assertEvent(testRealmId, OperationType.CREATE, AdminEventPaths.groupSubgroupsPath(firstGroupId), level2Group, ResourceType.GROUP);
assertEquals(new Long(allGroups.size()), realm.groups().count(true).get("count"));
assertEquals(new Long(allGroups.size() + 1), realm.groups().count(false).get("count"));
@ -1142,7 +1142,7 @@ public class GroupTest extends AbstractGroupTest {
for (GroupRepresentation group : realm.groups().groups()) {
GroupResource resource = realm.groups().group(group.getId());
resource.remove();
assertAdminEvents.assertEvent("test", OperationType.DELETE, AdminEventPaths.groupPath(group.getId()), ResourceType.GROUP);
assertAdminEvents.assertEvent(testRealmId, OperationType.DELETE, AdminEventPaths.groupPath(group.getId()), ResourceType.GROUP);
}
// Create two pages worth of groups in a random order

View file

@ -35,6 +35,7 @@ import org.keycloak.models.CibaConfig;
import org.keycloak.models.Constants;
import org.keycloak.models.OAuth2DeviceConfig;
import org.keycloak.models.ParConfig;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.protocol.saml.SamlProtocol;
import org.keycloak.representations.adapters.action.GlobalRequestResult;
@ -289,6 +290,7 @@ public class RealmTest extends AbstractAdminTest {
@Test
public void createRealmWithPasswordPolicyFromJsonWithValidPasswords() {
RealmRepresentation rep = loadJson(getClass().getResourceAsStream("/import/testrealm-keycloak-6146.json"), RealmRepresentation.class);
rep.setId(KeycloakModelUtils.generateId());
try (Creator<RealmResource> c = Creator.create(adminClient, rep)) {
RealmRepresentation created = c.resource().toRepresentation();
assertRealm(rep, created);

View file

@ -580,8 +580,6 @@ public abstract class AbstractAdvancedBrokerTest extends AbstractBrokerTest {
updateExecutions(AbstractBrokerTest::disableUpdateProfileOnFirstLogin);
ComponentRepresentation component = new ComponentRepresentation();
component.setId(DummyUserFederationProviderFactory.PROVIDER_NAME);
component.setName(DummyUserFederationProviderFactory.PROVIDER_NAME);
component.setProviderId(DummyUserFederationProviderFactory.PROVIDER_NAME);
component.setProviderType(UserStorageProvider.class.getName());

View file

@ -352,7 +352,9 @@ public abstract class AbstractRegCliTest extends AbstractCliTest {
private ComponentRepresentation findPolicyByProviderAndAuth(String realm, String providerId, String authType) {
// Change the policy to avoid checking hosts
List<ComponentRepresentation> reps = adminClient.realm(realm).components().query(realm, ClientRegistrationPolicy.class.getName());
RealmResource realmResource = adminClient.realm(realm);
List<ComponentRepresentation> reps = realmResource.components().query(
realmResource.toRepresentation().getId(), ClientRegistrationPolicy.class.getName());
for (ComponentRepresentation rep : reps) {
if (rep.getSubType().equals(authType) && rep.getProviderId().equals(providerId)) {
return rep;

View file

@ -300,7 +300,7 @@ public class ClientRegistrationPoliciesTest extends AbstractClientRegistrationTe
// Add client-disabled policy
ComponentRepresentation rep = new ComponentRepresentation();
rep.setName("Clients disabled");
rep.setParentId(REALM_NAME);
rep.setParentId(adminClient.realm(REALM_NAME).toRepresentation().getId());
rep.setProviderId(ClientDisabledClientRegistrationPolicyFactory.PROVIDER_ID);
rep.setProviderType(ClientRegistrationPolicy.class.getName());
rep.setSubType(getPolicyAnon());
@ -642,7 +642,8 @@ public class ClientRegistrationPoliciesTest extends AbstractClientRegistrationTe
private ComponentRepresentation findPolicyByProviderAndAuth(String providerId, String authType) {
// Change the policy to avoid checking hosts
List<ComponentRepresentation> reps = realmResource().components().query(REALM_NAME, ClientRegistrationPolicy.class.getName());
String parentId = realmResource().toRepresentation().getId();
List<ComponentRepresentation> reps = realmResource().components().query(parentId, ClientRegistrationPolicy.class.getName());
for (ComponentRepresentation rep : reps) {
if (rep.getSubType().equals(authType) && rep.getProviderId().equals(providerId)) {
return rep;

View file

@ -207,7 +207,8 @@ public class OIDCJwksClientRegistrationTest extends AbstractClientRegistrationTe
assertAuthenticateClientSuccess(generatedKeys, response, "a1");
// Assert item in publicKey cache for client1
String expectedCacheKey = PublicKeyStorageUtils.getClientModelCacheKey(REALM_NAME, response.getClientId());
String expectedCacheKey = PublicKeyStorageUtils.getClientModelCacheKey(
adminClient.realm(REALM_NAME).toRepresentation().getId(), response.getClientId());
Assert.assertTrue(testingClient.testing().cache(InfinispanConnectionProvider.KEYS_CACHE_NAME).contains(expectedCacheKey));
// Assert it's not possible to authenticate as client2 with the same "kid" like client1
@ -225,7 +226,8 @@ public class OIDCJwksClientRegistrationTest extends AbstractClientRegistrationTe
assertAuthenticateClientSuccess(generatedKeys, response, "a1");
// Assert item in publicKey cache for client1
String expectedCacheKey = PublicKeyStorageUtils.getClientModelCacheKey(REALM_NAME, response.getClientId());
String expectedCacheKey = PublicKeyStorageUtils.getClientModelCacheKey(
adminClient.realm(REALM_NAME).toRepresentation().getId(), response.getClientId());
Assert.assertTrue(testingClient.testing().cache(InfinispanConnectionProvider.KEYS_CACHE_NAME).contains(expectedCacheKey));

View file

@ -20,10 +20,12 @@ package org.keycloak.testsuite.events;
import org.apache.commons.lang3.StringUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.keycloak.common.util.Time;
import org.keycloak.events.EventType;
import org.keycloak.events.log.JBossLoggingEventListenerProviderFactory;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.representations.idm.EventRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;
@ -45,11 +47,16 @@ import org.keycloak.testsuite.util.WaitUtils;
*/
public class EventStoreProviderTest extends AbstractEventsTest {
public static final String REALM_NAME_1 = "realmName1";
public static final String REALM_NAME_2 = "realmName2";
private String realmId;
private String realmId2;
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
super.addTestRealms(testRealms);
for (String realmId : new String[] {"realmId", "realmId2"}) {
for (String realmId : new String[] {REALM_NAME_1, REALM_NAME_2}) {
RealmRepresentation adminRealmRep = new RealmRepresentation();
adminRealmRep.setId(realmId);
adminRealmRep.setRealm(realmId);
@ -60,6 +67,12 @@ public class EventStoreProviderTest extends AbstractEventsTest {
}
}
@Before
public void before() {
realmId = adminClient.realm(REALM_NAME_1).toRepresentation().getId();
realmId2 = adminClient.realm(REALM_NAME_2).toRepresentation().getId();
}
@After
public void after() {
testing().clearEventStore();
@ -67,7 +80,7 @@ public class EventStoreProviderTest extends AbstractEventsTest {
@Test
public void save() {
testing().onEvent(create(EventType.LOGIN, "realmId", "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(EventType.LOGIN, realmId, "clientId", "userId", "127.0.0.1", "error"));
}
@Test
@ -76,15 +89,15 @@ public class EventStoreProviderTest extends AbstractEventsTest {
long oldest = System.currentTimeMillis() - 30000;
long newest = System.currentTimeMillis() + 30000;
testing().onEvent(create(EventType.LOGIN, "realmId", "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(newest, EventType.REGISTER, "realmId", "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(newest, EventType.REGISTER, "realmId", "clientId", "userId2", "127.0.0.1", "error"));
testing().onEvent(create(EventType.LOGIN, "realmId2", "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(oldest, EventType.LOGIN, "realmId", "clientId2", "userId", "127.0.0.1", "error"));
testing().onEvent(create(EventType.LOGIN, "realmId", "clientId", "userId2", "127.0.0.1", "error"));
testing().onEvent(create(EventType.LOGIN, realmId, "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(newest, EventType.REGISTER, realmId, "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(newest, EventType.REGISTER, realmId, "clientId", "userId2", "127.0.0.1", "error"));
testing().onEvent(create(EventType.LOGIN, realmId2, "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(oldest, EventType.LOGIN, realmId, "clientId2", "userId", "127.0.0.1", "error"));
testing().onEvent(create(EventType.LOGIN, realmId, "clientId", "userId2", "127.0.0.1", "error"));
Assert.assertEquals(5, testing().queryEvents(null, null, "clientId", null, null, null, null, null, null).size());
Assert.assertEquals(5, testing().queryEvents("realmId", null, null, null, null, null, null, null, null).size());
Assert.assertEquals(5, testing().queryEvents(realmId, null, null, null, null, null, null, null, null).size());
Assert.assertEquals(4, testing().queryEvents(null, toList(EventType.LOGIN), null, null, null, null, null, null, null).size());
Assert.assertEquals(6, testing().queryEvents(null, toList(EventType.LOGIN, EventType.REGISTER), null, null, null, null, null, null, null).size());
Assert.assertEquals(4, testing().queryEvents(null, null, null, "userId", null, null, null, null, null).size());
@ -97,8 +110,8 @@ public class EventStoreProviderTest extends AbstractEventsTest {
Assert.assertEquals(newest, testing().queryEvents(null, null, null, null, null, null, null, null, 1).get(0).getTime());
Assert.assertEquals(oldest, testing().queryEvents(null, null, null, null, null, null, null, 5, 1).get(0).getTime());
testing().clearEventStore("realmId");
testing().clearEventStore("realmId2");
testing().clearEventStore(realmId);
testing().clearEventStore(realmId2);
Assert.assertEquals(0, testing().queryEvents(null, null, null, null, null, null, null, null, null).size());
@ -124,20 +137,20 @@ public class EventStoreProviderTest extends AbstractEventsTest {
e.printStackTrace();
}
testing().onEvent(create(date1, EventType.LOGIN, "realmId", "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(date1, EventType.LOGIN, "realmId", "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(date2, EventType.REGISTER, "realmId", "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(date2, EventType.REGISTER, "realmId", "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(date3, EventType.CODE_TO_TOKEN, "realmId", "clientId", "userId2", "127.0.0.1", "error"));
testing().onEvent(create(date3, EventType.LOGOUT, "realmId", "clientId", "userId2", "127.0.0.1", "error"));
testing().onEvent(create(date4, EventType.UPDATE_PROFILE, "realmId2", "clientId2", "userId2", "127.0.0.1", "error"));
testing().onEvent(create(date4, EventType.UPDATE_EMAIL, "realmId2", "clientId2", "userId2", "127.0.0.1", "error"));
testing().onEvent(create(date1, EventType.LOGIN, realmId, "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(date1, EventType.LOGIN, realmId, "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(date2, EventType.REGISTER, realmId, "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(date2, EventType.REGISTER, realmId, "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(date3, EventType.CODE_TO_TOKEN, realmId, "clientId", "userId2", "127.0.0.1", "error"));
testing().onEvent(create(date3, EventType.LOGOUT, realmId, "clientId", "userId2", "127.0.0.1", "error"));
testing().onEvent(create(date4, EventType.UPDATE_PROFILE, realmId2, "clientId2", "userId2", "127.0.0.1", "error"));
testing().onEvent(create(date4, EventType.UPDATE_EMAIL, realmId2, "clientId2", "userId2", "127.0.0.1", "error"));
Assert.assertEquals(6, testing().queryEvents(null, null, "clientId", null, null, null, null, null, null).size());
Assert.assertEquals(2, testing().queryEvents(null, null, "clientId2", null, null, null, null, null, null).size());
Assert.assertEquals(6, testing().queryEvents("realmId", null, null, null, null, null, null, null, null).size());
Assert.assertEquals(2, testing().queryEvents("realmId2", null, null, null, null, null, null, null, null).size());
Assert.assertEquals(6, testing().queryEvents(realmId, null, null, null, null, null, null, null, null).size());
Assert.assertEquals(2, testing().queryEvents(realmId2, null, null, null, null, null, null, null, null).size());
Assert.assertEquals(4, testing().queryEvents(null, null, null, "userId", null, null, null, null, null).size());
Assert.assertEquals(4, testing().queryEvents(null, null, null, "userId2", null, null, null, null, null).size());
@ -170,22 +183,22 @@ public class EventStoreProviderTest extends AbstractEventsTest {
@Test
public void clear() {
testing().onEvent(create(System.currentTimeMillis() - 30000, EventType.LOGIN, "realmId", "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis() - 20000, EventType.LOGIN, "realmId", "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis(), EventType.LOGIN, "realmId", "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis(), EventType.LOGIN, "realmId", "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis() - 30000, EventType.LOGIN, "realmId2", "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis() - 30000, EventType.LOGIN, realmId, "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis() - 20000, EventType.LOGIN, realmId, "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis(), EventType.LOGIN, realmId, "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis(), EventType.LOGIN, realmId, "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis() - 30000, EventType.LOGIN, realmId2, "clientId", "userId", "127.0.0.1", "error"));
testing().clearEventStore("realmId");
testing().clearEventStore(realmId);
Assert.assertEquals(1, testing().queryEvents(null, null, null, null, null, null, null, null, null).size());
}
@Test
public void lengthExceedLimit(){
testing().onEvent(create(System.currentTimeMillis() - 30000, EventType.LOGIN, "realmId", StringUtils.repeat("clientId", 100), "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis() - 30000, EventType.LOGIN, StringUtils.repeat("realmId", 100), "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis() - 30000, EventType.LOGIN, "realmId", "clientId", StringUtils.repeat("userId", 100), "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis() - 30000, EventType.LOGIN, realmId, StringUtils.repeat("clientId", 100), "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis() - 30000, EventType.LOGIN, StringUtils.repeat(realmId, 100), "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis() - 30000, EventType.LOGIN, realmId, "clientId", StringUtils.repeat("userId", 100), "127.0.0.1", "error"));
}
@ -196,41 +209,41 @@ public class EventStoreProviderTest extends AbstractEventsTest {
@Test
public void clearOld() {
testing().onEvent(create(System.currentTimeMillis() - 300000, EventType.LOGIN, "realmId", "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis() - 200000, EventType.LOGIN, "realmId", "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis(), EventType.LOGIN, "realmId", "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis(), EventType.LOGIN, "realmId", "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis() - 300000, EventType.LOGIN, "realmId2", "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis(), EventType.LOGIN, "realmId2", "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis() - 300000, EventType.LOGIN, realmId, "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis() - 200000, EventType.LOGIN, realmId, "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis(), EventType.LOGIN, realmId, "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis(), EventType.LOGIN, realmId, "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis() - 300000, EventType.LOGIN, realmId2, "clientId", "userId", "127.0.0.1", "error"));
testing().onEvent(create(System.currentTimeMillis(), EventType.LOGIN, realmId2, "clientId", "userId", "127.0.0.1", "error"));
// Set expiration of events for "realmId" .
RealmRepresentation realm = realmsResouce().realm("realmId").toRepresentation();
// Set expiration of events for realmId .
RealmRepresentation realm = realmsResouce().realm(REALM_NAME_1).toRepresentation();
realm.setEventsExpiration(100);
realmsResouce().realm("realmId").update(realm);
realmsResouce().realm(REALM_NAME_1).update(realm);
// The first 2 events from realmId will be deleted
testing().clearExpiredEvents();
Assert.assertEquals(4, testing().queryEvents(null, null, null, null, null, null, null, null, null).size());
// Set expiration of events for realmId2 as well
RealmRepresentation realm2 = realmsResouce().realm("realmId2").toRepresentation();
RealmRepresentation realm2 = realmsResouce().realm(REALM_NAME_2).toRepresentation();
realm2.setEventsExpiration(100);
realmsResouce().realm("realmId2").update(realm2);
realmsResouce().realm(REALM_NAME_2).update(realm2);
// The first event from "realmId2" will be deleted now
// The first event from realmId2 will be deleted now
testing().clearExpiredEvents();
Assert.assertEquals(3, testing().queryEvents(null, null, null, null, null, null, null, null, null).size());
// set time offset to the future. The remaining 2 events from "realmId" and 1 event from "realmId2" should be expired now
// set time offset to the future. The remaining 2 events from realmId and 1 event from realmId2 should be expired now
setTimeOffset(150);
testing().clearExpiredEvents();
Assert.assertEquals(0, testing().queryEvents(null, null, null, null, null, null, null, null, null).size());
// Revert expirations
realm.setEventsExpiration(0);
realmsResouce().realm("realmId").update(realm);
realmsResouce().realm(REALM_NAME_1).update(realm);
realm2.setEventsExpiration(0);
realmsResouce().realm("realmId2").update(realm2);
realmsResouce().realm(REALM_NAME_2).update(realm2);
}
private EventRepresentation create(EventType event, String realmId, String clientId, String userId, String ipAddress, String error) {

View file

@ -289,8 +289,8 @@ public class ExportImportTest extends AbstractKeycloakTest {
}
}
private boolean isRealmPresent(String realmId) {
return adminClient.realms().findAll().stream().anyMatch(realm -> realmId.equals(realm.getId()));
private boolean isRealmPresent(String realmName) {
return adminClient.realms().findAll().stream().anyMatch(realm -> realmName.equals(realm.getRealm()));
}
/*

View file

@ -18,6 +18,7 @@
package org.keycloak.testsuite.federation.kerberos;
import static org.keycloak.testsuite.admin.AbstractAdminTest.loadJson;
import static org.keycloak.testsuite.auth.page.AuthRealm.TEST;
import java.net.URI;
import java.security.Principal;
@ -143,8 +144,8 @@ public abstract class AbstractKerberosTest extends AbstractAuthTest {
public void beforeAbstractKeycloakTest() throws Exception {
super.beforeAbstractKeycloakTest();
testRealmPage.setAuthRealm(AuthRealm.TEST);
changePasswordPage.realm(AuthRealm.TEST);
testRealmPage.setAuthRealm(TEST);
changePasswordPage.realm(TEST);
getKerberosRule().setKrb5ConfPath(testingClient.testing());
@ -353,7 +354,8 @@ public abstract class AbstractKerberosTest extends AbstractAuthTest {
*
*/
protected void updateUserStorageProvider(Consumer<ComponentRepresentation> updater) {
List<ComponentRepresentation> reps = testRealmResource().components().query("test", UserStorageProvider.class.getName());
String parentId = testRealmResource().toRepresentation().getId();
List<ComponentRepresentation> reps = testRealmResource().components().query(parentId, UserStorageProvider.class.getName());
Assert.assertEquals(1, reps.size());
ComponentRepresentation kerberosProvider = reps.get(0);

View file

@ -40,6 +40,8 @@ import org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected;
import org.keycloak.testsuite.util.KerberosRule;
import org.keycloak.testsuite.KerberosEmbeddedServer;
import static org.keycloak.testsuite.auth.page.AuthRealm.TEST;
/**
* Test for the KerberosFederationProvider (kerberos without LDAP integration)
*
@ -82,7 +84,8 @@ public class KerberosStandaloneTest extends AbstractKerberosSingleRealmTest {
@Test
public void updateProfileEnabledTest() throws Exception {
// Switch updateProfileOnFirstLogin to on
List<ComponentRepresentation> reps = testRealmResource().components().query("test", UserStorageProvider.class.getName());
String parentId = testRealmResource().toRepresentation().getId();
List<ComponentRepresentation> reps = testRealmResource().components().query(parentId, UserStorageProvider.class.getName());
org.keycloak.testsuite.Assert.assertEquals(1, reps.size());
ComponentRepresentation kerberosProvider = reps.get(0);
kerberosProvider.getConfig().putSingle(KerberosConstants.UPDATE_PROFILE_FIRST_LOGIN, "true");
@ -114,7 +117,8 @@ public class KerberosStandaloneTest extends AbstractKerberosSingleRealmTest {
*/
@Test
public void noProvider() throws Exception {
List<ComponentRepresentation> reps = testRealmResource().components().query("test", UserStorageProvider.class.getName());
String parentId = testRealmResource().toRepresentation().getId();
List<ComponentRepresentation> reps = testRealmResource().components().query(parentId, UserStorageProvider.class.getName());
org.keycloak.testsuite.Assert.assertEquals(1, reps.size());
ComponentRepresentation kerberosProvider = reps.get(0);
testRealmResource().components().component(kerberosProvider.getId()).remove();
@ -159,8 +163,9 @@ public class KerberosStandaloneTest extends AbstractKerberosSingleRealmTest {
@Test
@UncaughtServerErrorExpected
public void handleUnknownKerberosRealm() throws Exception {
// Switch kerberos realm to "unavailable"
List<ComponentRepresentation> reps = testRealmResource().components().query("test", UserStorageProvider.class.getName());
// Switch kerberos realm to "unavailable
String parentId = testRealmResource().toRepresentation().getId();
List<ComponentRepresentation> reps = testRealmResource().components().query(parentId, UserStorageProvider.class.getName());
org.keycloak.testsuite.Assert.assertEquals(1, reps.size());
ComponentRepresentation kerberosProvider = reps.get(0);
kerberosProvider.getConfig().putSingle(KerberosConstants.KERBEROS_REALM, "unavailable");

View file

@ -119,7 +119,7 @@ public class LDAPAdminRestApiWithUserProfileTest extends LDAPAdminRestApiTest {
private void enableSyncRegistration(RealmRepresentation realmRep, Boolean aFalse) {
ComponentRepresentation ldapStorage = testRealm().components()
.query(realmRep.getRealm(), UserStorageProvider.class.getName()).get(0);
.query(realmRep.getId(), UserStorageProvider.class.getName()).get(0);
ldapStorage.getConfig().put(LDAPConstants.SYNC_REGISTRATIONS, Collections.singletonList(aFalse.toString()));
testRealm().components().component(ldapStorage.getId()).update(ldapStorage);
}

View file

@ -161,7 +161,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest {
testingClient.server().run(session -> {
RealmManager manager = new RealmManager(session);
RealmModel appRealm = manager.getRealm("test");
RealmModel appRealm = manager.getRealmByName("test");
UserModel user = session.userLocalStorage().getUserByUsername(appRealm, "johnkeycloak");
Assert.assertNull(user);
});

View file

@ -128,7 +128,7 @@ public class LDAPSyncTest extends AbstractLDAPTest {
UserStorageSyncManager usersSyncManager = new UserStorageSyncManager();
KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
SynchronizationResult syncResult = usersSyncManager.syncAllUsers(sessionFactory, "test", ctx.getLdapModel());
SynchronizationResult syncResult = usersSyncManager.syncAllUsers(sessionFactory, ctx.getRealm().getId(), ctx.getLdapModel());
LDAPTestAsserts.assertSyncEquals(syncResult, 5, 0, 0, 0);
});
@ -179,12 +179,12 @@ public class LDAPSyncTest extends AbstractLDAPTest {
// Trigger partial sync
KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
SynchronizationResult syncResult = usersSyncManager.syncChangedUsers(sessionFactory, "test", ctx.getLdapModel());
SynchronizationResult syncResult = usersSyncManager.syncChangedUsers(sessionFactory, testRealm.getId(), ctx.getLdapModel());
LDAPTestAsserts.assertSyncEquals(syncResult, 1, 1, 0, 0);
});
testingClient.server().run(session -> {
RealmModel testRealm = session.realms().getRealm("test");
RealmModel testRealm = session.realms().getRealmByName(TEST_REALM_NAME);
UserProvider userProvider = session.userLocalStorage();
// Assert users updated in local provider
LDAPTestAsserts.assertUserImported(userProvider, testRealm, "user5", "User5FN", "User5LN", "user5updated@email.org", "521");
@ -210,7 +210,7 @@ public class LDAPSyncTest extends AbstractLDAPTest {
LDAPTestContext ctx = LDAPTestContext.init(session);
// Assert syncing from LDAP fails due to duplicated username
SynchronizationResult result = new UserStorageSyncManager().syncAllUsers(session.getKeycloakSessionFactory(), "test", ctx.getLdapModel());
SynchronizationResult result = new UserStorageSyncManager().syncAllUsers(session.getKeycloakSessionFactory(), ctx.getRealm().getId(), ctx.getLdapModel());
Assert.assertEquals(1, result.getFailed());
// Remove "user7" from LDAP
@ -225,7 +225,7 @@ public class LDAPSyncTest extends AbstractLDAPTest {
LDAPTestContext ctx = LDAPTestContext.init(session);
// Assert syncing from LDAP fails due to duplicated email
SynchronizationResult result = new UserStorageSyncManager().syncAllUsers(session.getKeycloakSessionFactory(), "test", ctx.getLdapModel());
SynchronizationResult result = new UserStorageSyncManager().syncAllUsers(session.getKeycloakSessionFactory(), ctx.getRealm().getId(), ctx.getLdapModel());
Assert.assertEquals(1, result.getFailed());
Assert.assertNull(session.userLocalStorage().getUserByUsername(ctx.getRealm(), "user7-something"));
@ -235,13 +235,13 @@ public class LDAPSyncTest extends AbstractLDAPTest {
ctx.getLdapProvider().getLdapIdentityStore().update(duplicatedLdapUser);
// Assert user successfully synced now
result = new UserStorageSyncManager().syncAllUsers(session.getKeycloakSessionFactory(), "test", ctx.getLdapModel());
result = new UserStorageSyncManager().syncAllUsers(session.getKeycloakSessionFactory(), ctx.getRealm().getId(), ctx.getLdapModel());
Assert.assertEquals(0, result.getFailed());
});
// Assert user was imported. Use another transaction for that
testingClient.server().run(session -> {
RealmModel testRealm = session.realms().getRealm("test");
RealmModel testRealm = session.realms().getRealmByName(TEST_REALM_NAME);
LDAPTestAsserts.assertUserImported(session.userLocalStorage(), testRealm, "user7-something", "User7FNN", "User7LNL", "user7-changed@email.org", "126");
});
}
@ -255,7 +255,7 @@ public class LDAPSyncTest extends AbstractLDAPTest {
// Add user to LDAP
LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "beckybecks", "Becky", "Becks", "becky-becks@email.org", null, "123");
SynchronizationResult syncResult = new UserStorageSyncManager().syncAllUsers(sessionFactory, "test", ctx.getLdapModel());
SynchronizationResult syncResult = new UserStorageSyncManager().syncAllUsers(sessionFactory, ctx.getRealm().getId(), ctx.getLdapModel());
Assert.assertEquals(0, syncResult.getFailed());
});
@ -277,13 +277,13 @@ public class LDAPSyncTest extends AbstractLDAPTest {
// Trigger partial sync
KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
SynchronizationResult syncResult = usersSyncManager.syncChangedUsers(sessionFactory, "test", ctx.getLdapModel());
SynchronizationResult syncResult = usersSyncManager.syncChangedUsers(sessionFactory, testRealm.getId(), ctx.getLdapModel());
Assert.assertEquals(0, syncResult.getFailed());
});
testingClient.server().run(session -> {
LDAPTestContext ctx = LDAPTestContext.init(session);
RealmModel testRealm = session.realms().getRealm("test");
RealmModel testRealm = session.realms().getRealmByName(TEST_REALM_NAME);
UserProvider userProvider = session.userLocalStorage();
// Assert users updated in local provider
LDAPTestAsserts.assertUserImported(session.users(), testRealm, "beckyupdated", "Becky", "Becks", "becky-updated@email.org", "123");
@ -325,7 +325,7 @@ public class LDAPSyncTest extends AbstractLDAPTest {
LDAPTestContext ctx = LDAPTestContext.init(session);
KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
SynchronizationResult syncResult = new UserStorageSyncManager().syncAllUsers(sessionFactory, "test", ctx.getLdapModel());
SynchronizationResult syncResult = new UserStorageSyncManager().syncAllUsers(sessionFactory, ctx.getRealm().getId(), ctx.getLdapModel());
Assert.assertEquals(0, syncResult.getFailed());
});
@ -385,7 +385,7 @@ public class LDAPSyncTest extends AbstractLDAPTest {
LDAPTestContext ctx = LDAPTestContext.init(session);
KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
SynchronizationResult syncResult = new UserStorageSyncManager().syncAllUsers(sessionFactory, "test", ctx.getLdapModel());
SynchronizationResult syncResult = new UserStorageSyncManager().syncAllUsers(sessionFactory, ctx.getRealm().getId(), ctx.getLdapModel());
Assert.assertEquals(1, syncResult.getAdded());
Assert.assertTrue(syncResult.getFailed() > 0);
});
@ -414,7 +414,7 @@ public class LDAPSyncTest extends AbstractLDAPTest {
ComponentRepresentation ldapRep = testRealm().components().component(ldapModelId).toRepresentation();
try {
SynchronizationResultRepresentation syncResultRep = adminClient.realm("test").userStorage().syncUsers( ldapModelId, null);
SynchronizationResultRepresentation syncResultRep = adminClient.realm(TEST_REALM_NAME).userStorage().syncUsers( ldapModelId, null);
Assert.fail("Should throw 400");
} catch (Exception e) {
Assert.assertTrue(e instanceof BadRequestException);
@ -427,7 +427,7 @@ public class LDAPSyncTest extends AbstractLDAPTest {
ComponentRepresentation ldapRep = testRealm().components().component(ldapModelId).toRepresentation();
try {
SynchronizationResultRepresentation syncResultRep = adminClient.realm("test").userStorage().syncUsers( ldapModelId, "wrong action");
SynchronizationResultRepresentation syncResultRep = adminClient.realm(TEST_REALM_NAME).userStorage().syncUsers( ldapModelId, "wrong action");
Assert.fail("Should throw 400");
} catch (Exception e) {
Assert.assertTrue(e instanceof BadRequestException);
@ -572,7 +572,7 @@ public class LDAPSyncTest extends AbstractLDAPTest {
LDAPTestContext ctx = LDAPTestContext.init(session);
KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
SynchronizationResult syncResult = new UserStorageSyncManager().syncAllUsers(sessionFactory, "test", ctx.getLdapModel());
SynchronizationResult syncResult = new UserStorageSyncManager().syncAllUsers(sessionFactory, ctx.getRealm().getId(), ctx.getLdapModel());
Assert.assertEquals(2, syncResult.getAdded());
});

View file

@ -34,7 +34,7 @@ public class LDAPTestContext {
private final LDAPStorageProvider ldapProvider;
public static LDAPTestContext init(KeycloakSession session) {
RealmModel testRealm = session.realms().getRealm(AbstractLDAPTest.TEST_REALM_NAME);
RealmModel testRealm = session.realms().getRealmByName(AbstractLDAPTest.TEST_REALM_NAME);
ComponentModel ldapCompModel = LDAPTestUtils.getLdapProviderModel(testRealm);
UserStorageProviderModel ldapModel = new UserStorageProviderModel(ldapCompModel);
LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ldapModel);

View file

@ -43,7 +43,7 @@ public abstract class AbstractUserStorageDirtyDeletionTest extends AbstractConcu
public static void remove20UsersFromStorageProvider(KeycloakSession session) {
assertThat(REMOVED_USERS_COUNT, Matchers.lessThan(NUM_USERS));
final RealmModel realm = session.realms().getRealm(TEST_REALM_NAME);
final RealmModel realm = session.realms().getRealmByName(TEST_REALM_NAME);
UserStorageProvidersTestUtils.getEnabledStorageProviders(session, realm, UserMapStorage.class)
.forEachOrdered((UserMapStorage userMapStorage) -> {
Set<String> users = new HashSet<>(userMapStorage.getUsernames());

View file

@ -35,6 +35,7 @@ import org.keycloak.events.EventType;
import org.keycloak.models.UserModel;
import org.keycloak.models.credential.OTPCredentialModel;
import org.keycloak.models.credential.PasswordCredentialModel;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.models.utils.TimeBasedOTP;
import org.keycloak.representations.idm.ComponentRepresentation;
import org.keycloak.representations.idm.EventRepresentation;
@ -79,7 +80,7 @@ public class UserStorageOTPTest extends AbstractTestRealmKeycloakTest {
protected TimeBasedOTP totp = new TimeBasedOTP();
protected String componentId = KeycloakModelUtils.generateId();
@Override
public void configureTestRealm(RealmRepresentation testRealm) {
@ -90,7 +91,7 @@ public class UserStorageOTPTest extends AbstractTestRealmKeycloakTest {
public void addProvidersBeforeTest() throws URISyntaxException, IOException {
ComponentRepresentation dummyProvider = new ComponentRepresentation();
dummyProvider.setName("dummy");
dummyProvider.setId(DummyUserFederationProviderFactory.PROVIDER_NAME);
dummyProvider.setId(componentId);
dummyProvider.setProviderId(DummyUserFederationProviderFactory.PROVIDER_NAME);
dummyProvider.setProviderType(UserStorageProvider.class.getName());
dummyProvider.setConfig(new MultivaluedHashMap<>());
@ -113,7 +114,7 @@ public class UserStorageOTPTest extends AbstractTestRealmKeycloakTest {
public void testCredentialsThroughRESTAPI() {
// Test that test-user has federation link on him
UserResource user = ApiUtil.findUserByUsernameId(testRealm(), "test-user");
Assert.assertEquals(DummyUserFederationProviderFactory.PROVIDER_NAME, user.toRepresentation().getFederationLink());
Assert.assertEquals(componentId, user.toRepresentation().getFederationLink());
// Test that both "password" and "otp" are configured for the test-user
List<String> userStorageCredentialTypes = user.getConfiguredUserStorageCredentialTypes();
@ -214,7 +215,7 @@ public class UserStorageOTPTest extends AbstractTestRealmKeycloakTest {
// Assert he has federation link on him
UserResource userResource = ApiUtil.findUserByUsernameId(testRealm(), "test-user2");
Assert.assertEquals(DummyUserFederationProviderFactory.PROVIDER_NAME, userResource.toRepresentation().getFederationLink());
Assert.assertEquals(componentId, userResource.toRepresentation().getFederationLink());
// Assert no userStorage supported credentials shown through admin REST API for that user. For this user, the validation of password and OTP is not delegated
// to the dummy user storage provider

View file

@ -217,7 +217,7 @@ public class GeneratedEcdsaKeyProviderTest extends AbstractKeycloakTest {
protected ComponentRepresentation createRep(String name, String providerId) {
ComponentRepresentation rep = new ComponentRepresentation();
rep.setName(name);
rep.setParentId(TEST_REALM_NAME);
rep.setParentId(adminClient.realm(TEST_REALM_NAME).toRepresentation().getId());
rep.setProviderId(providerId);
rep.setProviderType(KeyProvider.class.getName());
rep.setConfig(new MultivaluedHashMap<>());

View file

@ -44,6 +44,7 @@ import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.keycloak.testsuite.admin.AbstractAdminTest.loadJson;
import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer;
/**
@ -180,7 +181,7 @@ public class GeneratedHmacKeyProviderTest extends AbstractKeycloakTest {
protected ComponentRepresentation createRep(String name, String providerId) {
ComponentRepresentation rep = new ComponentRepresentation();
rep.setName(name);
rep.setParentId("test");
rep.setParentId(adminClient.realm("test").toRepresentation().getId());
rep.setProviderId(providerId);
rep.setProviderType(KeyProvider.class.getName());
rep.setConfig(new MultivaluedHashMap<>());

View file

@ -251,7 +251,7 @@ public class GeneratedRsaKeyProviderTest extends AbstractKeycloakTest {
protected ComponentRepresentation createRep(String name, String providerId) {
ComponentRepresentation rep = new ComponentRepresentation();
rep.setName(name);
rep.setParentId("test");
rep.setParentId(adminClient.realm("test").toRepresentation().getId());
rep.setProviderId(providerId);
rep.setProviderType(KeyProvider.class.getName());
rep.setConfig(new MultivaluedHashMap<>());

View file

@ -282,7 +282,7 @@ public class ImportedRsaKeyProviderTest extends AbstractKeycloakTest {
protected ComponentRepresentation createRep(String name, String providerId) {
ComponentRepresentation rep = new ComponentRepresentation();
rep.setName(name);
rep.setParentId("test");
rep.setParentId(adminClient.realm("test").toRepresentation().getId());
rep.setProviderId(providerId);
rep.setProviderType(KeyProvider.class.getName());
rep.setConfig(new MultivaluedHashMap<>());

View file

@ -164,7 +164,7 @@ public class JavaKeystoreKeyProviderTest extends AbstractKeycloakTest {
protected ComponentRepresentation createRep(String name, long priority) {
ComponentRepresentation rep = new ComponentRepresentation();
rep.setName(name);
rep.setParentId("test");
rep.setParentId(adminClient.realm("test").toRepresentation().getId());
rep.setProviderId(JavaKeystoreKeyProviderFactory.ID);
rep.setProviderType(KeyProvider.class.getName());
rep.setConfig(new MultivaluedHashMap<>());

View file

@ -272,9 +272,10 @@ public class KeyRotationTest extends AbstractKeycloakTest {
String privateKeyPem = PemUtils.encodeKey(keyPair.getPrivate());
PublicKey publicKey = keyPair.getPublic();
String testRealmId = adminClient.realm("test").toRepresentation().getId();
ComponentRepresentation rep = new ComponentRepresentation();
rep.setName("mycomponent");
rep.setParentId("test");
rep.setParentId(testRealmId);
rep.setProviderId(ImportedRsaKeyProviderFactory.ID);
rep.setProviderType(KeyProvider.class.getName());
@ -288,7 +289,7 @@ public class KeyRotationTest extends AbstractKeycloakTest {
rep = new ComponentRepresentation();
rep.setName("mycomponent2");
rep.setParentId("test");
rep.setParentId(testRealmId);
rep.setProviderId(GeneratedHmacKeyProviderFactory.ID);
rep.setProviderType(KeyProvider.class.getName());
@ -312,7 +313,8 @@ public class KeyRotationTest extends AbstractKeycloakTest {
private void dropKeys(String priority) {
int r = 0;
for (ComponentRepresentation c : adminClient.realm("test").components().query("test", KeyProvider.class.getName())) {
String parentId = adminClient.realm("test").toRepresentation().getId();
for (ComponentRepresentation c : adminClient.realm("test").components().query(parentId, KeyProvider.class.getName())) {
if (c.getConfig().getFirst("priority").equals(priority)) {
adminClient.realm("test").components().component(c.getId()).remove();
r++;

View file

@ -49,7 +49,6 @@ public class LoginTimeoutValidationTest extends AbstractTestRealmKeycloakTest {
public void before() {
testingClient.server().run( session -> {
RealmModel realm = session.realms().getRealmByName("test");
realm = session.realms().getRealm("test");
session.users().addUser(realm, "user1");
});
}

View file

@ -513,16 +513,17 @@ public abstract class AbstractMigrationTest extends AbstractKeycloakTest {
protected void testExtractRealmKeysMasterRealm(RealmResource masterRealm) {
log.info("testing extract realm keys");
String expectedMasterRealmKey = "MIIEowIBAAKCAQEAiU54OXoCbHy0L0gHn1yasctcnKHRU1pHFIJnWvaI7rClJydet9dDJaiYXOxMKseiBm3eYznfN3cPyU8udYmRnMuKjiocZ77LT2IEttAjXb6Ggazx7loriFHRy0IOJeX4KxXhAPWmxqa3mkFNfLBEvFqVaBgUDHQ60cmnPvNSHYudBTW9K80s8nvmP2pso7HTwWJ1+Xatj1Ey/gTmB3CXlyqBegGWC9TeuErEYpYhdh+11TVWasgMBZyUCtL3NRPaBuhaPg1LpW8lWGk05nS+YM6dvTk3Mppv+z2RygEpxyO09oT3b4G+Zfwit1STqn0AvDTGzINdoKcNtFScV0j8TwIDAQABAoIBAHcbPKsPLZ8SJfOF1iblW8OzFulAbaaSf2pJHIMJrQrw7LKkMkPjVXoLX+/rgr7xYZmWIP2OLBWfEHCeYTzQUyHiZpSf7vgHx7Fa45/5uVQOe/ttHIiYa37bCtP4vvEdJkOpvP7qGPvljwsebqsk9Ns28LfVez66bHOjK5Mt2yOIulbTeEs7ch//h39YwKJv96vc+CHbV2O6qoOxZessO6y+287cOBvbFXmS2GaGle5Nx/EwncBNS4b7czoetmm70+9ht3yX+kxaP311YUT31KQjuaJt275kOiKsrXr27PvgO++bsIyGuSzqyS7G7fmxF2zUyphEqEpalyDGMKMnrAECgYEA1fCgFox03rPDjm0MhW/ThoS2Ld27sbWQ6reS+PBMdUTJZVZIU1D2//h6VXDnlddhk6avKjA4smdy1aDKzmjz3pt9AKn+kgkXqtTC2fD3wp+fC9hND0z+rQPGe/Gk7ZUnTdsqnfyowxr+woIgzdnRukOUrG+xQiP3RUUT7tt6NQECgYEApEz2xvgqMm+9/f/YxjLdsFUfLqc4WlafB863stYEVqlCYy5ujyo0VQ0ahKSKJkLDnf52+aMUqPOpwaGePpu3O6VkvpcKfPY2MUlZW7/6Sa9et9hxNkdTS7Gui2d1ELpaCBe1Bc62sk8EA01iHXE1PpvyUqDWrhNh+NrDICA9oU8CgYBgGDYACtTP11TmW2r9YK5VRLUDww30k4ZlN1GnyV++aMhBYVEZQ0u+y+A/EnijIFwu0vbo70H4OGknNZMCxbeMbLDoJHM5KyZbUDe5ZvgSjloFGwH59m6KTiDQOUkIgi9mVCQ/VGaFRFHcElEjxUvj60kTbxPijn8ZuR5r8l9hAQKBgQCQ9jL5pHWeoIayN20smi6M6N2lTPbkhe60dcgQatHTIG2pkosLl8IqlHAkPgSB84AiwyR351JQKwRJCm7TcJI/dxMnMZ6YWKfB3qSP1hdfsfJRJQ/mQxIUBAYrizF3e+P5peka4aLCOgMhYsJBlePThMZN7wja99EGPwXQL4IQ8wKBgB8Nis1lQK6Z30GCp9u4dYleGfEP71Lwqvk/eJb89/uz0fjF9CTpJMULFc+nA5u4yHP3LFnRg3zCU6aEwfwUyk4GH9lWGV/qIAisQtgrCEraVe4qxz0DVE59C7qjO26IhU2U66TEzPAqvQ3zqey+woDn/cz/JMWK1vpcSk+TKn3K";
List<ComponentRepresentation> components = masterRealm.components().query(MASTER, KeyProvider.class.getName());
String realmId = masterRealm.toRepresentation().getId();
List<ComponentRepresentation> components = masterRealm.components().query(realmId, KeyProvider.class.getName());
assertEquals(3, components.size());
components = masterRealm.components().query(MASTER, KeyProvider.class.getName(), "rsa");
components = masterRealm.components().query(realmId, KeyProvider.class.getName(), "rsa");
assertEquals(1, components.size());
ComponentRepresentation component = testingClient.server(MASTER).fetch(RunHelpers.internalComponent(components.get(0).getId()));
assertEquals(expectedMasterRealmKey, component.getConfig().getFirst("privateKey"));
components = masterRealm.components().query(MASTER, KeyProvider.class.getName(), "hmac-generated");
components = masterRealm.components().query(realmId, KeyProvider.class.getName(), "hmac-generated");
assertEquals(1, components.size());
}
@ -530,17 +531,17 @@ public abstract class AbstractMigrationTest extends AbstractKeycloakTest {
protected void testExtractRealmKeysMigrationRealm(RealmResource migrationRealm) {
log.info("testing extract realm keys");
String expectedMigrationRealmKey = "MIIEpAIBAAKCAQEApt6gCllWkVTZ7fy/oRIx6Bxjt9x3eKKyKGFXvN4iaafrNqpYU9lcqPngWJ9DyXGqUf8RpjPaQWiLWLxjw3xGBqLk2E1/Frb9e/dy8rj//fHGq6bujN1iguzyFwxPGT5Asd7jflRI3qU04M8JE52PArqPhGL2Fn+FiSK5SWRIGm+hVL7Ck/E/tVxM25sFG1/UTQqvrROm4q76TmP8FsyZaTLVf7cCwW2QPIX0N5HTVb3QbBb5KIsk4kKmk/g7uUxS9r42tu533LISzRr5CTyWZAL2XFRuF2RrKdE8gwqkEubw6sDmB2mE0EoPdY1DUhBQgVP/5rwJrCtTsUBR2xdEYQIDAQABAoIBAFbbsNBSOlZBpYJUOmcb8nBQPrOYhXN8tGGCccn0klMOvcdhmcJjdPDbyCQ5Gm7DxJUTwNsTSHsdcNMKlJ9Pk5+msJnKlOl87KrXXbTsCQvlCrWUmb0nCzz9GvJWTOHl3oT3cND0DE4gDksqWR4luCgCdevCGzgQvrBoK6wBD+r578uEW3iw10hnJ0+wnGiw8IvPzE1a9xbY4HD8/QrYdaLxuLb/aC1PDuzrz0cOjnvPkrws5JrbUSnbFygJiOv1z4l2Q00uGIxlHtXdwQBnTZZjVi4vOec2BYSHffgwDYEZIglw1mnrV7y0N1nnPbtJK/cegIkXoBQHXm8Q99TrWMUCgYEA9au86qcwrXZZg5H4BpR5cpy0MSkcKDbA1aRL1cAyTCqJxsczlAtLhFADF+NhnlXj4y7gwDEYWrz064nF73I+ZGicvCiyOy+tCTugTyTGS+XR948ElDMS6PCUUXsotS3dKa0b3c9wd2mxeddTjq/ArfgEVZJ6fE1KtjLt9dtfA+8CgYEAreK3JsvjR5b/Xct28TghYUU7Qnasombb/shqqy8FOMjYUr5OUm/OjNIgoCqhOlE8oQDJ4dOZofNSa7tL+oM8Gmbal+E3fRzxnx/9/EC4QV6sVaPLTIyk7EPfKTcZuzH7+BNZtAziTxJw9d6YJQRbkpg92EZIEoR8iDj2Xs5xrK8CgYEAwMVWwwYX8zT3vn7ukTM2LRH7bsvkVUXJgJqgCwT6Mrv6SmkK9vL5+cPS+Y6pjdW1sRGauBSOGL1Grf/4ug/6F03jFt4UJM8fRyxreU7Q7sNSQ6AMpsGA6BnHODycz7ZCYa59PErG5FyiL4of/cm5Nolz1TXQOPNpWZiTEqVlZC8CgYA4YPbjVF4nuxSnU64H/hwMjsbtAM9uhI016cN0J3W4+J3zDhMU9X1x+Tts0wWdg/N1fGz4lIQOl3cUyRCUc/KL2OdtMS+tmDHbVyMho9ZaE5kq10W2Vy+uDz+O/HeSU12QDK4cC8Vgv+jyPy7zaZtLR6NduUPrBRvfiyCOkr8WrwKBgQCY0h4RCdNFhr0KKLLmJipAtV8wBCGcg1jY1KoWKQswbcykfBKwHbF6EooVqkRW0ITjWB7ZZCf8TnSUxe0NXCUAkVBrhzS4DScgtoSZYOOUaSHgOxpfwgnQ3oYotKi98Yg3IsaLs1j4RuPG5Sp1z6o+ELP1uvr8azyn9YlLa+523Q==";
List<ComponentRepresentation> components = migrationRealm.components().query(MIGRATION, KeyProvider.class.getName());
String realmId = migrationRealm.toRepresentation().getId();
List<ComponentRepresentation> components = migrationRealm.components().query(realmId, KeyProvider.class.getName());
assertEquals(3, components.size());
components = migrationRealm.components().query(MIGRATION, KeyProvider.class.getName(), "rsa");
components = migrationRealm.components().query(realmId, KeyProvider.class.getName(), "rsa");
assertEquals(1, components.size());
ComponentRepresentation component = testingClient.server(MIGRATION).fetch(RunHelpers.internalComponent(components.get(0).getId()));
assertEquals(expectedMigrationRealmKey, component.getConfig().getFirst("privateKey"));
components = migrationRealm.components().query(MIGRATION, KeyProvider.class.getName(), "hmac-generated");
components = migrationRealm.components().query(realmId, KeyProvider.class.getName(), "hmac-generated");
assertEquals(1, components.size());
}

View file

@ -39,7 +39,7 @@ public class MigrationTest extends AbstractMigrationTest {
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
log.info("Adding no test realms for migration test. Test realm should be migrated from previous vesrion.");
log.info("Adding no test realms for migration test. Test realm should be migrated from previous version.");
}
@Before
@ -108,11 +108,11 @@ public class MigrationTest extends AbstractMigrationTest {
@Test
@Migration(versionFrom = "2.")
public void migration2_xTest() throws Exception {
//the realm with special characters in its id was succesfully migrated (no error during migration)
//the realm with special characters in its id was successfully migrated (no error during migration)
//removing it now as testMigratedData() expects specific clients and roles
//we need to perform the removal via run on server to workaround escaping parameters when using rest call
testingClient.server().run(session -> {
RealmModel realm = session.realms().getRealm("test ' and ; and -- and \"");
RealmModel realm = session.realms().getRealmByName("test ' and ; and -- and \"");
new RealmManager(session).removeRealm(realm);
});

View file

@ -56,23 +56,26 @@ import static org.keycloak.testsuite.arquillian.annotation.AuthServerContainerEx
@AuthServerContainerExclude(REMOTE)
public class AuthenticationSessionProviderTest extends AbstractTestRealmKeycloakTest {
private static String realmId;
@Rule
public InfinispanTestTimeServiceRule ispnTestTimeService = new InfinispanTestTimeServiceRule(this);
@Before
public void before() {
testingClient.server().run(session -> {
RealmModel realm = session.realms().getRealm("test");
RealmModel realm = session.realms().getRealmByName("test");
session.users().addUser(realm, "user1").setEmail("user1@localhost");
session.users().addUser(realm, "user2").setEmail("user2@localhost");
realmId = realm.getId();
});
}
@After
public void after() {
testingClient.server().run(session -> {
RealmModel realm = session.realms().getRealm("test");
RealmModel realm = session.realms().getRealm(realmId);
session.sessions().removeUserSessions(realm);
UserModel user1 = session.users().getUserByUsername(realm, "user1");
@ -97,7 +100,7 @@ public class AuthenticationSessionProviderTest extends AbstractTestRealmKeycloak
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCRUD1) -> {
KeycloakSession currentSession = sessionCRUD1;
RealmModel realm = currentSession.realms().getRealm("test");
RealmModel realm = currentSession.realms().getRealm(realmId);
ClientModel client1 = realm.getClientByClientId("test-app");
@ -113,7 +116,7 @@ public class AuthenticationSessionProviderTest extends AbstractTestRealmKeycloak
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCRUD2) -> {
KeycloakSession currentSession = sessionCRUD2;
RealmModel realm = currentSession.realms().getRealm("test");
RealmModel realm = currentSession.realms().getRealm(realmId);
ClientModel client1 = realm.getClientByClientId("test-app");
@ -132,7 +135,7 @@ public class AuthenticationSessionProviderTest extends AbstractTestRealmKeycloak
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCRUD3) -> {
KeycloakSession currentSession = sessionCRUD3;
RealmModel realm = currentSession.realms().getRealm("test");
RealmModel realm = currentSession.realms().getRealm(realmId);
UserModel user1 = currentSession.users().getUserByUsername(realm, "user1");
// Ensure currentSession was updated
@ -150,7 +153,7 @@ public class AuthenticationSessionProviderTest extends AbstractTestRealmKeycloak
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCRUD4) -> {
KeycloakSession currentSession = sessionCRUD4;
RealmModel realm = currentSession.realms().getRealm("test");
RealmModel realm = currentSession.realms().getRealm(realmId);
// Ensure currentSession was removed
assertThat(currentSession.authenticationSessions().getRootAuthenticationSession(realm, rootAuthSessionID.get()), nullValue());
@ -166,7 +169,7 @@ public class AuthenticationSessionProviderTest extends AbstractTestRealmKeycloak
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionRestart1) -> {
KeycloakSession currentSession = sessionRestart1;
RealmModel realm = currentSession.realms().getRealm("test");
RealmModel realm = currentSession.realms().getRealm(realmId);
ClientModel client1 = realm.getClientByClientId("test-app");
UserModel user1 = currentSession.users().getUserByUsername(realm, "user1");
@ -188,7 +191,7 @@ public class AuthenticationSessionProviderTest extends AbstractTestRealmKeycloak
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionRestart2) -> {
KeycloakSession currentSession = sessionRestart2;
RealmModel realm = currentSession.realms().getRealm("test");
RealmModel realm = currentSession.realms().getRealm(realmId);
// Test restart root authentication session
ClientModel client1 = realm.getClientByClientId("test-app");
@ -199,7 +202,7 @@ public class AuthenticationSessionProviderTest extends AbstractTestRealmKeycloak
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionRestart3) -> {
KeycloakSession currentSession = sessionRestart3;
RealmModel realm = currentSession.realms().getRealm("test");
RealmModel realm = currentSession.realms().getRealm(realmId);
ClientModel client1 = realm.getClientByClientId("test-app");
@ -255,7 +258,7 @@ public class AuthenticationSessionProviderTest extends AbstractTestRealmKeycloak
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesRealmRemoved1) -> {
KeycloakSession currentSession = sesRealmRemoved1;
RealmModel realm = currentSession.realms().getRealm("test");
RealmModel realm = currentSession.realms().getRealm(realmId);
RealmModel fooRealm = currentSession.realms().createRealm("foo-realm");
fooRealm.setDefaultRole(currentSession.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + fooRealm.getName()));
fooRealm.setAccessCodeLifespanLogin(1800);
@ -273,7 +276,7 @@ public class AuthenticationSessionProviderTest extends AbstractTestRealmKeycloak
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesRealmRemoved3) -> {
KeycloakSession currentSession = sesRealmRemoved3;
RealmModel realm = currentSession.realms().getRealm("test");
RealmModel realm = currentSession.realms().getRealm(realmId);
RootAuthenticationSessionModel authSession = currentSession.authenticationSessions().getRootAuthenticationSession(realm, authSessionID.get());
@ -291,7 +294,7 @@ public class AuthenticationSessionProviderTest extends AbstractTestRealmKeycloak
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesRealmRemoved1) -> {
KeycloakSession currentSession = sesRealmRemoved1;
RealmModel realm = currentSession.realms().getRealm("test");
RealmModel realm = currentSession.realms().getRealm(realmId);
authSessionID.set(currentSession.authenticationSessions().createRootAuthenticationSession(realm).getId());
@ -306,7 +309,7 @@ public class AuthenticationSessionProviderTest extends AbstractTestRealmKeycloak
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesRealmRemoved1) -> {
KeycloakSession currentSession = sesRealmRemoved1;
RealmModel realm = currentSession.realms().getRealm("test");
RealmModel realm = currentSession.realms().getRealm(realmId);
RootAuthenticationSessionModel rootAuthSession = currentSession.authenticationSessions().getRootAuthenticationSession(realm, authSessionID.get());
@ -319,7 +322,7 @@ public class AuthenticationSessionProviderTest extends AbstractTestRealmKeycloak
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesRealmRemoved1) -> {
KeycloakSession currentSession = sesRealmRemoved1;
RealmModel realm = currentSession.realms().getRealm("test");
RealmModel realm = currentSession.realms().getRealm(realmId);
RootAuthenticationSessionModel rootAuthSession = currentSession.authenticationSessions().getRootAuthenticationSession(realm, authSessionID.get());
assertThat(rootAuthSession.getAuthenticationSession(realm.getClientByClientId("test-app"), tab1ID.get()).getAuthNote("foo"), is("bar"));
@ -350,7 +353,7 @@ public class AuthenticationSessionProviderTest extends AbstractTestRealmKeycloak
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession createAuthSession) -> {
KeycloakSession currentSession = createAuthSession;
RealmModel realm = currentSession.realms().getRealm("test");
RealmModel realm = currentSession.realms().getRealm(realmId);
Time.setOffset(0);
authSessionID.set(currentSession.authenticationSessions().createRootAuthenticationSession(realm).getId());
@ -361,7 +364,7 @@ public class AuthenticationSessionProviderTest extends AbstractTestRealmKeycloak
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionExp) -> {
KeycloakSession currentSession = sessionExp;
RealmModel realm = currentSession.realms().getRealm("test");
RealmModel realm = currentSession.realms().getRealm(realmId);
Time.setOffset(offset);
currentSession.authenticationSessions().removeExpired(realm);
@ -369,7 +372,7 @@ public class AuthenticationSessionProviderTest extends AbstractTestRealmKeycloak
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionExpVerify) -> {
KeycloakSession currentSession = sessionExpVerify;
RealmModel realm = currentSession.realms().getRealm("test");
RealmModel realm = currentSession.realms().getRealm(realmId);
if (isSessionNull)
assertThat(currentSession.authenticationSessions().getRootAuthenticationSession(realm, authSessionID), nullValue());
@ -383,7 +386,7 @@ public class AuthenticationSessionProviderTest extends AbstractTestRealmKeycloak
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionLifespan) -> {
KeycloakSession currentSession = sessionLifespan;
RealmModel realm = currentSession.realms().getRealm("test");
RealmModel realm = currentSession.realms().getRealm(realmId);
if (lifespan != -1)
realm.setAccessCodeLifespan(lifespan);

View file

@ -1,6 +1,8 @@
package org.keycloak.testsuite.model;
import org.junit.Ignore;
import org.junit.Test;
import org.keycloak.common.Profile;
import org.keycloak.models.KeycloakSession;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.services.managers.RealmManager;
@ -33,6 +35,10 @@ public class BadRealmTest extends AbstractKeycloakTest {
@Test
@ModelTest
public void testBadRealmId(KeycloakSession session) {
if (Profile.isFeatureEnabled(Profile.Feature.MAP_STORAGE)) {
// when map storage is enabled, the id is always converted into a valid UUID.
return;
}
RealmManager manager = new RealmManager(session);
try {
manager.createRealm(id + script, name);

View file

@ -125,7 +125,7 @@ public class CompositeRolesModelTest extends AbstractTestRealmKeycloakTest {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession session5) -> {
RealmModel realm = session5.realms().getRealm("TestComposites");
RealmModel realm = session5.realms().getRealmByName("TestComposites");
Set<RoleModel> requestedRoles = getRequestedRoles(realm.getClientByClientId("APP_COMPOSITE_APPLICATION"), session.users().getUserByUsername(realm, "APP_COMPOSITE_USER"));
@ -166,7 +166,6 @@ public class CompositeRolesModelTest extends AbstractTestRealmKeycloakTest {
public void configureTestRealm(RealmRepresentation testRealm) {
log.infof("testcomposites imported");
RealmRepresentation newRealm = loadJson(getClass().getResourceAsStream("/model/testcomposites2.json"), RealmRepresentation.class);
newRealm.setId("TestComposites");
adminClient.realms().create(newRealm);
}

View file

@ -65,7 +65,7 @@ public class ConcurrentTransactionsTest extends AbstractTestRealmKeycloakTest {
try {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionSetup) -> {
RealmModel realm = sessionSetup.realms().getRealm("test");
RealmModel realm = sessionSetup.realms().getRealmByName("test");
sessionSetup.users().addUser(realm, "user1").setEmail("user1@localhost");
sessionSetup.users().addUser(realm, "user2").setEmail("user2@localhost");

View file

@ -65,11 +65,13 @@ public class MultipleRealmsTest extends AbstractTestRealmKeycloakTest {
AtomicReference<UserModel> r1user1Atomic = new AtomicReference<>();
String id1 = KeycloakModelUtils.generateId();
String id2 = KeycloakModelUtils.generateId();
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionTestUser1) -> {
KeycloakSession currentSession = sessionTestUser1;
RealmModel realm1 = currentSession.realms().createRealm("id1", "realm1");
RealmModel realm2 = currentSession.realms().createRealm("id2", "realm2");
RealmModel realm1 = currentSession.realms().createRealm(id1, "realm1");
RealmModel realm2 = currentSession.realms().createRealm(id2,"realm2");
realm1.setDefaultRole(currentSession.roles().addRealmRole(realm1, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + realm1.getName()));
realm2.setDefaultRole(currentSession.roles().addRealmRole(realm2, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + realm2.getName()));
@ -101,8 +103,8 @@ public class MultipleRealmsTest extends AbstractTestRealmKeycloakTest {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionTestUser2) -> {
KeycloakSession currentSession = sessionTestUser2;
RealmModel realm1 = currentSession.realms().getRealm("id1");
RealmModel realm2 = currentSession.realms().getRealm("id2");
RealmModel realm1 = currentSession.realms().getRealm(id1);
RealmModel realm2 = currentSession.realms().getRealm(id2);
UserModel r1user1 = r1user1Atomic.get();
@ -127,8 +129,8 @@ public class MultipleRealmsTest extends AbstractTestRealmKeycloakTest {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionTestUser3) -> {
KeycloakSession currentSession = sessionTestUser3;
currentSession.realms().removeRealm("id1");
currentSession.realms().removeRealm("id2");
currentSession.realms().removeRealm(id1);
currentSession.realms().removeRealm(id2);
});
}
@ -138,8 +140,10 @@ public class MultipleRealmsTest extends AbstractTestRealmKeycloakTest {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionById) -> {
KeycloakSession currentSession = sessionById;
RealmModel realm1 = currentSession.realms().createRealm("id1", "realm1");
RealmModel realm2 = currentSession.realms().createRealm("id2", "realm2");
String id1 = KeycloakModelUtils.generateId();
String id2 = KeycloakModelUtils.generateId();
RealmModel realm1 = currentSession.realms().createRealm(id1, "realm1");
RealmModel realm2 = currentSession.realms().createRealm(id2, "realm2");
realm1.setDefaultRole(currentSession.roles().addRealmRole(realm1, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + realm1.getName()));
realm2.setDefaultRole(currentSession.roles().addRealmRole(realm2, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + realm2.getName()));
@ -147,9 +151,9 @@ public class MultipleRealmsTest extends AbstractTestRealmKeycloakTest {
createObjects(currentSession, realm1);
createObjects(currentSession, realm2);
Assert.assertEquals(realm1, currentSession.realms().getRealm("id1"));
Assert.assertEquals(realm1, currentSession.realms().getRealm(id1));
Assert.assertEquals(realm1, currentSession.realms().getRealmByName("realm1"));
Assert.assertEquals(realm2, currentSession.realms().getRealm("id2"));
Assert.assertEquals(realm2, currentSession.realms().getRealm(id2));
Assert.assertEquals(realm2, currentSession.realms().getRealmByName("realm2"));
ClientModel r1app1 = realm1.getClientByClientId("app1");
@ -185,8 +189,8 @@ public class MultipleRealmsTest extends AbstractTestRealmKeycloakTest {
um.removeUser(realm2, user1a);
}
currentSession.realms().removeRealm("id1");
currentSession.realms().removeRealm("id2");
currentSession.realms().removeRealm(id1);
currentSession.realms().removeRealm(id2);
});
}

View file

@ -23,6 +23,7 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.keycloak.component.ComponentModel;
import org.keycloak.models.AuthenticationExecutionModel;
@ -58,6 +59,8 @@ import static org.keycloak.testsuite.admin.AbstractAdminTest.loadJson;
@AuthServerContainerExclude(AuthServerContainerExclude.AuthServer.REMOTE)
public class OwnerReplacementTest extends AbstractKeycloakTest {
private static String testRealmId;
private static String fooRealmId;
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
@ -75,10 +78,16 @@ public class OwnerReplacementTest extends AbstractKeycloakTest {
.name("foo")
.user(user)
.build();
realm2.setId("foo");
testRealms.add(realm2);
}
@Before
public void before() {
testingClient.server().run(session -> {
testRealmId = session.realms().getRealmByName("test").getId();
fooRealmId = session.realms().getRealmByName("foo").getId();
});
}
@Test
@ModelTest
@ -471,18 +480,17 @@ public class OwnerReplacementTest extends AbstractKeycloakTest {
// Transaction 1 - Lookup object of realm1
AtomicReference<String> realm1ObjectId = new AtomicReference<>();
KeycloakModelUtils.runJobInTransaction(session1.getKeycloakSessionFactory(), (KeycloakSession session) -> {
RealmModel realm1 = session.getProvider(RealmProvider.class).getRealm("test");
// can't use getRealmByName as that returns the infinispan realm adapter version, meaning the tests will query
// the cache instead of the actual provider.
RealmModel realm1 = session.getProvider(RealmProvider.class).getRealm(testRealmId);
realm1ObjectId.set(realm1ObjectIdProducer.apply(session, realm1));
});
// Transaction 2
KeycloakModelUtils.runJobInTransaction(session1.getKeycloakSessionFactory(), (KeycloakSession session) -> {
RealmModel realm1 = session.getProvider(RealmProvider.class).getRealm("test");
RealmModel realm2 = session.getProvider(RealmProvider.class).getRealm("foo");
RealmModel realm1 = session.getProvider(RealmProvider.class).getRealm(testRealmId);
RealmModel realm2 = session.getProvider(RealmProvider.class).getRealm(fooRealmId);
testLookupRealm1ObjectInRealm2.accept(session, realm2, realm1ObjectId.get());
updaterRealm1ObjectInRealm2.accept(session, realm1, realm2, realm1ObjectId.get());
@ -491,7 +499,7 @@ public class OwnerReplacementTest extends AbstractKeycloakTest {
// Transaction 3
KeycloakModelUtils.runJobInTransaction(session1.getKeycloakSessionFactory(), (KeycloakSession session) -> {
RealmModel realm1 = session.getProvider(RealmProvider.class).getRealm("test");
RealmModel realm1 = session.getProvider(RealmProvider.class).getRealm(testRealmId);
testUpdateFailed.accept(session, realm1, realm1ObjectId.get());
});
@ -499,8 +507,8 @@ public class OwnerReplacementTest extends AbstractKeycloakTest {
// Transaction 4
try {
KeycloakModelUtils.runJobInTransaction(session1.getKeycloakSessionFactory(), (KeycloakSession session) -> {
RealmModel realm1 = session.getProvider(RealmProvider.class).getRealm("test");
RealmModel realm2 = session.getProvider(RealmProvider.class).getRealm("foo");
RealmModel realm1 = session.getProvider(RealmProvider.class).getRealm(testRealmId);
RealmModel realm2 = session.getProvider(RealmProvider.class).getRealm(fooRealmId);
removeRealm1ObjectInRealm2.accept(session, realm1, realm2, realm1ObjectId.get());
});
@ -510,8 +518,7 @@ public class OwnerReplacementTest extends AbstractKeycloakTest {
// Transaction 5
KeycloakModelUtils.runJobInTransaction(session1.getKeycloakSessionFactory(), (KeycloakSession session) -> {
RealmModel realm1 = session.getProvider(RealmProvider.class).getRealm("test");
RealmModel realm1 = session.getProvider(RealmProvider.class).getRealm(testRealmId);
testRemoveFailed.accept(session, realm1, realm1ObjectId.get());
});
}

View file

@ -54,6 +54,8 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest {
private static ComponentModel clientStorageComponent;
private static String realmId;
@Before
public void before() {
testingClient.server().run(session -> {
@ -66,7 +68,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest {
testingClient.server().run(session -> {
RealmManager realmManager = new RealmManager(session);
RealmModel realm = realmManager.getRealmByName("original");
RealmModel realm = realmManager.getRealm(realmId);
if (realm != null) {
@ -148,6 +150,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest {
UserConsentModel maryHardcodedGrant = new UserConsentModel(hardcodedClient);
realmManager.getSession().users().addConsent(realm, mary.getId(), maryHardcodedGrant);
realmId = realm.getId();
});
}
@ -158,7 +161,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCT) -> {
KeycloakSession currentSession = sessionCT;
RealmModel realm = currentSession.realms().getRealm("original");
RealmModel realm = currentSession.realms().getRealm(realmId);
ClientModel fooClient = realm.getClientByClientId("foo-client");
ClientModel barClient = realm.getClientByClientId("bar-client");
@ -201,7 +204,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionACT) -> {
KeycloakSession currentSession = sessionACT;
RealmModel realm = currentSession.realms().getRealm("original");
RealmModel realm = currentSession.realms().getRealm(realmId);
ClientModel fooClient = realm.getClientByClientId("foo-client");
@ -237,7 +240,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession removalTestSession1) -> {
KeycloakSession currentSession = removalTestSession1;
RealmModel realm = currentSession.realms().getRealm("original");
RealmModel realm = currentSession.realms().getRealm(realmId);
ClientModel fooClient = realm.getClientByClientId("foo-client");
UserModel john = currentSession.users().getUserByUsername(realm, "john");
@ -254,7 +257,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession removalTestSession2) -> {
KeycloakSession currentSession = removalTestSession2;
RealmModel realm = currentSession.realms().getRealm("original");
RealmModel realm = currentSession.realms().getRealm(realmId);
ClientModel fooClient = realm.getClientByClientId("foo-client");
UserModel john = currentSession.users().getUserByUsername(realm, "john");
@ -271,7 +274,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionRT1) -> {
KeycloakSession currentSession = sessionRT1;
RealmModel realm = currentSession.realms().getRealm("original");
RealmModel realm = currentSession.realms().getRealm(realmId);
ClientModel fooClient = realm.getClientByClientId("foo-client");
UserModel john = currentSession.users().getUserByUsername(realm, "john");
@ -284,7 +287,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionRT2) -> {
KeycloakSession currentSession = sessionRT2;
RealmModel realm = currentSession.realms().getRealm("original");
RealmModel realm = currentSession.realms().getRealm(realmId);
ClientModel fooClient = realm.getClientByClientId("foo-client");
ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client");
@ -302,7 +305,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest {
// Validate user deleted without any referential constraint errors
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionUT) -> {
KeycloakSession currentSession = sessionUT;
RealmModel realm = currentSession.realms().getRealm("original");
RealmModel realm = currentSession.realms().getRealm(realmId);
UserModel john = currentSession.users().getUserByUsername(realm, "john");
currentSession.users().removeUser(realm, john);
@ -317,7 +320,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionST1) -> {
KeycloakSession currentSession = sessionST1;
RealmModel realm = currentSession.realms().getRealm("original");
RealmModel realm = currentSession.realms().getRealm(realmId);
ClientScopeModel fooScope = KeycloakModelUtils.getClientScopeByName(realm, "foo");
realm.removeClientScope(fooScope.getId());
@ -325,7 +328,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionST2) -> {
KeycloakSession currentSession = sessionST2;
RealmModel realm = currentSession.realms().getRealm("original");
RealmModel realm = currentSession.realms().getRealm(realmId);
ClientModel fooClient = realm.getClientByClientId("foo-client");
@ -344,7 +347,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionDCT1) -> {
KeycloakSession currentSession = sessionDCT1;
RealmModel realm = currentSession.realms().getRealm("original");
RealmModel realm = currentSession.realms().getRealm(realmId);
ClientModel barClient = realm.getClientByClientId("bar-client");
barClientID.set(barClient.getId());
@ -354,7 +357,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionDCT2) -> {
KeycloakSession currentSession = sessionDCT2;
RealmModel realm = currentSession.realms().getRealm("original");
RealmModel realm = currentSession.realms().getRealm(realmId);
ClientModel fooClient = realm.getClientByClientId("foo-client");
Assert.assertNull(realm.getClientByClientId("bar-client"));
@ -376,14 +379,14 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCST1) -> {
KeycloakSession currentSession = sessionCST1;
RealmModel realm = currentSession.realms().getRealm("original");
RealmModel realm = currentSession.realms().getRealm(realmId);
realm.removeComponent(clientStorageComponent);
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCST2) -> {
KeycloakSession currentSession = sessionCST2;
RealmModel realm = currentSession.realms().getRealm("original");
RealmModel realm = currentSession.realms().getRealm(realmId);
ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client");
Assert.assertNull(hardcodedClient);

View file

@ -365,7 +365,7 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesDelClient2) -> {
KeycloakSession currentSession = sesDelClient2;
RealmManager realmManager = new RealmManager(currentSession);
RealmModel realm = realmManager.getRealm("original");
RealmModel realm = realmManager.getRealmByName("original");
ClientModel fooClient = realm.getClientByClientId("foo-client");
Assert.assertNull(realm.getClientByClientId("bar-client"));

View file

@ -102,7 +102,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCrud2) -> {
currentSession = sessionCrud2;
realm = currentSession.realms().getRealm("test");
realm = currentSession.realms().getRealmByName("test");
sessionManager = new UserSessionManager(currentSession);
// Key is userSession ID, values are client UUIDS
@ -114,7 +114,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCrud3) -> {
currentSession = sessionCrud3;
realm = currentSession.realms().getRealm("test");
realm = currentSession.realms().getRealmByName("test");
sessionManager = new UserSessionManager(currentSession);
// Assert all previously saved offline sessions found
@ -150,7 +150,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCrud4) -> {
currentSession = sessionCrud4;
realm = currentSession.realms().getRealm("test");
realm = currentSession.realms().getRealmByName("test");
sessionManager = new UserSessionManager(currentSession);
// Assert userSession revoked
@ -179,7 +179,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCrud5) -> {
currentSession = sessionCrud5;
realm = currentSession.realms().getRealm("test");
realm = currentSession.realms().getRealmByName("test");
sessionManager = new UserSessionManager(currentSession);
ClientModel testApp = realm.getClientByClientId("test-app");
@ -208,9 +208,10 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
public void testOnRealmRemoved(KeycloakSession session) {
AtomicReference<String> userSessionID = new AtomicReference<>();
String realmId = KeycloakModelUtils.generateId();
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionRR1) -> {
currentSession = sessionRR1;
RealmModel fooRealm = currentSession.realms().createRealm("foo", "foo");
RealmModel fooRealm = currentSession.realms().createRealm(realmId, "foo");
fooRealm.setDefaultRole(currentSession.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + fooRealm.getName()));
fooRealm.setSsoSessionIdleTimeout(1800);
fooRealm.setSsoSessionMaxLifespan(36000);
@ -230,7 +231,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
sessionManager = new UserSessionManager(currentSession);
// Persist offline session
RealmModel fooRealm = currentSession.realms().getRealm("foo");
RealmModel fooRealm = currentSession.realms().getRealm(realmId);
UserSessionModel userSession = currentSession.sessions().getUserSession(fooRealm, userSessionID.get());
createOfflineSessionIncludeClientSessions(currentSession, userSession);
@ -242,12 +243,12 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
// Remove realm
RealmManager realmMgr = new RealmManager(currentSession);
realmMgr.removeRealm(realmMgr.getRealm("foo"));
realmMgr.removeRealm(realmMgr.getRealm(realmId));
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionRR3) -> {
currentSession = sessionRR3;
RealmModel fooRealm = currentSession.realms().createRealm("foo", "foo");
RealmModel fooRealm = currentSession.realms().createRealm(realmId, "foo");
fooRealm.setDefaultRole(currentSession.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + fooRealm.getName()));
fooRealm.addClient("foo-app");
@ -256,13 +257,13 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionRR4) -> {
currentSession = sessionRR4;
RealmModel fooRealm = currentSession.realms().getRealm("foo");
RealmModel fooRealm = currentSession.realms().getRealm(realmId);
Assert.assertEquals(0, currentSession.sessions().getOfflineSessionsCount(fooRealm, fooRealm.getClientByClientId("foo-app")));
// Cleanup
RealmManager realmMgr = new RealmManager(currentSession);
realmMgr.removeRealm(realmMgr.getRealm("foo"));
realmMgr.removeRealm(realmMgr.getRealm(realmId));
});
}
@ -270,6 +271,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
@ModelTest
public void testOnClientRemoved(KeycloakSession session) {
String realmId = KeycloakModelUtils.generateId();
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR) -> {
try {
int started = Time.currentTime();
@ -278,7 +280,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR1) -> {
currentSession = sessionCR1;
sessionManager = new UserSessionManager(currentSession);
RealmModel fooRealm = currentSession.realms().createRealm("foo", "foo");
RealmModel fooRealm = currentSession.realms().createRealm(realmId, "foo");
fooRealm.setDefaultRole(currentSession.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + fooRealm.getName()));
fooRealm.setSsoSessionIdleTimeout(1800);
fooRealm.setSsoSessionMaxLifespan(36000);
@ -299,7 +301,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR2) -> {
currentSession = sessionCR2;
// Create offline currentSession
RealmModel fooRealm = currentSession.realms().getRealm("foo");
RealmModel fooRealm = currentSession.realms().getRealm(realmId);
UserSessionModel userSession = currentSession.sessions().getUserSession(fooRealm, userSessionID.get());
createOfflineSessionIncludeClientSessions(currentSession, userSession);
});
@ -308,7 +310,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
currentSession = sessionCR3;
RealmManager realmMgr = new RealmManager(currentSession);
ClientManager clientMgr = new ClientManager(realmMgr);
RealmModel fooRealm = realmMgr.getRealm("foo");
RealmModel fooRealm = realmMgr.getRealm(realmId);
// Assert currentSession was persisted with both clientSessions
UserSessionModel offlineSession = currentSession.sessions().getOfflineUserSession(fooRealm, userSessionID.get());
@ -323,7 +325,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
currentSession = sessionCR4;
RealmManager realmMgr = new RealmManager(currentSession);
ClientManager clientMgr = new ClientManager(realmMgr);
RealmModel fooRealm = realmMgr.getRealm("foo");
RealmModel fooRealm = realmMgr.getRealm(realmId);
// Assert just one bar-app clientSession persisted now
UserSessionModel offlineSession = currentSession.sessions().getOfflineUserSession(fooRealm, userSessionID.get());
@ -339,7 +341,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
currentSession = sessionCR5;
// Assert nothing loaded - userSession was removed as well because it was last userSession
RealmManager realmMgr = new RealmManager(currentSession);
RealmModel fooRealm = realmMgr.getRealm("foo");
RealmModel fooRealm = realmMgr.getRealm(realmId);
UserSessionModel offlineSession = currentSession.sessions().getOfflineUserSession(fooRealm, userSessionID.get());
Assert.assertEquals(0, offlineSession.getAuthenticatedClientSessions().size());
});
@ -350,7 +352,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionTearDown) -> {
currentSession = sessionTearDown;
RealmManager realmMgr = new RealmManager(currentSession);
RealmModel fooRealm = realmMgr.getRealm("foo");
RealmModel fooRealm = realmMgr.getRealm(realmId);
UserModel user3 = currentSession.users().getUserByUsername(fooRealm, "user3");
// Remove user3
@ -358,7 +360,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
// Cleanup
realmMgr = new RealmManager(currentSession);
realmMgr.removeRealm(realmMgr.getRealm("foo"));
realmMgr.removeRealm(realmMgr.getRealm(realmId));
});
}
});
@ -368,6 +370,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
@ModelTest
public void testOnUserRemoved(KeycloakSession session) {
String realmId = KeycloakModelUtils.generateId();
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionUR) -> {
try {
int started = Time.currentTime();
@ -375,7 +378,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionUR1) -> {
currentSession = sessionUR1;
RealmModel fooRealm = currentSession.realms().createRealm("foo", "foo");
RealmModel fooRealm = currentSession.realms().createRealm(realmId, "foo");
fooRealm.setDefaultRole(currentSession.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + fooRealm.getName()));
fooRealm.setSsoSessionIdleTimeout(1800);
fooRealm.setSsoSessionMaxLifespan(36000);
@ -394,7 +397,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
currentSession = sessionUR2;
// Create offline session
RealmModel fooRealm = currentSession.realms().getRealm("foo");
RealmModel fooRealm = currentSession.realms().getRealm(realmId);
UserSessionModel userSession = currentSession.sessions().getUserSession(fooRealm, userSessionID.get());
createOfflineSessionIncludeClientSessions(currentSession, userSession);
});
@ -403,7 +406,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
currentSession = sessionUR3;
RealmManager realmMgr = new RealmManager(currentSession);
RealmModel fooRealm = realmMgr.getRealm("foo");
RealmModel fooRealm = realmMgr.getRealm(realmId);
UserModel user3 = currentSession.users().getUserByUsername(fooRealm, "user3");
// Assert session was persisted with both clientSessions
@ -418,7 +421,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
currentSession = sessionTearDown;
RealmManager realmMgr = new RealmManager(currentSession);
RealmModel fooRealm = realmMgr.getRealm("foo");
RealmModel fooRealm = realmMgr.getRealm(realmId);
UserModel user3 = currentSession.users().getUserByUsername(fooRealm, "user3");
// Remove user3
@ -426,7 +429,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
// Cleanup
realmMgr = new RealmManager(currentSession);
realmMgr.removeRealm(realmMgr.getRealm("foo"));
realmMgr.removeRealm(fooRealm);
});
}
});
@ -503,7 +506,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes
public static void reloadState(KeycloakSession session, Boolean initialConfig) {
currentSession = session;
realm = currentSession.realms().getRealm("test");
realm = currentSession.realms().getRealmByName("test");
if (initialConfig) {
currentSession.users().addUser(realm, "user1").setEmail("user1@localhost");
currentSession.users().addUser(realm, "user2").setEmail("user2@localhost");

View file

@ -78,7 +78,6 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest {
public void before() {
testingClient.server().run( session -> {
RealmModel realm = session.realms().getRealmByName("test");
realm = session.realms().getRealm("test");
session.users().addUser(realm, "user1").setEmail("user1@localhost");
session.users().addUser(realm, "user2").setEmail("user2@localhost");
});

View file

@ -504,7 +504,7 @@ public class OfflineTokenTest extends AbstractKeycloakTest {
setTimeOffset(86400);
// Remove expired sessions. This will remove "normal" userSession
testingClient.testing().removeUserSessions(appRealm.toRepresentation().getId());
testingClient.testing().removeUserSessions("test");
// Refresh with the offline token
tokenResponse = oauth.doRefreshTokenRequest(tokenResponse.getRefreshToken(), "secret1");

View file

@ -52,7 +52,7 @@ public class RunOnServerTest extends AbstractKeycloakTest {
final String realmName = "master";
RealmRepresentation realmRep = testingClient.server().fetch(session -> {
RealmModel master = session.realms().getRealm(realmName);
RealmModel master = session.realms().getRealmByName(realmName);
return ModelToRepresentation.toRepresentation(session, master, true);
}, RealmRepresentation.class);

View file

@ -46,7 +46,6 @@ public class SessionTimeoutValidationTest extends AbstractTestRealmKeycloakTest
public void before() {
testingClient.server().run( session -> {
RealmModel realm = session.realms().getRealmByName("test");
realm = session.realms().getRealm("test");
session.users().addUser(realm, "user1");
});
}

View file

@ -277,7 +277,8 @@ public class AssertAdminEvents implements TestRule {
AccessToken token = input.readJsonContent(AccessToken.class);
AuthDetailsRepresentation authDetails = new AuthDetailsRepresentation();
String realmId = token.getIssuer().substring(token.getIssuer().lastIndexOf('/') + 1);
String realmName = token.getIssuer().substring(token.getIssuer().lastIndexOf('/') + 1);
String realmId = context.getAdminClient().realm(realmName).toRepresentation().getId();
authDetails.setRealmId(realmId);
authDetails.setUserId(token.getSubject());
return authDetails;

View file

@ -50,7 +50,7 @@ public class AuthenticatorUtilTest extends AbstractTestRealmKeycloakTest {
public void variousFactoryProviders() {
testingClient.server().run(session -> {
RealmModel realm = session.realms().getRealm(TEST_REALM_NAME);
RealmModel realm = session.realms().getRealmByName(TEST_REALM_NAME);
assertThat(realm, notNullValue());
ClientModel client = realm.getClientByClientId("test-app");

View file

@ -110,6 +110,8 @@ public abstract class AbstractX509AuthenticationTest extends AbstractTestRealmKe
protected String userId2;
protected String realmId;
protected AuthenticationManagementResource authMgmtResource;
protected AuthenticationExecutionInfoRepresentation browserExecution;
@ -207,6 +209,7 @@ public abstract class AbstractX509AuthenticationTest extends AbstractTestRealmKe
@Before
public void configureFlows() {
authMgmtResource = adminClient.realms().realm(REALM_NAME).flows();
this.realmId = adminClient.realm(REALM_NAME).toRepresentation().getId();
AuthenticationFlowRepresentation browserFlow = copyBrowserFlow();
Assert.assertNotNull(browserFlow);
@ -320,7 +323,7 @@ public abstract class AbstractX509AuthenticationTest extends AbstractTestRealmKe
finally {
response.close();
}
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AssertAdminEvents.isExpectedPrefixFollowedByUuid(AdminEventPaths.authFlowsPath()), flowRep, ResourceType.AUTH_FLOW);
assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AssertAdminEvents.isExpectedPrefixFollowedByUuid(AdminEventPaths.authFlowsPath()), flowRep, ResourceType.AUTH_FLOW);
for (AuthenticationFlowRepresentation flow : authMgmtResource.getFlows()) {
if (flow.getAlias().equalsIgnoreCase(flowRep.getAlias())) {
@ -335,7 +338,7 @@ public abstract class AbstractX509AuthenticationTest extends AbstractTestRealmKe
HashMap<String, String> params = new HashMap<>();
params.put("newName", newFlow);
Response response = authMgmtResource.copy(existingFlow, params);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, Encode.decode(AdminEventPaths.authCopyFlowPath(existingFlow)), params, ResourceType.AUTH_FLOW);
assertAdminEvents.assertEvent(realmId, OperationType.CREATE, Encode.decode(AdminEventPaths.authCopyFlowPath(existingFlow)), params, ResourceType.AUTH_FLOW);
try {
Assert.assertEquals("Copy flow", 201, response.getStatus());
} finally {

View file

@ -253,7 +253,7 @@ public class UserSessionPersisterProviderTest extends KeycloakModelTest {
AtomicReference<String> userSessionID = new AtomicReference<>();
inComittedTransaction(session -> {
RealmModel fooRealm = session.realms().createRealm("foo", "foo");
RealmModel fooRealm = session.realms().createRealm("foo");
fooRealm.setDefaultRole(session.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + fooRealm.getName()));
fooRealm.addClient("foo-app");
@ -267,7 +267,7 @@ public class UserSessionPersisterProviderTest extends KeycloakModelTest {
inComittedTransaction(session -> {
// Persist offline session
RealmModel fooRealm = session.realms().getRealm("foo");
RealmModel fooRealm = session.realms().getRealmByName("foo");
UserSessionModel userSession = session.sessions().getUserSession(fooRealm, userSessionID.get());
persistUserSession(session, userSession, true);
});
@ -278,7 +278,7 @@ public class UserSessionPersisterProviderTest extends KeycloakModelTest {
// Remove realm
RealmManager realmMgr = new RealmManager(session);
realmMgr.removeRealm(realmMgr.getRealm("foo"));
realmMgr.removeRealm(realmMgr.getRealmByName("foo"));
});
inComittedTransaction(session -> {
@ -293,7 +293,7 @@ public class UserSessionPersisterProviderTest extends KeycloakModelTest {
AtomicReference<String> userSessionID = new AtomicReference<>();
inComittedTransaction(session -> {
RealmModel fooRealm = session.realms().createRealm("foo", "foo");
RealmModel fooRealm = session.realms().createRealm("foo");
fooRealm.setDefaultRole(session.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX));
fooRealm.addClient("foo-app");
@ -308,7 +308,7 @@ public class UserSessionPersisterProviderTest extends KeycloakModelTest {
});
inComittedTransaction(session -> {
RealmModel fooRealm = session.realms().getRealm("foo");
RealmModel fooRealm = session.realms().getRealmByName("foo");
// Persist offline session
UserSessionModel userSession = session.sessions().getUserSession(fooRealm, userSessionID.get());
@ -318,7 +318,7 @@ public class UserSessionPersisterProviderTest extends KeycloakModelTest {
inComittedTransaction(session -> {
RealmManager realmMgr = new RealmManager(session);
ClientManager clientMgr = new ClientManager(realmMgr);
RealmModel fooRealm = realmMgr.getRealm("foo");
RealmModel fooRealm = realmMgr.getRealmByName("foo");
// Assert session was persisted with both clientSessions
UserSessionModel persistedSession = loadPersistedSessionsPaginated(session, true, 10, 1, 1).get(0);
@ -332,7 +332,7 @@ public class UserSessionPersisterProviderTest extends KeycloakModelTest {
inComittedTransaction(session -> {
RealmManager realmMgr = new RealmManager(session);
ClientManager clientMgr = new ClientManager(realmMgr);
RealmModel fooRealm = realmMgr.getRealm("foo");
RealmModel fooRealm = realmMgr.getRealmByName("foo");
// Assert just one bar-app clientSession persisted now
UserSessionModel persistedSession = loadPersistedSessionsPaginated(session, true, 10, 1, 1).get(0);
@ -349,7 +349,7 @@ public class UserSessionPersisterProviderTest extends KeycloakModelTest {
// Cleanup
RealmManager realmMgr = new RealmManager(session);
realmMgr.removeRealm(realmMgr.getRealm("foo"));
realmMgr.removeRealm(realmMgr.getRealmByName("foo"));
});
}