From c566b46e8fb9976e561945736e8ef64526e7e3e8 Mon Sep 17 00:00:00 2001 From: Hynek Mlnarik Date: Mon, 22 Jun 2020 22:23:40 +0200 Subject: [PATCH] KEYCLOAK-14549 Make ClientProvider independent of RealmProvider Co-Authored-By: vramik --- .github/workflows/ci.yml | 23 +++++ .../client/resource/RoleByIdResource.java | 4 +- .../admin/client/resource/RoleResource.java | 4 +- .../cache/infinispan/ClientAdapter.java | 17 ++-- .../cache/infinispan/ClientScopeAdapter.java | 13 +-- .../models/cache/infinispan/RealmAdapter.java | 8 +- .../cache/infinispan/RealmCacheSession.java | 54 +++++----- .../cache/infinispan/UserCacheSession.java | 2 +- .../keycloak/models/jpa/ClientAdapter.java | 7 +- .../models/jpa/ClientScopeAdapter.java | 7 +- .../models/jpa/JpaClientProviderFactory.java | 55 +++++++++++ .../keycloak/models/jpa/JpaRealmProvider.java | 68 +++++++------ .../org/keycloak/models/jpa/RealmAdapter.java | 35 +++---- .../org/keycloak/models/jpa/RoleAdapter.java | 4 +- .../models/jpa/entities/RoleEntity.java | 27 +++-- .../META-INF/jpa-changelog-11.0.0.xml | 25 +++++ .../META-INF/jpa-changelog-master.xml | 2 + .../org.keycloak.models.ClientProviderFactory | 18 ++++ .../models/cache/CacheRealmProvider.java | 3 +- .../org/keycloak/models/ClientProvider.java | 84 +++++++++++++--- .../org/keycloak/models/KeycloakSession.java | 9 ++ .../org/keycloak/models/RealmProvider.java | 98 ++++++++++++++++++- .../keycloak/models/ScopeContainerModel.java | 4 +- .../storage/client/ClientLookupProvider.java | 64 +++++++++++- .../ClientIdAndSecretAuthenticator.java | 2 +- .../endpoints/LoginStatusIframeEndpoint.java | 2 +- .../services/DefaultKeycloakSession.java | 21 +++- .../AbstractClientRegistrationProvider.java | 2 +- .../services/managers/RealmManager.java | 4 +- .../resources/LoginActionsService.java | 2 +- .../resources/admin/RoleByIdResource.java | 8 +- .../admin/RoleContainerResource.java | 12 +-- .../resources/admin/UserResource.java | 8 +- .../storage/ClientStorageManager.java | 66 ++++--------- .../OpenshiftClientStorageProvider.java | 10 +- .../openshift/OpenshiftSAClientAdapter.java | 8 +- .../HardcodedClientStorageProvider.java | 14 ++- .../servlet/UserStorageConsentTest.java | 2 +- .../testsuite/admin/ConsentsTest.java | 2 +- .../admin/FineGrainAdminUnitTest.java | 2 +- .../testsuite/admin/PermissionsTest.java | 10 +- .../PolicyEvaluationCompositeRoleTest.java | 2 +- .../testsuite/authz/PolicyEvaluationTest.java | 24 ++--- .../broker/JsonUserAttributeMapperTest.java | 6 +- .../broker/KcOidcBrokerConfiguration.java | 2 - .../broker/KcSamlBrokerConfiguration.java | 1 - .../testsuite/broker/SocialLoginTest.java | 2 +- .../keycloak/testsuite/cli/KcinitTest.java | 2 +- .../testsuite/forms/ChallengeFlowTest.java | 2 +- .../testsuite/forms/FlowOverrideTest.java | 4 +- .../keycloak/testsuite/model/CacheTest.java | 2 +- .../testsuite/model/ClientModelTest.java | 33 ++++--- .../model/ConcurrentTransactionsTest.java | 14 +-- .../testsuite/model/UserConsentModelTest.java | 12 +-- .../UserConsentWithUserStorageModelTest.java | 12 +-- .../testsuite/oauth/OAuthRedirectUriTest.java | 18 ++-- .../oauth/TokenEndpointCorsTest.java | 2 +- .../oauth/TokenRevocationCorsTest.java | 2 +- .../oauth/UserInfoEndpointCorsTest.java | 2 +- .../OpenShiftTokenReviewEndpointTest.java | 10 +- .../testsuite/saml/SamlConsentTest.java | 1 - .../saml/SessionNotOnOrAfterTest.java | 10 +- .../testsuite/util/cli/RoleCommands.java | 6 +- 63 files changed, 656 insertions(+), 323 deletions(-) create mode 100644 model/jpa/src/main/java/org/keycloak/models/jpa/JpaClientProviderFactory.java create mode 100644 model/jpa/src/main/resources/META-INF/jpa-changelog-11.0.0.xml create mode 100644 model/jpa/src/main/resources/META-INF/services/org.keycloak.models.ClientProviderFactory diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 74134a4e62..e07048a8d9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -49,3 +49,26 @@ jobs: run: mvn clean install -B -Pauth-server-wildfly -DskipTests -f testsuite/pom.xml - name: Run base tests run: mvn clean install -B -Pauth-server-wildfly -f testsuite/integration-arquillian/tests/base/pom.xml | misc/log/trimmer.sh; exit ${PIPESTATUS[0]} + test-undertow-map: + name: Test undertow - map provider + needs: build + runs-on: ubuntu-latest + env: + MAVEN_OPTS: -Xmx2048m + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-java@v1 + with: + java-version: 1.8 + - name: Download Maven Repo + uses: actions/download-artifact@v1 + with: + name: maven-repo + path: . + - name: Extract Maven Repo + shell: bash + run: tar -xzvf maven-repo.tgz -C ~ + - name: Build testsuite + run: mvn clean install -B -DskipTests -f testsuite/pom.xml + - name: Run base tests - undertow + run: mvn clean install -B -f testsuite/integration-arquillian/tests/base/pom.xml -Dkeycloak.client.provider=map | misc/log/trimmer.sh; exit ${PIPESTATUS[0]} \ No newline at end of file diff --git a/integration/admin-client/src/main/java/org/keycloak/admin/client/resource/RoleByIdResource.java b/integration/admin-client/src/main/java/org/keycloak/admin/client/resource/RoleByIdResource.java index e837f5ff58..bb3238f44d 100755 --- a/integration/admin-client/src/main/java/org/keycloak/admin/client/resource/RoleByIdResource.java +++ b/integration/admin-client/src/main/java/org/keycloak/admin/client/resource/RoleByIdResource.java @@ -68,10 +68,10 @@ public interface RoleByIdResource { @Produces(MediaType.APPLICATION_JSON) Set getRealmRoleComposites(@PathParam("role-id") String id); - @Path("{role-id}/composites/clients/{client}") + @Path("{role-id}/composites/clients/{clientUuid}") @GET @Produces(MediaType.APPLICATION_JSON) - Set getClientRoleComposites(@PathParam("role-id") String id, @PathParam("client") String client); + Set getClientRoleComposites(@PathParam("role-id") String id, @PathParam("clientUuid") String clientUuid); @Path("{role-id}/composites") @DELETE diff --git a/integration/admin-client/src/main/java/org/keycloak/admin/client/resource/RoleResource.java b/integration/admin-client/src/main/java/org/keycloak/admin/client/resource/RoleResource.java index b83930f369..53ca36df06 100755 --- a/integration/admin-client/src/main/java/org/keycloak/admin/client/resource/RoleResource.java +++ b/integration/admin-client/src/main/java/org/keycloak/admin/client/resource/RoleResource.java @@ -87,9 +87,9 @@ public interface RoleResource { Set getRealmRoleComposites(); @GET - @Path("composites/clients/{appName}") + @Path("composites/clients/{clientUuid}") @Produces(MediaType.APPLICATION_JSON) - Set getClientRoleComposites(@PathParam("appName") String appName); + Set getClientRoleComposites(@PathParam("clientUuid") String clientUuid); @POST @Path("composites") diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/ClientAdapter.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/ClientAdapter.java index 6e7462b770..23c5cd526d 100755 --- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/ClientAdapter.java +++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/ClientAdapter.java @@ -32,6 +32,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Stream; /** * @author Bill Burke @@ -53,7 +54,7 @@ public class ClientAdapter implements ClientModel, CachedObject { private void getDelegateForUpdate() { if (updated == null) { cacheSession.registerClientInvalidation(cached.getId(), cached.getClientId(), cachedRealm.getId()); - updated = cacheSession.getRealmDelegate().getClientById(cached.getId(), cachedRealm); + updated = cacheSession.getClientDelegate().getClientById(cachedRealm, cached.getId()); if (updated == null) throw new IllegalStateException("Not found in database"); } } @@ -65,7 +66,7 @@ public class ClientAdapter implements ClientModel, CachedObject { protected boolean isUpdated() { if (updated != null) return true; if (!invalidated) return false; - updated = cacheSession.getRealmDelegate().getClientById(cached.getId(), cachedRealm); + updated = cacheSession.getClientDelegate().getClientById(cachedRealm, cached.getId()); if (updated == null) throw new IllegalStateException("Not found in database"); return true; } @@ -253,14 +254,10 @@ public class ClientAdapter implements ClientModel, CachedObject { } - public Set getScopeMappings() { - if (isUpdated()) return updated.getScopeMappings(); - Set roles = new HashSet<>(); - for (String id : cached.getScope()) { - roles.add(cacheSession.getRoleById(id, getRealm())); - - } - return roles; + public Stream getScopeMappingsStream() { + if (isUpdated()) return updated.getScopeMappingsStream(); + return cached.getScope().stream() + .map(id -> cacheSession.getRoleById(id, cachedRealm)); } public void addScopeMapping(RoleModel role) { diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/ClientScopeAdapter.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/ClientScopeAdapter.java index 7a49b08450..151b6c214a 100755 --- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/ClientScopeAdapter.java +++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/ClientScopeAdapter.java @@ -28,6 +28,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; +import java.util.stream.Stream; /** * @author Bill Burke @@ -156,14 +157,10 @@ public class ClientScopeAdapter implements ClientScopeModel { updated.setProtocol(protocol); } - public Set getScopeMappings() { - if (isUpdated()) return updated.getScopeMappings(); - Set roles = new HashSet<>(); - for (String id : cached.getScope()) { - roles.add(cacheSession.getRoleById(id, getRealm())); - - } - return roles; + public Stream getScopeMappingsStream() { + if (isUpdated()) return updated.getScopeMappingsStream(); + return cached.getScope().stream() + .map(id -> cacheSession.getRoleById(id, cachedRealm)); } public void addScopeMapping(RoleModel role) { diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmAdapter.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmAdapter.java index 5d365b19d0..764069b0fe 100755 --- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmAdapter.java +++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmAdapter.java @@ -776,23 +776,23 @@ public class RealmAdapter implements CachedRealmModel { @Override public boolean removeClient(String id) { - return cacheSession.removeClient(id, this); + return cacheSession.removeClient(this, id); } @Override public ClientModel getClientById(String id) { if (isUpdated()) return updated.getClientById(id); - return cacheSession.getClientById(id, this); + return cacheSession.getClientById(this, id); } @Override public ClientModel getClientByClientId(String clientId) { - return cacheSession.getClientByClientId(clientId, this); + return cacheSession.getClientByClientId(this, clientId); } @Override public List searchClientByClientId(String clientId, Integer firstResult, Integer maxResults) { - return cacheSession.searchClientsByClientId(clientId, firstResult, maxResults, this); + return cacheSession.searchClientsByClientId(this, clientId, firstResult, maxResults); } @Override diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmCacheSession.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmCacheSession.java index 0ace0d848b..a5e6ddc1d8 100755 --- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmCacheSession.java +++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmCacheSession.java @@ -482,6 +482,7 @@ public class RealmCacheSession implements CacheRealmProvider { RealmModel realm = getRealm(id); if (realm == null) return false; + listInvalidations.add(id); evictRealmOnRemoval(realm); return getRealmDelegate().removeRealm(id); } @@ -495,13 +496,13 @@ public class RealmCacheSession implements CacheRealmProvider { @Override public ClientModel addClient(RealmModel realm, String clientId) { - ClientModel client = getRealmDelegate().addClient(realm, clientId); + ClientModel client = getClientDelegate().addClient(realm, clientId); return addedClient(realm, client); } @Override public ClientModel addClient(RealmModel realm, String id, String clientId) { - ClientModel client = getRealmDelegate().addClient(realm, id, clientId); + ClientModel client = getClientDelegate().addClient(realm, id, clientId); return addedClient(realm, client); } @@ -552,8 +553,13 @@ public class RealmCacheSession implements CacheRealmProvider { } @Override - public boolean removeClient(String id, RealmModel realm) { - ClientModel client = getClientById(id, realm); + public void removeClients(RealmModel realm) { + getClientDelegate().removeClients(realm); + } + + @Override + public boolean removeClient(RealmModel realm, String id) { + ClientModel client = getClientById(realm, id); if (client == null) return false; invalidateClient(client.getId()); @@ -575,7 +581,7 @@ public class RealmCacheSession implements CacheRealmProvider { } } - return getRealmDelegate().removeClient(id, realm); + return getClientDelegate().removeClient(realm, id); } @@ -636,7 +642,7 @@ public class RealmCacheSession implements CacheRealmProvider { @Override public Set getClientRoles(RealmModel realm, ClientModel client) { String cacheKey = getRolesCacheKey(client.getId()); - boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(client.getId()); + boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(client.getId()) || listInvalidations.contains(realm.getId()); if (queryDB) { return getRealmDelegate().getClientRoles(realm, client); } @@ -735,7 +741,7 @@ public class RealmCacheSession implements CacheRealmProvider { @Override public RoleModel getClientRole(RealmModel realm, ClientModel client, String name) { String cacheKey = getRoleByNameCacheKey(client.getId(), name); - boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(client.getId()); + boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(client.getId()) || listInvalidations.contains(realm.getId()); if (queryDB) { return getRealmDelegate().getClientRole(realm, client, name); } @@ -882,8 +888,8 @@ public class RealmCacheSession implements CacheRealmProvider { } @Override - public Long getClientsCount(RealmModel realm) { - return getRealmDelegate().getClientsCount(realm); + public long getClientsCount(RealmModel realm) { + return getClientDelegate().getClientsCount(realm); } @Override @@ -1035,24 +1041,26 @@ public class RealmCacheSession implements CacheRealmProvider { } @Override - public ClientModel getClientById(String id, RealmModel realm) { + public ClientModel getClientById(RealmModel realm, String id) { CachedClient cached = cache.get(id, CachedClient.class); if (cached != null && !cached.getRealm().equals(realm.getId())) { cached = null; } + boolean queryDB = invalidations.contains(id) || listInvalidations.contains(realm.getId()); + if (queryDB) { // short-circuit if the client has been potentially invalidated + return getClientDelegate().getClientById(realm, id); + } if (cached != null) { logger.tracev("client by id cache hit: {0}", cached.getClientId()); } if (cached == null) { Long loaded = cache.getCurrentRevision(id); - ClientModel model = getClientDelegate().getClientById(id, realm); + ClientModel model = getClientDelegate().getClientById(realm, id); if (model == null) return null; ClientModel adapter = cacheClient(realm, model, loaded); managedApplications.put(id, adapter); return adapter; - } else if (invalidations.contains(id)) { - return getRealmDelegate().getClientById(id, realm); } else if (managedApplications.containsKey(id)) { return managedApplications.get(id); } @@ -1111,7 +1119,7 @@ public class RealmCacheSession implements CacheRealmProvider { // its also hard to test stuff if (model.shouldInvalidate(cached)) { registerClientInvalidation(cached.getId(), cached.getClientId(), realm.getId()); - return getClientDelegate().getClientById(cached.getId(), realm); + return getClientDelegate().getClientById(realm, cached.getId()); } } ClientAdapter adapter = new ClientAdapter(realm, cached, this); @@ -1120,38 +1128,40 @@ public class RealmCacheSession implements CacheRealmProvider { } @Override - public List searchClientsByClientId(String clientId, Integer firstResult, Integer maxResults, RealmModel realm) { - return getClientDelegate().searchClientsByClientId(clientId, firstResult, maxResults, realm); + public List searchClientsByClientId(RealmModel realm, String clientId, Integer firstResult, Integer maxResults) { + return getClientDelegate().searchClientsByClientId(realm, clientId, firstResult, maxResults); } @Override - public ClientModel getClientByClientId(String clientId, RealmModel realm) { + public ClientModel getClientByClientId(RealmModel realm, String clientId) { String cacheKey = getClientByClientIdCacheKey(clientId, realm.getId()); ClientListQuery query = cache.get(cacheKey, ClientListQuery.class); String id = null; + boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(realm.getId()); + if (queryDB) { // short-circuit if the client has been potentially invalidated + return getClientDelegate().getClientByClientId(realm, clientId); + } if (query != null) { logger.tracev("client by name cache hit: {0}", clientId); } if (query == null) { Long loaded = cache.getCurrentRevision(cacheKey); - ClientModel model = getClientDelegate().getClientByClientId(clientId, realm); + ClientModel model = getClientDelegate().getClientByClientId(realm, clientId); if (model == null) return null; if (invalidations.contains(model.getId())) return model; id = model.getId(); query = new ClientListQuery(loaded, cacheKey, realm, id); logger.tracev("adding client by name cache miss: {0}", clientId); cache.addRevisioned(query, startupRevision); - } else if (invalidations.contains(cacheKey)) { - return getClientDelegate().getClientByClientId(clientId, realm); } else { id = query.getClients().iterator().next(); if (invalidations.contains(id)) { - return getClientDelegate().getClientByClientId(clientId, realm); + return getClientDelegate().getClientByClientId(realm, clientId); } } - return getClientById(id, realm); + return getClientById(realm, id); } static String getClientByClientIdCacheKey(String clientId, String realmId) { diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserCacheSession.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserCacheSession.java index af8a06386f..087b7d45a3 100755 --- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserCacheSession.java +++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserCacheSession.java @@ -737,7 +737,7 @@ public class UserCacheSession implements UserCache { } private UserConsentModel toConsentModel(RealmModel realm, CachedUserConsent cachedConsent) { - ClientModel client = session.realms().getClientById(cachedConsent.getClientDbId(), realm); + ClientModel client = session.clients().getClientById(realm, cachedConsent.getClientDbId()); if (client == null) { return null; } diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/ClientAdapter.java b/model/jpa/src/main/java/org/keycloak/models/jpa/ClientAdapter.java index 0481ea2725..db01efaf23 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/ClientAdapter.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/ClientAdapter.java @@ -46,7 +46,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; -import java.util.stream.Collectors; +import java.util.stream.Stream; /** * @author Bill Burke @@ -255,12 +255,11 @@ public class ClientAdapter implements ClientModel, JpaModel { } @Override - public Set getScopeMappings() { + public Stream getScopeMappingsStream() { return getEntity().getScopeMapping().stream() .map(RoleEntity::getId) .map(realm::getRoleById) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); + .filter(Objects::nonNull); } @Override diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/ClientScopeAdapter.java b/model/jpa/src/main/java/org/keycloak/models/jpa/ClientScopeAdapter.java index acbc33a7cd..8677935a5f 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/ClientScopeAdapter.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/ClientScopeAdapter.java @@ -37,7 +37,7 @@ import java.util.Iterator; import java.util.Map; import java.util.Objects; import java.util.Set; -import java.util.stream.Collectors; +import java.util.stream.Stream; /** * @author Bill Burke @@ -227,12 +227,11 @@ public class ClientScopeAdapter implements ClientScopeModel, JpaModel getScopeMappings() { + public Stream getScopeMappingsStream() { return getEntity().getScopeMapping().stream() .map(RoleEntity::getId) .map(realm::getRoleById) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); + .filter(Objects::nonNull); } @Override diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaClientProviderFactory.java b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaClientProviderFactory.java new file mode 100644 index 0000000000..9da10c5dd9 --- /dev/null +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaClientProviderFactory.java @@ -0,0 +1,55 @@ +/* + * Copyright 2020 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.jpa; + +import org.keycloak.Config; +import org.keycloak.connections.jpa.JpaConnectionProvider; +import org.keycloak.models.ClientProvider; +import org.keycloak.models.ClientProviderFactory; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.KeycloakSessionFactory; + +import javax.persistence.EntityManager; + +public class JpaClientProviderFactory implements ClientProviderFactory { + + @Override + public void init(Config.Scope config) { + } + + @Override + public void postInit(KeycloakSessionFactory factory) { + + } + + @Override + public String getId() { + return "jpa"; + } + + @Override + public ClientProvider create(KeycloakSession session) { + EntityManager em = session.getProvider(JpaConnectionProvider.class).getEntityManager(); + return new JpaRealmProvider(session, em); + } + + @Override + public void close() { + } + +} diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java index b05f8ea043..d1cd2c44bc 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java @@ -23,6 +23,7 @@ import org.keycloak.connections.jpa.util.JpaUtils; import org.keycloak.migration.MigrationModel; import org.keycloak.models.ClientInitialAccessModel; import org.keycloak.models.ClientModel; +import org.keycloak.models.ClientProvider; import org.keycloak.models.ClientScopeModel; import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; @@ -46,13 +47,14 @@ import javax.persistence.TypedQuery; import java.util.*; import java.util.stream.Collectors; import org.keycloak.models.ModelException; +import static org.keycloak.common.util.StackUtil.getShortStackTrace; /** * @author Bill Burke * @version $Revision: 1 $ */ -public class JpaRealmProvider implements RealmProvider { +public class JpaRealmProvider implements RealmProvider, ClientProvider { protected static final Logger logger = Logger.getLogger(JpaRealmProvider.class); private final KeycloakSession session; protected EntityManager em; @@ -152,13 +154,7 @@ public class JpaRealmProvider implements RealmProvider { int num = em.createNamedQuery("deleteGroupRoleMappingsByRealm") .setParameter("realm", realm.getId()).executeUpdate(); - TypedQuery query = em.createNamedQuery("getClientIdsByRealm", String.class); - query.setParameter("realm", realm.getId()); - List clients = query.getResultList(); - for (String client : clients) { - // No need to go through cache. Clients were already invalidated - removeClient(client, adapter); - } + session.clients().removeClients(adapter); num = em.createNamedQuery("deleteDefaultClientScopeRealmMappingByRealm") .setParameter("realm", realm).executeUpdate(); @@ -245,11 +241,10 @@ public class JpaRealmProvider implements RealmProvider { if (getClientRole(realm, client, name) != null) { throw new ModelDuplicateException(); } - ClientEntity clientEntity = em.getReference(ClientEntity.class, client.getId()); RoleEntity roleEntity = new RoleEntity(); roleEntity.setId(id); roleEntity.setName(name); - roleEntity.setClient(clientEntity); + roleEntity.setClientId(client.getId()); roleEntity.setClientRole(true); roleEntity.setRealmId(realm.getId()); em.persist(roleEntity); @@ -450,10 +445,11 @@ public class JpaRealmProvider implements RealmProvider { } @Override - public Long getClientsCount(RealmModel realm) { - return em.createNamedQuery("getRealmClientsCount", Long.class) - .setParameter("realm", realm.getId()) - .getSingleResult(); + public long getClientsCount(RealmModel realm) { + final Long res = em.createNamedQuery("getRealmClientsCount", Long.class) + .setParameter("realm", realm.getId()) + .getSingleResult(); + return res == null ? 0l : res; } @Override @@ -593,6 +589,9 @@ public class JpaRealmProvider implements RealmProvider { if (clientId == null) { clientId = id; } + + logger.tracef("addClient(%s, %s, %s)%s", realm, id, clientId, getShortStackTrace()); + ClientEntity entity = new ClientEntity(); entity.setId(id); entity.setClientId(clientId); @@ -628,17 +627,12 @@ public class JpaRealmProvider implements RealmProvider { if (clients.isEmpty()) return Collections.EMPTY_LIST; List list = new LinkedList<>(); for (String id : clients) { - ClientModel client = session.realms().getClientById(id, realm); + ClientModel client = session.clients().getClientById(realm, id); if (client != null) list.add(client); } return Collections.unmodifiableList(list); } - @Override - public List getClients(RealmModel realm) { - return this.getClients(realm, null, null); - } - @Override public List getAlwaysDisplayInConsoleClients(RealmModel realm) { TypedQuery query = em.createNamedQuery("getAlwaysDisplayInConsoleClients", String.class); @@ -647,14 +641,16 @@ public class JpaRealmProvider implements RealmProvider { if (clients.isEmpty()) return Collections.EMPTY_LIST; List list = new LinkedList<>(); for (String id : clients) { - ClientModel client = session.realms().getClientById(id, realm); + ClientModel client = session.clients().getClientById(realm, id); if (client != null) list.add(client); } return Collections.unmodifiableList(list); } @Override - public ClientModel getClientById(String id, RealmModel realm) { + public ClientModel getClientById(RealmModel realm, String id) { + logger.tracef("getClientById(%s, %s)%s", realm, id, getShortStackTrace()); + ClientEntity app = em.find(ClientEntity.class, id); // Check if application belongs to this realm if (app == null || !realm.getId().equals(app.getRealm().getId())) return null; @@ -664,18 +660,20 @@ public class JpaRealmProvider implements RealmProvider { } @Override - public ClientModel getClientByClientId(String clientId, RealmModel realm) { + public ClientModel getClientByClientId(RealmModel realm, String clientId) { + logger.tracef("getClientByClientId(%s, %s)%s", realm, clientId, getShortStackTrace()); + TypedQuery query = em.createNamedQuery("findClientIdByClientId", String.class); query.setParameter("clientId", clientId); query.setParameter("realm", realm.getId()); List results = query.getResultList(); if (results.isEmpty()) return null; String id = results.get(0); - return session.realms().getClientById(id, realm); + return session.clients().getClientById(realm, id); } @Override - public List searchClientsByClientId(String clientId, Integer firstResult, Integer maxResults, RealmModel realm) { + public List searchClientsByClientId(RealmModel realm, String clientId, Integer firstResult, Integer maxResults) { TypedQuery query = em.createNamedQuery("searchClientsByClientId", String.class); if (firstResult != null && firstResult > 0) { query.setFirstResult(firstResult); @@ -687,12 +685,26 @@ public class JpaRealmProvider implements RealmProvider { query.setParameter("realm", realm.getId()); List results = query.getResultList(); if (results.isEmpty()) return Collections.EMPTY_LIST; - return results.stream().map(id -> session.realms().getClientById(id, realm)).collect(Collectors.toList()); + return results.stream().map(id -> session.clients().getClientById(realm, id)).collect(Collectors.toList()); } @Override - public boolean removeClient(String id, RealmModel realm) { - final ClientModel client = getClientById(id, realm); + public void removeClients(RealmModel realm) { + TypedQuery query = em.createNamedQuery("getClientIdsByRealm", String.class); + query.setParameter("realm", realm.getId()); + List clients = query.getResultList(); + for (String client : clients) { + // No need to go through cache. Clients were already invalidated + removeClient(realm, client); + } + } + + @Override + public boolean removeClient(RealmModel realm, String id) { + + logger.tracef("removeClient(%s, %s)%s", realm, id, getShortStackTrace()); + + final ClientModel client = getClientById(realm, id); if (client == null) return false; session.users().preRemove(realm, client); diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/RealmAdapter.java b/model/jpa/src/main/java/org/keycloak/models/jpa/RealmAdapter.java index 055bc17da9..d19543fda2 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/RealmAdapter.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/RealmAdapter.java @@ -17,6 +17,7 @@ package org.keycloak.models.jpa; +import org.keycloak.Config; import org.jboss.logging.Logger; import org.keycloak.common.enums.SslRequired; import org.keycloak.common.util.MultivaluedHashMap; @@ -829,27 +830,27 @@ public class RealmAdapter implements RealmModel, JpaModel { } @Override public List getClients() { - return session.realms().getClients(this); + return session.clients().getClients(this); } @Override public List getClients(Integer firstResult, Integer maxResults) { - return session.realms().getClients(this, firstResult, maxResults); + return session.clients().getClients(this, firstResult, maxResults); } @Override public List getAlwaysDisplayInConsoleClients() { - return session.realms().getAlwaysDisplayInConsoleClients(this); + return session.clients().getAlwaysDisplayInConsoleClients(this); } @Override public ClientModel addClient(String name) { - return session.realms().addClient(this, name); + return session.clients().addClient(this, name); } @Override public ClientModel addClient(String id, String clientId) { - return session.realms().addClient(this, id, clientId); + return session.clients().addClient(this, id, clientId); } @Override @@ -857,22 +858,22 @@ public class RealmAdapter implements RealmModel, JpaModel { if (id == null) return false; ClientModel client = getClientById(id); if (client == null) return false; - return session.realms().removeClient(id, this); + return session.clients().removeClient(this, id); } @Override public ClientModel getClientById(String id) { - return session.realms().getClientById(id, this); + return session.clients().getClientById(this, id); } @Override public ClientModel getClientByClientId(String clientId) { - return session.realms().getClientByClientId(clientId, this); + return session.clients().getClientByClientId(this, clientId); } @Override public List searchClientByClientId(String clientId, Integer firstResult, Integer maxResults) { - return session.realms().searchClientsByClientId(clientId, firstResult, maxResults, this); + return session.clients().searchClientsByClientId(this, clientId, firstResult, maxResults); } private static final String BROWSER_HEADER_PREFIX = "_browser_header."; @@ -1253,18 +1254,10 @@ public class RealmAdapter implements RealmModel, JpaModel { if (masterAdminClientId == null) { return null; } - ClientEntity masterAdminClient = em.find(ClientEntity.class, masterAdminClientId); - if (masterAdminClient == null) { - return null; - } - RealmModel masterRealm = null; - String masterAdminClientRealmId = masterAdminClient.getRealm().getId(); - if (masterAdminClientRealmId.equals(getId())) { - masterRealm = this; - } else { - masterRealm = session.realms().getRealm(masterAdminClientRealmId); - } - return session.realms().getClientById(masterAdminClient.getId(), masterRealm); + RealmModel masterRealm = getName().equals(Config.getAdminRealm()) + ? this + : session.realms().getRealm(Config.getAdminRealm()); + return session.clients().getClientById(masterRealm, masterAdminClientId); } @Override diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/RoleAdapter.java b/model/jpa/src/main/java/org/keycloak/models/jpa/RoleAdapter.java index eb10c37a78..18ce834d0d 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/RoleAdapter.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/RoleAdapter.java @@ -202,7 +202,7 @@ public class RoleAdapter implements RoleModel, JpaModel { @Override public String getContainerId() { - if (isClientRole()) return role.getClient().getId(); + if (isClientRole()) return role.getClientId(); else return realm.getId(); } @@ -210,7 +210,7 @@ public class RoleAdapter implements RoleModel, JpaModel { @Override public RoleContainerModel getContainer() { if (role.isClientRole()) { - return realm.getClientById(role.getClient().getId()); + return realm.getClientById(role.getClientId()); } else { return realm; diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/entities/RoleEntity.java b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/RoleEntity.java index 71f09b9c6e..c4cec5df94 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/entities/RoleEntity.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/RoleEntity.java @@ -55,11 +55,11 @@ import java.util.Set; @UniqueConstraint(columnNames = { "NAME", "CLIENT_REALM_CONSTRAINT" }) }) @NamedQueries({ - @NamedQuery(name="getClientRoles", query="select role from RoleEntity role where role.client.id = :client order by role.name"), - @NamedQuery(name="getClientRoleIds", query="select role.id from RoleEntity role where role.client.id = :client"), - @NamedQuery(name="getClientRoleByName", query="select role from RoleEntity role where role.name = :name and role.client = :client"), - @NamedQuery(name="getClientRoleIdByName", query="select role.id from RoleEntity role where role.name = :name and role.client.id = :client"), - @NamedQuery(name="searchForClientRoles", query="select role from RoleEntity role where role.client.id = :client and ( lower(role.name) like :search or lower(role.description) like :search ) order by role.name"), + @NamedQuery(name="getClientRoles", query="select role from RoleEntity role where role.clientId = :client order by role.name"), + @NamedQuery(name="getClientRoleIds", query="select role.id from RoleEntity role where role.clientId = :client"), + @NamedQuery(name="getClientRoleByName", query="select role from RoleEntity role where role.name = :name and role.clientId = :client"), + @NamedQuery(name="getClientRoleIdByName", query="select role.id from RoleEntity role where role.name = :name and role.clientId = :client"), + @NamedQuery(name="searchForClientRoles", query="select role from RoleEntity role where role.clientId = :client and ( lower(role.name) like :search or lower(role.description) like :search ) order by role.name"), @NamedQuery(name="getRealmRoles", query="select role from RoleEntity role where role.clientRole = false and role.realm.id = :realm order by role.name"), @NamedQuery(name="getRealmRoleIds", query="select role.id from RoleEntity role where role.clientRole = false and role.realm.id = :realm"), @NamedQuery(name="getRealmRoleByName", query="select role from RoleEntity role where role.clientRole = false and role.name = :name and role.realm = :realm"), @@ -91,9 +91,8 @@ public class RoleEntity { @Column(name="CLIENT_ROLE") private boolean clientRole; - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "CLIENT") - private ClientEntity client; + @Column(name="CLIENT") + private String clientId; // Hack to ensure that either name+client or name+realm are unique. Needed due to MS-SQL as it don't allow multiple NULL values in the column, which is part of constraint @Column(name="CLIENT_REALM_CONSTRAINT", length = 36) @@ -179,15 +178,13 @@ public class RoleEntity { this.clientRealmConstraint = realm.getId(); } - public ClientEntity getClient() { - return client; + public String getClientId() { + return clientId; } - public void setClient(ClientEntity client) { - this.client = client; - if (client != null) { - this.clientRealmConstraint = client.getId(); - } + public void setClientId(String clientId) { + this.clientId = clientId; + this.clientRealmConstraint = clientId; } public String getClientRealmConstraint() { diff --git a/model/jpa/src/main/resources/META-INF/jpa-changelog-11.0.0.xml b/model/jpa/src/main/resources/META-INF/jpa-changelog-11.0.0.xml new file mode 100644 index 0000000000..34c4c9cd22 --- /dev/null +++ b/model/jpa/src/main/resources/META-INF/jpa-changelog-11.0.0.xml @@ -0,0 +1,25 @@ + + + + + + + + + + diff --git a/model/jpa/src/main/resources/META-INF/jpa-changelog-master.xml b/model/jpa/src/main/resources/META-INF/jpa-changelog-master.xml index 1af1ea82af..4317a1ec84 100755 --- a/model/jpa/src/main/resources/META-INF/jpa-changelog-master.xml +++ b/model/jpa/src/main/resources/META-INF/jpa-changelog-master.xml @@ -66,4 +66,6 @@ + + diff --git a/model/jpa/src/main/resources/META-INF/services/org.keycloak.models.ClientProviderFactory b/model/jpa/src/main/resources/META-INF/services/org.keycloak.models.ClientProviderFactory new file mode 100644 index 0000000000..3dd0e98d10 --- /dev/null +++ b/model/jpa/src/main/resources/META-INF/services/org.keycloak.models.ClientProviderFactory @@ -0,0 +1,18 @@ +# +# Copyright 2020 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. +# + +org.keycloak.models.jpa.JpaClientProviderFactory \ No newline at end of file diff --git a/server-spi-private/src/main/java/org/keycloak/models/cache/CacheRealmProvider.java b/server-spi-private/src/main/java/org/keycloak/models/cache/CacheRealmProvider.java index 41ee75ea38..6ae0bca030 100755 --- a/server-spi-private/src/main/java/org/keycloak/models/cache/CacheRealmProvider.java +++ b/server-spi-private/src/main/java/org/keycloak/models/cache/CacheRealmProvider.java @@ -17,13 +17,14 @@ package org.keycloak.models.cache; +import org.keycloak.models.ClientProvider; import org.keycloak.models.RealmProvider; /** * @author Bill Burke * @version $Revision: 1 $ */ -public interface CacheRealmProvider extends RealmProvider { +public interface CacheRealmProvider extends RealmProvider, ClientProvider { void clear(); RealmProvider getRealmDelegate(); diff --git a/server-spi/src/main/java/org/keycloak/models/ClientProvider.java b/server-spi/src/main/java/org/keycloak/models/ClientProvider.java index 2d5f7f82c3..2df6c7197a 100644 --- a/server-spi/src/main/java/org/keycloak/models/ClientProvider.java +++ b/server-spi/src/main/java/org/keycloak/models/ClientProvider.java @@ -20,30 +20,92 @@ import org.keycloak.provider.Provider; import org.keycloak.storage.client.ClientLookupProvider; import java.util.List; -import java.util.Set; /** + * Provider of the client records. + * * @author Bill Burke * @version $Revision: 1 $ */ public interface ClientProvider extends ClientLookupProvider, Provider { + + /** + * Returns the clients of the given realm. + * @param realm Realm. + * @param firstResult First result to return. Ignored if negative or {@code null}. + * @param maxResults Maximim number of results to return. Ignored if negative or {@code null}. + * @return List of the clients. Never returns {@code null}. + */ List getClients(RealmModel realm, Integer firstResult, Integer maxResults); - List getClients(RealmModel realm); + /** + * Returns all the clients of the given realm. + * Effectively the same as the call {@code getClients(realm, null, null)}. + * @param realm Realm. + * @return List of the clients. Never returns {@code null}. + */ + default List getClients(RealmModel realm) { + return this.getClients(realm, null, null); + } - ClientModel addClient(RealmModel realm, String clientId); + /** + * Adds a client with given {@code clientId} to the given realm. + * The internal ID of the client will be created automatically. + * @param realm Realm owning this client. + * @param clientId String that identifies the client to the external parties. + * Maps to {@code client_id} in OIDC or {@code entityID} in SAML. + * @return Model of the created client. + */ + default ClientModel addClient(RealmModel realm, String clientId) { + return addClient(realm, null, clientId); + } + /** + * Adds a client with given internal ID and {@code clientId} to the given realm. + * @param realm Realm owning this client. + * @param id Internal ID of the client or {@code null} if one is to be created by the underlying store + * @param clientId String that identifies the client to the external parties. + * Maps to {@code client_id} in OIDC or {@code entityID} in SAML. + * @return Model of the created client. + * @throws IllegalArgumentException If {@code id} does not conform + * the format understood by the underlying store. + */ ClientModel addClient(RealmModel realm, String id, String clientId); - RoleModel addClientRole(RealmModel realm, ClientModel client, String name); - - RoleModel addClientRole(RealmModel realm, ClientModel client, String id, String name); - - RoleModel getClientRole(RealmModel realm, ClientModel client, String name); - - Set getClientRoles(RealmModel realm, ClientModel client); + /** + * Returns number of clients in the given realm + * @param realm Realm. + * @return Number of the clients in the given realm. + */ + long getClientsCount(RealmModel realm); + /** + * Returns a list of clients that are expected to always show up in account console. + * @param realm Realm owning the clients. + * @return List of the clients. Never returns {@code null}. + */ List getAlwaysDisplayInConsoleClients(RealmModel realm); - boolean removeClient(String id, RealmModel realm); + /** + * Removes given client from the given realm. + * @param id Internal ID of the client + * @param realm Realm. + * @return {@code true} if the client existed and has been removed, {@code false} otherwise. + * @deprecated Use {@link #removeClient(RealmModel, String)} instead. + */ + default boolean removeClient(String id, RealmModel realm) { return this.removeClient(realm, id); } + + /** + * Removes given client from the given realm. + * @param realm Realm. + * @param id Internal ID of the client + * @return {@code true} if the client existed and has been removed, {@code false} otherwise. + */ + boolean removeClient(RealmModel realm, String id); + + /** + * Removes all clients from the given realm. + * @param realm Realm. + */ + void removeClients(RealmModel realm); } diff --git a/server-spi/src/main/java/org/keycloak/models/KeycloakSession.java b/server-spi/src/main/java/org/keycloak/models/KeycloakSession.java index b2902214dc..49ad3c8f37 100755 --- a/server-spi/src/main/java/org/keycloak/models/KeycloakSession.java +++ b/server-spi/src/main/java/org/keycloak/models/KeycloakSession.java @@ -106,6 +106,15 @@ public interface KeycloakSession { */ RealmProvider realms(); + /** + * Returns a managed provider instance. Will start a provider transaction. This transaction is managed by the KeycloakSession + * transaction. + * + * @return + * @throws IllegalStateException if transaction is not active + */ + ClientProvider clients(); + /** * Returns a managed provider instance. Will start a provider transaction. This transaction is managed by the KeycloakSession * transaction. diff --git a/server-spi/src/main/java/org/keycloak/models/RealmProvider.java b/server-spi/src/main/java/org/keycloak/models/RealmProvider.java index edd04a69dd..75334b89cf 100755 --- a/server-spi/src/main/java/org/keycloak/models/RealmProvider.java +++ b/server-spi/src/main/java/org/keycloak/models/RealmProvider.java @@ -27,7 +27,7 @@ import java.util.Set; * @author Bill Burke * @version $Revision: 1 $ */ -public interface RealmProvider extends Provider, ClientProvider { +public interface RealmProvider extends Provider /* TODO: Remove in future version */, ClientProvider /* up to here */ { // Note: The reason there are so many query methods here is for layering a cache on top of an persistent KeycloakSession MigrationModel getMigrationModel(); @@ -42,7 +42,10 @@ public interface RealmProvider extends Provider, ClientProvider { Long getGroupsCount(RealmModel realm, Boolean onlyTopGroups); - Long getClientsCount(RealmModel realm); + /** + * @deprecated Use the corresponding method from {@link ClientProvider}. */ + @Override + long getClientsCount(RealmModel realm); Long getGroupsCountByNameContaining(RealmModel realm, String search); @@ -101,7 +104,6 @@ public interface RealmProvider extends Provider, ClientProvider { List getRealms(); List getRealmsWithProviderType(Class type); boolean removeRealm(String id); - void close(); ClientInitialAccessModel createClientInitialAccessModel(RealmModel realm, int expiration, int count); ClientInitialAccessModel getClientInitialAccessModel(RealmModel realm, String id); @@ -110,4 +112,94 @@ public interface RealmProvider extends Provider, ClientProvider { void removeExpiredClientInitialAccess(); void decreaseRemainingCount(RealmModel realm, ClientInitialAccessModel clientInitialAccess); // Separate provider method to ensure we decrease remainingCount atomically instead of doing classic update + /** + * TODO: To be @deprecated Use the corresponding method from {@link ??RoleProvider}. */ + public Set getClientRoles(RealmModel realm, ClientModel client); + + /** + * TODO: To be @deprecated Use the corresponding method from {@link ??RoleProvider}. */ + public RoleModel getClientRole(RealmModel realm, ClientModel client, String name); + + /** + * TODO: To be @deprecated Use the corresponding method from {@link ??RoleProvider}. */ + public RoleModel addClientRole(RealmModel realm, ClientModel client, String id, String name); + + /** + * TODO: To be @deprecated Use the corresponding method from {@link ??RoleProvider}. */ + public RoleModel addClientRole(RealmModel realm, ClientModel client, String name); + + // The methods below are going to be removed in future version of Keycloak + // Sadly, we have to copy-paste the declarations from the respective interfaces + // including the "default" body to be able to add a note on deprecation + + /** + * @deprecated Use the corresponding method from {@link ClientProvider}. */ + @Override + public ClientModel addClient(RealmModel realm, String id, String clientId); + + /** + * @deprecated Use the corresponding method from {@link ClientProvider}. */ + @Override + default ClientModel addClient(RealmModel realm, String clientId) { + return addClient(realm, null, clientId); + } + + /** + * @deprecated Use the corresponding method from {@link ClientProvider}. */ + @Override + default List getClients(RealmModel realm) { + return this.getClients(realm, null, null); + } + + /** + * @deprecated Use the corresponding method from {@link ClientProvider}. */ + @Override + public List getClients(RealmModel realm, Integer firstResult, Integer maxResults); + + /** + * @deprecated Use the corresponding method from {@link ClientProvider}. */ + @Override + default List searchClientsByClientId(String clientId, Integer firstResult, Integer maxResults, RealmModel realm) { + return searchClientsByClientId(realm, clientId, firstResult, maxResults); + } + + /** + * @deprecated Use the corresponding method from {@link ClientProvider}. */ + @Override + default ClientModel getClientByClientId(String clientId, RealmModel realm) { return getClientByClientId(realm, clientId); } + + /** + * @deprecated Use the corresponding method from {@link ClientProvider}. */ + @Override + default ClientModel getClientById(String id, RealmModel realm) { return getClientById(realm, id); } + + /** + * @deprecated Use the corresponding method from {@link ClientProvider}. */ + @Override + public List searchClientsByClientId(RealmModel realm, String clientId, Integer firstResult, Integer maxResults); + + /** + * @deprecated Use the corresponding method from {@link ClientProvider}. */ + @Override + public ClientModel getClientByClientId(RealmModel realm, String clientId); + + /** + * @deprecated Use the corresponding method from {@link ClientProvider}. */ + @Override + public ClientModel getClientById(RealmModel realm, String id); + + /** + * @deprecated Use the corresponding method from {@link ClientProvider}. */ + @Override + public boolean removeClient(RealmModel realm, String id); + + /** + * @deprecated Use the corresponding method from {@link ClientProvider}. */ + default boolean removeClient(String id, RealmModel realm) { return this.removeClient(realm, id); } + + /** + * @deprecated Use the corresponding method from {@link ClientProvider}. */ + @Override + public List getAlwaysDisplayInConsoleClients(RealmModel realm); + } diff --git a/server-spi/src/main/java/org/keycloak/models/ScopeContainerModel.java b/server-spi/src/main/java/org/keycloak/models/ScopeContainerModel.java index 907ffe6393..c3327a7d84 100755 --- a/server-spi/src/main/java/org/keycloak/models/ScopeContainerModel.java +++ b/server-spi/src/main/java/org/keycloak/models/ScopeContainerModel.java @@ -32,9 +32,7 @@ public interface ScopeContainerModel { return getScopeMappingsStream().collect(Collectors.toSet()); } - default Stream getScopeMappingsStream() { - return getScopeMappings().stream(); - }; + Stream getScopeMappingsStream(); /** * From the scope mappings returned by {@link #getScopeMappings()} returns only those diff --git a/server-spi/src/main/java/org/keycloak/storage/client/ClientLookupProvider.java b/server-spi/src/main/java/org/keycloak/storage/client/ClientLookupProvider.java index edfda976dc..d9e09c296d 100644 --- a/server-spi/src/main/java/org/keycloak/storage/client/ClientLookupProvider.java +++ b/server-spi/src/main/java/org/keycloak/storage/client/ClientLookupProvider.java @@ -28,7 +28,65 @@ import java.util.List; * @version $Revision: 1 $ */ public interface ClientLookupProvider { - ClientModel getClientById(String id, RealmModel realm); - ClientModel getClientByClientId(String clientId, RealmModel realm); - List searchClientsByClientId(String clientId, Integer firstResult, Integer maxResults, RealmModel realm); + + /** + * Exact search for a client by its internal ID. + * @param realm Realm to limit the search. + * @param id Internal ID + * @return Model of the client, or {@code null} if no client is found. + */ + ClientModel getClientById(RealmModel realm, String id); + + /** + * Exact search for a client by its internal ID. + * @param realm Realm to limit the search. + * @param id Internal ID + * @return Model of the client, or {@code null} if no client is found. + * @deprecated Use {@link #getClientById(org.keycloak.models.RealmModel, java.lang.String)} instead. + */ + default ClientModel getClientById(String id, RealmModel realm) { return getClientById(realm, id); } + + /** + * Exact search for a client by its public client identifier. + * @param realm Realm to limit the search for clients. + * @param clientId String that identifies the client to the external parties. + * Maps to {@code client_id} in OIDC or {@code entityID} in SAML. + * @return Model of the client, or {@code null} if no client is found. + */ + ClientModel getClientByClientId(RealmModel realm, String clientId); + + /** + * Exact search for a client by its public client identifier. + * @param realm Realm to limit the search. + * @param clientId String that identifies the client to the external parties. + * Maps to {@code client_id} in OIDC or {@code entityID} in SAML. + * @return Model of the client, or {@code null} if no client is found. + * @deprecated Use {@link #getClientByClientId(org.keycloak.models.RealmModel, java.lang.String)} instead. + */ + default ClientModel getClientByClientId(String clientId, RealmModel realm) { return getClientByClientId(realm, clientId); } + + /** + * Case-insensitive search for clients that contain the given string in their public client identifier. + * @param realm Realm to limit the search for clients. + * @param clientId Searched substring of the public client + * identifier ({@code client_id} in OIDC or {@code entityID} in SAML.) + * @param firstResult First result to return. Ignored if negative or {@code null}. + * @param maxResults Maximim number of results to return. Ignored if negative or {@code null}. + * @return Model of the client, or {@code null} if no client is found. + */ + List searchClientsByClientId(RealmModel realm, String clientId, Integer firstResult, Integer maxResults); + + /** + * Case-insensitive search for clients that contain the given string in their public client identifier. + * @param realm Realm to limit the search for clients. + * @param clientId Searched substring of the public client + * identifier ({@code client_id} in OIDC or {@code entityID} in SAML.) + * @param firstResult First result to return. Ignored if negative or {@code null}. + * @param maxResults Maximim number of results to return. Ignored if negative or {@code null}. + * @return Models of the matching clients. Never returns {@code null}. + * @deprecated Use {@link #searchClientsByClientId(org.keycloak.models.RealmModel, java.lang.String, java.lang.Integer, java.lang.Integer)} instead. + */ + default List searchClientsByClientId(String clientId, Integer firstResult, Integer maxResults, RealmModel realm) { + return searchClientsByClientId(realm, clientId, firstResult, maxResults); + } } diff --git a/services/src/main/java/org/keycloak/authentication/authenticators/client/ClientIdAndSecretAuthenticator.java b/services/src/main/java/org/keycloak/authentication/authenticators/client/ClientIdAndSecretAuthenticator.java index 669e4d1927..351ce13ca4 100644 --- a/services/src/main/java/org/keycloak/authentication/authenticators/client/ClientIdAndSecretAuthenticator.java +++ b/services/src/main/java/org/keycloak/authentication/authenticators/client/ClientIdAndSecretAuthenticator.java @@ -101,7 +101,7 @@ public class ClientIdAndSecretAuthenticator extends AbstractClientAuthenticator context.getEvent().client(client_id); - ClientModel client = context.getRealm().getClientByClientId(client_id); + ClientModel client = context.getSession().clients().getClientByClientId(context.getRealm(), client_id); if (client == null) { context.failure(AuthenticationFlowError.CLIENT_NOT_FOUND, null); return; diff --git a/services/src/main/java/org/keycloak/protocol/oidc/endpoints/LoginStatusIframeEndpoint.java b/services/src/main/java/org/keycloak/protocol/oidc/endpoints/LoginStatusIframeEndpoint.java index ebd61f2d60..aa1b0eea36 100755 --- a/services/src/main/java/org/keycloak/protocol/oidc/endpoints/LoginStatusIframeEndpoint.java +++ b/services/src/main/java/org/keycloak/protocol/oidc/endpoints/LoginStatusIframeEndpoint.java @@ -55,7 +55,7 @@ public class LoginStatusIframeEndpoint { try { UriInfo uriInfo = session.getContext().getUri(); RealmModel realm = session.getContext().getRealm(); - ClientModel client = session.realms().getClientByClientId(clientId, realm); + ClientModel client = session.clients().getClientByClientId(realm, clientId); if (client != null && client.isEnabled()) { Set validWebOrigins = WebOriginsUtils.resolveValidWebOrigins(session, client); validWebOrigins.add(UriUtils.getOrigin(uriInfo.getRequestUri())); diff --git a/services/src/main/java/org/keycloak/services/DefaultKeycloakSession.java b/services/src/main/java/org/keycloak/services/DefaultKeycloakSession.java index 0006df053b..3cb8d81c1a 100644 --- a/services/src/main/java/org/keycloak/services/DefaultKeycloakSession.java +++ b/services/src/main/java/org/keycloak/services/DefaultKeycloakSession.java @@ -66,6 +66,7 @@ public class DefaultKeycloakSession implements KeycloakSession { private final DefaultKeycloakTransactionManager transactionManager; private final Map attributes = new HashMap<>(); private RealmProvider model; + private ClientProvider clientProvider; private UserStorageManager userStorageManager; private ClientStorageManager clientStorageManager; private UserCredentialStoreManager userCredentialStorageManager; @@ -99,6 +100,16 @@ public class DefaultKeycloakSession implements KeycloakSession { } } + private ClientProvider getClientProvider() { + // TODO: Extract ClientProvider from CacheRealmProvider and use that instead + ClientProvider cache = getProvider(CacheRealmProvider.class); + if (cache != null) { + return cache; + } else { + return clientStorageManager(); + } + } + @Override public UserCache userCache() { return getProvider(UserCache.class); @@ -162,7 +173,7 @@ public class DefaultKeycloakSession implements KeycloakSession { @Override public ClientProvider clientLocalStorage() { - return realmLocalStorage(); + return getProvider(ClientProvider.class); } @Override @@ -275,6 +286,14 @@ public class DefaultKeycloakSession implements KeycloakSession { return model; } + @Override + public ClientProvider clients() { + if (clientProvider == null) { + clientProvider = getClientProvider(); + } + return clientProvider; + } + @Override public UserSessionProvider sessions() { diff --git a/services/src/main/java/org/keycloak/services/clientregistration/AbstractClientRegistrationProvider.java b/services/src/main/java/org/keycloak/services/clientregistration/AbstractClientRegistrationProvider.java index 4b9018dd5c..927a470064 100755 --- a/services/src/main/java/org/keycloak/services/clientregistration/AbstractClientRegistrationProvider.java +++ b/services/src/main/java/org/keycloak/services/clientregistration/AbstractClientRegistrationProvider.java @@ -66,7 +66,7 @@ public abstract class AbstractClientRegistrationProvider implements ClientRegist try { RealmModel realm = session.getContext().getRealm(); - ClientModel clientModel = new ClientManager(new RealmManager(session)).createClient(session, realm, client, true); + ClientModel clientModel = ClientManager.createClient(session, realm, client, true); if (clientModel.isServiceAccountsEnabled()) { new ClientManager(new RealmManager(session)).enableServiceAccount(clientModel); diff --git a/services/src/main/java/org/keycloak/services/managers/RealmManager.java b/services/src/main/java/org/keycloak/services/managers/RealmManager.java index 149929a800..961716adb4 100755 --- a/services/src/main/java/org/keycloak/services/managers/RealmManager.java +++ b/services/src/main/java/org/keycloak/services/managers/RealmManager.java @@ -177,7 +177,7 @@ public class RealmManager { } protected void setupAdminConsoleLocaleMapper(RealmModel realm) { - ClientModel adminConsole = realm.getClientByClientId(Constants.ADMIN_CONSOLE_CLIENT_ID); + ClientModel adminConsole = session.clients().getClientByClientId(realm, Constants.ADMIN_CONSOLE_CLIENT_ID); ProtocolMapperModel localeMapper = adminConsole.getProtocolMapperByName(OIDCLoginProtocol.LOGIN_PROTOCOL, OIDCLoginProtocolFactory.LOCALE); if (localeMapper == null) { @@ -251,7 +251,7 @@ public class RealmManager { boolean removed = model.removeRealm(realm.getId()); if (removed) { if (masterAdminClient != null) { - new ClientManager(this).removeClient(getKeycloakAdminstrationRealm(), masterAdminClient); + session.clients().removeClient(getKeycloakAdminstrationRealm(), masterAdminClient.getId()); } UserSessionProvider sessions = session.sessions(); diff --git a/services/src/main/java/org/keycloak/services/resources/LoginActionsService.java b/services/src/main/java/org/keycloak/services/resources/LoginActionsService.java index 955c648bf7..6a7d5d25df 100755 --- a/services/src/main/java/org/keycloak/services/resources/LoginActionsService.java +++ b/services/src/main/java/org/keycloak/services/resources/LoginActionsService.java @@ -395,7 +395,7 @@ public class LoginActionsService { throws UriBuilderException, IllegalArgumentException { AuthenticationSessionModel authSession; - ClientModel client = session.realms().getClientByClientId(clientID, realm); + ClientModel client = session.clients().getClientByClientId(realm, clientID); String redirectUri; if (client == null) { diff --git a/services/src/main/java/org/keycloak/services/resources/admin/RoleByIdResource.java b/services/src/main/java/org/keycloak/services/resources/admin/RoleByIdResource.java index b8101a0d32..1bfb8a3d11 100755 --- a/services/src/main/java/org/keycloak/services/resources/admin/RoleByIdResource.java +++ b/services/src/main/java/org/keycloak/services/resources/admin/RoleByIdResource.java @@ -194,19 +194,19 @@ public class RoleByIdResource extends RoleResource { * Get client-level roles for the client that are in the role's composite * * @param id - * @param client + * @param clientUuid * @return */ - @Path("{role-id}/composites/clients/{client}") + @Path("{role-id}/composites/clients/{clientUuid}") @GET @NoCache @Produces(MediaType.APPLICATION_JSON) public Set getClientRoleComposites(final @PathParam("role-id") String id, - final @PathParam("client") String client) { + final @PathParam("clientUuid") String clientUuid) { RoleModel role = getRoleModel(id); auth.roles().requireView(role); - ClientModel clientModel = realm.getClientById(client); + ClientModel clientModel = realm.getClientById(clientUuid); if (clientModel == null) { throw new NotFoundException("Could not find client"); } diff --git a/services/src/main/java/org/keycloak/services/resources/admin/RoleContainerResource.java b/services/src/main/java/org/keycloak/services/resources/admin/RoleContainerResource.java index 80f389b83d..5ac47d6897 100755 --- a/services/src/main/java/org/keycloak/services/resources/admin/RoleContainerResource.java +++ b/services/src/main/java/org/keycloak/services/resources/admin/RoleContainerResource.java @@ -289,25 +289,25 @@ public class RoleContainerResource extends RoleResource { } /** - * An app-level roles for the specified app for the role's composite + * Get client-level roles for the client that are in the role's composite * * @param roleName role's name (not id!) - * @param client + * @param clientUuid * @return */ - @Path("{role-name}/composites/clients/{client}") + @Path("{role-name}/composites/clients/{clientUuid}") @GET @NoCache @Produces(MediaType.APPLICATION_JSON) public Set getClientRoleComposites(final @PathParam("role-name") String roleName, - final @PathParam("client") String client) { + final @PathParam("clientUuid") String clientUuid) { auth.roles().requireView(roleContainer); RoleModel role = roleContainer.getRole(roleName); if (role == null) { throw new NotFoundException("Could not find role"); } - ClientModel clientModel = realm.getClientById(client); - if (client == null) { + ClientModel clientModel = realm.getClientById(clientUuid); + if (clientModel == null) { throw new NotFoundException("Could not find client"); } diff --git a/services/src/main/java/org/keycloak/services/resources/admin/UserResource.java b/services/src/main/java/org/keycloak/services/resources/admin/UserResource.java index e81388ce39..1a604b90ff 100755 --- a/services/src/main/java/org/keycloak/services/resources/admin/UserResource.java +++ b/services/src/main/java/org/keycloak/services/resources/admin/UserResource.java @@ -357,13 +357,13 @@ public class UserResource { * * @return */ - @Path("offline-sessions/{clientId}") + @Path("offline-sessions/{clientUuid}") @GET @NoCache @Produces(MediaType.APPLICATION_JSON) - public List getOfflineSessions(final @PathParam("clientId") String clientId) { + public List getOfflineSessions(final @PathParam("clientUuid") String clientUuid) { auth.users().requireView(user); - ClientModel client = realm.getClientById(clientId); + ClientModel client = realm.getClientById(clientUuid); if (client == null) { throw new NotFoundException("Client not found"); } @@ -373,7 +373,7 @@ public class UserResource { UserSessionRepresentation rep = ModelToRepresentation.toRepresentation(session); // Update lastSessionRefresh with the timestamp from clientSession - AuthenticatedClientSessionModel clientSession = session.getAuthenticatedClientSessionByClient(clientId); + AuthenticatedClientSessionModel clientSession = session.getAuthenticatedClientSessionByClient(clientUuid); // Skip if userSession is not for this client if (clientSession == null) { diff --git a/services/src/main/java/org/keycloak/storage/ClientStorageManager.java b/services/src/main/java/org/keycloak/storage/ClientStorageManager.java index c5caf7f65d..70ca290577 100644 --- a/services/src/main/java/org/keycloak/storage/ClientStorageManager.java +++ b/services/src/main/java/org/keycloak/storage/ClientStorageManager.java @@ -24,16 +24,13 @@ import org.keycloak.models.ClientProvider; import org.keycloak.models.KeycloakSession; import org.keycloak.models.ModelException; import org.keycloak.models.RealmModel; -import org.keycloak.models.RoleModel; import org.keycloak.storage.client.ClientLookupProvider; import org.keycloak.storage.client.ClientStorageProvider; import org.keycloak.storage.client.ClientStorageProviderFactory; import org.keycloak.storage.client.ClientStorageProviderModel; -import java.util.Collections; import java.util.LinkedList; import java.util.List; -import java.util.Set; /** * @author Bill Burke @@ -126,38 +123,38 @@ public class ClientStorageManager implements ClientProvider { } @Override - public ClientModel getClientById(String id, RealmModel realm) { + public ClientModel getClientById(RealmModel realm, String id) { StorageId storageId = new StorageId(id); if (storageId.getProviderId() == null) { - return session.clientLocalStorage().getClientById(id, realm); + return session.clientLocalStorage().getClientById(realm, id); } ClientLookupProvider provider = (ClientLookupProvider)getStorageProvider(session, realm, storageId.getProviderId()); if (provider == null) return null; if (!isStorageProviderEnabled(realm, storageId.getProviderId())) return null; - return provider.getClientById(id, realm); + return provider.getClientById(realm, id); } @Override - public ClientModel getClientByClientId(String clientId, RealmModel realm) { - ClientModel client = session.clientLocalStorage().getClientByClientId(clientId, realm); + public ClientModel getClientByClientId(RealmModel realm, String clientId) { + ClientModel client = session.clientLocalStorage().getClientByClientId(realm, clientId); if (client != null) { return client; } for (ClientLookupProvider provider : getEnabledStorageProviders(session, realm, ClientLookupProvider.class)) { - client = provider.getClientByClientId(clientId, realm); + client = provider.getClientByClientId(realm, clientId); if (client != null) return client; } return null; } @Override - public List searchClientsByClientId(String clientId, Integer firstResult, Integer maxResults, RealmModel realm) { - List clients = session.clientLocalStorage().searchClientsByClientId(clientId, firstResult, maxResults, realm); + public List searchClientsByClientId(RealmModel realm, String clientId, Integer firstResult, Integer maxResults) { + List clients = session.clientLocalStorage().searchClientsByClientId(realm, clientId, firstResult, maxResults); if (clients != null) { return clients; } for (ClientLookupProvider provider : getEnabledStorageProviders(session, realm, ClientLookupProvider.class)) { - clients = provider.searchClientsByClientId(clientId, firstResult, maxResults, realm); + clients = provider.searchClientsByClientId(realm, clientId, firstResult, maxResults); if (clients != null) return clients; } return null; @@ -173,9 +170,6 @@ public class ClientStorageManager implements ClientProvider { return session.clientLocalStorage().addClient(realm, id, clientId); } - - - @Override public List getClients(RealmModel realm, Integer firstResult, Integer maxResults) { return session.clientLocalStorage().getClients(realm, firstResult, maxResults); @@ -187,37 +181,8 @@ public class ClientStorageManager implements ClientProvider { } @Override - public RoleModel addClientRole(RealmModel realm, ClientModel client, String name) { - if (!StorageId.isLocalStorage(client.getId())) { - throw new RuntimeException("Federated clients do not support this operation"); - } - return session.clientLocalStorage().addClientRole(realm, client, name); - } - - @Override - public RoleModel addClientRole(RealmModel realm, ClientModel client, String id, String name) { - if (!StorageId.isLocalStorage(client.getId())) { - throw new RuntimeException("Federated clients do not support this operation"); - } - return session.clientLocalStorage().addClientRole(realm, client, id, name); - } - - @Override - public RoleModel getClientRole(RealmModel realm, ClientModel client, String name) { - if (!StorageId.isLocalStorage(client.getId())) { - //throw new RuntimeException("Federated clients do not support this operation"); - return null; - } - return session.clientLocalStorage().getClientRole(realm, client, name); - } - - @Override - public Set getClientRoles(RealmModel realm, ClientModel client) { - if (!StorageId.isLocalStorage(client.getId())) { - //throw new RuntimeException("Federated clients do not support this operation"); - return Collections.EMPTY_SET; - } - return session.clientLocalStorage().getClientRoles(realm, client); + public long getClientsCount(RealmModel realm) { + return session.clientLocalStorage().getClientsCount(realm); } @Override @@ -225,17 +190,22 @@ public class ClientStorageManager implements ClientProvider { return session.clientLocalStorage().getAlwaysDisplayInConsoleClients(realm); } + @Override + public void removeClients(RealmModel realm) { + session.clientLocalStorage().removeClients(realm); + } + @Override public void close() { } @Override - public boolean removeClient(String id, RealmModel realm) { + public boolean removeClient(RealmModel realm, String id) { if (!StorageId.isLocalStorage(id)) { throw new RuntimeException("Federated clients do not support this operation"); } - return session.clientLocalStorage().removeClient(id, realm); + return session.clientLocalStorage().removeClient(realm, id); } diff --git a/services/src/main/java/org/keycloak/storage/openshift/OpenshiftClientStorageProvider.java b/services/src/main/java/org/keycloak/storage/openshift/OpenshiftClientStorageProvider.java index 2a0573db36..2d274768af 100644 --- a/services/src/main/java/org/keycloak/storage/openshift/OpenshiftClientStorageProvider.java +++ b/services/src/main/java/org/keycloak/storage/openshift/OpenshiftClientStorageProvider.java @@ -46,15 +46,15 @@ public class OpenshiftClientStorageProvider implements ClientStorageProvider { } @Override - public ClientModel getClientById(String id, RealmModel realm) { + public ClientModel getClientById(RealmModel realm, String id) { StorageId storageId = new StorageId(id); if (!storageId.getProviderId().equals(providerModel.getId())) return null; String clientId = storageId.getExternalId(); - return getClientByClientId(clientId, realm); + return getClientByClientId(realm, clientId); } @Override - public ClientModel getClientByClientId(String clientId, RealmModel realm) { + public ClientModel getClientByClientId(RealmModel realm, String clientId) { Matcher matcher = OpenshiftClientStorageProviderFactory.SERVICE_ACCOUNT_PATTERN.matcher(clientId); IResource resource = null; @@ -76,9 +76,9 @@ public class OpenshiftClientStorageProvider implements ClientStorageProvider { } @Override - public List searchClientsByClientId(String clientId, Integer firstResult, Integer maxResults, RealmModel realm) { + public List searchClientsByClientId(RealmModel realm, String clientId, Integer firstResult, Integer maxResults) { // TODO not sure about this, but I don't see this implementation using the search now - return Collections.singletonList(getClientByClientId(clientId, realm)); + return Collections.singletonList(getClientByClientId(realm, clientId)); } @Override diff --git a/services/src/main/java/org/keycloak/storage/openshift/OpenshiftSAClientAdapter.java b/services/src/main/java/org/keycloak/storage/openshift/OpenshiftSAClientAdapter.java index 085d55afd6..0e30672396 100644 --- a/services/src/main/java/org/keycloak/storage/openshift/OpenshiftSAClientAdapter.java +++ b/services/src/main/java/org/keycloak/storage/openshift/OpenshiftSAClientAdapter.java @@ -345,8 +345,8 @@ public final class OpenshiftSAClientAdapter extends AbstractReadOnlyClientStorag } @Override - public Set getScopeMappings() { - return Collections.emptySet(); + public Stream getScopeMappingsStream() { + return Stream.empty(); } @Override @@ -464,8 +464,8 @@ public final class OpenshiftSAClientAdapter extends AbstractReadOnlyClientStorag } @Override - public Set getScopeMappings() { - return Collections.emptySet(); + public Stream getScopeMappingsStream() { + return Stream.empty(); } @Override diff --git a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/HardcodedClientStorageProvider.java b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/HardcodedClientStorageProvider.java index bd5f007724..0c7fdbc5fe 100644 --- a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/HardcodedClientStorageProvider.java +++ b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/HardcodedClientStorageProvider.java @@ -38,6 +38,7 @@ import java.util.Map; import java.util.Set; import java.util.List; import java.util.stream.Collectors; +import java.util.stream.Stream; /** * @author Bill Burke @@ -59,7 +60,7 @@ public class HardcodedClientStorageProvider implements ClientStorageProvider, Cl } @Override - public ClientModel getClientById(String id, RealmModel realm) { + public ClientModel getClientById(RealmModel realm, String id) { StorageId storageId = new StorageId(id); final String clientId = storageId.getExternalId(); if (this.clientId.equals(clientId)) return new ClientAdapter(realm); @@ -67,7 +68,7 @@ public class HardcodedClientStorageProvider implements ClientStorageProvider, Cl } @Override - public ClientModel getClientByClientId(String clientId, RealmModel realm) { + public ClientModel getClientByClientId(RealmModel realm, String clientId) { if (this.clientId.equals(clientId)) return new ClientAdapter(realm); return null; } @@ -78,7 +79,7 @@ public class HardcodedClientStorageProvider implements ClientStorageProvider, Cl } @Override - public List searchClientsByClientId(String clientId, Integer firstResult, Integer maxResults, RealmModel realm) { + public List searchClientsByClientId(RealmModel realm, String clientId, Integer firstResult, Integer maxResults) { if (clientId != null && this.clientId.toLowerCase().contains(clientId.toLowerCase())) { return Collections.singletonList(new ClientAdapter(realm)); } @@ -274,11 +275,8 @@ public class HardcodedClientStorageProvider implements ClientStorageProvider, Cl } @Override - public Set getScopeMappings() { - RoleModel offlineAccess = realm.getRole("offline_access"); - Set set = new HashSet<>(); - set.add(offlineAccess); - return set; + public Stream getScopeMappingsStream() { + return Stream.of(realm.getRole("offline_access")); } @Override diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/UserStorageConsentTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/UserStorageConsentTest.java index 4b2e56200a..c48facf120 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/UserStorageConsentTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/UserStorageConsentTest.java @@ -102,7 +102,7 @@ public class UserStorageConsentTest extends AbstractServletsAdapterTest { public static void setupConsent(KeycloakSession session) { RealmModel realm = session.realms().getRealmByName("demo"); - ClientModel product = session.realms().getClientByClientId("product-portal", realm); + ClientModel product = session.clients().getClientByClientId(realm, "product-portal"); product.setConsentRequired(true); ClientScopeModel clientScope = realm.addClientScope("clientScope"); clientScope.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/ConsentsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/ConsentsTest.java index 1529ae65ea..1f69b6f814 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/ConsentsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/ConsentsTest.java @@ -97,7 +97,7 @@ public class ConsentsTest extends AbstractKeycloakTest { protected List createProviderClients() { ClientRepresentation client = new ClientRepresentation(); - client.setId(CLIENT_ID); + client.setClientId(CLIENT_ID); client.setName(CLIENT_ID); client.setSecret(CLIENT_SECRET); client.setEnabled(true); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/FineGrainAdminUnitTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/FineGrainAdminUnitTest.java index b8d18939de..33f44ebe88 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/FineGrainAdminUnitTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/FineGrainAdminUnitTest.java @@ -1260,7 +1260,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest { private static void setupTokenExchange(KeycloakSession session) { RealmModel realm = session.realms().getRealmByName("master"); - ClientModel client = session.realms().getClientByClientId("kcinit", realm); + ClientModel client = session.clients().getClientByClientId(realm, "kcinit"); if (client != null) { return; } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/PermissionsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/PermissionsTest.java index 8a49f3915a..37097dd6ea 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/PermissionsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/PermissionsTest.java @@ -85,6 +85,8 @@ import static org.keycloak.services.resources.admin.AdminAuth.Resource.CLIENT; import static org.keycloak.testsuite.util.ServerURLs.getAuthServerContextRoot; import org.keycloak.testsuite.utils.tls.TLSUtils; +import org.jgroups.util.UUID; +import org.keycloak.models.utils.KeycloakModelUtils; /** * @author Stian Thorgersen @@ -712,7 +714,7 @@ public class PermissionsTest extends AbstractKeycloakTest { invoke(new Invocation() { public void invoke(RealmResource realm) { - realm.clients().get("nosuch").roles().list(); + realm.clients().get(UUID.randomUUID().toString()).roles().list(); } }, Resource.CLIENT, false, true); invoke(new Invocation() { @@ -1070,7 +1072,7 @@ public class PermissionsTest extends AbstractKeycloakTest { }, Resource.REALM, false); invoke(new Invocation() { public void invoke(RealmResource realm) { - realm.roles().get("sample-role").getClientRoleComposites("nosuch"); + realm.roles().get("sample-role").getClientRoleComposites(KeycloakModelUtils.generateId()); } }, Resource.REALM, false); adminClient.realms().realm(REALM_NAME).roles().deleteRole("sample-role"); @@ -1297,7 +1299,7 @@ public class PermissionsTest extends AbstractKeycloakTest { }, Resource.REALM, false, true); invoke(new Invocation() { public void invoke(RealmResource realm) { - realm.rolesById().getClientRoleComposites(role.getId(), "nosuch"); + realm.rolesById().getClientRoleComposites(role.getId(), KeycloakModelUtils.generateId()); } }, Resource.REALM, false, true); @@ -1457,7 +1459,7 @@ public class PermissionsTest extends AbstractKeycloakTest { }, Resource.USER, false); invoke(new Invocation() { public void invoke(RealmResource realm) { - realm.users().get(user.getId()).getOfflineSessions("nosuch"); + realm.users().get(user.getId()).getOfflineSessions(KeycloakModelUtils.generateId()); } }, Resource.USER, false); invoke(new Invocation() { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PolicyEvaluationCompositeRoleTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PolicyEvaluationCompositeRoleTest.java index 26b7f48385..106e38638c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PolicyEvaluationCompositeRoleTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PolicyEvaluationCompositeRoleTest.java @@ -69,7 +69,7 @@ public class PolicyEvaluationCompositeRoleTest extends AbstractAuthzTest { session.getContext().setRealm(realm); - ClientModel client = session.realms().addClient(realm, "myclient"); + ClientModel client = session.clients().addClient(realm, "myclient"); RoleModel role1 = client.addRole("client-role1"); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PolicyEvaluationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PolicyEvaluationTest.java index a00a6e076e..b76e76502a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PolicyEvaluationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PolicyEvaluationTest.java @@ -133,7 +133,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest { public static void testCheckDateAndTime(KeycloakSession session) { session.getContext().setRealm(session.realms().getRealmByName("authz-test")); AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class); - ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm()); + ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test"); StoreFactory storeFactory = authorization.getStoreFactory(); ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId()); TimePolicyRepresentation policyRepresentation = new TimePolicyRepresentation(); @@ -168,7 +168,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest { public static void testCheckUserInGroup(KeycloakSession session) { session.getContext().setRealm(session.realms().getRealmByName("authz-test")); AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class); - ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm()); + ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test"); StoreFactory storeFactory = authorization.getStoreFactory(); ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId()); JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation(); @@ -327,7 +327,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest { public static void testCheckUserInRole(KeycloakSession session) { session.getContext().setRealm(session.realms().getRealmByName("authz-test")); AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class); - ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm()); + ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test"); StoreFactory storeFactory = authorization.getStoreFactory(); ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId()); JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation(); @@ -374,7 +374,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest { public static void testCheckUserInClientRole(KeycloakSession session) { session.getContext().setRealm(session.realms().getRealmByName("authz-test")); AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class); - ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm()); + ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test"); StoreFactory storeFactory = authorization.getStoreFactory(); ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId()); JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation(); @@ -421,7 +421,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest { public static void testCheckGroupInRole(KeycloakSession session) { session.getContext().setRealm(session.realms().getRealmByName("authz-test")); AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class); - ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm()); + ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test"); StoreFactory storeFactory = authorization.getStoreFactory(); ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId()); JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation(); @@ -468,7 +468,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest { public static void testCheckUserRealmRoles(KeycloakSession session) { session.getContext().setRealm(session.realms().getRealmByName("authz-test")); AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class); - ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm()); + ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test"); StoreFactory storeFactory = authorization.getStoreFactory(); ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId()); JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation(); @@ -500,7 +500,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest { public static void testCheckUserClientRoles(KeycloakSession session) { session.getContext().setRealm(session.realms().getRealmByName("authz-test")); AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class); - ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm()); + ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test"); StoreFactory storeFactory = authorization.getStoreFactory(); ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId()); JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation(); @@ -532,7 +532,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest { public static void testCheckUserGroups(KeycloakSession session) { session.getContext().setRealm(session.realms().getRealmByName("authz-test")); AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class); - ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm()); + ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test"); StoreFactory storeFactory = authorization.getStoreFactory(); ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId()); JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation(); @@ -570,7 +570,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest { session.getContext().setRealm(realm); AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class); - ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm()); + ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test"); StoreFactory storeFactory = authorization.getStoreFactory(); ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId()); JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation(); @@ -602,7 +602,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest { public static void testCheckResourceAttributes(KeycloakSession session) { session.getContext().setRealm(session.realms().getRealmByName("authz-test")); AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class); - ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm()); + ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test"); StoreFactory storeFactory = authorization.getStoreFactory(); ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId()); JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation(); @@ -639,7 +639,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest { public static void testCheckReadOnlyInstances(KeycloakSession session) { session.getContext().setRealm(session.realms().getRealmByName("authz-test")); AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class); - ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm()); + ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test"); StoreFactory storeFactory = authorization.getStoreFactory(); ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId()); JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation(); @@ -685,7 +685,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest { public static void testCachedDecisionsWithNegativePolicies(KeycloakSession session) { session.getContext().setRealm(session.realms().getRealmByName("authz-test")); AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class); - ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm()); + ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test"); StoreFactory storeFactory = authorization.getStoreFactory(); ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/JsonUserAttributeMapperTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/JsonUserAttributeMapperTest.java index b484070925..7357be7583 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/JsonUserAttributeMapperTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/JsonUserAttributeMapperTest.java @@ -8,6 +8,7 @@ import org.keycloak.broker.oidc.mappers.AbstractJsonUserAttributeMapper; import org.keycloak.models.IdentityProviderMapperModel; import org.keycloak.models.IdentityProviderMapperSyncMode; import org.keycloak.protocol.oidc.mappers.HardcodedClaim; +import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.representations.idm.IdentityProviderMapperRepresentation; import org.keycloak.representations.idm.IdentityProviderRepresentation; import org.keycloak.representations.idm.ProtocolMapperRepresentation; @@ -126,7 +127,8 @@ public class JsonUserAttributeMapperTest extends AbstractIdentityProviderMapperT private void updateClaimSentToIDP(String claim, String updatedValue) { ProtocolMapperRepresentation claimMapper = null; - ProtocolMappersResource protocolMappers = adminClient.realm(bc.providerRealmName()).clients().get(BrokerTestConstants.CLIENT_ID).getProtocolMappers(); + final ClientRepresentation brokerClient = adminClient.realm(bc.providerRealmName()).clients().findByClientId(BrokerTestConstants.CLIENT_ID).get(0); + ProtocolMappersResource protocolMappers = adminClient.realm(bc.providerRealmName()).clients().get(brokerClient.getId()).getProtocolMappers(); for (ProtocolMapperRepresentation representation : protocolMappers.getMappers()) { if (representation.getProtocolMapper().equals(HardcodedClaim.PROVIDER_ID)) { claimMapper = representation; @@ -134,7 +136,7 @@ public class JsonUserAttributeMapperTest extends AbstractIdentityProviderMapperT } assertThat(claimMapper, notNullValue()); claimMapper.getConfig().put(HardcodedClaim.CLAIM_VALUE, "{\"" + claim + "\": \"" + updatedValue + "\"}"); - adminClient.realm(bc.providerRealmName()).clients().get(BrokerTestConstants.CLIENT_ID).getProtocolMappers().update(claimMapper.getId(), claimMapper); + adminClient.realm(bc.providerRealmName()).clients().get(brokerClient.getId()).getProtocolMappers().update(claimMapper.getId(), claimMapper); } private void assertUserAttribute(String value, UserRepresentation userRep) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerConfiguration.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerConfiguration.java index e7dcebba90..9064ca30de 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerConfiguration.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerConfiguration.java @@ -57,7 +57,6 @@ public class KcOidcBrokerConfiguration implements BrokerConfiguration { @Override public List createProviderClients() { ClientRepresentation client = new ClientRepresentation(); - client.setId(CLIENT_ID); client.setClientId(getIDPClientIdInProviderRealm()); client.setName(CLIENT_ID); client.setSecret(CLIENT_SECRET); @@ -155,7 +154,6 @@ public class KcOidcBrokerConfiguration implements BrokerConfiguration { @Override public List createConsumerClients() { ClientRepresentation client = new ClientRepresentation(); - client.setId("broker-app"); client.setClientId("broker-app"); client.setName("broker-app"); client.setSecret("broker-app-secret"); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlBrokerConfiguration.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlBrokerConfiguration.java index 93a5698547..fd4a841e46 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlBrokerConfiguration.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlBrokerConfiguration.java @@ -185,7 +185,6 @@ public class KcSamlBrokerConfiguration implements BrokerConfiguration { .attribute(SAML_ASSERTION_CONSUMER_URL_POST_ATTRIBUTE, getConsumerRoot() + "/sales-post/saml") .build(), ClientBuilder.create() - .id("broker-app") .clientId("broker-app") .name("broker-app") .secret("broker-app-secret") diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/SocialLoginTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/SocialLoginTest.java index 464eb1f7ef..747f9f783b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/SocialLoginTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/SocialLoginTest.java @@ -209,7 +209,7 @@ public class SocialLoginTest extends AbstractKeycloakTest { public static void setupClientExchangePermissions(KeycloakSession session) { RealmModel realm = session.realms().getRealmByName(REALM); - ClientModel client = session.realms().getClientByClientId(EXCHANGE_CLIENT, realm); + ClientModel client = session.clients().getClientByClientId(realm, EXCHANGE_CLIENT); // lazy init if (client != null) return; client = realm.addClient(EXCHANGE_CLIENT); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/KcinitTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/KcinitTest.java index a9395e6fc4..a9a68f282e 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/KcinitTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/KcinitTest.java @@ -102,7 +102,7 @@ public class KcinitTest extends AbstractTestRealmKeycloakTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - ClientModel client = session.realms().getClientByClientId("kcinit", realm); + ClientModel client = session.clients().getClientByClientId(realm, "kcinit"); if (client != null) { return; } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ChallengeFlowTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ChallengeFlowTest.java index 2fc0cd289a..018915114e 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ChallengeFlowTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ChallengeFlowTest.java @@ -84,7 +84,7 @@ public class ChallengeFlowTest extends AbstractTestRealmKeycloakTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - ClientModel client = session.realms().getClientByClientId("test-app-flow", realm); + ClientModel client = session.clients().getClientByClientId(realm, "test-app-flow"); if (client != null) { return; } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/FlowOverrideTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/FlowOverrideTest.java index 1c4e2a92de..bebf98c88e 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/FlowOverrideTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/FlowOverrideTest.java @@ -99,12 +99,12 @@ public class FlowOverrideTest extends AbstractTestRealmKeycloakTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - ClientModel client = session.realms().getClientByClientId("test-app-flow", realm); + ClientModel client = session.clients().getClientByClientId(realm, "test-app-flow"); if (client != null) { return; } - client = session.realms().getClientByClientId("test-app", realm); + client = session.clients().getClientByClientId(realm, "test-app"); client.setDirectAccessGrantsEnabled(true); // Parent flow diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CacheTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CacheTest.java index 93f8491a66..c310ae128d 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CacheTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CacheTest.java @@ -99,7 +99,7 @@ public class CacheTest extends AbstractTestRealmKeycloakTest { realm = session.realms().getRealmByName("test"); Assert.assertEquals(200, realm.getAccessCodeLifespanLogin()); - testApp = session.realms().getClientById(appId, realm); + testApp = session.clients().getClientById(realm, appId); Assert.assertFalse(testApp.isEnabled()); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/ClientModelTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/ClientModelTest.java index eb61c3069f..03f3e037ae 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/ClientModelTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/ClientModelTest.java @@ -141,7 +141,7 @@ public class ClientModelTest extends AbstractKeycloakTest { RoleModel role = currentSession.realms().getRoleById(roleId, realm); from.removeRole(role); - currentSession.realms().removeClient(from.getId(), realm); + currentSession.clients().removeClient(realm, from.getId()); }); @@ -155,7 +155,7 @@ public class ClientModelTest extends AbstractKeycloakTest { // used to throw an NPE assertThat("Scope Mappings must be 0", scopeMappings.size(), is(0)); - currentSession.realms().removeClient(scoped.getId(), realm); + currentSession.clients().removeClient(realm, scoped.getId()); }); } @@ -191,8 +191,8 @@ public class ClientModelTest extends AbstractKeycloakTest { // used to throw an NPE assertThat("Scope Mappings is not 0", scopeMappings.size(), is(0)); - currentSession.realms().removeClient(scoped.getId(), realm); - currentSession.realms().removeClient(from.getId(), realm); + currentSession.clients().removeClient(realm, scoped.getId()); + currentSession.clients().removeClient(realm, from.getId()); }); } @@ -227,7 +227,7 @@ public class ClientModelTest extends AbstractKeycloakTest { Set scopeMappings = scoped.getScopeMappings(); // used to throw an NPE assertThat("Scope Mappings is not 0", scopeMappings.size(), is(0)); - currentSession.realms().removeClient(scoped.getId(), realm); + currentSession.clients().removeClient(realm, scoped.getId()); }); } @@ -252,7 +252,7 @@ public class ClientModelTest extends AbstractKeycloakTest { // this hit the circular cache and failed with a stack overflow ClientModel scoped1 = realm.getClientByClientId("scoped1"); - currentSession.realms().removeClient(scoped1.getId(), realm); + currentSession.clients().removeClient(realm, scoped1.getId()); }); } @@ -270,7 +270,7 @@ public class ClientModelTest extends AbstractKeycloakTest { client.unregisterNode("node1"); client.unregisterNode("10.20.30.40"); - currentSession.realms().removeClient(client.getId(), realm); + currentSession.clients().removeClient(realm, client.getId()); }); } @@ -296,8 +296,8 @@ public class ClientModelTest extends AbstractKeycloakTest { client.unregisterNode("node1"); client.unregisterNode("10.20.30.40"); - currentSession.realms().removeClient(client.getId(), realm); - currentSession.realms().removeClient(copyClient.getId(), realm); + currentSession.clients().removeClient(realm, client.getId()); + currentSession.clients().removeClient(realm, copyClient.getId()); currentSession.realms().removeRealm(realm.getId()); }); } @@ -305,21 +305,22 @@ public class ClientModelTest extends AbstractKeycloakTest { @Test @ModelTest public void testAddApplicationWithId(KeycloakSession session) { + final String id = KeycloakModelUtils.generateId(); KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionAppWithId1) -> { currentSession = sessionAppWithId1; RealmModel realm = currentSession.realms().getRealmByName(realmName); - client = realm.addClient("app-123", "application2"); + client = realm.addClient(id, "application2"); }); KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionAppWithId2) -> { currentSession = sessionAppWithId2; RealmModel realm = currentSession.realms().getRealmByName(realmName); - client = currentSession.realms().getClientById("app-123", realm); + client = currentSession.clients().getClientById(realm, id); assertThat("Client 'app-123' is NULL!!", client, notNullValue()); - currentSession.realms().removeClient(client.getId(), realm); + currentSession.clients().removeClient(realm, client.getId()); }); } @@ -407,7 +408,7 @@ public class ClientModelTest extends AbstractKeycloakTest { assertThat("Client Scope contains 'scope2':", clientScopes2.containsKey("scope2"), is(false)); assertThat("Client Scope contains 'scope3':", clientScopes2.containsKey("scope3"), is(true)); - currentSession.realms().removeClient(client.getId(), realm); + currentSession.clients().removeClient(realm, client.getId()); client.removeClientScope(scope3); realm.removeClientScope(scope1Atomic.get().getId()); realm.removeClientScope(scope2Atomic.get().getId()); @@ -444,7 +445,7 @@ public class ClientModelTest extends AbstractKeycloakTest { // Expected } - currentSession.realms().removeClient(client.getId(), realm); + currentSession.clients().removeClient(realm, client.getId()); realm.removeClientScope(scope1Atomic.get().getId()); assertThat("Error with removing Client from realm.", realm.getClientById(client.getId()), nullValue()); @@ -521,7 +522,7 @@ public class ClientModelTest extends AbstractKeycloakTest { assertThat("Client Scope contains 'scope2':", clientScopes2.containsKey("scope2"), is(true)); assertThat("Client Scope contains 'scope3':", clientScopes2.containsKey("scope3"), is(true)); - currentSession.realms().removeClient(client.getId(), realm); + currentSession.clients().removeClient(realm, client.getId()); // Remove some realm default client scopes realm.removeDefaultClientScope(scope1); realm.removeDefaultClientScope(scope2); @@ -549,7 +550,7 @@ public class ClientModelTest extends AbstractKeycloakTest { assertThat("Client Scope contains 'scope2':", clientScopes2.containsKey("scope2"), is(false)); assertThat("Client Scope contains 'scope3':", clientScopes2.containsKey("scope3"), is(true)); - currentSession.realms().removeClient(client.getId(), realm); + currentSession.clients().removeClient(realm, client.getId()); realm.removeClientScope(scope1Atomic.get().getId()); realm.removeClientScope(scope2Atomic.get().getId()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/ConcurrentTransactionsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/ConcurrentTransactionsTest.java index b28901e49d..86e1012ae1 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/ConcurrentTransactionsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/ConcurrentTransactionsTest.java @@ -21,10 +21,10 @@ import org.jboss.logging.Logger; import org.junit.Assert; import org.junit.Test; import org.keycloak.models.ClientModel; +import org.keycloak.models.ClientProvider; import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSessionFactory; import org.keycloak.models.RealmModel; -import org.keycloak.models.RealmProvider; import org.keycloak.models.UserManager; import org.keycloak.models.UserModel; import org.keycloak.models.utils.KeycloakModelUtils; @@ -69,7 +69,7 @@ public class ConcurrentTransactionsTest extends AbstractTestRealmKeycloakTest { realm = sessionSetup.realms().createRealm("original"); - client[0] = sessionSetup.realms().addClient(realm, "client"); + client[0] = sessionSetup.clients().addClient(realm, "client"); client[0].setSecret("old"); }); @@ -96,7 +96,7 @@ public class ConcurrentTransactionsTest extends AbstractTestRealmKeycloakTest { // Read client RealmModel realm1 = currentSession.realms().getRealmByName("original"); - ClientModel client1 = currentSession.realms().getClientByClientId("client", realm1); + ClientModel client1 = currentSession.clients().getClientByClientId(realm1, "client"); logger.info("transaction1: Read client finished"); readLatch.countDown(); @@ -107,7 +107,7 @@ public class ConcurrentTransactionsTest extends AbstractTestRealmKeycloakTest { logger.info("transaction1: Going to read client again"); - client1 = currentSession.realms().getClientByClientId("client", realm1); + client1 = currentSession.clients().getClientByClientId(realm1, "client"); logger.info("transaction1: secret: " + client1.getSecret()); } catch (Exception e) { @@ -136,7 +136,7 @@ public class ConcurrentTransactionsTest extends AbstractTestRealmKeycloakTest { logger.info("transaction2: Going to update client secret"); RealmModel realm12 = currentSession.realms().getRealmByName("original"); - ClientModel client12 = currentSession.realms().getClientByClientId("client", realm12); + ClientModel client12 = currentSession.clients().getClientByClientId(realm12, "client"); client12.setSecret("new"); } catch (Exception e) { exceptionHolder.set(e); @@ -168,8 +168,8 @@ public class ConcurrentTransactionsTest extends AbstractTestRealmKeycloakTest { RealmModel realm = session2.realms().getRealmByName("original"); String clientDBId = clientDBIdAtomic.get(); - ClientModel clientFromCache = session2.realms().getClientById(clientDBId, realm); - ClientModel clientFromDB = session2.getProvider(RealmProvider.class).getClientById(clientDBId, realm); + ClientModel clientFromCache = session2.clients().getClientById(realm, clientDBId); + ClientModel clientFromDB = session2.getProvider(ClientProvider.class).getClientById(realm, clientDBId); logger.info("SECRET FROM DB : " + clientFromDB.getSecret()); logger.info("SECRET FROM CACHE : " + clientFromCache.getSecret()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserConsentModelTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserConsentModelTest.java index e2d24c0213..6ebaee3dec 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserConsentModelTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserConsentModelTest.java @@ -141,7 +141,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest { clientStorage.setParentId(realm.getId()); clientStorageComponent = realm.addComponentModel(clientStorage); - ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm); + ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client"); Assert.assertNotNull(hardcodedClient); @@ -183,7 +183,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest { Assert.assertNotNull("Created Date should be set", maryConsent.getCreatedDate()); Assert.assertNotNull("Last Updated Date should be set", maryConsent.getLastUpdatedDate()); - ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm); + ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client"); UserConsentModel maryHardcodedConsent = currentSession.users().getConsentByClient(realm, mary.getId(), hardcodedClient.getId()); Assert.assertEquals(maryHardcodedConsent.getGrantedClientScopes().size(), 0); Assert.assertNotNull("Created Date should be set", maryHardcodedConsent.getCreatedDate()); @@ -210,7 +210,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest { List johnConsents = currentSession.users().getConsents(realm, john.getId()); Assert.assertEquals(2, johnConsents.size()); - ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm); + ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client"); List maryConsents = currentSession.users().getConsents(realm, mary.getId()); Assert.assertEquals(2, maryConsents.size()); @@ -277,7 +277,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest { UserModel mary = currentSession.users().getUserByUsername("mary", realm); currentSession.users().revokeConsentForClient(realm, john.getId(), fooClient.getId()); - ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm); + ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client"); currentSession.users().revokeConsentForClient(realm, mary.getId(), hardcodedClient.getId()); }); @@ -286,7 +286,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest { RealmModel realm = currentSession.realms().getRealm("original"); ClientModel fooClient = realm.getClientByClientId("foo-client"); - ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm); + ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client"); UserModel john = currentSession.users().getUserByUsername("john", realm); Assert.assertNull(currentSession.users().getConsentByClient(realm, john.getId(), fooClient.getId())); @@ -384,7 +384,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest { KeycloakSession currentSession = sessionCST2; RealmModel realm = currentSession.realms().getRealm("original"); - ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm); + ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client"); Assert.assertNull(hardcodedClient); UserModel mary = currentSession.users().getUserByUsername("mary", realm); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserConsentWithUserStorageModelTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserConsentWithUserStorageModelTest.java index 5f77e84164..3b1e28bc0b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserConsentWithUserStorageModelTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserConsentWithUserStorageModelTest.java @@ -152,7 +152,7 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo clientStorage.setParentId(realm.getId()); clientStorageComponent = realm.addComponentModel(clientStorage); - ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm); + ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client"); Assert.assertNotNull(hardcodedClient); @@ -193,7 +193,7 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo Assert.assertNotNull("Created Date should be set", maryConsent.getCreatedDate()); Assert.assertNotNull("Last Updated Date should be set", maryConsent.getLastUpdatedDate()); - ClientModel hardcodedClient = currentSessionCT.realms().getClientByClientId("hardcoded-client", realm); + ClientModel hardcodedClient = currentSessionCT.clients().getClientByClientId(realm, "hardcoded-client"); UserConsentModel maryHardcodedConsent = currentSession.users().getConsentByClient(realm, mary.getId(), hardcodedClient.getId()); Assert.assertEquals(maryHardcodedConsent.getGrantedClientScopes().size(), 0); Assert.assertNotNull("Created Date should be set", maryHardcodedConsent.getCreatedDate()); @@ -220,7 +220,7 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo List johnConsents = currentSession.users().getConsents(realm, john.getId()); Assert.assertEquals(2, johnConsents.size()); - ClientModel hardcodedClient = currentSessionACT.realms().getClientByClientId("hardcoded-client", realm); + ClientModel hardcodedClient = currentSessionACT.clients().getClientByClientId(realm, "hardcoded-client"); List maryConsents = currentSession.users().getConsents(realm, mary.getId()); Assert.assertEquals(2, maryConsents.size()); @@ -287,7 +287,7 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo UserModel mary = currentSession.users().getUserByUsername("mary", realm); currentSession.users().revokeConsentForClient(realm, john.getId(), fooClient.getId()); - ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm); + ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client"); currentSession.users().revokeConsentForClient(realm, mary.getId(), hardcodedClient.getId()); }); @@ -296,7 +296,7 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo RealmModel realm = currentSession.realms().getRealmByName("original"); ClientModel fooClient = realm.getClientByClientId("foo-client"); - ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm); + ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client"); UserModel john = currentSession.users().getUserByUsername("john", realm); Assert.assertNull(currentSession.users().getConsentByClient(realm, john.getId(), fooClient.getId())); @@ -396,7 +396,7 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo KeycloakSession currentSession = sesDelClientStore2; RealmModel realm = currentSession.realms().getRealmByName("original"); - ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm); + ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client"); Assert.assertNull(hardcodedClient); UserModel mary = currentSession.users().getUserByUsername("mary", realm); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthRedirectUriTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthRedirectUriTest.java index d696c75ed1..3a849a3a48 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthRedirectUriTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthRedirectUriTest.java @@ -102,49 +102,49 @@ public class OAuthRedirectUriTest extends AbstractKeycloakTest { RealmRepresentation realmRepresentation = loadJson(getClass().getResourceAsStream("/testrealm.json"), RealmRepresentation.class); RealmBuilder realm = RealmBuilder.edit(realmRepresentation).testEventListener(); - ClientBuilder installedApp = ClientBuilder.create().id("test-installed").name("test-installed") + ClientBuilder installedApp = ClientBuilder.create().clientId("test-installed").name("test-installed") .redirectUris(Constants.INSTALLED_APP_URN, Constants.INSTALLED_APP_URL) .secret("password"); realm.client(installedApp); - ClientBuilder installedApp2 = ClientBuilder.create().id("test-installed2").name("test-installed2") + ClientBuilder installedApp2 = ClientBuilder.create().clientId("test-installed2").name("test-installed2") .redirectUris(Constants.INSTALLED_APP_URL + "/myapp") .secret("password"); realm.client(installedApp2); - ClientBuilder installedApp3 = ClientBuilder.create().id("test-wildcard").name("test-wildcard") + ClientBuilder installedApp3 = ClientBuilder.create().clientId("test-wildcard").name("test-wildcard") .redirectUris("http://example.com/foo/*", "http://with-dash.example.local/foo/*", "http://localhost:8280/foo/*") .secret("password"); realm.client(installedApp3); - ClientBuilder installedApp4 = ClientBuilder.create().id("test-dash").name("test-dash") + ClientBuilder installedApp4 = ClientBuilder.create().clientId("test-dash").name("test-dash") .redirectUris("http://with-dash.example.local", "http://with-dash.example.local/foo") .secret("password"); realm.client(installedApp4); - ClientBuilder installedApp5 = ClientBuilder.create().id("test-root-url").name("test-root-url") + ClientBuilder installedApp5 = ClientBuilder.create().clientId("test-root-url").name("test-root-url") .rootUrl("http://with-dash.example.local") .redirectUris("/foo") .secret("password"); realm.client(installedApp5); - ClientBuilder installedApp6 = ClientBuilder.create().id("test-relative-url").name("test-relative-url") + ClientBuilder installedApp6 = ClientBuilder.create().clientId("test-relative-url").name("test-relative-url") .rootUrl("") .redirectUris("/auth") .secret("password"); realm.client(installedApp6); - ClientBuilder installedApp7 = ClientBuilder.create().id("test-query-component").name("test-query-component") + ClientBuilder installedApp7 = ClientBuilder.create().clientId("test-query-component").name("test-query-component") .redirectUris("http://localhost?foo=bar", "http://localhost?foo=bar*") .secret("password"); realm.client(installedApp7); - ClientBuilder installedApp8 = ClientBuilder.create().id("test-fragment").name("test-fragment") + ClientBuilder installedApp8 = ClientBuilder.create().clientId("test-fragment").name("test-fragment") .redirectUris("http://localhost:8180/*", "https://localhost:8543/*") .secret("password"); realm.client(installedApp8); - ClientBuilder installedAppCustomScheme = ClientBuilder.create().id("custom-scheme").name("custom-scheme") + ClientBuilder installedAppCustomScheme = ClientBuilder.create().clientId("custom-scheme").name("custom-scheme") .redirectUris("android-app://org.keycloak.examples.cordova/https/keycloak-cordova-example.github.io/login") .secret("password"); realm.client(installedAppCustomScheme); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenEndpointCorsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenEndpointCorsTest.java index 2e20c0fa10..b1f3acff8f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenEndpointCorsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenEndpointCorsTest.java @@ -41,7 +41,7 @@ public class TokenEndpointCorsTest extends AbstractKeycloakTest { @Override public void addTestRealms(List testRealms) { RealmRepresentation realm = loadJson(getClass().getResourceAsStream("/testrealm.json"), RealmRepresentation.class); - realm.getClients().add(ClientBuilder.create().redirectUris(VALID_CORS_URL + "/realms/master/app").addWebOrigin(VALID_CORS_URL).id("test-app2").clientId("test-app2").publicClient().directAccessGrants().build()); + realm.getClients().add(ClientBuilder.create().redirectUris(VALID_CORS_URL + "/realms/master/app").addWebOrigin(VALID_CORS_URL).clientId("test-app2").publicClient().directAccessGrants().build()); testRealms.add(realm); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenRevocationCorsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenRevocationCorsTest.java index 571655b462..5e2f83f965 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenRevocationCorsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenRevocationCorsTest.java @@ -48,7 +48,7 @@ public class TokenRevocationCorsTest extends AbstractKeycloakTest { public void addTestRealms(List testRealms) { RealmRepresentation realm = loadJson(getClass().getResourceAsStream("/testrealm.json"), RealmRepresentation.class); realm.getClients().add(ClientBuilder.create().redirectUris(VALID_CORS_URL + "/realms/master/app") - .addWebOrigin(VALID_CORS_URL).id("test-app2").clientId("test-app2").publicClient().directAccessGrants().build()); + .addWebOrigin(VALID_CORS_URL).clientId("test-app2").publicClient().directAccessGrants().build()); testRealms.add(realm); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/UserInfoEndpointCorsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/UserInfoEndpointCorsTest.java index 0c477c2ef4..e0020b949b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/UserInfoEndpointCorsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/UserInfoEndpointCorsTest.java @@ -28,7 +28,7 @@ public class UserInfoEndpointCorsTest extends AbstractKeycloakTest { @Override public void addTestRealms(List testRealms) { RealmRepresentation realm = loadJson(getClass().getResourceAsStream("/testrealm.json"), RealmRepresentation.class); - realm.getClients().add(ClientBuilder.create().redirectUris(VALID_CORS_URL + "/realms/master/app").addWebOrigin(VALID_CORS_URL).id("test-app2").clientId("test-app2").publicClient().directAccessGrants().build()); + realm.getClients().add(ClientBuilder.create().redirectUris(VALID_CORS_URL + "/realms/master/app").addWebOrigin(VALID_CORS_URL).clientId("test-app2").publicClient().directAccessGrants().build()); testRealms.add(realm); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/openshift/OpenShiftTokenReviewEndpointTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/openshift/OpenShiftTokenReviewEndpointTest.java index a1047b389e..d448d557e4 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/openshift/OpenShiftTokenReviewEndpointTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/openshift/OpenShiftTokenReviewEndpointTest.java @@ -206,14 +206,16 @@ public class OpenShiftTokenReviewEndpointTest extends AbstractTestRealmKeycloakT public void customScopes() { ClientScopeRepresentation clientScope = new ClientScopeRepresentation(); clientScope.setProtocol("openid-connect"); - clientScope.setId("user:info"); clientScope.setName("user:info"); - testRealm().clientScopes().create(clientScope); + String id; + try (Response r = testRealm().clientScopes().create(clientScope)) { + id = ApiUtil.getCreatedId(r); + } ClientRepresentation clientRep = testRealm().clients().findByClientId("test-app").get(0); - testRealm().clients().get(clientRep.getId()).addOptionalClientScope("user:info"); + testRealm().clients().get(clientRep.getId()).addOptionalClientScope(id); try { oauth.scope("user:info"); @@ -221,7 +223,7 @@ public class OpenShiftTokenReviewEndpointTest extends AbstractTestRealmKeycloakT .invoke() .assertSuccess().assertScope("openid", "user:info", "profile", "email"); } finally { - testRealm().clients().get(clientRep.getId()).removeOptionalClientScope("user:info"); + testRealm().clients().get(clientRep.getId()).removeOptionalClientScope(id); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/SamlConsentTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/SamlConsentTest.java index ec2aedccd4..68c1345f1c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/SamlConsentTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/SamlConsentTest.java @@ -1,6 +1,5 @@ package org.keycloak.testsuite.saml; -import org.keycloak.protocol.saml.SamlClient; import org.keycloak.protocol.saml.SamlConfigAttributes; import org.keycloak.protocol.saml.SamlProtocol; import org.junit.Test; diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/SessionNotOnOrAfterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/SessionNotOnOrAfterTest.java index 1302840890..a7eaf8e00e 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/SessionNotOnOrAfterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/SessionNotOnOrAfterTest.java @@ -97,7 +97,7 @@ public class SessionNotOnOrAfterTest extends AbstractSamlTest { .idpInitiatedLogin(getAuthServerSamlEndpoint(REALM_NAME), "sales-post").build() .login().user(bburkeUser).build() .processSamlResponse(SamlClient.Binding.POST) - .transformObject(r -> { checkSessionNotOnOrAfter(r, SSO_MAX_LIFESPAN, ACCESS_CODE_LIFESPAN, ACCESS_TOKEN_LIFESPAN); }) + .transformObject(r -> { return checkSessionNotOnOrAfter(r, SSO_MAX_LIFESPAN, ACCESS_CODE_LIFESPAN, ACCESS_TOKEN_LIFESPAN); }) .build() .execute(); } @@ -116,7 +116,7 @@ public class SessionNotOnOrAfterTest extends AbstractSamlTest { .idpInitiatedLogin(getAuthServerSamlEndpoint(REALM_NAME), "sales-post").build() .login().user(bburkeUser).build() .processSamlResponse(SamlClient.Binding.POST) - .transformObject(r -> { checkSessionNotOnOrAfter(r, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); }) + .transformObject(r -> { return checkSessionNotOnOrAfter(r, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); }) .build() .execute(); } @@ -136,7 +136,7 @@ public class SessionNotOnOrAfterTest extends AbstractSamlTest { .build() .login().user(bburkeUser).build() .processSamlResponse(SamlClient.Binding.POST) - .transformObject(r -> { checkSessionNotOnOrAfter(r, SSO_MAX_LIFESPAN, ACCESS_CODE_LIFESPAN, ACCESS_TOKEN_LIFESPAN); }) + .transformObject(r -> { return checkSessionNotOnOrAfter(r, SSO_MAX_LIFESPAN, ACCESS_CODE_LIFESPAN, ACCESS_TOKEN_LIFESPAN); }) .build() .execute(); } @@ -152,7 +152,7 @@ public class SessionNotOnOrAfterTest extends AbstractSamlTest { .idpInitiatedLogin(getAuthServerSamlEndpoint(REALM_NAME), "sales-post").build() .login().user(bburkeUser).build() .processSamlResponse(SamlClient.Binding.POST) - .transformObject(r -> { checkSessionNotOnOrAfter(r, ssoMaxLifespan, 2000, 2000); }) + .transformObject(r -> { return checkSessionNotOnOrAfter(r, ssoMaxLifespan, 2000, 2000); }) .build() .execute(); } @@ -169,7 +169,7 @@ public class SessionNotOnOrAfterTest extends AbstractSamlTest { .build() .login().user(bburkeUser).build() .processSamlResponse(SamlClient.Binding.POST) - .transformObject(r -> { checkSessionNotOnOrAfter(r, ssoMaxLifespan, 1800, 1800); }) + .transformObject(r -> { return checkSessionNotOnOrAfter(r, ssoMaxLifespan, 1800, 1800); }) .build() .execute(); } diff --git a/testsuite/utils/src/main/java/org/keycloak/testsuite/util/cli/RoleCommands.java b/testsuite/utils/src/main/java/org/keycloak/testsuite/util/cli/RoleCommands.java index 2ac3054994..8dfc1607e2 100644 --- a/testsuite/utils/src/main/java/org/keycloak/testsuite/util/cli/RoleCommands.java +++ b/testsuite/utils/src/main/java/org/keycloak/testsuite/util/cli/RoleCommands.java @@ -17,16 +17,12 @@ package org.keycloak.testsuite.util.cli; -import java.util.HashSet; -import java.util.Set; import org.keycloak.models.ClientModel; import org.keycloak.models.KeycloakSession; -import org.keycloak.models.KeycloakSessionTask; import org.keycloak.models.RealmModel; import org.keycloak.models.RoleContainerModel; import org.keycloak.models.RoleModel; -import org.keycloak.models.utils.KeycloakModelUtils; /** * @author Marek Posolda @@ -83,7 +79,7 @@ public class RoleCommands { return realm; } else { String clientId = parts[1]; - ClientModel client = session.realms().getClientByClientId(clientId, realm); + ClientModel client = session.clients().getClientByClientId(realm, clientId); if (client == null) { log.errorf("Unknown client: %s", clientId); throw new HandledException();