From dcd598da4d4dd7ed24852cb1d712b60336aeb78c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Barto=C5=A1?= Date: Tue, 10 Mar 2026 15:10:08 +0100 Subject: [PATCH 1/4] New client service - PUT/POST - update or create client MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #46785 Signed-off-by: Martin Bartoš --- .../models/mapper/BaseClientModelMapper.java | 1 + .../org/keycloak/services/RolesService.java | 28 ++++ .../services/client/DefaultClientService.java | 31 ++--- .../services/client/NewClientService.java | 131 ++++++++++++++++++ .../admin/client/v2/ClientPoliciesV2Test.java | 50 ++++++- .../context/AdminClientUpdatedContext.java | 4 +- .../services/managers/ClientManager.java | 26 ++++ .../resources/admin/ClientResource.java | 24 +--- .../admin/RoleContainerResource.java | 9 ++ 9 files changed, 262 insertions(+), 42 deletions(-) create mode 100644 rest/admin-v2/api/src/main/java/org/keycloak/services/RolesService.java diff --git a/rest/admin-v2/api/src/main/java/org/keycloak/models/mapper/BaseClientModelMapper.java b/rest/admin-v2/api/src/main/java/org/keycloak/models/mapper/BaseClientModelMapper.java index 2a212a0833d..4f9b4e039ba 100644 --- a/rest/admin-v2/api/src/main/java/org/keycloak/models/mapper/BaseClientModelMapper.java +++ b/rest/admin-v2/api/src/main/java/org/keycloak/models/mapper/BaseClientModelMapper.java @@ -46,6 +46,7 @@ public ClientModel toModel(BaseClientRepresentation rep, ClientModel existingMod existingModel = createClientModel(rep); } + existingModel.setProtocol(rep.getProtocol()); existingModel.setEnabled(Boolean.TRUE.equals(rep.getEnabled())); existingModel.setClientId(rep.getClientId()); existingModel.setDescription(rep.getDescription()); diff --git a/rest/admin-v2/api/src/main/java/org/keycloak/services/RolesService.java b/rest/admin-v2/api/src/main/java/org/keycloak/services/RolesService.java new file mode 100644 index 00000000000..413183bdd2b --- /dev/null +++ b/rest/admin-v2/api/src/main/java/org/keycloak/services/RolesService.java @@ -0,0 +1,28 @@ +package org.keycloak.services; + +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.RealmModel; +import org.keycloak.models.RoleContainerModel; +import org.keycloak.services.resources.admin.AdminEventBuilder; +import org.keycloak.services.resources.admin.RoleContainerResource; +import org.keycloak.services.resources.admin.fgap.AdminPermissionEvaluator; + +public class RolesService { + private final KeycloakSession session; + private final RealmModel realm; + private final AdminPermissionEvaluator permissions; + private final AdminEventBuilder adminEventBuilder; + + public RolesService(KeycloakSession session, RealmModel realm, AdminPermissionEvaluator permissions, AdminEventBuilder adminEventBuilder) { + this.session = session; + this.realm = realm; + this.permissions = permissions; + this.adminEventBuilder = adminEventBuilder; + } + + public RoleContainerResource resource(RoleContainerModel roleContainer) { + var resource = new RoleContainerResource(session, session.getContext().getUri(), realm, permissions, adminEventBuilder); + resource.setRoleContainer(roleContainer); + return resource; + } +} diff --git a/rest/admin-v2/api/src/main/java/org/keycloak/services/client/DefaultClientService.java b/rest/admin-v2/api/src/main/java/org/keycloak/services/client/DefaultClientService.java index fcfa7ef1b97..22dd933328e 100644 --- a/rest/admin-v2/api/src/main/java/org/keycloak/services/client/DefaultClientService.java +++ b/rest/admin-v2/api/src/main/java/org/keycloak/services/client/DefaultClientService.java @@ -34,10 +34,13 @@ import org.keycloak.representations.idm.RoleRepresentation; import org.keycloak.services.PatchType; import org.keycloak.services.ServiceException; +import org.keycloak.services.managers.ClientManager; +import org.keycloak.services.managers.RealmManager; import org.keycloak.services.resources.admin.AdminEventBuilder; import org.keycloak.services.resources.admin.ClientResource; import org.keycloak.services.resources.admin.ClientsResource; import org.keycloak.services.resources.admin.RealmAdminResource; +import org.keycloak.services.resources.admin.RoleContainerResource; import org.keycloak.services.resources.admin.fgap.AdminPermissionEvaluator; import org.keycloak.services.util.ObjectMapperResolver; import org.keycloak.utils.StringUtil; @@ -114,7 +117,7 @@ public CreateOrUpdateResult createOrUpdateClient(RealmModel realm, String client return createOrUpdate(realm, clientId, client, CreateOrUpdateStrategy.PUT); } - private enum CreateOrUpdateStrategy { + protected enum CreateOrUpdateStrategy { ONLY_CREATE(CreateClient.class), PUT(PutClient.class), PATCH(PatchClient.class); @@ -194,9 +197,9 @@ private CreateOrUpdateResult createOrUpdate(RealmModel realm, String clientId, B }); } - handleRoles(clientResource, client.getRoles()); + handleRoles(clientResource.getRoleContainerResource(), client.getRoles()); if (client instanceof OIDCClientRepresentation oidcClient) { - handleServiceAccount(clientResource, model, oidcClient); + handleServiceAccount(clientResource.getRoleContainerResource(), realmResource.getRoleContainerResource(), model, oidcClient); } fireAdminEvent(created ? OperationType.CREATE : OperationType.UPDATE, mapper.fromModel(model)); @@ -282,13 +285,11 @@ protected void assertSameClientIds(String pathId, String payloadId) { *

* Reuses API v1 logic */ - protected void handleRoles(ClientResource clientResource, Set rolesFromRep) { - var roleResource = clientResource.getRoleContainerResource(); - + protected void handleRoles(RoleContainerResource clientRoles, Set rolesFromRep) { Set desiredRoleNames = Optional.ofNullable(rolesFromRep) .orElse(Collections.emptySet()); - Set currentRoleNames = roleResource.getRoles(null, null, null, false) + Set currentRoleNames = clientRoles.getRoles(null, null, null, false) .map(RoleRepresentation::getName) .collect(Collectors.toSet()); @@ -296,7 +297,7 @@ protected void handleRoles(ClientResource clientResource, Set rolesFromR desiredRoleNames.stream() .filter(roleName -> !currentRoleNames.contains(roleName)) .forEach(roleName -> { - try (var response = roleResource.createRole(new RoleRepresentation(roleName, "", false))) { + try (var response = clientRoles.createRole(new RoleRepresentation(roleName, "", false))) { // close response and consume payload due to performance reasons EntityUtils.consumeQuietly((HttpEntity) response.getEntity()); } @@ -305,7 +306,7 @@ protected void handleRoles(ClientResource clientResource, Set rolesFromR // Remove extra roles (in currentRoleNames but not in desiredRoleNames) currentRoleNames.stream() .filter(role -> !desiredRoleNames.contains(role)) - .forEach(roleResource::deleteRole); + .forEach(clientRoles::deleteRole); } /** @@ -313,20 +314,18 @@ protected void handleRoles(ClientResource clientResource, Set rolesFromR *

* Reuses API v1 logic */ - protected void handleServiceAccount(ClientResource clientResource, ClientModel model, OIDCClientRepresentation rep) { + protected void handleServiceAccount(RoleContainerResource clientRoleResource, RoleContainerResource realmRoleResource, ClientModel model, OIDCClientRepresentation rep) { boolean serviceAccountEnabled = rep.getLoginFlows().contains(OIDCClientRepresentation.Flow.SERVICE_ACCOUNT); - ClientResource.updateClientServiceAccount(session, model, serviceAccountEnabled); + ClientManager.updateClientServiceAccount(session, model, serviceAccountEnabled); if (!serviceAccountEnabled) { return; } - var clientRoleResource = clientResource.getRoleContainerResource(); - var realmRoleResource = realmResource.getRoleContainerResource(); - - var serviceAccountUser = session.users().getServiceAccount(model); - var serviceAccountRoleResource = realmResource.users().user(clientResource.getServiceAccountUser().getId()).getRoleMappings(); + var serviceAccountUser = new ClientManager(new RealmManager(session)).getServiceAccountUser(model) + .orElseThrow(() -> new ServiceException("Cannot find service account user", Response.Status.BAD_REQUEST)); + var serviceAccountRoleResource = realmResource.users().user(serviceAccountUser.getId()).getRoleMappings(); Set desiredRoleNames = Optional.ofNullable(rep.getServiceAccountRoles()).orElse(Collections.emptySet()); Set currentRoles = serviceAccountUser.getRoleMappingsStream().collect(Collectors.toSet()); diff --git a/rest/admin-v2/api/src/main/java/org/keycloak/services/client/NewClientService.java b/rest/admin-v2/api/src/main/java/org/keycloak/services/client/NewClientService.java index d24b199b7b6..13666473fa3 100644 --- a/rest/admin-v2/api/src/main/java/org/keycloak/services/client/NewClientService.java +++ b/rest/admin-v2/api/src/main/java/org/keycloak/services/client/NewClientService.java @@ -1,9 +1,11 @@ package org.keycloak.services.client; +import java.util.Objects; import java.util.Optional; import java.util.stream.Stream; import jakarta.annotation.Nonnull; +import jakarta.validation.groups.Default; import jakarta.ws.rs.core.Response; import org.keycloak.authorization.fgap.AdminPermissionsSchema; @@ -15,16 +17,33 @@ import org.keycloak.models.ModelException; import org.keycloak.models.ModelValidationException; import org.keycloak.models.RealmModel; +import org.keycloak.models.mapper.ClientModelMapper; +import org.keycloak.models.utils.KeycloakModelUtils; +import org.keycloak.models.utils.ModelToRepresentation; import org.keycloak.representations.admin.v2.BaseClientRepresentation; +import org.keycloak.representations.admin.v2.OIDCClientRepresentation; +import org.keycloak.representations.idm.ClientRepresentation; +import org.keycloak.services.RolesService; import org.keycloak.services.ServiceException; import org.keycloak.services.clientpolicy.ClientPolicyException; +import org.keycloak.services.clientpolicy.context.AdminClientRegisterContext; +import org.keycloak.services.clientpolicy.context.AdminClientRegisteredContext; import org.keycloak.services.clientpolicy.context.AdminClientUnregisterContext; +import org.keycloak.services.clientpolicy.context.AdminClientUpdateContext; +import org.keycloak.services.clientpolicy.context.AdminClientUpdatedContext; import org.keycloak.services.clientpolicy.context.AdminClientViewContext; import org.keycloak.services.managers.ClientManager; import org.keycloak.services.managers.RealmManager; import org.keycloak.services.resources.admin.AdminEventBuilder; import org.keycloak.services.resources.admin.RealmAdminResource; import org.keycloak.services.resources.admin.fgap.AdminPermissionEvaluator; +import org.keycloak.validation.ValidationUtil; +import org.keycloak.validation.jakarta.HibernateValidatorProvider; +import org.keycloak.validation.jakarta.JakartaValidatorProvider; +import org.keycloak.validation.jakarta.ValidationContext; + +import static org.keycloak.representations.admin.v2.validation.ClientSecretNotBlankValidator.isClientSecret; +import static org.keycloak.utils.StringUtil.isBlank; /** * New client service (name is just temporary) that should not rely on the Admin API v1 @@ -35,6 +54,8 @@ public class NewClientService extends DefaultClientService implements ClientServ private final KeycloakSession session; private final AdminPermissionEvaluator permissions; private final AdminEventBuilder adminEventBuilder; + private final JakartaValidatorProvider validator; + private final RolesService rolesService; public NewClientService(@Nonnull KeycloakSession session, @Nonnull RealmModel realm, @@ -45,6 +66,8 @@ public NewClientService(@Nonnull KeycloakSession session, this.session = session; this.permissions = permissions; this.adminEventBuilder = new AdminEventV2Builder(realm, permissions.adminAuth(), session, session.getContext().getConnection()).resource(ResourceType.CLIENT); + this.validator = new HibernateValidatorProvider(new ValidationContext(session, realm)); + this.rolesService = new RolesService(session, realm, permissions, adminEventBuilder); } protected Optional avoidClientIdPhishing(ClientModel client) throws ServiceException { @@ -91,6 +114,19 @@ public Stream getClients(@Nonnull RealmModel realm, } } + @Override + public BaseClientRepresentation createClient(RealmModel realm, BaseClientRepresentation client) throws ServiceException { + return createOrUpdate(realm, null, client, CreateOrUpdateStrategy.ONLY_CREATE).representation(); + } + + @Override + public CreateOrUpdateResult createOrUpdateClient(RealmModel realm, String clientId, BaseClientRepresentation client) throws ServiceException { + if (!Objects.equals(clientId, client.getClientId())) { + throw new ServiceException("Field 'clientId' in payload does not match the provided 'clientId'", Response.Status.BAD_REQUEST); + } + return createOrUpdate(realm, clientId, client, CreateOrUpdateStrategy.PUT); + } + @Override public void deleteClient(RealmModel realm, String clientId) throws ServiceException { ClientModel client = avoidClientIdPhishing(realm.getClientByClientId(clientId)) @@ -115,4 +151,99 @@ public void deleteClient(RealmModel realm, String clientId) throws ServiceExcept throw new ServiceException("Could not delete client", Response.Status.BAD_REQUEST); } } + + private CreateOrUpdateResult createOrUpdate(RealmModel realm, String clientId, BaseClientRepresentation client, CreateOrUpdateStrategy strategy) throws ServiceException { + validateUnknownFields(client); + ClientModel model = avoidClientIdPhishing(realm.getClientByClientId(clientId)).orElse(null); + boolean alreadyExists = model != null; + ClientModelMapper mapper = getMapper(client.getProtocol()); + + try { + if (alreadyExists) { + switch (strategy) { + case ONLY_CREATE -> throw new ServiceException("Client already exists", Response.Status.CONFLICT); + case PUT, PATCH -> { + // Check permissions, execute validations and trigger client policies + permissions.clients().requireConfigure(model); + validator.validate(client, strategy.getValidationGroup(), Default.class); + var proposedRepresentation = getProposedOldRepresentation(realm, client, mapper); + session.clientPolicy().triggerOnEvent(new AdminClientUpdateContext(proposedRepresentation, model, permissions.adminAuth())); + + // Update model + model = mapper.toModel(client, model); + + // Validate the fully populated model + ValidationUtil.validateClient(session, model, false, r -> { + session.getTransactionManager().setRollbackOnly(); + throw new ServiceException(r.getAllErrorsAsString(), Response.Status.BAD_REQUEST); + }); + + session.clientPolicy().triggerOnEvent(new AdminClientUpdatedContext(proposedRepresentation, model, permissions.adminAuth())); + } + } + } else { + // Check permissions, execute validations and trigger client policies + permissions.clients().requireManage(); + validator.validate(client, strategy.getValidationGroup(), Default.class); + var proposedRepresentation = getProposedOldRepresentation(realm, client, mapper); + session.clientPolicy().triggerOnEvent(new AdminClientRegisterContext(proposedRepresentation, permissions.adminAuth())); + + // Add basic attributes + model = realm.addClient(clientId); + model.setProtocol(client.getProtocol()); + + // Generate random secret if applicable + if (client.getProtocol().equals(OIDCClientRepresentation.PROTOCOL)) { + // TODO we should find a way on how to evoke it on the mapper level? + var auth = ((OIDCClientRepresentation) client).getAuth(); + if (auth != null && isClientSecret(auth.getMethod()) && isBlank(auth.getSecret())) { + auth.setSecret(KeycloakModelUtils.generateSecret(model)); + } + } + mapper.toModel(client, model); + + // Validate the fully populated model + ValidationUtil.validateClient(session, model, true, r -> { + session.getTransactionManager().setRollbackOnly(); + throw new ServiceException(r.getAllErrorsAsString(), Response.Status.BAD_REQUEST); + }); + session.clientPolicy().triggerOnEvent(new AdminClientRegisteredContext(model, permissions.adminAuth())); + } + } catch (ClientPolicyException e) { + throw new ServiceException(e.getErrorDetail(), Response.Status.BAD_REQUEST); + } + + if (model == null) { + throw new ServiceException("Cannot create/update client"); + } + + // Setup roles + var clientRoles = rolesService.resource(model); + handleRoles(clientRoles, client.getRoles()); + + // OIDC specific + if (client instanceof OIDCClientRepresentation oidcClient) { + handleServiceAccount(clientRoles, rolesService.resource(realm), model, oidcClient); + } + + fireAdminEvent(alreadyExists ? OperationType.UPDATE : OperationType.CREATE, mapper.fromModel(model)); + return new CreateOrUpdateResult(mapper.fromModel(model), !alreadyExists); + } + + /** + * Creates a temporary client to convert BaseClientRepresentation to ClientRepresentation. + * Required because client policy contexts expect ClientRepresentation (v1), but there's no + * direct converter from BaseClientRepresentation (v2 API). The temp client is immediately removed. + */ + private ClientRepresentation getProposedOldRepresentation(RealmModel realm, BaseClientRepresentation client, ClientModelMapper mapper) { + String tempId = "__temp__" + client.getClientId() + "__" + System.nanoTime(); + ClientModel tempModel = mapper.toModel(client, realm.addClient(tempId)); + try { + var proposedRepresentation = ModelToRepresentation.toRepresentation(tempModel, session); + proposedRepresentation.setClientId(client.getClientId()); + return proposedRepresentation; + } finally { + realm.removeClient(tempModel.getId()); + } + } } diff --git a/rest/admin-v2/tests/src/test/java/org/keycloak/tests/admin/client/v2/ClientPoliciesV2Test.java b/rest/admin-v2/tests/src/test/java/org/keycloak/tests/admin/client/v2/ClientPoliciesV2Test.java index 5b099da6026..f9c8b9a5b6f 100644 --- a/rest/admin-v2/tests/src/test/java/org/keycloak/tests/admin/client/v2/ClientPoliciesV2Test.java +++ b/rest/admin-v2/tests/src/test/java/org/keycloak/tests/admin/client/v2/ClientPoliciesV2Test.java @@ -152,7 +152,12 @@ public void createClientWithUnacceptableAuthType() throws Exception { // Should fail with 400 Bad Request due to policy violation assertEquals(400, response.getStatusLine().getStatusCode()); String body = EntityUtils.toString(response.getEntity()); - assertThat(body, containsString("invalid_client_metadata")); + if (ClientServiceHelper.isLegacyClientServiceEnabled()) { + assertThat(body, containsString("invalid_client_metadata")); + } else { + // TODO might be more consistent in error messages + assertThat(body, containsString("Invalid client metadata: token_endpoint_auth_method")); + } } } @@ -275,7 +280,27 @@ public void updateClientViaPutWithUnacceptableAuthType() throws Exception { // Should fail with 400 Bad Request due to policy violation assertEquals(400, response.getStatusLine().getStatusCode()); String body = EntityUtils.toString(response.getEntity()); - assertThat(body, containsString("invalid_client_metadata")); + if (ClientServiceHelper.isLegacyClientServiceEnabled()) { + assertThat(body, containsString("invalid_client_metadata")); + } else { + // TODO might be more consistent in error messages + assertThat(body, containsString("Invalid client metadata: token_endpoint_auth_method")); + } + } + + // Verify the client was NOT updated (transaction rollback worked) + HttpGet getRequest = new HttpGet(getClientsApiUrl() + "/test-put-update-client"); + setAuthHeader(getRequest); + try (var response = client.execute(getRequest)) { + assertEquals(200, response.getStatusLine().getStatusCode()); + String body = EntityUtils.toString(response.getEntity()); + OIDCClientRepresentation current = mapper.readValue(body, OIDCClientRepresentation.class); + + // Should still have the original auth method, not the rejected one + assertEquals(JWTClientSecretAuthenticator.PROVIDER_ID, current.getAuth().getMethod(), + "Client auth method should remain unchanged after policy rejection"); + assertEquals("secret", current.getAuth().getSecret(), + "Client secret should remain unchanged after policy rejection"); } } @@ -365,6 +390,21 @@ public void updateClientViaPatchWithUnacceptableAuthType() throws Exception { String body = EntityUtils.toString(response.getEntity()); assertThat(body, containsString("invalid_client_metadata")); } + + // Verify the client was NOT updated (transaction rollback worked) + HttpGet getRequest = new HttpGet(getClientsApiUrl() + "/test-patch-update-client"); + setAuthHeader(getRequest); + try (var response = client.execute(getRequest)) { + assertEquals(200, response.getStatusLine().getStatusCode()); + String body = EntityUtils.toString(response.getEntity()); + OIDCClientRepresentation current = mapper.readValue(body, OIDCClientRepresentation.class); + + // Should still have the original auth method, not the rejected one + assertEquals(JWTClientSecretAuthenticator.PROVIDER_ID, current.getAuth().getMethod(), + "Client auth method should remain unchanged after policy rejection"); + assertEquals("secret", current.getAuth().getSecret(), + "Client secret should remain unchanged after policy rejection"); + } } @@ -489,7 +529,11 @@ public void updateClientUpdateEvent() throws Exception { } // for now, the VIEW is also present, but it is not required for update - assertClientPolicyEventIsEmitted(ClientPolicyEvent.VIEW, ClientPolicyEvent.UPDATE, ClientPolicyEvent.UPDATED); + if (ClientServiceHelper.isLegacyClientServiceEnabled()) { + assertClientPolicyEventIsEmitted(ClientPolicyEvent.VIEW, ClientPolicyEvent.UPDATE, ClientPolicyEvent.UPDATED); + } else { + assertClientPolicyEventIsEmitted(ClientPolicyEvent.UPDATE, ClientPolicyEvent.UPDATED); + } } /** diff --git a/services/src/main/java/org/keycloak/services/clientpolicy/context/AdminClientUpdatedContext.java b/services/src/main/java/org/keycloak/services/clientpolicy/context/AdminClientUpdatedContext.java index 9dfda2c1314..7f3073c99ad 100644 --- a/services/src/main/java/org/keycloak/services/clientpolicy/context/AdminClientUpdatedContext.java +++ b/services/src/main/java/org/keycloak/services/clientpolicy/context/AdminClientUpdatedContext.java @@ -27,9 +27,9 @@ public class AdminClientUpdatedContext extends AbstractAdminClientCRUDContext { private final ClientRepresentation proposedClientRepresentation; private final ClientModel updatedClient; - public AdminClientUpdatedContext(ClientRepresentation roposedClientRepresentation, ClientModel updatedClient, AdminAuth adminAuth) { + public AdminClientUpdatedContext(ClientRepresentation proposedClientRepresentation, ClientModel updatedClient, AdminAuth adminAuth) { super(adminAuth); - this.proposedClientRepresentation = roposedClientRepresentation; + this.proposedClientRepresentation = proposedClientRepresentation; this.updatedClient = updatedClient; } diff --git a/services/src/main/java/org/keycloak/services/managers/ClientManager.java b/services/src/main/java/org/keycloak/services/managers/ClientManager.java index 277719e59b7..14b7677e07d 100644 --- a/services/src/main/java/org/keycloak/services/managers/ClientManager.java +++ b/services/src/main/java/org/keycloak/services/managers/ClientManager.java @@ -21,6 +21,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; @@ -233,6 +234,31 @@ public void clientIdChanged(ClientModel client, ClientRepresentation newClientRe } } + public Optional getServiceAccountUser(ClientModel client) { + UserModel user = realmManager.getSession().users().getServiceAccount(client); + if (user == null) { + if (client.isServiceAccountsEnabled()) { + enableServiceAccount(client); + user = realmManager.getSession().users().getServiceAccount(client); + } + } + return Optional.ofNullable(user); + } + + public static void updateClientServiceAccount(KeycloakSession session, ClientModel client, Boolean isServiceAccountEnabled) { + UserModel serviceAccount = session.users().getServiceAccount(client); + boolean serviceAccountScopeAssigned = client.getClientScopes(true).containsKey(ServiceAccountConstants.SERVICE_ACCOUNT_SCOPE); + if (Boolean.TRUE.equals(isServiceAccountEnabled)) { + if (serviceAccount == null || !serviceAccountScopeAssigned) { + new ClientManager(new RealmManager(session)).enableServiceAccount(client); + } + } else if (Boolean.FALSE.equals(isServiceAccountEnabled) || !client.isServiceAccountsEnabled()) { + if (serviceAccount != null || serviceAccountScopeAssigned) { + new ClientManager(new RealmManager(session)).disableServiceAccount(client); + } + } + } + @JsonPropertyOrder({"realm", "realm-public-key", "bearer-only", "auth-server-url", "ssl-required", "resource", "public-client", "verify-token-audience", "credentials", "use-resource-role-mappings"}) diff --git a/services/src/main/java/org/keycloak/services/resources/admin/ClientResource.java b/services/src/main/java/org/keycloak/services/resources/admin/ClientResource.java index b57655ee046..82b0c9a6d55 100755 --- a/services/src/main/java/org/keycloak/services/resources/admin/ClientResource.java +++ b/services/src/main/java/org/keycloak/services/resources/admin/ClientResource.java @@ -42,7 +42,6 @@ import org.keycloak.client.clienttype.ClientTypeException; import org.keycloak.common.ClientConnection; import org.keycloak.common.Profile; -import org.keycloak.common.constants.ServiceAccountConstants; import org.keycloak.common.util.Time; import org.keycloak.events.Errors; import org.keycloak.events.admin.OperationType; @@ -506,15 +505,8 @@ public ClientScopeEvaluateResource clientScopeEvaluateResource() { public UserRepresentation getServiceAccountUser() { auth.clients().requireView(client); - UserModel user = session.users().getServiceAccount(client); - if (user == null) { - if (client.isServiceAccountsEnabled()) { - new ClientManager(new RealmManager(session)).enableServiceAccount(client); - user = session.users().getServiceAccount(client); - } else { - throw new BadRequestException("Service account not enabled for the client '" + client.getClientId() + "'"); - } - } + UserModel user = new ClientManager(new RealmManager(session)).getServiceAccountUser(client) + .orElseThrow(() -> new BadRequestException("Service account not enabled for the client '" + client.getClientId() + "'")); return ModelToRepresentation.toRepresentation(session, realm, user); } @@ -864,17 +856,7 @@ public static void validateClientScopeAssignment(KeycloakSession session, Client } public static void updateClientServiceAccount(KeycloakSession session, ClientModel client, Boolean isServiceAccountEnabled) { - UserModel serviceAccount = session.users().getServiceAccount(client); - boolean serviceAccountScopeAssigned = client.getClientScopes(true).containsKey(ServiceAccountConstants.SERVICE_ACCOUNT_SCOPE); - if (Boolean.TRUE.equals(isServiceAccountEnabled)) { - if (serviceAccount == null || !serviceAccountScopeAssigned) { - new ClientManager(new RealmManager(session)).enableServiceAccount(client); - } - } else if (Boolean.FALSE.equals(isServiceAccountEnabled) || !client.isServiceAccountsEnabled()) { - if (serviceAccount != null || serviceAccountScopeAssigned) { - new ClientManager(new RealmManager(session)).disableServiceAccount(client); - } - } + ClientManager.updateClientServiceAccount(session, client, isServiceAccountEnabled); } private void updateAuthorizationSettings(ClientRepresentation rep) { 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 9cf6337a708..cc8788d656a 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 @@ -102,6 +102,15 @@ public RoleContainerResource(KeycloakSession session, UriInfo uriInfo, RealmMode this.session = session; } + public RoleContainerResource(KeycloakSession session, UriInfo uriInfo, RealmModel realm, + AdminPermissionEvaluator auth, AdminEventBuilder adminEvent) { + this(session, uriInfo, realm, auth, null, adminEvent); + } + + public void setRoleContainer(RoleContainerModel roleContainer) { + this.roleContainer = roleContainer; + } + /** * Get all roles for the realm or client * From f6287d3c77f54444dfa0a47ff14d1a49a5ba9f75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Barto=C5=A1?= Date: Fri, 27 Mar 2026 16:28:24 +0100 Subject: [PATCH 2/4] Assert same payload and path clientId for PUT/PATCH as in legacy service MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Martin Bartoš --- .../org/keycloak/services/client/NewClientService.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/rest/admin-v2/api/src/main/java/org/keycloak/services/client/NewClientService.java b/rest/admin-v2/api/src/main/java/org/keycloak/services/client/NewClientService.java index 13666473fa3..84f1ca3f7c7 100644 --- a/rest/admin-v2/api/src/main/java/org/keycloak/services/client/NewClientService.java +++ b/rest/admin-v2/api/src/main/java/org/keycloak/services/client/NewClientService.java @@ -1,6 +1,5 @@ package org.keycloak.services.client; -import java.util.Objects; import java.util.Optional; import java.util.stream.Stream; @@ -121,9 +120,6 @@ public BaseClientRepresentation createClient(RealmModel realm, BaseClientReprese @Override public CreateOrUpdateResult createOrUpdateClient(RealmModel realm, String clientId, BaseClientRepresentation client) throws ServiceException { - if (!Objects.equals(clientId, client.getClientId())) { - throw new ServiceException("Field 'clientId' in payload does not match the provided 'clientId'", Response.Status.BAD_REQUEST); - } return createOrUpdate(realm, clientId, client, CreateOrUpdateStrategy.PUT); } @@ -154,6 +150,10 @@ public void deleteClient(RealmModel realm, String clientId) throws ServiceExcept private CreateOrUpdateResult createOrUpdate(RealmModel realm, String clientId, BaseClientRepresentation client, CreateOrUpdateStrategy strategy) throws ServiceException { validateUnknownFields(client); + if (!strategy.equals(CreateOrUpdateStrategy.ONLY_CREATE)) { + assertSameClientIds(clientId, client.getClientId()); + } + ClientModel model = avoidClientIdPhishing(realm.getClientByClientId(clientId)).orElse(null); boolean alreadyExists = model != null; ClientModelMapper mapper = getMapper(client.getProtocol()); From da6469680d64e3e3a1e1ac138cdeacf0b4b38912 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Barto=C5=A1?= Date: Mon, 30 Mar 2026 12:08:49 +0200 Subject: [PATCH 3/4] Provide link to a spike around client policices rep MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Martin Bartoš --- .../java/org/keycloak/services/client/NewClientService.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/rest/admin-v2/api/src/main/java/org/keycloak/services/client/NewClientService.java b/rest/admin-v2/api/src/main/java/org/keycloak/services/client/NewClientService.java index 84f1ca3f7c7..e661bfd0725 100644 --- a/rest/admin-v2/api/src/main/java/org/keycloak/services/client/NewClientService.java +++ b/rest/admin-v2/api/src/main/java/org/keycloak/services/client/NewClientService.java @@ -234,6 +234,8 @@ private CreateOrUpdateResult createOrUpdate(RealmModel realm, String clientId, B * Creates a temporary client to convert BaseClientRepresentation to ClientRepresentation. * Required because client policy contexts expect ClientRepresentation (v1), but there's no * direct converter from BaseClientRepresentation (v2 API). The temp client is immediately removed. + *

+ * For more details, see the keycloak#47576. */ private ClientRepresentation getProposedOldRepresentation(RealmModel realm, BaseClientRepresentation client, ClientModelMapper mapper) { String tempId = "__temp__" + client.getClientId() + "__" + System.nanoTime(); From c5fb47fd86acab2c6fabac8ca81af609fedc1b30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Barto=C5=A1?= Date: Wed, 8 Apr 2026 18:06:55 +0200 Subject: [PATCH 4/4] Remove phishing check for CREATE MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Martin Bartoš --- .../org/keycloak/services/client/NewClientService.java | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/rest/admin-v2/api/src/main/java/org/keycloak/services/client/NewClientService.java b/rest/admin-v2/api/src/main/java/org/keycloak/services/client/NewClientService.java index e661bfd0725..8d3fd6bbc43 100644 --- a/rest/admin-v2/api/src/main/java/org/keycloak/services/client/NewClientService.java +++ b/rest/admin-v2/api/src/main/java/org/keycloak/services/client/NewClientService.java @@ -150,11 +150,11 @@ public void deleteClient(RealmModel realm, String clientId) throws ServiceExcept private CreateOrUpdateResult createOrUpdate(RealmModel realm, String clientId, BaseClientRepresentation client, CreateOrUpdateStrategy strategy) throws ServiceException { validateUnknownFields(client); + ClientModel model = null; if (!strategy.equals(CreateOrUpdateStrategy.ONLY_CREATE)) { assertSameClientIds(clientId, client.getClientId()); + model = avoidClientIdPhishing(realm.getClientByClientId(clientId)).orElse(null); } - - ClientModel model = avoidClientIdPhishing(realm.getClientByClientId(clientId)).orElse(null); boolean alreadyExists = model != null; ClientModelMapper mapper = getMapper(client.getProtocol()); @@ -213,10 +213,6 @@ private CreateOrUpdateResult createOrUpdate(RealmModel realm, String clientId, B throw new ServiceException(e.getErrorDetail(), Response.Status.BAD_REQUEST); } - if (model == null) { - throw new ServiceException("Cannot create/update client"); - } - // Setup roles var clientRoles = rolesService.resource(model); handleRoles(clientRoles, client.getRoles());