8000 Remove the SCIM group members or user groups listed in a PATCH remove value by Prasad484 · Pull Request #55310 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,32 @@ curl -X PATCH http://localhost:8080/realms/myrealm/scim/v2/Groups/{groupId} \
}'
----

You can also list the members to remove in the operation's `value`, without a filter in the path.
This is the form Microsoft Entra ID uses:

[source,bash]
----
curl -X PATCH http://localhost:8080/realms/myrealm/scim/v2/Groups/{groupId} \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/scim+json" \
-d '{
"schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
"Operations": [
{
"op": "remove",
"path": "members",
"value": [{"value": "{userId1}"}, {"value": "{userId2}"}]
}
]
}'
----

Removing a user that is not a member of the group succeeds and changes nothing.
If any listed user does not exist, the request is rejected with a `400 Bad Request` error and no member is removed.

NOTE: A `remove` operation on `members` cannot have both a filter in the path and a `value`.
Such a request is rejected with a `400 Bad Request` error.

=== Filtering limitations in PATCH operations

Filtering in PATCH remove operations is supported only for multivalued attributes (such as `members`).
Expand Down
22 changes: 22 additions & 0 deletions docs/documentation/server_admin/topics/scim/managing-users.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,28 @@ curl -X PATCH http://localhost:8080/realms/myrealm/scim/v2/Users/{id} \
}'
----

You can also list the groups to remove in the operation's `value`, without a filter in the path:

[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": "remove",
"path": "groups",
"value": [{"value": "{groupIdA}"}, {"value": "{groupIdB}"}]
}
]
}'
----

A `remove` operation cannot have both a filter in the path and a `value`.
Such a request is rejected with a `400 Bad Request` error.

=== Querying group membership

To retrieve a user's groups, include `groups` in the `attributes` parameter:
Expand Down
17 changes: 17 additions & 0 deletions docs/documentation/upgrading/topics/changes/changes-27_0_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -735,6 +735,23 @@ keytool -importcert -alias <server-alias> -file server.crt \

Deployments using CA-signed certificates or a truststore that already contains the server certificate are not affected.

=== SCIM PATCH removes the members or groups listed in the operation value
// https://github.com/keycloak/keycloak/issues/55307

A SCIM `PATCH` with `"op": "remove"` and a list in `value` now removes the listed entries.
On a group, `"path": "members"` removes the listed members; on a user, `"path": "groups"` removes the user from the listed groups.
Previously, {project_name} answered `200 OK` and changed nothing.
Microsoft Entra ID uses this form to remove a member from a provisioned group, so groups it manages may still hold members it already recorded as removed.
The upgrade does not remove them; review the membership of such groups after upgrading.

If a listed user or group does not exist, the request now fails with `400 Bad Request` and removes nothing.
For group members, this matches the filter form `members[value eq "<id>"]`.
A `remove` that has both a filter in its `path` and a `value` is now rejected with `400 Bad Request` for every attribute of a user or a group; previously the `value` was ignored.
An entry without a `value` is also rejected with `400 Bad Request`: a member in an `add` or a `remove` on a group, and a group in an `add`, a `remove` or a `PUT` on a user.
In an `add` or a `remove` on a multi-valued complex attribute such as `members` or `groups`, an entry that is not an object, for example `null` or a bare id, and an entry whose fields cannot be read, for example `{"value": {}}`, are now rejected with `400 Bad Request` instead of failing with `500 Internal Server Error`.
Simple multi-valued attributes, such as a custom attribute that holds strings, still accept string entries.
An `add` or a `remove` that spells such an attribute in another case, for example `"path": "Members"`, with a single object in `value` now works as the lowercase spelling does, instead of failing with `500 Internal Server Error`.

=== Hibernate second-level cache disabled
// https://github.com/keycloak/keycloak/issues/55297

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,11 @@ public Builder remove(String path) {
return this;
}

public Builder remove(String path, String value) {
operation("remove", path, value);
return this;
}

private void operation(String operation, String path, String value) {
operations.add(new PatchOperation(operation, path, value));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,16 +99,35 @@ public void add(M model, String rawPath, JsonNode value) {

@Override
public void remove(R resource, M model, String rawPath) {
remove(resource, model, rawPath, null);
}

@Override
public void remove(R resource, M model, String rawPath, JsonNode value) {
Objects.requireNonNull(model, "model cannot be null");

if (isBlank(rawPath)) {
throw new ModelValidationException("Missing path for patch operation remove");
}

Path path = new Path(this, rawPath);
boolean hasValue = value != null && !value.isNull();

if (hasValue && path.hasFilter()) {
// the two would select the values to remove in different ways, and one of them would be silently ignored
throw new ModelValidationException("Patch operation remove cannot have both a filter in the path and a value");
}

for (Entry<Attribute<M, R>, JsonNode> entry : resolveAttributes(path.getPath(), NullNode.getInstance()).entrySet()) {
setValue(model, entry.getKey(), path.getValue(entry.getKey()), REMOVE);
Attribute<M, R> attribute = entry.getKey();
JsonNode values = path.getValue(attribute);

if (hasValue && attribute.isMultivalued() && attribute.getComplexType() != null) {
// the value lists the values to remove, e.g. "members" with [{"value": "<user id>"}], normalized as for add
values = ofNullable(resolveAttributes(path.getPath(), value).get(attribute)).orElse(NullNode.getInstance());
Comment thread
Prasad484 marked this conversation as resolved.
Resolved
Comment thread
Prasad484 marked this conversation as resolved.
Resolved
}

setValue(model, attribute, values, REMOVE);
}
}

Expand Down Expand Up @@ -261,6 +280,10 @@ private Map<Attribute<M,R>, JsonNode> resolveAttributes(String path, JsonNode va
Attribute<M, R> attr = entry.getValue();

if (hasPath(attr, path)) {
if (valueJson.isObject() && attr.isMultivalued() && attr.getComplexType() != null && attr.equals(getAttributes().get(attr.getName()))) {
// another spelling of the attribute name, e.g. "Members": resolve the object as for "members" instead of unwrapping it
return resolveAttributes(attr.getName(), valueJson);
}
return Map.of(attr, resolveAttributeValue(attr, valueJson));
}
}
Expand Down Expand Up @@ -379,6 +402,15 @@ private void setValue(M model, Attribute<M, R> attribute, Object value, Operatio

JsonNode jsonValue = toJsonNode(value);

if (operation != SET && attribute.isMultivalued() && attribute.getComplexType() != null && jsonValue != null && jsonValue.isArray()) {
for (JsonNode entry : jsonValue) {
if (!entry.isObject()) {
// e.g. "members" with [null] or ["<user id>"] instead of [{"value": "<user id>"}]
throw new ModelValidationException("Each entry of " + attribute.getName() + " must be an object");
}
}
}

switch (operation) {
case SET -> attribute.set(model, jsonValue);
case ADD -> attribute.add(model, jsonValue);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,21 @@ default void remove(R resource, M model, String path) {
throw new UnsupportedOperationException("Add operation is not supported for this schema");
}

/**
* Performs a PATCH {@code remove} operation on the given {@code model} for the attribute defined by the given {@code path},
* using the operation's {@code value}, if any, to select the values to remove from a multi-valued attribute when the
* path has no filter. For example, Microsoft Entra ID removes a group member with {@code "path": "members"} and a
* {@code "value"} listing the members to remove.
*
* @param resource the resource to perform the operation on
* @param model the model to perform the operation on
* @param path the path of the attribute to perform the operation on
* @param value the value of the operation, or {@code null} if the operation has no value
*/
default void remove(R resource, M model, String path, JsonNode value) {
remove(resource, model, path);
}

/**
* Performs a PATCH {@code replace} operation on the given {@code model} for the attribute defined by the given {@code path}.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import org.keycloak.common.util.TriConsumer;
import org.keycloak.models.Model;
import org.keycloak.models.ModelValidationException;
import org.keycloak.util.JsonSerialization;

import com.fasterxml.jackson.databind.JsonNode;
Expand Down Expand Up @@ -105,21 +106,13 @@ private void setValue(M model, JsonNode value, TriConsumer<M, String, Object> mo
if (v.isValueNode()) {
values.add(v.textValue());
} else {
try {
values.add(JsonSerialization.readValue(v.toString(), complexType));
} catch (IOException e) {
throw new RuntimeException(e);
}
values.add(readComplexValue(v, complexType));
}
}
} else if (value.isTextual()) {
values.add(value.textValue());
} else if (!value.isNull()) {
try {
values.add(JsonSerialization.readValue(value.toString(), complexType));
} catch (IOException e) {
throw new RuntimeException(e);
}
values.add(readComplexValue(value, complexType));
}

modelSetter.accept(model, name, values);
Expand All @@ -131,6 +124,15 @@ private void setValue(M model, JsonNode value, TriConsumer<M, String, Object> mo
}
}

private Object readComplexValue(JsonNode value, Class<?> complexType) {
try {
return JsonSerialization.readValue(value.toString(), complexType);
} catch (IOException e) {
// e.g. "members" with [{"value": {}}], whose id cannot be read as a string
throw new ModelValidationException("Invalid value for " + attribute.getName());
}
}

void setAttribute(Attribute<M, R> attribute) {
this.attribute = attribute;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ public String getPath() {
return path;
}

public boolean hasFilter() {
return filter != null;
}

public JsonNode getValue(Attribute<?, ?> attribute) {
if (filter == null) 10BC8 {
return NullNode.getInstance();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ protected void applyPatch(R existing, M model, List<PatchOperation> operations)
switch (op.toLowerCase()) {
case "add" -> schema.add(model, path, value);
case "replace" -> schema.replace(existing, model, path, value);
case "remove" -> schema.remove(existing, model, path);
case "remove" -> schema.remove(existing, model, path, value);
default -> throw new ModelValidationException("Unsupported patch operation " + op);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,9 @@ protected Map<String, Attribute<GroupModel, Group>> getAttributeMappers() {
}

for (Member member : values) {
if (isBlank(member.getValue())) {
throw new ModelValidationException("Member value is required");
}
UserModel user = session.users().getUserById(realm, member.getValue());
if (user == null || !canViewUser(user)) {
throw new ModelValidationException("User with id " + member.getValue() + " not found");
Expand All @@ -172,6 +175,9 @@ protected Map<String, Attribute<GroupModel, Group>> getAttributeMappers() {
checkGroupMembershipPermission(session.getContext().getPermissions(), model);

for (Member member : values) {
if (isBlank(member.getValue())) {
throw new ModelValidationException("Member value is required");
}
UserModel user = session.users().getUserById(realm, member.getValue());
if (user == null || !canViewUser(user)) {
throw new ModelValidationException("User with id " + member.getValue() + " not found");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
import org.keycloak.utils.GroupUtils;
import org.keycloak.utils.KeycloakSessionUtil;

import static org.keycloak.utils.StringUtil.isBlank;

public final class UserCoreModelSchema extends AbstractUserModelSchema {

private final List<MembershipChange> membershipChanges = new ArrayList<>();
Expand Down Expand Up @@ -171,12 +173,15 @@ protected Map<String, Attribute<UserModel, User>> getAttributeMappers() {
List<GroupModel> remove = new ArrayList<>();

for (GroupUtils.GroupMembership membership : GroupUtils.getAllMemberships(session, model.getGroupsStream().toList())) {
if (values.stream().noneMatch(m -> m.getValue().equals(membership.group().getId()))) {
if (values.stream().noneMatch(m -> membership.group().getId().equals(m.getValue()))) {
remove.add(membership.group());
}
}

for (GroupMembership membership : values) {
if (isBlank(membership.getValue())) {
throw new ModelValidationException("Group value is required");
}
GroupModel group = session.groups().getGroupById(realm, membership.getValue());

if (group == null || !canViewGroup(group)) {
Expand Down Expand Up @@ -216,6 +221,9 @@ protected Map<String, Attribute<UserModel, User>> getAttributeMappers() {
checkUserMembershipPermission(session.getContext().getPermissions(), model);

for (GroupMembership membership : values) {
if (isBlank(membership.getValue())) {
throw new ModelValidationException("Group value is required");
}
GroupModel group = session.groups().getGroupById(realm, membership.getValue());

if (group == null || !canViewGroup(group)) {
Expand All @@ -235,6 +243,9 @@ protected Map<String, Attribute<UserModel, User>> getAttributeMappers() {
checkUserMembershipPermission(session.getContext().getPermissions(), model);

for (GroupMembership membership : values) {
if (isBlank(membership.getValue())) {
throw new ModelValidationException("Group value is required");
}
GroupModel group = session.groups().getGroupById(realm, membership.getValue());

if (group == null || !canViewGroup(group)) {
Expand Down
Loading
Loading
0