From 47a9712252ea5c2f732f79706f2da21b692b5403 Mon Sep 17 00:00:00 2001 From: Konstantin Kauz Date: Tue, 1 Dec 2026 09:27:09 +0400 Subject: [PATCH 1/2] Support the password attribute in the SCIM User resource The core User schema gets the password attribute of RFC 7643, Section 4.1.1: writeOnly, returned never, on POST, PUT and PATCH. It is set as the password credential once the user is persisted, as the reset password endpoint of the Admin REST API does, so the password policy of the realm applies. A policy violation or a blank password is rejected with scimType invalidValue. Write-only values are read as sent on POST and PUT, not trimmed. The Service Provider Configuration reports changePassword as supported. Closes #55680 Signed-off-by: Konstantin Kauz --- .../release_notes/topics/27_0_0.adoc | 7 + .../topics/scim/accessing-service-config.adoc | 7 +- .../topics/scim/managing-users.adoc | 42 ++++++ .../resource/schema/AbstractModelSchema.java | 17 ++- .../resource/schema/attribute/Attribute.java | 18 +++ .../spi/ScimInvalidValueException.java | 38 +++++ .../org/keycloak/scim/resource/user/User.java | 11 ++ ...iceProviderConfigResourceTypeProvider.java | 2 +- .../schema/SchemaResourceTypeProvider.java | 8 +- .../scim/model/user/UserCoreModelSchema.java | 23 +++ .../user/UserModelAttributeRecorder.java | 12 ++ .../model/user/UserResourceTypeProvider.java | 23 +++ .../org/keycloak/scim/services/Error.java | 22 ++- .../keycloak/tests/scim/tck/SchemaTest.java | 7 +- .../scim/tck/ServiceProviderConfigTest.java | 2 +- .../org/keycloak/tests/scim/tck/UserTest.java | 138 ++++++++++++++++++ 16 files changed, 357 insertions(+), 20 deletions(-) create mode 100644 scim/core/src/main/java/org/keycloak/scim/resource/spi/ScimInvalidValueException.java diff --git a/docs/documentation/release_notes/topics/27_0_0.adoc b/docs/documentation/release_notes/topics/27_0_0.adoc index 48ecfa8075a8..fb6230d3312a 100644 --- a/docs/documentation/release_notes/topics/27_0_0.adoc +++ b/docs/documentation/release_notes/topics/27_0_0.adoc @@ -13,6 +13,13 @@ This removes the need for a separate API call to discover the service account us The dedicated `GET /admin/realms/\{realm}/clients/\{id}/service-account-user` endpoint has been removed. See the upgrading guide for migration details. +== Passwords through SCIM + +The SCIM `/Users` endpoint now supports the `password` attribute of the core user schema, and the Service Provider +Configuration reports `changePassword` as supported. A provisioning client can set the password of a user when it +creates the user, with a full replace and with a `PATCH` operation. The password policy of the realm applies, and the +password is never returned. For more details, see the link:{adminguide_link}#_scim_setting_password_[{adminguide_name}]. + = Security and Standards == Post-quantum WebAuthn signatures (experimental) diff --git a/docs/documentation/server_admin/topics/scim/accessing-service-config.adoc b/docs/documentation/server_admin/topics/scim/accessing-service-config.adoc index 549c991dd71a..a302cf1b58e4 100644 --- a/docs/documentation/server_admin/topics/scim/accessing-service-config.adoc +++ b/docs/documentation/server_admin/topics/scim/accessing-service-config.adoc @@ -33,7 +33,7 @@ A successful response returns the capabilities of the SCIM API, including suppor "maxResults": 100 }, "changePassword": { - "supported": false + "supported": true }, "sort": { "supported": false @@ -63,10 +63,9 @@ capabilities defined by RFC 7644 are *not* supported in this release: are returned in the default order of the underlying store. * *ETag / resource versioning* (`etag.supported` is `false`). Resources do not carry a `meta.version`, and conditional requests such as `If-Match` are not honored. -* *Password changes* (`changePassword.supported` is `false`). The `password` attribute cannot be set or updated through - SCIM. Manage credentials through the Admin Console or the Admin REST API instead. -The `patch` and `filter` capabilities are supported. List and search requests return at most `100` results per request +The `patch`, `filter` and `changePassword` capabilities are supported. For setting passwords, see +<<_scim_setting_password_,Setting a password>>. List and search requests return at most `100` results per request (`filter.maxResults`); use pagination to retrieve additional results. See <<_scim_filtering_resources,Filtering resources>>. Future releases may allow customization of certain capabilities, such as supported authentication schemes or maximum filter results. diff --git a/docs/documentation/server_admin/topics/scim/managing-users.adoc b/docs/documentation/server_admin/topics/scim/managing-users.adoc index 24b3fdea181b..be090e46307d 100644 --- a/docs/documentation/server_admin/topics/scim/managing-users.adoc +++ b/docs/documentation/server_admin/topics/scim/managing-users.adoc @@ -43,6 +43,10 @@ given user account. When multiple email values are submitted, only the first val | `externalId` | (custom attribute) | An identifier from an external system. Requires user profile configuration. See <<_scim_mapping_attributes_,Mapping attributes>>. + +| `password` +| password credential +| Sets the password of the user. Write-only, never returned. See <<_scim_setting_password_,Setting a password>>. |=== Additional name sub-attributes (`name.middleName`, `name.honorificPrefix`, `name.honorificSuffix`) can be mapped @@ -333,6 +337,44 @@ NOTE: The `and` operator is not supported for any multivalued attributes because All other comparison operators are not supported. +[[_scim_setting_password_]] +== Setting a password + +The `password` attribute sets the password credential of the user, as the reset password endpoint of the Admin REST +API does: the new password replaces the current one, and the current password is not required. Use it from trusted +provisioning clients. The attribute is write-only (`mutability: writeOnly`, `returned: never`), so it is never +included in a response, also not when requested with the `attributes` parameter. + +The password can be set when creating a user (`POST`), with a full replace (`PUT`), and with a `PATCH` operation: + +[source,bash] +---- +curl -X PATCH http://localhost:8080/realms/myrealm/scim/v2/Users/{id} \ + -H "Authorization: Bearer $ACCESS_TOKEN" \ + -H "Content-Type: application/scim+json" \ + -d '{ + "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], + "Operations": [ + { + "op": "replace", + "path": "password", + "value": "{new-password}" + } + ] + }' +---- + +A `PUT` request without the `password` attribute keeps the current password. + +The password policy of the realm applies. A password that does not meet it, or an empty password, is rejected with a +`400 Bad Request` response and `scimType: "invalidValue"`, and the request changes nothing. + +Only the password credential is affected. Other credentials of the user, such as OTP or WebAuthn, are not managed through SCIM. + +NOTE: A password set through SCIM is always permanent. SCIM has no equivalent of a temporary password, so the +*Update Password* required action is not added to the user. To make the user choose a new password at the next login, +add the required action through the Admin Console or the Admin REST API. + == Managing group membership You can manage a user's group memberships directly through the user resource. Group membership can also be managed diff --git a/scim/core/src/main/java/org/keycloak/scim/resource/schema/AbstractModelSchema.java b/scim/core/src/main/java/org/keycloak/scim/resource/schema/AbstractModelSchema.java index cda7d6b0a27d..e7738aef821f 100644 --- a/scim/core/src/main/java/org/keycloak/scim/resource/schema/AbstractModelSchema.java +++ b/scim/core/src/main/java/org/keycloak/scim/resource/schema/AbstractModelSchema.java @@ -196,7 +196,7 @@ private void populateModel(M model, R resource) { scimName = attribute.getSimpleName(); } - Object value = getJsonValue(valueNode, scimName); + Object value = attribute.isWriteOnly() ? getRawValue(valueNode, scimName) : getJsonValue(valueNode, scimName); if (value != null) { setValue(model, attribute, value); @@ -204,6 +204,21 @@ private void populateModel(M model, R resource) { } } + /** + * Returns the value of a top-level attribute as sent, unlike {@link org.keycloak.utils.JsonUtils#getJsonValue}, + * which trims text and drops blank text. A write-only attribute such as {@code password} must reach the model + * unchanged, so that a blank value can be rejected and surrounding whitespace is kept, as with PATCH. + */ + private Object getRawValue(ObjectNode node, String name) { + JsonNode value = node.get(name); + + if (value == null || value.isNull()) { + return null; + } + + return value.isTextual() ? value.textValue() : value; + } + private void populateResourceType(R resource, M model, List requestedAttributes, List excludedAttributes) { for (Entry> entry : getAttributes().entrySet()) { Attribute attribute = entry.getValue(); diff --git a/scim/core/src/main/java/org/keycloak/scim/resource/schema/attribute/Attribute.java b/scim/core/src/main/java/org/keycloak/scim/resource/schema/attribute/Attribute.java index a2fbe4718415..732d8b3e27ee 100644 --- a/scim/core/src/main/java/org/keycloak/scim/resource/schema/attribute/Attribute.java +++ b/scim/core/src/main/java/org/keycloak/scim/resource/schema/attribute/Attribute.java @@ -180,6 +180,19 @@ public boolean isImmutable() { return Objects.equals(mutability, "immutable"); } + public boolean isWriteOnly() { + return Objects.equals(mutability, "writeOnly"); + } + + /** + * The mutability characteristic of the attribute as published in the schema (RFC 7643, Section 2.2). + * + * @return {@code immutable}, {@code writeOnly} or {@code readWrite} + */ + public String getMutability() { + return mutability == null ? "readWrite" : mutability; + } + public String getReturned() { return returned; } @@ -473,6 +486,11 @@ public Builder immutable() { return this; } + public Builder writeOnly() { + this.mutability = "writeOnly"; + return this; + } + public Builder returned(String returned) { this.returned = returned; return this; diff --git a/scim/core/src/main/java/org/keycloak/scim/resource/spi/ScimInvalidValueException.java b/scim/core/src/main/java/org/keycloak/scim/resource/spi/ScimInvalidValueException.java new file mode 100644 index 000000000000..c0cb11bc2379 --- /dev/null +++ b/scim/core/src/main/java/org/keycloak/scim/resource/spi/ScimInvalidValueException.java @@ -0,0 +1,38 @@ +/* + * Copyright 2026 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.scim.resource.spi; + +/** + * Exception thrown when a value is not acceptable for an attribute, for example a password that does not meet the + * password policy of the realm. It maps to the SCIM error type {@code invalidValue} (RFC 7644, Section 3.12). + * + *

The message may be a key of the message bundle, formatted with the given parameters. + */ +public class ScimInvalidValueException extends RuntimeException { + + private final Object[] parameters; + + public ScimInvalidValueException(String message, Object... parameters) { + super(message); + this.parameters = parameters; + } + + public Object[] getParameters() { + return parameters; + } +} diff --git a/scim/core/src/main/java/org/keycloak/scim/resource/user/User.java b/scim/core/src/main/java/org/keycloak/scim/resource/user/User.java index c81701929414..76c6dd0419d8 100644 --- a/scim/core/src/main/java/org/keycloak/scim/resource/user/User.java +++ b/scim/core/src/main/java/org/keycloak/scim/resource/user/User.java @@ -52,6 +52,9 @@ public class User extends ResourceTypeRepresentation { @JsonProperty("emails") private List emails; + @JsonProperty("password") + private String password; + @JsonProperty("groups") private List groups; @@ -226,4 +229,12 @@ public void addGroup(GroupMembership membership) { } groups.add(membership); } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } } diff --git a/scim/model/src/main/java/org/keycloak/scim/model/config/ServiceProviderConfigResourceTypeProvider.java b/scim/model/src/main/java/org/keycloak/scim/model/config/ServiceProviderConfigResourceTypeProvider.java index 7c70abf4e79a..86e091138d59 100644 --- a/scim/model/src/main/java/org/keycloak/scim/model/config/ServiceProviderConfigResourceTypeProvider.java +++ b/scim/model/src/main/java/org/keycloak/scim/model/config/ServiceProviderConfigResourceTypeProvider.java @@ -34,7 +34,7 @@ public ServiceProviderConfig getSingleton() { config.setPatch(Supported.TRUE); config.setEtag(Supported.FALSE); config.setAuthenticationSchemes(List.of()); - config.setChangePassword(Supported.FALSE); + config.setChangePassword(Supported.TRUE); config.setCreatedTimestamp(Time.currentTimeMillis()); config.setSort(Supported.FALSE); config.setFilter(getFilterSupport()); diff --git a/scim/model/src/main/java/org/keycloak/scim/model/schema/SchemaResourceTypeProvider.java b/scim/model/src/main/java/org/keycloak/scim/model/schema/SchemaResourceTypeProvider.java index 76a3a2055135..087616ffff46 100644 --- a/scim/model/src/main/java/org/keycloak/scim/model/schema/SchemaResourceTypeProvider.java +++ b/scim/model/src/main/java/org/keycloak/scim/model/schema/SchemaResourceTypeProvider.java @@ -107,7 +107,7 @@ private void buildSchema(ModelSchema modelSchema) { subAttr.setType(attribute.getType()); subAttr.setMultiValued(false); subAttr.setReturned(attribute.getReturned()); - subAttr.setMutability(attribute.isImmutable() ? "immutable" : "readWrite"); + subAttr.setMutability(attribute.getMutability()); subAttr.setCaseExact(attribute.isCaseExact()); subAttr.setUniqueness(attribute.getUniqueness()); @@ -124,7 +124,7 @@ private void buildSchema(ModelSchema modelSchema) { p.setName(k); p.setType("complex"); p.setMultiValued(attribute.isMultivalued()); - p.setMutability(attribute.isImmutable() ? "immutable" : "readWrite"); + p.setMutability(attribute.getMutability()); p.setRequired(attribute.isRequired()); p.setCaseExact(attribute.isCaseExact()); p.setUniqueness(attribute.getUniqueness()); @@ -136,7 +136,7 @@ private void buildSchema(ModelSchema modelSchema) { subAttr.setType(attribute.getType()); subAttr.setMultiValued(false); subAttr.setReturned(attribute.getReturned()); - subAttr.setMutability(attribute.isImmutable() ? "immutable" : "readWrite"); + subAttr.setMutability(attribute.getMutability()); subAttr.setRequired(attribute.isRequired()); subAttr.setCaseExact(attribute.isCaseExact()); subAttr.setUniqueness(attribute.getUniqueness()); @@ -187,7 +187,7 @@ private Attribute createTopLevelAttribute(org.keycloak.scim.resource.schema.attr attr.setType(attribute.getType()); attr.setMultiValued(attribute.isMultivalued()); attr.setReturned(attribute.getReturned()); - attr.setMutability(attribute.isImmutable() ? "immutable" : "readWrite"); + attr.setMutability(attribute.getMutability()); attr.setRequired(attribute.isRequired()); attr.setCaseExact(attribute.isCaseExact()); attr.setUniqueness(attribute.getUniqueness()); diff --git a/scim/model/src/main/java/org/keycloak/scim/model/user/UserCoreModelSchema.java b/scim/model/src/main/java/org/keycloak/scim/model/user/UserCoreModelSchema.java index 3a820205c108..bc8e9378494d 100644 --- a/scim/model/src/main/java/org/keycloak/scim/model/user/UserCoreModelSchema.java +++ b/scim/model/src/main/java/org/keycloak/scim/model/user/UserCoreModelSchema.java @@ -23,6 +23,7 @@ import org.keycloak.scim.resource.Scim; import org.keycloak.scim.resource.schema.attribute.Attribute; import org.keycloak.scim.resource.spi.MembershipChange; +import org.keycloak.scim.resource.spi.ScimInvalidValueException; import org.keycloak.scim.resource.user.Email; import org.keycloak.scim.resource.user.GroupMembership; import org.keycloak.scim.resource.user.Name; @@ -153,6 +154,28 @@ protected Map> getAttributeMappers() { } ) .build()); + // RFC 7643, Section 4.1.1: write-only and never returned. The value is staged and set as a + // credential when the user is persisted, so it passes the password policy of the realm. + attributes.addAll(Attribute.simple("password") + .writeOnly() + .returned(Attribute.RETURNED_NEVER) + .caseExact() + .modelAttributeResolver(Attribute::getName) + .withModelSetter((TriConsumer) (model, name, value) -> { + if (value == null) { + return; + } + if (!(model instanceof UserModelAttributeRecorder recorder)) { + throw new IllegalStateException("password can only be set while the user is persisted"); + } + if (value.isBlank()) { + throw new ScimInvalidValueException("password must not be blank"); + } + recorder.setPassword(value); + }, (BiConsumer) (user, value) -> { + // never returned + }) + .build()); attributes.addAll(Attribute.simple("meta.created") .timestamp() .immutable() diff --git a/scim/model/src/main/java/org/keycloak/scim/model/user/UserModelAttributeRecorder.java b/scim/model/src/main/java/org/keycloak/scim/model/user/UserModelAttributeRecorder.java index 371dfa910562..c13a72777799 100644 --- a/scim/model/src/main/java/org/keycloak/scim/model/user/UserModelAttributeRecorder.java +++ b/scim/model/src/main/java/org/keycloak/scim/model/user/UserModelAttributeRecorder.java @@ -12,6 +12,7 @@ public class UserModelAttributeRecorder extends UserModelDelegate { private final Map> attributes; + private String password; public UserModelAttributeRecorder(UserModel delegate, Map> attributes) { super(delegate); @@ -33,6 +34,17 @@ public void removeAttribute(String name) { attributes.put(name, List.of()); } + /** + * Stages a new password. It is set as a credential once the user profile is persisted. + */ + public void setPassword(String password) { + this.password = password; + } + + public String getPassword() { + return password; + } + @Override public void setUsername(String username) { setSingleAttribute(UserModel.USERNAME, username); diff --git a/scim/model/src/main/java/org/keycloak/scim/model/user/UserResourceTypeProvider.java b/scim/model/src/main/java/org/keycloak/scim/model/user/UserResourceTypeProvider.java index 0c1aa96fc3e5..9efd52a6a721 100644 --- a/scim/model/src/main/java/org/keycloak/scim/model/user/UserResourceTypeProvider.java +++ b/scim/model/src/main/java/org/keycloak/scim/model/user/UserResourceTypeProvider.java @@ -22,9 +22,11 @@ import org.keycloak.connections.jpa.JpaConnectionProvider; import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; +import org.keycloak.models.ModelException; import org.keycloak.models.ModelValidationException; import org.keycloak.models.Permissions; import org.keycloak.models.RealmModel; +import org.keycloak.models.UserCredentialModel; import org.keycloak.models.UserManager; import org.keycloak.models.UserModel; import org.keycloak.models.UserProvider; @@ -40,6 +42,7 @@ import org.keycloak.scim.resource.schema.attribute.Attribute; import org.keycloak.scim.resource.spi.AbstractScimResourceTypeProvider; import org.keycloak.scim.resource.spi.MembershipChange; +import org.keycloak.scim.resource.spi.ScimInvalidValueException; import org.keycloak.scim.resource.spi.ScimPatchException; import org.keycloak.scim.resource.spi.SearchOptions; import org.keycloak.scim.resource.user.User; @@ -166,6 +169,26 @@ private void persist(UserModelAttributeRecorder recorder) { } catch (ValidationException ve) { throw handleValidationException(ve); } + + updatePassword(recorder); + } + + private void updatePassword(UserModelAttributeRecorder recorder) { + String password = recorder.getPassword(); + + if (password == null) { + return; + } + + try { + // as the admin API does when it resets a password; the password policy of the realm applies + recorder.getDelegate().credentialManager().updateCredential(UserCredentialModel.password(password, false)); + } catch (ModelException me) { + // e.g. PasswordPolicyNotMetException; its message is a key of the message bundle + throw new ScimInvalidValueException(me.getMessage(), me.getParameters()); + } finally { + recorder.setPassword(null); + } } @Override diff --git a/scim/services/src/main/java/org/keycloak/scim/services/Error.java b/scim/services/src/main/java/org/keycloak/scim/services/Error.java index 450122620e42..208b39150f3d 100644 --- a/scim/services/src/main/java/org/keycloak/scim/services/Error.java +++ b/scim/services/src/main/java/org/keycloak/scim/services/Error.java @@ -16,6 +16,7 @@ import org.keycloak.scim.filter.ScimFilterException; import org.keycloak.scim.protocol.ForbiddenException; import org.keycloak.scim.protocol.response.ErrorResponse; +import org.keycloak.scim.resource.spi.ScimInvalidValueException; import org.keycloak.scim.resource.spi.ScimMutabilityException; import org.keycloak.scim.resource.spi.ScimPatchException; import org.keycloak.theme.Theme; @@ -29,14 +30,10 @@ class Error { static Response toResponse(KeycloakSession session, Exception e) { session.getTransactionManager().setRollbackOnly(); - if (e instanceof ModelValidationException mve) { - String language = session.getContext().getRequestHeaders().getHeaderString(HttpHeaders.ACCEPT_LANGUAGE); - Properties messages = getMessageBundle(session, language); - String format = messages.getProperty(mve.getMessage(), mve.getMessage()) - .replace("{{", "{").replace("}}", "}") - .replace("'", ""); - String message = MessageFormat.format(format, mve.getParameters()); - return invalidSyntax(message); + if (e instanceof ScimInvalidValueException ive) { + return badRequest("invalidValue", localize(session, ive.getMessage(), ive.getParameters())); + } else if (e instanceof ModelValidationException mve) { + return invalidSyntax(localize(session, mve.getMessage(), mve.getParameters())); } else if (e instanceof ModelDuplicateException) { return errorResponse(Status.CONFLICT, "uniqueness", "A resource with the same unique attribute already exists"); } else if (e instanceof ScimFilterException) { @@ -86,6 +83,15 @@ private static Response errorResponse(Status status, String detail) { return errorResponse(status, null, detail); } + private static String localize(KeycloakSession session, String key, Object[] parameters) { + String language = session.getContext().getRequestHeaders().getHeaderString(HttpHeaders.ACCEPT_LANGUAGE); + Properties messages = getMessageBundle(session, language); + String format = messages.getProperty(key, key) + .replace("{{", "{").replace("}}", "}") + .replace("'", ""); + return MessageFormat.format(format, parameters); + } + private static Properties getMessageBundle(KeycloakSession session, String lang) { try { Theme theme = session.theme().getTheme(Theme.Type.ADMIN); diff --git a/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/SchemaTest.java b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/SchemaTest.java index 70a546153235..321ad8d5b6d6 100644 --- a/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/SchemaTest.java +++ b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/SchemaTest.java @@ -105,7 +105,7 @@ public void testGetUserCoreSchema() { .map(Schema.Attribute::getName) .collect(Collectors.toSet()); - assertEquals(14, attributeNames.size(), "User schema should have exactly 14 attributes"); + assertEquals(15, attributeNames.size(), "User schema should have exactly 15 attributes"); assertAttribute(findAttribute(schema, "userName"), "string", false, true, false, "readWrite", "server"); assertAttribute(findAttribute(schema, "emails"), "complex", true, false, false, "readWrite", "global"); @@ -122,6 +122,11 @@ public void testGetUserCoreSchema() { assertAttribute(findAttribute(schema, "active"), "boolean", false, false, false, "readWrite", "none"); assertAttribute(findAttribute(schema, "groups"), "complex", true, false, false, "readWrite", "none"); + // RFC 7643, Section 4.1.1: the password is write-only and never returned + Schema.Attribute password = findAttribute(schema, "password"); + assertAttribute(password, "string", false, false, true, "writeOnly", "none"); + assertEquals("never", password.getReturned()); + // Verify name sub-attributes Schema.Attribute name = findAttribute(schema, "name"); assertNotNull(name.getSubAttributes(), "name should have sub-attributes"); diff --git a/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/ServiceProviderConfigTest.java b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/ServiceProviderConfigTest.java index a7909f0b7a3b..e9cf8e30af6f 100644 --- a/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/ServiceProviderConfigTest.java +++ b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/ServiceProviderConfigTest.java @@ -33,7 +33,7 @@ public void testFeatureDisabled() { assertFalse(etag.getSupported()); Supported changePassword = config.getChangePassword(); assertNotNull(changePassword); - assertFalse(changePassword.getSupported()); + assertTrue(changePassword.getSupported()); Supported patch = config.getPatch(); assertNotNull(patch); assertTrue(patch.getSupported()); diff --git a/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/UserTest.java b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/UserTest.java index 0f444066c55d..a2988d36a3c2 100644 --- a/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/UserTest.java +++ b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/UserTest.java @@ -23,6 +23,7 @@ import org.keycloak.events.admin.ResourceType; import org.keycloak.http.simple.SimpleHttp; import org.keycloak.http.simple.SimpleHttpResponse; +import org.keycloak.models.UserCredentialModel; import org.keycloak.models.UserModel; import org.keycloak.models.UserModel.UserRemovedEvent; import org.keycloak.models.utils.KeycloakModelUtils; @@ -799,6 +800,123 @@ public void testDeleteFiresUserRemovedEvent() { runOnServer.run(assertUserRemovedEventFired()); } + @Test + public void testCreateWithPassword() { + String password = KeycloakModelUtils.generateId(); + User expected = createUser(); + expected.setPassword(password); + + User created = client.users().create(expected); + + // RFC 7643, Section 4.1.1: the password is never returned + assertNull(created.getPassword()); + assertNull(client.users().get(created.getId()).getPassword()); + assertPassword(created.getId(), password); + + // a password credential, not a user attribute + assertEquals(List.of("password"), realm.admin().users().get(created.getId()).credentials().stream() + .map(credential -> credential.getType()) + .toList()); + assertFalse(ofNullable(realm.admin().users().get(created.getId()).toRepresentation().getAttributes()) + .map(attributes -> attributes.containsKey("password")) + .orElse(false)); + } + + @Test + public void testReplaceWithPassword() { + String password = KeycloakModelUtils.generateId(); + User user = createUser(); + user.setPassword(password); + User created = client.users().create(user); + + // a full replace without the password keeps it + created.setPassword(null); + created.setDisplayName("Replaced"); + User replaced = client.users().update(created); + assertNull(replaced.getPassword()); + assertPassword(created.getId(), password); + + String newPassword = KeycloakModelUtils.generateId(); + created.setPassword(newPassword); + replaced = client.users().update(created); + assertNull(replaced.getPassword()); + assertPassword(created.getId(), newPassword); + assertNotPassword(created.getId(), password); + } + + @Test + public void testPatchPassword() { + String password = KeycloakModelUtils.generateId(); + User user = createUser(); + user.setPassword(password); + User created = client.users().create(user); + + String newPassword = KeycloakModelUtils.generateId(); + client.users().patch(created.getId(), PatchRequest.create() + .replace("password", newPassword) + .build()); + + assertNull(client.users().get(created.getId()).getPassword()); + assertPassword(created.getId(), newPassword); + assertNotPassword(created.getId(), password); + } + + @Test + public void testPasswordPolicyViolation() { + realm.updateWithCleanup(r -> r.passwordPolicy("length(12)")); + + // create: rejected, and the user is not created + User user = createUser(); + user.setPassword("short"); + ScimClientException sce = assertThrows(ScimClientException.class, () -> client.users().create(user)); + assertInvalidValue(sce); + assertTrue(realm.admin().users().search(user.getUserName(), true).isEmpty()); + + String password = KeycloakModelUtils.generateId(); + user.setPassword(password); + User created = client.users().create(user); + + // full replace: rejected, the password is unchanged + created.setPassword("short"); + sce = assertThrows(ScimClientException.class, () -> client.users().update(created)); + assertInvalidValue(sce); + assertPassword(created.getId(), password); + + // patch: rejected, the password is unchanged + sce = assertThrows(ScimClientException.class, () -> client.users().patch(created.getId(), PatchRequest.create() + .replace("password", "short") + .build())); + assertInvalidValue(sce); + assertPassword(created.getId(), password); + } + + @Test + public void testPasswordKeptAsSent() { + // surrounding whitespace is part of the password, on create as with PATCH + String password = " " + KeycloakModelUtils.generateId() + " "; + User user = createUser(); + user.setPassword(password); + User created = client.users().create(user); + assertPassword(created.getId(), password); + assertNotPassword(created.getId(), password.trim()); + + String newPassword = " " + KeycloakModelUtils.generateId() + " "; + client.users().patch(created.getId(), PatchRequest.create() + .replace("password", newPassword) + .build()); + assertPassword(created.getId(), newPassword); + assertNotPassword(created.getId(), newPassword.trim()); + } + + @Test + public void testBlankPassword() { + User user = createUser(); + user.setPassword(" "); + ScimClientException sce = assertThrows(ScimClientException.class, () -> client.users().create(user)); + assertInvalidValue(sce); + assertTrue(realm.admin().users().search(user.getUserName(), true).isEmpty()); + } + @Test public void testError() { User user = client.users().create(createUser()); @@ -3621,6 +3739,26 @@ private void unregisterProviderEventListener() { }); } + private void assertPassword(String userId, String password) { + runOnServer.run(session -> assertTrue(session.users() + .getUserById(session.getContext().getRealm(), userId) + .credentialManager().isValid(UserCredentialModel.password(password)))); + } + + private void assertNotPassword(String userId, String password) { + runOnServer.run(session -> assertFalse(session.users() + .getUserById(session.getContext().getRealm(), userId) + .credentialManager().isValid(UserCredentialModel.password(password)))); + } + + private static void assertInvalidValue(ScimClientException sce) { + ErrorResponse error = sce.getError(); + assertNotNull(error); + assertEquals(400, error.getStatusInt()); + assertEquals("invalidValue", error.getScimType()); + assertNotNull(error.getDetail()); + } + private static RunOnServer assertUserRemovedEventFired() { return session -> assertFalse(ProviderEventCollector.getInstance().getEvents(UserRemovedEvent.class).isEmpty(), "User removed event was not fired"); } From 582d31b5cad6cca7efb45d0c23dffe93f01a4bf4 Mon Sep 17 00:00:00 2001 From: Konstantin Kauz Date: Tue, 1 Dec 2026 09:42:20 +0400 Subject: [PATCH 2/2] Require reset-password for SCIM passwords and reject their removal Setting a password through SCIM now needs the reset-password permission on the user, as the Admin REST API does; managing the user is not enough. A PATCH remove of the password is rejected with scimType invalidValue instead of being ignored, also after an add in the same request. A PATCH replace still works: its remove is followed by the new password. Closes #55680 Signed-off-by: Konstantin Kauz --- .../scim/model/user/UserCoreModelSchema.java | 7 +++ .../user/UserModelAttributeRecorder.java | 18 ++++++ .../model/user/UserResourceTypeProvider.java | 15 ++++- .../tests/scim/tck/AuthorizationTest.java | 55 +++++++++++++++++++ .../org/keycloak/tests/scim/tck/UserTest.java | 24 ++++++++ .../keycloak/services/DefaultPermissions.java | 2 + 6 files changed, 120 insertions(+), 1 deletion(-) diff --git a/scim/model/src/main/java/org/keycloak/scim/model/user/UserCoreModelSchema.java b/scim/model/src/main/java/org/keycloak/scim/model/user/UserCoreModelSchema.java index bc8e9378494d..09b1856e1d0b 100644 --- a/scim/model/src/main/java/org/keycloak/scim/model/user/UserCoreModelSchema.java +++ b/scim/model/src/main/java/org/keycloak/scim/model/user/UserCoreModelSchema.java @@ -175,6 +175,13 @@ protected Map> getAttributeMappers() { }, (BiConsumer) (user, value) -> { // never returned }) + // PATCH remove, also as the first half of a PATCH replace; rejected when the user is persisted + // unless a new password follows + .withModelRemover((model, name, values) -> { + if (model instanceof UserModelAttributeRecorder recorder) { + recorder.removePassword(); + } + }) .build()); attributes.addAll(Attribute.simple("meta.created") .timestamp() diff --git a/scim/model/src/main/java/org/keycloak/scim/model/user/UserModelAttributeRecorder.java b/scim/model/src/main/java/org/keycloak/scim/model/user/UserModelAttributeRecorder.java index c13a72777799..9c5be7fc3186 100644 --- a/scim/model/src/main/java/org/keycloak/scim/model/user/UserModelAttributeRecorder.java +++ b/scim/model/src/main/java/org/keycloak/scim/model/user/UserModelAttributeRecorder.java @@ -13,6 +13,7 @@ public class UserModelAttributeRecorder extends UserModelDelegate { private final Map> attributes; private String password; + private boolean passwordRemoved; public UserModelAttributeRecorder(UserModel delegate, Map> attributes) { super(delegate); @@ -39,6 +40,23 @@ public void removeAttribute(String name) { */ public void setPassword(String password) { this.password = password; + this.passwordRemoved = false; + } + + /** + * Records a PATCH remove of the password and drops a password staged before it. A PATCH replace is a remove + * followed by an add, which stages the new password again. + */ + public void removePassword() { + this.password = null; + this.passwordRemoved = true; + } + + /** + * Returns {@code true} if the password was removed and no new one was staged after that. + */ + public boolean isPasswordRemoved() { + return passwordRemoved; } public String getPassword() { diff --git a/scim/model/src/main/java/org/keycloak/scim/model/user/UserResourceTypeProvider.java b/scim/model/src/main/java/org/keycloak/scim/model/user/UserResourceTypeProvider.java index 9efd52a6a721..9a097f889507 100644 --- a/scim/model/src/main/java/org/keycloak/scim/model/user/UserResourceTypeProvider.java +++ b/scim/model/src/main/java/org/keycloak/scim/model/user/UserResourceTypeProvider.java @@ -174,15 +174,28 @@ private void persist(UserModelAttributeRecorder recorder) { } private void updatePassword(UserModelAttributeRecorder recorder) { + if (recorder.isPasswordRemoved()) { + // SCIM sets or replaces the password, it does not delete the credential + throw new ScimInvalidValueException("password cannot be removed"); + } + String password = recorder.getPassword(); if (password == null) { return; } + UserModel user = recorder.getDelegate(); + + // as the admin API: managing a user does not imply resetting its password + if (!session.getContext().getPermissions().hasPermission(user, AdminPermissionsSchema.USERS_RESOURCE_TYPE, AdminPermissionsSchema.RESET_PASSWORD)) { + recorder.setPassword(null); + throw new ForbiddenException(); + } + try { // as the admin API does when it resets a password; the password policy of the realm applies - recorder.getDelegate().credentialManager().updateCredential(UserCredentialModel.password(password, false)); + user.credentialManager().updateCredential(UserCredentialModel.password(password, false)); } catch (ModelException me) { // e.g. PasswordPolicyNotMetException; its message is a key of the message bundle throw new ScimInvalidValueException(me.getMessage(), me.getParameters()); diff --git a/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/AuthorizationTest.java b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/AuthorizationTest.java index a39f15450c35..76a62ab46db3 100644 --- a/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/AuthorizationTest.java +++ b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/AuthorizationTest.java @@ -583,6 +583,61 @@ public void testGroupMembersAddDeniedWithoutUserViewFGAP() { assertEquals(Status.BAD_REQUEST.getStatusCode(), exception.getError().getStatusInt()); } + @Test + public void testPasswordDeniedWithoutResetPasswordFGAP() { + RealmRepresentation realmRep = this.realm.admin().toRepresentation(); + realmRep.setAdminPermissionsEnabled(true); + realm.admin().update(realmRep); + + UserPolicyRepresentation policy = createUserPolicy(getServiceAccount().getId()); + // a policy that does not apply to the SCIM client: reset-password is denied explicitly + UserPolicyRepresentation otherPolicy = createUserPolicy(managedUser.getId()); + + createPermission(AdminPermissionsSchema.USERS_RESOURCE_TYPE, + Set.of(managedUser.getId()), + Set.of(AdminPermissionsSchema.MANAGE, AdminPermissionsSchema.VIEW), + policy.getName()); + createPermission(AdminPermissionsSchema.USERS_RESOURCE_TYPE, + Set.of(managedUser.getId()), + Set.of(AdminPermissionsSchema.RESET_PASSWORD), + otherPolicy.getName()); + + // managing the user is allowed + noAccessClient.users().patch(managedUser.getId(), PatchRequest.create() + .replace("name.givenName", "Changed") + .build()); + assertEquals("Changed", realm.admin().users().get(managedUser.getId()).toRepresentation().getFirstName()); + + // setting its password is not, as with the admin API + assertAccessDenied(() -> noAccessClient.users().patch(managedUser.getId(), PatchRequest.create() + .replace("password", KeycloakModelUtils.generateId()) + .build())); + User user = noAccessClient.users().get(managedUser.getId()); + user.setPassword(KeycloakModelUtils.generateId()); + user.setTitle("Denied"); + assertAccessDenied(() -> noAccessClient.users().update(user)); + assertTrue(realm.admin().users().get(managedUser.getId()).credentials().isEmpty()); + } + + @Test + public void testPasswordAllowedWithResetPasswordFGAP() { + RealmRepresentation realmRep = this.realm.admin().toRepresentation(); + realmRep.setAdminPermissionsEnabled(true); + realm.admin().update(realmRep); + + UserPolicyRepresentation policy = createUserPolicy(getServiceAccount().getId()); + + createPermission(AdminPermissionsSchema.USERS_RESOURCE_TYPE, + Set.of(managedUser.getId()), + Set.of(AdminPermissionsSchema.MANAGE, AdminPermissionsSchema.VIEW, AdminPermissionsSchema.RESET_PASSWORD), + policy.getName()); + + noAccessClient.users().patch(managedUser.getId(), PatchRequest.create() + .replace("password", KeycloakModelUtils.generateId()) + .build()); + assertEquals(1, realm.admin().users().get(managedUser.getId()).credentials().size()); + } + @Test public void testGroupMembershipDeniedWithoutManageGroupMembershipFGAP() { RealmRepresentation realmRep = this.realm.admin().toRepresentation(); diff --git a/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/UserTest.java b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/UserTest.java index a2988d36a3c2..f09acbd9a491 100644 --- a/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/UserTest.java +++ b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/UserTest.java @@ -908,6 +908,30 @@ public void testPasswordKeptAsSent() { assertNotPassword(created.getId(), newPassword.trim()); } + @Test + public void testRemovePasswordRejected() { + String password = KeycloakModelUtils.generateId(); + User user = createUser(); + user.setPassword(password); + User created = client.users().create(user); + + ScimClientException sce = assertThrows(ScimClientException.class, () -> client.users().patch(created.getId(), PatchRequest.create() + .remove("password") + .build())); + assertInvalidValue(sce); + assertPassword(created.getId(), password); + + // a remove does not go through after a password was staged by the same request either + String newPassword = KeycloakModelUtils.generateId(); + sce = assertThrows(ScimClientException.class, () -> client.users().patch(created.getId(), PatchRequest.create() + .add("password", newPassword) + .remove("password") + .build())); + assertInvalidValue(sce); + assertPassword(created.getId(), password); + assertNotPassword(created.getId(), newPassword); + } + @Test public void testBlankPassword() { User user = createUser(); diff --git a/services/src/main/java/org/keycloak/services/DefaultPermissions.java b/services/src/main/java/org/keycloak/services/DefaultPermissions.java index 66d929c85862..b546d13f4c8c 100644 --- a/services/src/main/java/org/keycloak/services/DefaultPermissions.java +++ b/services/src/main/java/org/keycloak/services/DefaultPermissions.java @@ -108,6 +108,8 @@ private boolean evaluateUserPermission(Model model, String scope) { return model == null ? users.canManage() : users.canManage((UserModel) model); } else if (AdminPermissionsSchema.MANAGE_GROUP_MEMBERSHIP.equals(scope)) { return model != null && users.canManageGroupMembership((UserModel) model); + } else if (AdminPermissionsSchema.RESET_PASSWORD.equals(scope)) { + return model != null && users.canResetPassword((UserModel) model); } else if (AdminPermissionsSchema.QUERY.equals(scope)) { return users.canQuery(); }