diff --git a/common/src/main/java/org/keycloak/common/Profile.java b/common/src/main/java/org/keycloak/common/Profile.java
index 2c71620f48f0..010e497a22eb 100755
--- a/common/src/main/java/org/keycloak/common/Profile.java
+++ b/common/src/main/java/org/keycloak/common/Profile.java
@@ -205,6 +205,8 @@ public enum Feature {
SCIM_API("Exposes a SCIM API for managing realm resources on a per-realm basis", Type.DEFAULT),
+ SCIM_GROUP_MEMBERSHIP_CLAIMS("Groups owned by the SCIM client that created them, with full member lists on PUT", Type.EXPERIMENTAL, SCIM_API),
+
RESOURCE_INDICATORS("Resource Indicators for OAuth 2.0", Type.EXPERIMENTAL),
IDENTITY_BROKERING_API_V1("Identity Brokering API V1", Type.DEFAULT, 1, true, null, null),
diff --git a/docs/documentation/server_admin/topics/scim/managing-groups.adoc b/docs/documentation/server_admin/topics/scim/managing-groups.adoc
index 2bf04737cd91..b066abfce963 100644
--- a/docs/documentation/server_admin/topics/scim/managing-groups.adoc
+++ b/docs/documentation/server_admin/topics/scim/managing-groups.adoc
@@ -46,6 +46,7 @@ A successful response returns the created group with a `201 Created` status.
NOTE: Group members cannot be specified during group creation. Attempting to include members in the `POST`
request results in a `400 Bad Request` error. Use the `PATCH` method to add members after creating the group.
+Realms where groups are owned by a SCIM client accept members on `POST`. See <<_scim_membership_claims_,Groups owned by a SCIM client>>.
If a group with the same `displayName` already exists, the API returns a `409 Conflict` response with
`scimType: "uniqueness"`.
@@ -93,6 +94,8 @@ curl -X PUT http://localhost:8080/realms/myrealm/scim/v2/Groups/{id} \
NOTE: Group members cannot be modified through `PUT` requests. Attempting to include members in the `PUT`
request results in a `400 Bad Request` error. Use the `PATCH` method to manage group members.
+Realms where groups are owned by a SCIM client accept `members` on `PUT` from the client that owns the group. See
+<<_scim_membership_claims_,Groups owned by a SCIM client>>.
== Partially updating a group
@@ -232,6 +235,85 @@ NOTE: Organization-related groups cannot have their members managed through the
remove members from an organization group returns a `400 Bad Request` error. Use the Organization API to manage
organization group memberships.
+[[_scim_membership_claims_]]
+=== Groups owned by a SCIM client
+
+Some identity providers send the full member list of a group on every update, with `PUT`. Okta applications built
+with the App Integration Wizard work this way and cannot be switched to `PATCH`. A realm can accept these requests
+by letting the SCIM client that creates a group own it. Two switches must both be on:
+
+* the experimental server feature `scim-group-membership-claims`, for example `--features=scim-group-membership-claims`;
+* the realm attribute `scimGroupMembershipClaims`, set to `true`.
+
+Both are off by default. While either is off, the SCIM endpoints behave as described in the rest of this chapter.
+
+The realm attribute has no toggle in the Admin Console. Set it with the Admin REST API. A realm update replaces the
+realm's attributes with the ones it sends, so read the realm first, add the attribute, and send the whole
+representation back:
+
+[source,bash]
+----
+curl -s http://localhost:8080/admin/realms/myrealm \
+ -H "Authorization: Bearer $ADMIN_TOKEN" \
+ | jq '.attributes.scimGroupMembershipClaims = "true"' \
+ | curl -X PUT http://localhost:8080/admin/realms/myrealm \
+ -H "Authorization: Bearer $ADMIN_TOKEN" \
+ -H "Content-Type: application/json" \
+ -d @-
+----
+
+To turn it off, set the attribute to `false` the same way.
+
+When it is on, the SCIM client that creates a group with `POST /Groups` owns that group. The client is the one the
+access token was issued to. {project_name} stores the owner by the client's Client ID. The rules are:
+
+* A `POST` can include `members`. The group is created with them, and the caller becomes its owner.
+* The owner can send the full member list with `PUT`, or with a `PATCH` that replaces `members`. A `replace` with no
+ path, or with the Group schema URN as its path, and `members` in its `value` counts the same. {project_name} adds
+ the listed users who are not members yet, and removes the members who are not listed.
+* The owner can also use `PATCH` `add` and `remove`. A `remove` can name the members with a
+ `members[value eq "{userId}"]` filter in the path or, as Microsoft Entra ID does, with a `value` listing them.
+ A `remove` on `members` with neither removes every member that the owner may remove. An empty `value` list
+ removes nobody.
+* Service accounts and administrators stay in the group. When the owner's full list leaves one out, that member is
+ kept, the rest of the request is applied, and the request succeeds. A request that names one in an `add` or a
+ `remove`, or lists one who is not a member yet, is rejected with a `400 Bad Request` or `403 Forbidden` error, as
+ in a realm without owners. Listing one who is already a member changes nothing and is accepted.
+* A listed user that does not exist rejects the whole request. Every member in a request is checked before anything
+ changes. If one member is invalid, nothing in the request is applied.
+* Requests that change the members of the same group are processed one after the other.
+* Any other SCIM client that sends a `PUT`, a `PATCH` or a `DELETE` for an owned group gets a `403 Forbidden` error
+ saying that the group is managed by another SCIM client. Deleting a group deletes its subgroups, so a client also
+ gets a `403 Forbidden` error when it deletes a group that has a group owned by another client anywhere below it.
+* A user's `groups` cannot be used to change the members of an owned group, as RFC 7643 section 4.1.2 describes.
+ A `POST`, `PUT` or `PATCH` on `/Users` that would add the user to an owned group, or remove the user from one, is
+ rejected with a `400 Bad Request` error and `scimType: "mutability"`. A request that sends no `groups`, or that
+ sends the user's current direct groups unchanged, is accepted. Changes to groups that no SCIM client owns work as
+ before.
+* A read of an owned group shows every member to every client, without `attributes=members`. A client that pushes a
+ full member list therefore reads back the full list. Members are left out when the request excludes them
+ (`excludedAttributes=members`), or when `attributes` names other attributes but not `members`.
+
+A group that no SCIM client owns behaves as described in the rest of this chapter. Such a group was created before
+the switches were turned on, or by an administrator. Any SCIM client can change its members with `PATCH` `add` and
+`remove`, a `PUT` with `members` is rejected, and any SCIM client with permission to manage groups can delete it.
+A client never becomes the owner of an existing group. An identity provider that offers to link a group it pushes to
+an existing group, as Okta does, cannot manage that group's members with full lists. Let the identity provider
+create the group instead.
+
+The owner is stored by Client ID, so it outlives the client. If the owning client is deleted, its groups keep the
+owner, and no other SCIM client can change or delete them. A client created again with the same Client ID owns them
+again. Renaming a client's Client ID has the same effect as deleting it: its groups have no reachable owner until a
+client with the old Client ID exists again.
+
+Administrators are not limited by these rules yet. An administrator can change the members of an owned group in the
+Admin Console or with the Admin REST API. The owner's next full list, sent with `PUT` or with a `PATCH` that replaces
+`members`, then overwrites that change, except for service accounts and administrators, who stay.
+
+NOTE: Memberships stored outside the {project_name} database, for example by an LDAP group mapper, cannot be
+managed this way. A request that would remove one is rejected before anything changes. A request that would add one
+returns an error, but a change already written to the external store is not undone.
+
== Deleting a group
[source,bash]
diff --git a/docs/documentation/server_admin/topics/scim/managing-users.adoc b/docs/documentation/server_admin/topics/scim/managing-users.adoc
index ae1511b535c3..06544fd80f99 100644
--- a/docs/documentation/server_admin/topics/scim/managing-users.adoc
+++ b/docs/documentation/server_admin/topics/scim/managing-users.adoc
@@ -338,6 +338,10 @@ All other comparison operators are not supported.
You can manage a user's group memberships directly through the user resource. Group membership can also be managed
from the group side using the `/Groups` endpoint. See <<_scim_managing_groups_,Managing groups>> for details.
+NOTE: In a realm where groups are owned by a SCIM client, a request in this section that would add a user to an
+owned group, or remove the user from one, is rejected with a `400 Bad Request` error and `scimType: "mutability"`.
+Groups that no SCIM client owns are not affected. See <<_scim_membership_claims_,Groups owned by a SCIM client>>.
+
=== Adding a user to groups on creation
When creating a user, you can specify the groups the user should belong to:
diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/entities/ScimGroupOwnerEntity.java b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/ScimGroupOwnerEntity.java
new file mode 100644
index 000000000000..e4ac94d15ccd
--- /dev/null
+++ b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/ScimGroupOwnerEntity.java
@@ -0,0 +1,73 @@
+/*
+ * 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.models.jpa.entities;
+
+import java.util.Objects;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
+
+/**
+ * The SCIM client that created a group, and so owns it.
+ *
+ *
The owner is stored by the client's {@code clientId}, not by its internal id, and has no foreign key to the
+ * client. Deleting the client keeps the row, and a client created again with the same {@code clientId} owns the group
+ * again. The database removes the row together with the group. A group without a row was created some other way, for
+ * example by an administrator, or before the realm turned ownership on.
+ */
+@Entity
+@Table(name = "SCIM_GROUP_OWNER")
+public class ScimGroupOwnerEntity {
+
+ @Id
+ @Column(name = "GROUP_ID", length = 36)
+ protected String groupId;
+
+ @Column(name = "CLIENT_ID", nullable = false)
+ protected String clientId;
+
+ public ScimGroupOwnerEntity() {
+ }
+
+ public ScimGroupOwnerEntity(String groupId, String clientId) {
+ this.groupId = groupId;
+ this.clientId = clientId;
+ }
+
+ public String getGroupId() {
+ return groupId;
+ }
+
+ public String getClientId() {
+ return clientId;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof ScimGroupOwnerEntity that)) return false;
+ return Objects.equals(groupId, that.groupId);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hashCode(groupId);
+ }
+}
diff --git a/model/jpa/src/main/resources/META-INF/jpa-changelog-27.0.0.xml b/model/jpa/src/main/resources/META-INF/jpa-changelog-27.0.0.xml
index 7cc9cbf148a2..d37026d182ab 100644
--- a/model/jpa/src/main/resources/META-INF/jpa-changelog-27.0.0.xml
+++ b/model/jpa/src/main/resources/META-INF/jpa-changelog-27.0.0.xml
@@ -25,4 +25,26 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/scim/core/src/main/java/org/keycloak/scim/protocol/ForbiddenException.java b/scim/core/src/main/java/org/keycloak/scim/protocol/ForbiddenException.java
index 1625537d645c..93d6fd557eb4 100644
--- a/scim/core/src/main/java/org/keycloak/scim/protocol/ForbiddenException.java
+++ b/scim/core/src/main/java/org/keycloak/scim/protocol/ForbiddenException.java
@@ -5,4 +5,13 @@
*/
public class ForbiddenException extends RuntimeException{
+ public ForbiddenException() {
+ }
+
+ /**
+ * @param message the detail returned to the caller in the error response
+ */
+ public ForbiddenException(String message) {
+ super(message);
+ }
}
diff --git a/scim/core/src/main/java/org/keycloak/scim/resource/spi/BaseResourceTypeProvider.java b/scim/core/src/main/java/org/keycloak/scim/resource/spi/BaseResourceTypeProvider.java
index 39fdf5cfd51d..4810292c7a02 100644
--- a/scim/core/src/main/java/org/keycloak/scim/resource/spi/BaseResourceTypeProvider.java
+++ b/scim/core/src/main/java/org/keycloak/scim/resource/spi/BaseResourceTypeProvider.java
@@ -111,6 +111,14 @@ public Stream getAll(SearchOptions searchOptions) {
}
}
+ return render(models, searchOptions);
+ }
+
+ /**
+ * Turns the models for one page into representations. A resource type that needs something about the whole page,
+ * such as one query for every id on it, overrides this instead of querying once per model.
+ */
+ protected Stream render(Stream models, SearchOptions searchOptions) {
return models.map(m -> createResourceTypeInstance(m, searchOptions.getAttributes(), searchOptions.getExcludedAttributes()));
}
diff --git a/scim/core/src/main/java/org/keycloak/scim/resource/spi/ScimResourceTypeProvider.java b/scim/core/src/main/java/org/keycloak/scim/resource/spi/ScimResourceTypeProvider.java
index db0d440977d7..186b98f97a43 100644
--- a/scim/core/src/main/java/org/keycloak/scim/resource/spi/ScimResourceTypeProvider.java
+++ b/scim/core/src/main/java/org/keycloak/scim/resource/spi/ScimResourceTypeProvider.java
@@ -156,6 +156,14 @@ default List pollMembershipChanges() {
return List.of();
}
+ /**
+ * Returns the group membership changes made by the last {@link #create} call that the caller should record as
+ * {@code GROUP_MEMBERSHIP} admin events, then clears them. By default a create reports none.
+ */
+ default List pollCreateMembershipChanges() {
+ return List.of();
+ }
+
/**
* Returns the admin event {@link ResourceType} for this SCIM resource type.
* By default, derives it from {@link #getName()} by converting to uppercase and matching against known values.
diff --git a/scim/model/src/main/java/org/keycloak/scim/model/group/GroupCoreModelSchema.java b/scim/model/src/main/java/org/keycloak/scim/model/group/GroupCoreModelSchema.java
index 4ef11c59b48a..5385444ba12d 100644
--- a/scim/model/src/main/java/org/keycloak/scim/model/group/GroupCoreModelSchema.java
+++ b/scim/model/src/main/java/org/keycloak/scim/model/group/GroupCoreModelSchema.java
@@ -214,6 +214,29 @@ void clearMembershipChanges() {
membershipChanges.clear();
}
+ void recordMembershipChange(MembershipChange change) {
+ membershipChanges.add(change);
+ }
+
+ /**
+ * The members of {@code model} as a read that asks for {@code members} returns them.
+ */
+ List readMembers(GroupModel model) {
+ @SuppressWarnings("unchecked")
+ List users = (List) getAttributeValue(model, "members");
+ List members = new ArrayList<>();
+
+ for (UserModel user : users) {
+ Member member = new Member();
+ member.setValue(user.getId());
+ member.setDisplay(user.getUsername());
+ member.setType("User");
+ members.add(member);
+ }
+
+ return members;
+ }
+
private void setTimestamps(Group resource, GroupModel model) {
Long createdTimestamp = model.getCreatedTimestamp();
if (createdTimestamp != null) {
@@ -225,7 +248,7 @@ private void setTimestamps(Group resource, GroupModel model) {
}
}
- private static void checkGroupMembershipPermission(Permissions permissions, GroupModel group) {
+ static void checkGroupMembershipPermission(Permissions permissions, GroupModel group) {
if (GroupModel.Type.ORGANIZATION.equals(group.getType()) && group.getOrganization() != null) {
throw new ModelValidationException("Invalid group");
}
@@ -237,7 +260,7 @@ private static void checkGroupMembershipPermission(Permissions permissions, Grou
}
}
- private void checkRequireManageGroupMembership(Permissions permissions, UserModel model) {
+ void checkRequireManageGroupMembership(Permissions permissions, UserModel model) {
if (model.isServiceAccount()) {
throw new ForbiddenException();
}
@@ -261,7 +284,7 @@ private void checkGroupHasNoServiceAccounts(RealmModel realm, GroupModel group)
.forEach(subGroup -> checkGroupHasNoServiceAccounts(realm, subGroup));
}
- private boolean canViewUser(UserModel u) {
+ boolean canViewUser(UserModel u) {
if (u.isServiceAccount()) {
return false;
}
diff --git a/scim/model/src/main/java/org/keycloak/scim/model/group/GroupOwnership.java b/scim/model/src/main/java/org/keycloak/scim/model/group/GroupOwnership.java
new file mode 100644
index 000000000000..6bff18e61900
--- /dev/null
+++ b/scim/model/src/main/java/org/keycloak/scim/model/group/GroupOwnership.java
@@ -0,0 +1,389 @@
+/*
+ * 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.model.group;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.LockModeType;
+
+import org.keycloak.Token;
+import org.keycloak.common.Profile;
+import org.keycloak.connections.jpa.JpaConnectionProvider;
+import org.keycloak.models.ClientModel;
+import org.keycloak.models.GroupModel;
+import org.keycloak.models.KeycloakSession;
+import org.keycloak.models.ModelValidationException;
+import org.keycloak.models.RealmModel;
+import org.keycloak.models.UserModel;
+import org.keycloak.models.cache.UserCache;
+import org.keycloak.models.jpa.entities.GroupEntity;
+import org.keycloak.models.jpa.entities.ScimGroupOwnerEntity;
+import org.keycloak.representations.AccessToken;
+import org.keycloak.scim.protocol.ForbiddenException;
+import org.keycloak.scim.resource.spi.MembershipChange;
+import org.keycloak.storage.UserStorageUtil;
+
+import static org.keycloak.utils.StringUtil.isBlank;
+
+/**
+ * Groups owned by the SCIM client that created them.
+ *
+ * A realm turns this on with two switches: the experimental server feature {@code scim-group-membership-claims},
+ * and the realm attribute {@value #REALM_ATTRIBUTE} set to {@code true}. With either one off, nothing here runs and
+ * SCIM behaves as it does without the feature.
+ *
+ *
When it is on, the SCIM client that creates a group with {@code POST /Groups} owns it. The owner is stored by the
+ * client's {@code clientId}. Only the owner may change or delete the group through SCIM, and the owner may send the
+ * full member list with {@code PUT}, or with a PATCH that replaces {@code members}. Members that the regular PATCH
+ * refuses to manage, such as service accounts and administrators, are never removed by an owner's write: a full list
+ * that leaves one out keeps it. A group that no SCIM client created behaves as it does without the feature, and never
+ * gets an owner later.
+ *
+ *
Every change to an owned group's members first locks the group row, so that two requests for the same group run
+ * one after the other.
+ */
+public final class GroupOwnership {
+
+ public static final String REALM_ATTRIBUTE = "scimGroupMembershipClaims";
+
+ static final String MANAGED_BY_ANOTHER_CLIENT = "The group is managed by another SCIM client";
+
+ private final KeycloakSession session;
+ private final GroupCoreModelSchema schema;
+ private final EntityManager em;
+
+ GroupOwnership(KeycloakSession session, GroupCoreModelSchema schema) {
+ this.session = session;
+ this.schema = schema;
+ this.em = session.getProvider(JpaConnectionProvider.class).getEntityManager();
+ }
+
+ public static boolean isEnabled(RealmModel realm) {
+ return Profile.isFeatureEnabled(Profile.Feature.SCIM_GROUP_MEMBERSHIP_CLAIMS)
+ && Boolean.parseBoolean(realm.getAttribute(REALM_ATTRIBUTE));
+ }
+
+ /**
+ * The ids, among {@code groupIds}, of the groups that a SCIM client owns.
+ */
+ public static Set ownedAmong(KeycloakSession session, Collection groupIds) {
+ if (groupIds.isEmpty()) {
+ return Set.of();
+ }
+
+ EntityManager em = session.getProvider(JpaConnectionProvider.class).getEntityManager();
+ List owned = em.createQuery("select o.groupId from ScimGroupOwnerEntity o where o.groupId in :groupIds", String.class)
+ .setParameter("groupIds", groupIds)
+ .getResultList();
+
+ return new HashSet<>(owned);
+ }
+
+ /**
+ * The {@code clientId} of the client that owns {@code group}, or {@code null} when no SCIM client owns it.
+ */
+ String ownerOf(GroupModel group) {
+ ScimGroupOwnerEntity entity = em.find(ScimGroupOwnerEntity.class, group.getId());
+ return entity == null ? null : entity.getClientId();
+ }
+
+ /**
+ * Records {@code owner} as the client that created {@code group}.
+ */
+ void recordOwner(GroupModel group, String owner) {
+ em.persist(new ScimGroupOwnerEntity(group.getId(), owner));
+ em.flush();
+ }
+
+ /**
+ * The {@code clientId} of the client the access token of the current request was issued to, or {@code null} when
+ * the token names no client of the realm.
+ */
+ String caller() {
+ Token token = session.getContext().getBearerToken();
+
+ if (!(token instanceof AccessToken accessToken) || isBlank(accessToken.getIssuedFor())) {
+ return null;
+ }
+
+ ClientModel client = session.getContext().getRealm().getClientByClientId(accessToken.getIssuedFor());
+
+ return client == null ? null : client.getClientId();
+ }
+
+ /**
+ * The {@code clientId} of the calling client. It becomes the owner of a group it creates.
+ */
+ String requireCaller() {
+ String caller = caller();
+
+ if (caller == null) {
+ throw new ForbiddenException();
+ }
+
+ return caller;
+ }
+
+ /**
+ * Refuses the request unless the caller is {@code owner}.
+ */
+ void checkOwner(String owner) {
+ if (!owner.equals(caller())) {
+ throw new ForbiddenException(MANAGED_BY_ANOTHER_CLIENT);
+ }
+ }
+
+ /**
+ * Refuses the request when another SCIM client owns {@code group} or any group below it, since deleting a group
+ * deletes its subgroups too. A group that no SCIM client owns is not checked.
+ */
+ void checkDelete(GroupModel group) {
+ String owner = ownerOf(group);
+
+ if (owner != null) {
+ checkOwner(owner);
+ }
+
+ group.getSubGroupsStream().forEach(this::checkDelete);
+ }
+
+ /**
+ * Checks that the caller may change the members of {@code group}, as the regular PATCH does.
+ */
+ void checkGroup(GroupModel group) {
+ GroupCoreModelSchema.checkGroupMembershipPermission(session.getContext().getPermissions(), group);
+ }
+
+ /**
+ * Locks the group row until the transaction ends. Reads of the members made after this see every change committed
+ * before it.
+ */
+ void lock(GroupModel group) {
+ em.flush();
+ GroupEntity entity = em.find(GroupEntity.class, group.getId(), LockModeType.PESSIMISTIC_WRITE);
+
+ if (entity == null) {
+ throw new ModelValidationException("Invalid group");
+ }
+ }
+
+ /**
+ * The ids of the direct members of {@code group}, wherever they are stored. Call {@link #lock(GroupModel)} first.
+ */
+ Set currentMembers(GroupModel group) {
+ RealmModel realm = session.getContext().getRealm();
+ return session.users().getGroupMembersStream(realm, group)
+ .map(UserModel::getId)
+ .collect(Collectors.toCollection(LinkedHashSet::new));
+ }
+
+ /**
+ * Checks a member that a PATCH {@code add} or {@code remove} names, the way the regular PATCH checks it: the user
+ * must exist, and the caller must be allowed to change the user's memberships, whether or not the user is a
+ * member.
+ *
+ * @return the user id
+ */
+ String named(String userId) {
+ checkMayChange(find(userId));
+ return userId;
+ }
+
+ /**
+ * Checks a member of a full member list: a {@code POST}, a {@code PUT}, or a PATCH that replaces {@code members}.
+ * The user must exist. A user who is already a member is accepted as it is, even one the caller may not change, so
+ * that a list read back from the group can be sent again. Any other user is checked as {@link #named(String)}
+ * checks it.
+ *
+ * @return the user id
+ */
+ String listed(String userId, Set current) {
+ UserModel user = find(userId);
+
+ if (!current.contains(userId)) {
+ checkMayChange(user);
+ }
+
+ return userId;
+ }
+
+ /**
+ * Works out how to get from the {@code current} members to the {@code desired} ones, and checks the change before
+ * anything is changed. A current member that the caller may not change, for example a service account or an
+ * administrator, stays even when {@code desired} leaves it out. Every user in {@code desired} that is not a current
+ * member must have been checked with {@link #named(String)} or {@link #listed(String, Set)}.
+ */
+ Change plan(GroupModel group, Set current, Set desired) {
+ RealmModel realm = session.getContext().getRealm();
+ Set stored = storedMembers(group);
+ List leave = new ArrayList<>();
+ List join = new ArrayList<>();
+
+ for (String userId : current) {
+ if (desired.contains(userId)) {
+ continue;
+ }
+
+ UserModel user = session.users().getUserById(realm, userId);
+
+ if (user == null || !mayChange(user)) {
+ // protected: kept, whatever the list says
+ continue;
+ }
+
+ if (!stored.contains(userId) && !isStored(group.getId(), userId)) {
+ // An administrator does not take the group lock, so the membership may have been removed after the
+ // members were read. Only a membership the user still has outside the database is refused.
+ UserModel fresh = uncached(realm, userId);
+
+ if (fresh != null && fresh.getGroupsStream().anyMatch(g -> g.getId().equals(group.getId()))) {
+ throw cannotManage(userId);
+ }
+
+ continue;
+ }
+
+ leave.add(userId);
+ }
+
+ for (String userId : desired) {
+ if (!current.contains(userId)) {
+ join.add(userId);
+ }
+ }
+
+ return new Change(leave, join);
+ }
+
+ /**
+ * Applies a change worked out by {@link #plan(GroupModel, Set, Set)}, reporting each membership that is added or
+ * removed.
+ */
+ void apply(GroupModel group, Change change, Consumer changes) {
+ RealmModel realm = session.getContext().getRealm();
+
+ for (String userId : change.leave()) {
+ UserModel user = uncached(realm, userId);
+
+ if (user != null && isStored(group.getId(), userId)) {
+ user.leaveGroup(group);
+ changes.accept(new MembershipChange(group, user, false));
+ }
+ }
+
+ for (String userId : change.join()) {
+ UserModel user = uncached(realm, userId);
+
+ if (user == null) {
+ throw new ModelValidationException("User with id " + userId + " not found");
+ }
+
+ if (isStored(group.getId(), userId)) {
+ continue;
+ }
+
+ user.joinGroup(group);
+ em.flush();
+
+ if (!isStored(group.getId(), userId)) {
+ // The membership is stored outside the Keycloak database, for example by an LDAP group mapper.
+ throw cannotManage(userId);
+ }
+
+ changes.accept(new MembershipChange(group, user, true));
+ }
+
+ em.flush();
+ }
+
+ /**
+ * The members to remove and to add.
+ */
+ record Change(List leave, List join) {
+ }
+
+ private UserModel find(String userId) {
+ if (isBlank(userId)) {
+ throw new ModelValidationException("Member value is required");
+ }
+
+ UserModel user = session.users().getUserById(session.getContext().getRealm(), userId);
+
+ if (user == null) {
+ throw new ModelValidationException("User with id " + userId + " not found");
+ }
+
+ return user;
+ }
+
+ private void checkMayChange(UserModel user) {
+ if (!schema.canViewUser(user)) {
+ throw new ModelValidationException("User with id " + user.getId() + " not found");
+ }
+
+ schema.checkRequireManageGroupMembership(session.getContext().getPermissions(), user);
+ }
+
+ private boolean mayChange(UserModel user) {
+ try {
+ checkMayChange(user);
+ return true;
+ } catch (ForbiddenException | ModelValidationException e) {
+ return false;
+ }
+ }
+
+ private static ModelValidationException cannotManage(String userId) {
+ return new ModelValidationException("Membership of user " + userId + " cannot be managed through SCIM");
+ }
+
+ /**
+ * The user as stored in the database. A cached user can still list a membership that a request committed while
+ * this one waited for the group lock, and then {@code joinGroup} and {@code leaveGroup} change nothing. Evicting
+ * the user makes both read the database, and drops the stale entry from the cache when the transaction commits.
+ */
+ private UserModel uncached(RealmModel realm, String userId) {
+ UserCache cache = UserStorageUtil.userCache(session);
+ UserModel user = session.users().getUserById(realm, userId);
+
+ if (cache != null && user != null) {
+ cache.evict(realm, user);
+ user = session.users().getUserById(realm, userId);
+ }
+
+ return user;
+ }
+
+ /**
+ * The ids of the members of {@code group} whose membership is stored in the Keycloak database.
+ */
+ private Set storedMembers(GroupModel group) {
+ List ids = em.createQuery("select m.user.id from UserGroupMembershipEntity m where m.groupId = :groupId", String.class)
+ .setParameter("groupId", group.getId())
+ .getResultList();
+ return new HashSet<>(ids);
+ }
+
+ private boolean isStored(String groupId, String userId) {
+ return em.createQuery("select count(m) from UserGroupMembershipEntity m where m.groupId = :groupId and m.user.id = :userId", Long.class)
+ .setParameter("groupId", groupId)
+ .setParameter("userId", userId)
+ .getSingleResult() > 0;
+ }
+}
diff --git a/scim/model/src/main/java/org/keycloak/scim/model/group/GroupResourceTypeProvider.java b/scim/model/src/main/java/org/keycloak/scim/model/group/GroupResourceTypeProvider.java
index d2e0056921f7..a512c2136e94 100644
--- a/scim/model/src/main/java/org/keycloak/scim/model/group/GroupResourceTypeProvider.java
+++ b/scim/model/src/main/java/org/keycloak/scim/model/group/GroupResourceTypeProvider.java
@@ -11,8 +11,13 @@
package org.keycloak.scim.model.group;
import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
import java.util.List;
+import java.util.Locale;
import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
import java.util.function.BiPredicate;
import java.util.stream.Stream;
@@ -40,12 +45,18 @@
import org.keycloak.scim.model.filter.ScimAttributeJpaExpressionResolver;
import org.keycloak.scim.model.filter.ScimJPAPredicateEvaluator;
import org.keycloak.scim.protocol.ForbiddenException;
+import org.keycloak.scim.protocol.request.PatchRequest.PatchOperation;
import org.keycloak.scim.resource.group.Group;
+import org.keycloak.scim.resource.group.Member;
import org.keycloak.scim.resource.schema.attribute.Attribute;
+import org.keycloak.scim.resource.schema.path.Path;
import org.keycloak.scim.resource.spi.AbstractScimResourceTypeProvider;
import org.keycloak.scim.resource.spi.MembershipChange;
import org.keycloak.scim.resource.spi.SearchOptions;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
import static org.keycloak.models.jpa.PaginationUtils.paginateQuery;
import static org.keycloak.utils.StreamsUtil.closing;
@@ -53,6 +64,11 @@ public class GroupResourceTypeProvider extends AbstractScimResourceTypeProvider<
private final GroupCoreModelSchema schema;
+ /**
+ * The owned ids on the page being listed. A single read leaves this null and looks the group up on its own.
+ */
+ private Set ownedOnPage;
+
public GroupResourceTypeProvider(KeycloakSession session) {
this(session, new GroupCoreModelSchema(session));
}
@@ -69,16 +85,74 @@ public List pollMembershipChanges() {
return changes;
}
+ /**
+ * A group created with members in a realm with group ownership records each join, as PUT and PATCH do. Elsewhere
+ * a create with members is refused, so nothing is reported.
+ */
+ @Override
+ public List pollCreateMembershipChanges() {
+ return pollMembershipChanges();
+ }
+
@Override
protected Group onCreate(Group group) {
RealmModel realm = session.getContext().getRealm();
+
+ if (!GroupOwnership.isEnabled(realm)) {
+ GroupModel model = session.groups().createGroup(realm, group.getDisplayName());
+ populate(model, group);
+ group.setCreatedTimestamp(model.getCreatedTimestamp());
+ group.setLastModifiedTimestamp(model.getLastModifiedTimestamp());
+ return group;
+ }
+
+ // The caller becomes the group's owner, whether or not it sends members. Every member is checked before the
+ // group is created.
+ GroupOwnership ownership = new GroupOwnership(session, schema);
+ String owner = ownership.requireCaller();
+ List members = group.getMembers();
+ Set desired = new LinkedHashSet<>();
+
+ for (String userId : memberValues(members)) {
+ desired.add(ownership.named(userId));
+ }
+
+ group.setMembers(null);
GroupModel model = session.groups().createGroup(realm, group.getDisplayName());
populate(model, group);
+ ownership.recordOwner(model, owner);
+
+ if (!desired.isEmpty()) {
+ ownership.checkGroup(model);
+ ownership.lock(model);
+ ownership.apply(model, ownership.plan(model, Set.of(), desired), schema::recordMembershipChange);
+ }
+
+ group.setMembers(members);
group.setCreatedTimestamp(model.getCreatedTimestamp());
group.setLastModifiedTimestamp(model.getLastModifiedTimestamp());
return group;
}
+ @Override
+ public Group get(String id, List attributes, List excludedAttributes) {
+ ownedOnPage = null;
+ return super.get(id, attributes, excludedAttributes);
+ }
+
+ @Override
+ protected Stream render(Stream models, SearchOptions searchOptions) {
+ if (!GroupOwnership.isEnabled(session.getContext().getRealm())
+ || !returnsMembers(searchOptions.getAttributes(), searchOptions.getExcludedAttributes())) {
+ ownedOnPage = null;
+ return super.render(models, searchOptions);
+ }
+
+ List page = models.toList();
+ ownedOnPage = GroupOwnership.ownedAmong(session, page.stream().map(GroupModel::getId).toList());
+ return page.stream().map(model -> createResourceTypeInstance(model, searchOptions.getAttributes(), searchOptions.getExcludedAttributes()));
+ }
+
@Override
protected Group createResourceTypeInstance(GroupModel model, List attributes, List excludedAttributes) {
if (session.getContext().getPermissions().isAdminGroup(model)) {
@@ -91,11 +165,76 @@ protected Group createResourceTypeInstance(GroupModel model, List attrib
return group;
}
- return super.createResourceTypeInstance(model, attributes, excludedAttributes);
+ Group group = super.createResourceTypeInstance(model, attributes, excludedAttributes);
+
+ if (!GroupOwnership.isEnabled(session.getContext().getRealm())
+ || !returnsMembers(attributes, excludedAttributes)) {
+ return group;
+ }
+
+ boolean owned = ownedOnPage != null
+ ? ownedOnPage.contains(model.getId())
+ : new GroupOwnership(session, schema).ownerOf(model) != null;
+
+ if (owned) {
+ // An owner that sends full member lists may build the next list from a read, so a read of an owned group
+ // shows every member without being asked, unless the request leaves them out.
+ List members = schema.readMembers(model);
+ group.setMembers(members.isEmpty() ? null : members);
+ }
+
+ return group;
+ }
+
+ /**
+ * Whether a read of an owned group includes members: always, unless the request excludes them or asks only for
+ * other attributes.
+ */
+ private static boolean returnsMembers(List attributes, List excludedAttributes) {
+ if (excludedAttributes != null && excludedAttributes.stream().anyMatch(GroupResourceTypeProvider::namesMembers)) {
+ return false;
+ }
+
+ return attributes == null || attributes.stream().allMatch(String::isBlank)
+ || attributes.stream().anyMatch(GroupResourceTypeProvider::namesMembers);
+ }
+
+ /**
+ * Whether an attribute name in a request refers to {@code members}: {@code members}, a sub-attribute such as
+ * {@code members.value}, or either with the schema URN in front.
+ */
+ private static boolean namesMembers(String name) {
+ String attribute = name.trim();
+ int colon = attribute.lastIndexOf(':');
+
+ if (colon >= 0) {
+ attribute = attribute.substring(colon + 1);
+ }
+
+ String lower = attribute.toLowerCase(Locale.ROOT);
+ return lower.equals("members") || lower.startsWith("members.");
}
@Override
public Group update(Group resource) {
+ if (GroupOwnership.isEnabled(session.getContext().getRealm())) {
+ GroupModel model = getModel(resource.getId());
+
+ // Callers that cannot manage the group get the regular refusal below, and learn nothing about its owner.
+ if (model != null && hasPermission(model, getRealmResourceType(), AdminPermissionsSchema.MANAGE)) {
+ GroupOwnership ownership = new GroupOwnership(session, schema);
+ String owner = ownership.ownerOf(model);
+
+ if (owner != null) {
+ ownership.checkOwner(owner);
+
+ if (resource.getMembers() != null) {
+ return updateAsOwner(model, resource, ownership);
+ }
+ }
+ }
+ }
+
if (resource.getMembers() != null) {
throw new ModelValidationException("Managing members on updates is not supported");
}
@@ -103,6 +242,294 @@ public Group update(Group resource) {
return super.update(resource);
}
+ /**
+ * PUT from the owner: the request's member list becomes the group's members, except that members the caller may
+ * not change stay. Every member is checked before anything changes, and the group stays locked until the
+ * transaction ends.
+ */
+ private Group updateAsOwner(GroupModel model, Group resource, GroupOwnership ownership) {
+ ownership.checkGroup(model);
+ ownership.lock(model);
+ Set current = ownership.currentMembers(model);
+ Set desired = new LinkedHashSet<>();
+
+ for (String userId : memberValues(resource.getMembers())) {
+ desired.add(ownership.listed(userId, current));
+ }
+
+ GroupOwnership.Change change = ownership.plan(model, current, desired);
+
+ resource.setMembers(null);
+ Group updated = super.update(resource);
+ ownership.apply(model, change, schema::recordMembershipChange);
+ List members = schema.readMembers(model);
+ updated.setMembers(members.isEmpty() ? null : members);
+
+ return updated;
+ }
+
+ @Override
+ protected void applyPatch(Group existing, GroupModel model, List operations) {
+ if (GroupOwnership.isEnabled(session.getContext().getRealm())) {
+ GroupOwnership ownership = new GroupOwnership(session, schema);
+ String owner = ownership.ownerOf(model);
+
+ if (owner != null) {
+ ownership.checkOwner(owner);
+
+ if (operations.stream().anyMatch(this::isMembersOperation)) {
+ patchAsOwner(existing, model, operations, ownership);
+ return;
+ }
+ }
+ }
+
+ super.applyPatch(existing, model, operations);
+ }
+
+ /**
+ * PATCH from the owner. The member operations are replayed, in order, on the group's current members: add puts
+ * members in, replace sets the full list, remove takes members out, and a remove without a filter or value takes
+ * out every member. Members the caller may not change stay whatever the operations say, but naming one in an add
+ * or remove is refused, as the regular PATCH refuses it. Every member is checked before anything changes. Other
+ * operations go through the regular path.
+ */
+ private void patchAsOwner(Group existing, GroupModel model, List operations, GroupOwnership ownership) {
+ ownership.checkGroup(model);
+ ownership.lock(model);
+ Set current = ownership.currentMembers(model);
+ Set desired = new LinkedHashSet<>(current);
+ List others = new ArrayList<>();
+
+ for (PatchOperation operation : operations) {
+ String op = Optional.ofNullable(operation.getOp()).orElse("").toLowerCase(Locale.ROOT);
+ String path = operation.getPath();
+
+ if (isResourceRoot(path)) {
+ JsonNode value = operation.getValue();
+ String field = value != null && value.isObject() ? membersField(value) : null;
+
+ if (field == null) {
+ others.add(operation);
+ continue;
+ }
+
+ List ids = memberIds(value.get(field));
+
+ switch (op) {
+ case "add" -> ids.forEach(id -> desired.add(ownership.named(id)));
+ case "replace" -> {
+ desired.clear();
+ ids.forEach(id -> desired.add(ownership.listed(id, current)));
+ }
+ default -> throw new ModelValidationException("Unsupported operation on members: " + operation.getOp());
+ }
+
+ ObjectNode rest = value.deepCopy();
+ rest.remove(field);
+
+ if (!rest.isEmpty()) {
+ PatchOperation remaining = new PatchOperation();
+ remaining.setOp(operation.getOp());
+ remaining.setPath(path);
+ remaining.setValue(rest);
+ others.add(remaining);
+ }
+
+ continue;
+ }
+
+ MembersPath membersPath = membersPath(path);
+
+ if (membersPath == null) {
+ others.add(operation);
+ continue;
+ }
+
+ List filterValues = membersPath.filterValues();
+
+ switch (op) {
+ case "add" -> {
+ rejectFilter(filterValues);
+ memberIds(operation.getValue()).forEach(id -> desired.add(ownership.named(id)));
+ }
+ case "replace" -> {
+ rejectFilter(filterValues);
+ desired.clear();
+ memberIds(operation.getValue()).forEach(id -> desired.add(ownership.listed(id, current)));
+ }
+ case "remove" -> {
+ if (filterValues != null) {
+ filterValues.forEach(id -> desired.remove(ownership.named(id)));
+ } else if (operation.getValue() == null || operation.getValue().isNull()) {
+ // no filter and no value: every member goes, except those the caller may not change. An
+ // explicit empty list removes nobody.
+ desired.clear();
+ } else {
+ // a value listing the members, as Microsoft Entra ID sends it
+ memberIds(operation.getValue()).forEach(id -> desired.remove(ownership.named(id)));
+ }
+ }
+ default -> throw new ModelValidationException("Unsupported operation on members: " + operation.getOp());
+ }
+ }
+
+ GroupOwnership.Change change = ownership.plan(model, current, desired);
+
+ if (!others.isEmpty()) {
+ super.applyPatch(existing, model, others);
+ }
+
+ ownership.apply(model, change, schema::recordMembershipChange);
+ }
+
+ private static void rejectFilter(List filterValues) {
+ if (filterValues != null) {
+ throw new ModelValidationException("A filter in the path is only supported when removing members");
+ }
+ }
+
+ private boolean isMembersOperation(PatchOperation operation) {
+ String path = operation.getPath();
+
+ if (isResourceRoot(path)) {
+ JsonNode value = operation.getValue();
+ return value != null && value.isObject() && membersField(value) != null;
+ }
+
+ return membersPath(path) != null;
+ }
+
+ /**
+ * Whether a PATCH path targets the group itself: no path, or the Group schema URN (RFC 7644 section 3.5.2). The
+ * value then holds attributes by name, {@code members} among them.
+ */
+ private boolean isResourceRoot(String path) {
+ return path == null || path.isBlank() || path.trim().equalsIgnoreCase(schema.getId());
+ }
+
+ /**
+ * A PATCH path that targets {@code members}.
+ *
+ * @param filterValues the user ids from a {@code members[value eq "a" or value eq "b"]} filter, or {@code null}
+ * without a filter
+ */
+ private record MembersPath(List filterValues) {
+ }
+
+ /**
+ * @return {@code null} when the path targets another attribute
+ */
+ private MembersPath membersPath(String path) {
+ Path parsed;
+
+ try {
+ parsed = new Path(schema, path);
+ } catch (RuntimeException ex) {
+ throw new ModelValidationException("Only a members[value eq \"id\"] filter is supported in the path");
+ }
+
+ Attribute attribute = schema.getAttributeByPath(parsed.getPath());
+
+ if (attribute == null || !"members".equals(attribute.getName())) {
+ return null;
+ }
+
+ JsonNode value = parsed.getValue(attribute);
+
+ if (value == null || value.isNull()) {
+ return new MembersPath(null);
+ }
+
+ return new MembersPath(filterIds(value));
+ }
+
+ /**
+ * The user ids from a filter the shared parser accepted: one comparison, or an {@code or} of them.
+ */
+ private static List filterIds(JsonNode value) {
+ List ids = new ArrayList<>();
+
+ if (value.isArray()) {
+ value.forEach(node -> ids.add(filterId(node)));
+ } else if (value.isObject()) {
+ ids.add(filterId(value));
+ } else {
+ throw new ModelValidationException("Only a members[value eq \"id\"] filter is supported in the path");
+ }
+
+ return ids;
+ }
+
+ private static String filterId(JsonNode node) {
+ JsonNode id = node.get("value");
+
+ if (id == null || !id.isTextual()) {
+ throw new ModelValidationException("Only a members[value eq \"id\"] filter is supported in the path");
+ }
+
+ return id.asText();
+ }
+
+ private static String membersField(JsonNode value) {
+ Iterator names = value.fieldNames();
+
+ while (names.hasNext()) {
+ String name = names.next();
+ if ("members".equalsIgnoreCase(name)) {
+ return name;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * The user ids in a {@code members} value: an array, or a single item, where each item is an object with a
+ * {@code value} or a bare user id. A missing value is kept as {@code null} so that the check reports it.
+ */
+ private static List memberIds(JsonNode value) {
+ if (value == null || value.isNull()) {
+ return List.of();
+ }
+
+ List items = new ArrayList<>();
+
+ if (value.isArray()) {
+ value.forEach(items::add);
+ } else {
+ items.add(value);
+ }
+
+ List ids = new ArrayList<>();
+
+ for (JsonNode item : items) {
+ if (item.isTextual()) {
+ // a bare user id, as the regular PATCH path also accepts
+ ids.add(item.asText());
+ } else if (item.isObject()) {
+ JsonNode id = item.get("value");
+ ids.add(id == null || id.isNull() ? null : id.asText());
+ } else {
+ throw new ModelValidationException("Invalid members value");
+ }
+ }
+
+ return ids;
+ }
+
+ private static List memberValues(List members) {
+ List ids = new ArrayList<>();
+
+ if (members != null) {
+ for (Member member : members) {
+ ids.add(member == null ? null : member.getValue());
+ }
+ }
+
+ return ids;
+ }
+
@Override
protected Group onUpdate(GroupModel model, Group resource) {
model.setLastModifiedTimestamp(Time.currentTimeMillis());
@@ -184,6 +611,9 @@ public boolean onDelete(GroupModel model) {
RealmModel realm = session.getContext().getRealm();
Permissions permissions = session.getContext().getPermissions();
rejectIfAdminDescendant(model, permissions);
+ if (GroupOwnership.isEnabled(realm)) {
+ new GroupOwnership(session, schema).checkDelete(model);
+ }
return session.groups().removeGroup(realm, model);
}
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 e3e73d721959..bf22586bc07a 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
@@ -2,6 +2,7 @@
import java.util.ArrayList;
import java.util.Collection;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -19,10 +20,12 @@
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.utils.RoleUtils;
+import org.keycloak.scim.model.group.GroupOwnership;
import org.keycloak.scim.protocol.ForbiddenException;
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.ScimMutabilityException;
import org.keycloak.scim.resource.user.Email;
import org.keycloak.scim.resource.user.GroupMembership;
import org.keycloak.scim.resource.user.Name;
@@ -168,6 +171,14 @@ protected Map> getAttributeMappers() {
KeycloakSession session = KeycloakSessionUtil.getKeycloakSession();
RealmModel realm = session.getContext().getRealm();
checkUserMembershipPermission(session.getContext().getPermissions(), model);
+ if (GroupOwnership.isEnabled(realm)) {
+ Set requested = groupIds(values);
+ Set direct = directGroupIds(model);
+ Set changed = new HashSet<>(requested);
+ changed.removeAll(direct);
+ direct.stream().filter(id -> !requested.contains(id)).forEach(changed::add);
+ checkOwnedGroupsUnchanged(session, changed);
+ }
List remove = new ArrayList<>();
for (GroupUtils.GroupMembership membership : GroupUtils.getAllMemberships(session, model.getGroupsStream().toList())) {
@@ -214,6 +225,11 @@ protected Map> getAttributeMappers() {
KeycloakSession session = KeycloakSessionUtil.getKeycloakSession();
RealmModel realm = session.getContext().getRealm();
checkUserMembershipPermission(session.getContext().getPermissions(), model);
+ if (GroupOwnership.isEnabled(realm)) {
+ Set removed = groupIds(values);
+ removed.retainAll(directGroupIds(model));
+ checkOwnedGroupsUnchanged(session, removed);
+ }
for (GroupMembership membership : values) {
GroupModel group = session.groups().getGroupById(realm, membership.getValue());
@@ -233,6 +249,11 @@ protected Map> getAttributeMappers() {
KeycloakSession session = KeycloakSessionUtil.getKeycloakSession();
RealmModel realm = session.getContext().getRealm();
checkUserMembershipPermission(session.getContext().getPermissions(), model);
+ if (GroupOwnership.isEnabled(realm)) {
+ Set added = groupIds(values);
+ added.removeAll(directGroupIds(model));
+ checkOwnedGroupsUnchanged(session, added);
+ }
for (GroupMembership membership : values) {
GroupModel group = session.groups().getGroupById(realm, membership.getValue());
@@ -253,6 +274,41 @@ protected Map> getAttributeMappers() {
return attributes.stream().collect(Collectors.toMap(Attribute::getName, Function.identity()));
}
+ private static Set groupIds(Collection> values) {
+ Set ids = new HashSet<>();
+
+ if (values != null) {
+ for (Object value : values) {
+ if (value instanceof GroupMembership membership) {
+ ids.add(membership.getValue());
+ } else if (value != null) {
+ ids.add(value.toString());
+ }
+ }
+ }
+
+ return ids;
+ }
+
+ private static Set directGroupIds(UserModel model) {
+ return model.getGroupsStream().map(GroupModel::getId).collect(Collectors.toCollection(HashSet::new));
+ }
+
+ /**
+ * A group owned by a SCIM client takes its members from that client's writes to the Group resource. A membership
+ * changed through a User would go around the owner, and RFC 7643 section 4.1.2 makes a User's {@code groups}
+ * read-only anyway, so such a write is refused. A write that changes no membership of an owned group is accepted,
+ * and groups that no SCIM client owns behave as before. Callers check {@link GroupOwnership#isEnabled} first, so a
+ * realm without group ownership reads nothing more than before.
+ *
+ * @param changed the ids of the groups the write would add the user to or remove the user from
+ */
+ private static void checkOwnedGroupsUnchanged(KeycloakSession session, Set changed) {
+ if (!GroupOwnership.ownedAmong(session, changed).isEmpty()) {
+ throw new ScimMutabilityException("Membership of a group owned by a SCIM client cannot be changed through the User resource. Use the Group resource instead.");
+ }
+ }
+
@Override
public void populate(User resource, UserModel model) {
super.populate(resource, model);
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..9acb1ab557dc 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
@@ -47,7 +47,8 @@ static Response toResponse(KeycloakSession session, Exception e) {
return badRequest("tooMany", e.getMessage());
} else if (e instanceof ForbiddenException) {
logger.debug("SCIM request denied: caller does not have the required permissions");
- return forbidden();
+ // a ForbiddenException without a message gives the same response as before
+ return errorResponse(Status.FORBIDDEN, e.getMessage());
} else if (e instanceof jakarta.ws.rs.ForbiddenException fe) {
throw fe;
}
diff --git a/scim/services/src/main/java/org/keycloak/scim/services/ScimResourceTypeResource.java b/scim/services/src/main/java/org/keycloak/scim/services/ScimResourceTypeResource.java
index b0f37bc4a641..0b9c1379ab1f 100644
--- a/scim/services/src/main/java/org/keycloak/scim/services/ScimResourceTypeResource.java
+++ b/scim/services/src/main/java/org/keycloak/scim/services/ScimResourceTypeResource.java
@@ -87,6 +87,7 @@ public Response create(InputStream is) {
.resourcePath(session.getContext().getUri(), created.getId())
.representation(created)
.success();
+ emitMembershipChangeEvents(created.getId(), false, resourceTypeProvider.pollCreateMembershipChanges());
return created;
});
}
@@ -266,14 +267,22 @@ public Response patch(@PathParam("id") String id, PatchRequest request) {
* (group id, user id) is not already {@code id}
*/
private void emitMembershipChangeEvents(String id) {
- for (MembershipChange change : resourceTypeProvider.pollMembershipChanges()) {
+ emitMembershipChangeEvents(id, true, resourceTypeProvider.pollMembershipChanges());
+ }
+
+ /**
+ * @param idInUri whether the current request URI already ends with {@code id}. The URI of a create ends at the
+ * collection, so the new resource's id goes into the event's resource path as well.
+ */
+ private void emitMembershipChangeEvents(String id, boolean idInUri, List changes) {
+ for (MembershipChange change : changes) {
String otherId = id.equals(change.user().getId()) ? change.group().getId() : change.user().getId();
// reset accumulated details from a previous iteration: detail() is a no-op for blank values,
// so a blank value on this change could otherwise inherit the previous change's detail
adminEvent.getEvent().setDetails(null);
adminEvent.operation(change.added() ? OperationType.CREATE : OperationType.DELETE)
.resource(ResourceType.GROUP_MEMBERSHIP)
- .resourcePath(session.getContext().getUri(), otherId)
+ .resourcePath(session.getContext().getUri(), idInUri ? otherId : id + "/" + otherId)
.representation(ModelToRepresentation.toRepresentation(change.group(), true))
.detail(UserModel.USERNAME, change.user().getUsername())
.detail(UserModel.EMAIL, change.user().getEmail())
diff --git a/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipAttributeOffRealmConfig.java b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipAttributeOffRealmConfig.java
new file mode 100644
index 000000000000..92f7fa9c9dbd
--- /dev/null
+++ b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipAttributeOffRealmConfig.java
@@ -0,0 +1,25 @@
+/*
+ * 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.tests.scim.tck;
+
+import org.keycloak.testframework.realm.RealmBuilder;
+import org.keycloak.testframework.realm.RealmConfig;
+
+/**
+ * A SCIM realm without the group ownership realm attribute.
+ */
+public class GroupOwnershipAttributeOffRealmConfig implements RealmConfig {
+
+ @Override
+ public RealmBuilder configure(RealmBuilder realm) {
+ return realm.scimEnabled(true);
+ }
+}
diff --git a/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipAttributeOffTest.java b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipAttributeOffTest.java
new file mode 100644
index 000000000000..e8398e5b83d8
--- /dev/null
+++ b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipAttributeOffTest.java
@@ -0,0 +1,68 @@
+/*
+ * 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.tests.scim.tck;
+
+import org.keycloak.scim.client.ScimClient;
+import org.keycloak.testframework.annotations.InjectRealm;
+import org.keycloak.testframework.annotations.KeycloakIntegrationTest;
+import org.keycloak.testframework.realm.ManagedRealm;
+import org.keycloak.testframework.scim.client.annotations.InjectScimClient;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+/**
+ * The experimental server feature is on, but the realm attribute is not set: SCIM must behave as it does without it.
+ */
+@KeycloakIntegrationTest(config = GroupOwnershipServerConfig.class)
+public class GroupOwnershipAttributeOffTest {
+
+ @InjectRealm(config = GroupOwnershipAttributeOffRealmConfig.class)
+ ManagedRealm realm;
+
+ @InjectScimClient(clientId = "okta-directory")
+ ScimClient okta;
+
+ @InjectScimClient(clientId = "entra-directory")
+ ScimClient entra;
+
+ GroupOwnershipOffChecks checks;
+
+ @BeforeEach
+ public void setUp() {
+ checks = new GroupOwnershipOffChecks(realm, okta, entra);
+ }
+
+ @Test
+ public void testCreateWithMembersIsRefused() {
+ checks.createWithMembersIsRefused();
+ }
+
+ @Test
+ public void testPutWithMembersIsRefused() {
+ checks.putWithMembersIsRefused();
+ }
+
+ @Test
+ public void testAnyClientCanWriteAndDelete() {
+ checks.anyClientCanWriteAndDelete();
+ }
+
+ @Test
+ public void testUsersGroupsWritesWork() {
+ checks.usersGroupsWritesWork();
+ }
+
+ @Test
+ public void testReadShowsMembersOnlyOnRequest() {
+ checks.readShowsMembersOnlyOnRequest();
+ }
+}
diff --git a/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipBoundaryTest.java b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipBoundaryTest.java
new file mode 100644
index 000000000000..c23cb92f2116
--- /dev/null
+++ b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipBoundaryTest.java
@@ -0,0 +1,282 @@
+/*
+ * 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.tests.scim.tck;
+
+import java.util.List;
+
+import jakarta.ws.rs.core.Response;
+
+import org.keycloak.models.utils.KeycloakModelUtils;
+import org.keycloak.representations.idm.ClientRepresentation;
+import org.keycloak.representations.idm.GroupRepresentation;
+import org.keycloak.representations.idm.ProtocolMapperRepresentation;
+import org.keycloak.scim.client.ScimClient;
+import org.keycloak.scim.protocol.request.PatchRequest;
+import org.keycloak.scim.protocol.request.PatchRequest.PatchOperation;
+import org.keycloak.scim.resource.group.Group;
+import org.keycloak.scim.resource.user.User;
+import org.keycloak.testframework.annotations.InjectRealm;
+import org.keycloak.testframework.annotations.KeycloakIntegrationTest;
+import org.keycloak.testframework.realm.ClientBuilder;
+import org.keycloak.testframework.realm.ManagedRealm;
+import org.keycloak.testframework.scim.client.annotations.InjectScimClient;
+import org.keycloak.testframework.util.ApiUtil;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.keycloak.tests.scim.tck.GroupOwnershipSupport.assertManagedByAnotherClient;
+import static org.keycloak.tests.scim.tck.GroupOwnershipSupport.assertMutability;
+import static org.keycloak.tests.scim.tck.GroupOwnershipSupport.assertStatus;
+import static org.keycloak.tests.scim.tck.GroupOwnershipSupport.group;
+import static org.keycloak.tests.scim.tck.GroupOwnershipSupport.members;
+import static org.keycloak.tests.scim.tck.GroupOwnershipSupport.patch;
+import static org.keycloak.tests.scim.tck.GroupOwnershipSupport.put;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The edges of group ownership: other SCIM clients, a User's {@code groups}, groups that no SCIM client owns, and the
+ * owning client being deleted.
+ */
+@KeycloakIntegrationTest(config = GroupOwnershipServerConfig.class)
+public class GroupOwnershipBoundaryTest {
+
+ private static final String TEMPORARY_DIRECTORY = "ownership-temporary-directory";
+
+ @InjectRealm(config = GroupOwnershipRealmConfig.class)
+ ManagedRealm realm;
+
+ @InjectScimClient(clientId = "okta-directory")
+ ScimClient okta;
+
+ @InjectScimClient(clientId = "entra-directory")
+ ScimClient entra;
+
+ @InjectScimClient(clientId = TEMPORARY_DIRECTORY)
+ ScimClient temporary;
+
+ GroupOwnershipSupport support;
+
+ @BeforeEach
+ public void setUp() {
+ support = new GroupOwnershipSupport(realm);
+ }
+
+ @Test
+ public void testAnotherClientCannotWriteToAnOwnedGroup() {
+ String alice = support.createUser();
+ String bob = support.createUser();
+ Group group = support.createGroup(okta, alice);
+ String name = group.getDisplayName();
+
+ assertManagedByAnotherClient(() -> put(entra, group, bob));
+ // a PUT without members, and a PATCH that only renames, are refused too
+ Group rename = new Group();
+ rename.setId(group.getId());
+ rename.setDisplayName("owned-renamed-" + KeycloakModelUtils.generateId());
+ assertManagedByAnotherClient(() -> entra.groups().update(rename));
+ assertManagedByAnotherClient(() -> patch(entra, group.getId(), new PatchOperation("replace", "displayName", "owned-renamed")));
+ assertManagedByAnotherClient(() -> patch(entra, group.getId(), new PatchOperation("Add", "members", members(bob))));
+ assertManagedByAnotherClient(() -> patch(entra, group.getId(), new PatchOperation("Remove", "members", members(alice))));
+ assertManagedByAnotherClient(() -> entra.groups().delete(group.getId()));
+
+ support.assertMembers(group.getId(), alice);
+ assertEquals(name, support.groupName(group.getId()));
+
+ okta.groups().delete(group.getId());
+ assertFalse(support.groupExists(group.getId()));
+ }
+
+ // An administrator can move one directory's group under another's. Deleting the parent would delete both.
+ @Test
+ public void testClientCannotDeleteAGroupThatHoldsAnotherClientsGroup() {
+ Group child = support.createGroup(okta);
+ Group parent = support.createGroup(entra);
+ GroupRepresentation moved = realm.admin().groups().group(child.getId()).toRepresentation();
+ try (Response response = realm.admin().groups().group(parent.getId()).subGroup(moved)) {
+ assertEquals(204, response.getStatus());
+ }
+
+ assertManagedByAnotherClient(() -> entra.groups().delete(parent.getId()));
+ assertTrue(support.groupExists(child.getId()));
+
+ // A group below it that no SCIM client owns does not stop the delete.
+ realm.admin().groups().group(child.getId()).remove();
+ GroupRepresentation manual = new GroupRepresentation();
+ manual.setName("unowned-" + KeycloakModelUtils.generateId());
+ try (Response response = realm.admin().groups().group(parent.getId()).subGroup(manual)) {
+ assertEquals(201, response.getStatus());
+ }
+
+ entra.groups().delete(parent.getId());
+ assertFalse(support.groupExists(parent.getId()));
+ }
+
+ // RFC 7643 section 4.1.2: a User's groups are read-only, membership changes go through the Group resource
+ @Test
+ public void testUsersPatchCannotChangeAnOwnedGroup() {
+ String alice = support.createUser();
+ String bob = support.createUser();
+ Group group = support.createGroup(okta, alice);
+
+ assertMutability(() -> okta.users().patch(bob, PatchRequest.create().add("groups", group.getId()).build()));
+ assertMutability(() -> okta.users().patch(alice, PatchRequest.create()
+ .remove("groups[value eq \"" + group.getId() + "\"]").build()));
+ support.assertMembers(group.getId(), alice);
+ }
+
+ @Test
+ public void testUsersPutThatChangesAnOwnedGroupIsRefused() {
+ String bob = support.createUser();
+ Group group = support.createGroup(okta);
+ User user = okta.users().get(bob);
+ user.addGroup(group.getId());
+
+ assertMutability(() -> okta.users().update(user));
+ support.assertMembers(group.getId());
+ }
+
+ @Test
+ public void testUsersCreateWithAnOwnedGroupIsRefused() {
+ Group group = support.createGroup(okta);
+ User user = newUser();
+ user.addGroup(group.getId());
+
+ assertMutability(() -> okta.users().create(user));
+ support.assertMembers(group.getId());
+ }
+
+ // Okta's user PUT carries no groups. It must neither be refused nor drop the user's memberships.
+ @Test
+ public void testUsersPutWithoutGroupsKeepsMemberships() {
+ String alice = support.createUser();
+ Group group = support.createGroup(okta, alice);
+
+ User user = okta.users().get(alice);
+ user.setGroups(null);
+ user.setFirstName("NoGroupsSent");
+ okta.users().update(user);
+
+ support.assertMembers(group.getId(), alice);
+ assertEquals("NoGroupsSent", okta.users().get(alice).getFirstName());
+ }
+
+ @Test
+ public void testUsersPutWithUnchangedGroupsIsAccepted() {
+ String alice = support.createUser();
+ Group group = support.createGroup(okta, alice);
+
+ User user = okta.users().get(alice, List.of("groups"));
+ assertNotNull(user.getGroups());
+ user.setFirstName("Unchanged");
+ okta.users().update(user);
+
+ support.assertMembers(group.getId(), alice);
+ assertEquals("Unchanged", okta.users().get(alice).getFirstName());
+ }
+
+ // A group that no SCIM client owns keeps the behaviour of a realm without owners, also through /Users
+ @Test
+ public void testUsersWritesToAnUnownedGroupWorkAsBefore() {
+ String bob = support.createUser();
+ String unowned = support.createAdminGroup();
+
+ okta.users().patch(bob, PatchRequest.create().add("groups", unowned).build());
+ support.assertMembers(unowned, bob);
+ entra.users().patch(bob, PatchRequest.create().remove("groups[value eq \"" + unowned + "\"]").build());
+ support.assertMembers(unowned);
+ }
+
+ @Test
+ public void testUnownedGroupWorksAsBeforeAndIsNeverAdopted() {
+ String alice = support.createUser();
+ String bob = support.createUser();
+ String id = support.createAdminGroup();
+ Group unowned = group(id, support.groupName(id));
+
+ // PATCH add and remove work for any client
+ patch(okta, id, new PatchOperation("Add", "members", members(alice, bob)));
+ patch(entra, id, new PatchOperation("Remove", "members[value eq \"" + alice + "\"]", null));
+ support.assertMembers(id, bob);
+
+ // A PUT with members is refused, for every client, and does not make the caller its owner
+ assertStatus(400, () -> put(okta, unowned, alice));
+ assertStatus(400, () -> put(entra, unowned));
+ support.assertMembers(id, bob);
+
+ // Nobody owns it after all of this: another client can still change and delete it
+ patch(entra, id, new PatchOperation("Add", "members", members(alice)));
+ support.assertMembers(id, alice, bob);
+ entra.groups().delete(id);
+ assertFalse(support.groupExists(id));
+ }
+
+ // The owner is stored by clientId. Deleting the client keeps it, and a new client with the same clientId owns
+ // the group again.
+ @Test
+ public void testOwnerSurvivesClientDeletionAndComesBackWithTheSameClientId() {
+ String alice = support.createUser();
+ String bob = support.createUser();
+ Group group = support.createGroup(temporary, alice);
+ ClientRepresentation original = realm.admin().clients().findByClientId(TEMPORARY_DIRECTORY).get(0);
+ List mappers = realm.admin().clients().get(original.getId()).getProtocolMappers().getMappers();
+
+ realm.admin().clients().get(original.getId()).remove();
+
+ try {
+ // No owner left that can be reached, but the group is still owned.
+ assertManagedByAnotherClient(() -> put(okta, group, bob));
+ assertManagedByAnotherClient(() -> okta.groups().delete(group.getId()));
+ } finally {
+ recreateClient(mappers);
+ }
+
+ put(temporary, group, bob);
+ support.assertMembers(group.getId(), bob);
+ assertManagedByAnotherClient(() -> put(okta, group, alice));
+ }
+
+ /**
+ * Creates the temporary directory's client again, as the SCIM client supplier first created it.
+ */
+ private void recreateClient(List mappers) {
+ mappers.forEach(mapper -> mapper.setId(null));
+
+ try (Response response = realm.admin().clients().create(ClientBuilder.create()
+ .clientId(TEMPORARY_DIRECTORY)
+ .secret("secret")
+ .serviceAccountsEnabled(true)
+ .fullScopeEnabled(false)
+ .protocolMappers(mappers.toArray(ProtocolMapperRepresentation[]::new))
+ .enabled(true)
+ .build())) {
+ assertEquals(201, response.getStatus());
+ String id = ApiUtil.getCreatedId(response);
+ String serviceAccountUserId = realm.admin().clients().get(id).toRepresentation().getServiceAccountUserId();
+ support.grantManageUsers(serviceAccountUserId);
+ realm.admin().clients().get(id).getScopeMappings().clientLevel(support.realmManagementId()).add(List.of(support.manageUsersRole()));
+ }
+ }
+
+ private static User newUser() {
+ String name = "owned-" + KeycloakModelUtils.generateId();
+ User user = new User();
+ user.setUserName(name);
+ user.setEmail(name + "@testco.example");
+ user.setFirstName("Lab");
+ user.setLastName("User");
+ return user;
+ }
+}
diff --git a/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipFeatureOffTest.java b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipFeatureOffTest.java
new file mode 100644
index 000000000000..227654943c94
--- /dev/null
+++ b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipFeatureOffTest.java
@@ -0,0 +1,68 @@
+/*
+ * 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.tests.scim.tck;
+
+import org.keycloak.scim.client.ScimClient;
+import org.keycloak.testframework.annotations.InjectRealm;
+import org.keycloak.testframework.annotations.KeycloakIntegrationTest;
+import org.keycloak.testframework.realm.ManagedRealm;
+import org.keycloak.testframework.scim.client.annotations.InjectScimClient;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+/**
+ * The realm attribute is set, but the experimental server feature is off: SCIM must behave as it does without it.
+ */
+@KeycloakIntegrationTest
+public class GroupOwnershipFeatureOffTest {
+
+ @InjectRealm(config = GroupOwnershipRealmConfig.class)
+ ManagedRealm realm;
+
+ @InjectScimClient(clientId = "okta-directory")
+ ScimClient okta;
+
+ @InjectScimClient(clientId = "entra-directory")
+ ScimClient entra;
+
+ GroupOwnershipOffChecks checks;
+
+ @BeforeEach
+ public void setUp() {
+ checks = new GroupOwnershipOffChecks(realm, okta, entra);
+ }
+
+ @Test
+ public void testCreateWithMembersIsRefused() {
+ checks.createWithMembersIsRefused();
+ }
+
+ @Test
+ public void testPutWithMembersIsRefused() {
+ checks.putWithMembersIsRefused();
+ }
+
+ @Test
+ public void testAnyClientCanWriteAndDelete() {
+ checks.anyClientCanWriteAndDelete();
+ }
+
+ @Test
+ public void testUsersGroupsWritesWork() {
+ checks.usersGroupsWritesWork();
+ }
+
+ @Test
+ public void testReadShowsMembersOnlyOnRequest() {
+ checks.readShowsMembersOnlyOnRequest();
+ }
+}
diff --git a/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipOffChecks.java b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipOffChecks.java
new file mode 100644
index 000000000000..d13ebbb345ac
--- /dev/null
+++ b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipOffChecks.java
@@ -0,0 +1,96 @@
+/*
+ * 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.tests.scim.tck;
+
+import java.util.List;
+import java.util.Set;
+
+import org.keycloak.models.utils.KeycloakModelUtils;
+import org.keycloak.scim.client.ScimClient;
+import org.keycloak.scim.protocol.request.PatchRequest;
+import org.keycloak.scim.protocol.request.PatchRequest.PatchOperation;
+import org.keycloak.scim.resource.group.Group;
+import org.keycloak.testframework.realm.ManagedRealm;
+
+import static org.keycloak.tests.scim.tck.GroupOwnershipSupport.assertStatus;
+import static org.keycloak.tests.scim.tck.GroupOwnershipSupport.group;
+import static org.keycloak.tests.scim.tck.GroupOwnershipSupport.memberIds;
+import static org.keycloak.tests.scim.tck.GroupOwnershipSupport.members;
+import static org.keycloak.tests.scim.tck.GroupOwnershipSupport.patch;
+import static org.keycloak.tests.scim.tck.GroupOwnershipSupport.put;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * What SCIM does when one of the two group ownership switches is off: exactly what it does without the feature.
+ */
+final class GroupOwnershipOffChecks {
+
+ private final ManagedRealm realm;
+ private final GroupOwnershipSupport support;
+ private final ScimClient okta;
+ private final ScimClient entra;
+
+ GroupOwnershipOffChecks(ManagedRealm realm, ScimClient okta, ScimClient entra) {
+ this.realm = realm;
+ this.support = new GroupOwnershipSupport(realm);
+ this.okta = okta;
+ this.entra = entra;
+ }
+
+ void createWithMembersIsRefused() {
+ String alice = support.createUser();
+ String name = "unowned-" + KeycloakModelUtils.generateId();
+
+ assertStatus(400, () -> okta.groups().create(group(null, name, alice)));
+ assertTrue(realm.admin().groups().query(name).stream().noneMatch(g -> name.equals(g.getName())));
+ }
+
+ void putWithMembersIsRefused() {
+ String alice = support.createUser();
+ Group group = support.createGroup(okta);
+
+ assertStatus(400, () -> put(okta, group, alice));
+ assertStatus(400, () -> put(okta, group));
+ support.assertMembers(group.getId());
+ }
+
+ void anyClientCanWriteAndDelete() {
+ String alice = support.createUser();
+ Group group = support.createGroup(okta);
+
+ patch(entra, group.getId(), new PatchOperation("Add", "members", members(alice)));
+ support.assertMembers(group.getId(), alice);
+ patch(entra, group.getId(), new PatchOperation("replace", "displayName", "unowned-" + KeycloakModelUtils.generateId()));
+
+ entra.groups().delete(group.getId());
+ assertFalse(support.groupExists(group.getId()));
+ }
+
+ void usersGroupsWritesWork() {
+ String bob = support.createUser();
+ Group group = support.createGroup(okta);
+
+ entra.users().patch(bob, PatchRequest.create().add("groups", group.getId()).build());
+ support.assertMembers(group.getId(), bob);
+ }
+
+ void readShowsMembersOnlyOnRequest() {
+ String alice = support.createUser();
+ Group group = support.createGroup(okta);
+ support.adminJoin(alice, group.getId());
+
+ assertTrue(memberIds(okta.groups().get(group.getId())).isEmpty());
+ assertEquals(Set.of(alice), memberIds(okta.groups().get(group.getId(), List.of("displayName", "members"))));
+ }
+}
diff --git a/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipRealmConfig.java b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipRealmConfig.java
new file mode 100644
index 000000000000..4d96b489cf7f
--- /dev/null
+++ b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipRealmConfig.java
@@ -0,0 +1,27 @@
+/*
+ * 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.tests.scim.tck;
+
+import org.keycloak.testframework.realm.RealmBuilder;
+import org.keycloak.testframework.realm.RealmConfig;
+
+/**
+ * A SCIM realm where the SCIM client that creates a group owns it.
+ */
+public class GroupOwnershipRealmConfig implements RealmConfig {
+
+ static final String REALM_ATTRIBUTE = "scimGroupMembershipClaims";
+
+ @Override
+ public RealmBuilder configure(RealmBuilder realm) {
+ return realm.scimEnabled(true).attribute(REALM_ATTRIBUTE, "true");
+ }
+}
diff --git a/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipServerConfig.java b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipServerConfig.java
new file mode 100644
index 000000000000..7df734143dd4
--- /dev/null
+++ b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipServerConfig.java
@@ -0,0 +1,26 @@
+/*
+ * 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.tests.scim.tck;
+
+import org.keycloak.common.Profile;
+import org.keycloak.testframework.server.KeycloakServerConfig;
+import org.keycloak.testframework.server.KeycloakServerConfigBuilder;
+
+/**
+ * A server with the experimental SCIM group ownership feature enabled.
+ */
+public class GroupOwnershipServerConfig implements KeycloakServerConfig {
+
+ @Override
+ public KeycloakServerConfigBuilder configure(KeycloakServerConfigBuilder config) {
+ return config.features(Profile.Feature.SCIM_GROUP_MEMBERSHIP_CLAIMS);
+ }
+}
diff --git a/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipSupport.java b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipSupport.java
new file mode 100644
index 000000000000..a8f54533e0f9
--- /dev/null
+++ b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipSupport.java
@@ -0,0 +1,210 @@
+/*
+ * 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.tests.scim.tck;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import jakarta.ws.rs.NotFoundException;
+import jakarta.ws.rs.core.Response;
+
+import org.keycloak.models.AdminRoles;
+import org.keycloak.models.Constants;
+import org.keycloak.models.utils.KeycloakModelUtils;
+import org.keycloak.representations.idm.ClientRepresentation;
+import org.keycloak.representations.idm.GroupRepresentation;
+import org.keycloak.representations.idm.RoleRepresentation;
+import org.keycloak.representations.idm.UserRepresentation;
+import org.keycloak.scim.client.ScimClient;
+import org.keycloak.scim.client.ScimClientException;
+import org.keycloak.scim.protocol.request.PatchRequest;
+import org.keycloak.scim.protocol.request.PatchRequest.PatchOperation;
+import org.keycloak.scim.resource.group.Group;
+import org.keycloak.scim.resource.group.Member;
+import org.keycloak.testframework.realm.ClientBuilder;
+import org.keycloak.testframework.realm.ManagedRealm;
+import org.keycloak.testframework.util.ApiUtil;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * Shared steps for the SCIM group ownership tests.
+ */
+final class GroupOwnershipSupport {
+
+ static final String MANAGED_BY_ANOTHER_CLIENT = "The group is managed by another SCIM client";
+
+ private final ManagedRealm realm;
+
+ GroupOwnershipSupport(ManagedRealm realm) {
+ this.realm = realm;
+ }
+
+ Group createGroup(ScimClient client, String... memberIds) {
+ Group group = client.groups().create(group(null, "owned-" + KeycloakModelUtils.generateId(), memberIds));
+ cleanupGroup(group.getId());
+ return group;
+ }
+
+ String createAdminGroup() {
+ GroupRepresentation rep = new GroupRepresentation();
+ rep.setName("unowned-" + KeycloakModelUtils.generateId());
+
+ try (Response response = realm.admin().groups().add(rep)) {
+ assertEquals(201, response.getStatus());
+ String id = ApiUtil.getCreatedId(response);
+ cleanupGroup(id);
+ return id;
+ }
+ }
+
+ void cleanupGroup(String id) {
+ realm.cleanup().add(r -> {
+ if (r.groups().groups().stream().anyMatch(g -> g.getId().equals(id))) {
+ r.groups().group(id).remove();
+ }
+ });
+ }
+
+ String createUser() {
+ UserRepresentation user = new UserRepresentation();
+ user.setUsername("owned-" + KeycloakModelUtils.generateId());
+ user.setEnabled(true);
+
+ try (Response response = realm.admin().users().create(user)) {
+ assertEquals(201, response.getStatus());
+ String id = ApiUtil.getCreatedId(response);
+ realm.cleanup().add(r -> r.users().delete(id).close());
+ return id;
+ }
+ }
+
+ String createAdminUser() {
+ String id = createUser();
+ grantManageUsers(id);
+ return id;
+ }
+
+ String createServiceAccountUser() {
+ ClientRepresentation client = ClientBuilder.create()
+ .clientId("owned-" + KeycloakModelUtils.generateId())
+ .secret("secret")
+ .serviceAccountsEnabled(true)
+ .enabled(true)
+ .build();
+
+ try (Response response = realm.admin().clients().create(client)) {
+ assertEquals(201, response.getStatus());
+ String id = ApiUtil.getCreatedId(response);
+ realm.cleanup().add(r -> r.clients().get(id).remove());
+ return realm.admin().clients().get(id).toRepresentation().getServiceAccountUserId();
+ }
+ }
+
+ void grantManageUsers(String userId) {
+ realm.admin().users().get(userId).roles().clientLevel(realmManagementId()).add(List.of(manageUsersRole()));
+ }
+
+ String realmManagementId() {
+ return realm.admin().clients().findByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID).get(0).getId();
+ }
+
+ RoleRepresentation manageUsersRole() {
+ return realm.admin().clients().get(realmManagementId()).roles().get(AdminRoles.MANAGE_USERS).toRepresentation();
+ }
+
+ void adminJoin(String userId, String groupId) {
+ realm.admin().users().get(userId).joinGroup(groupId);
+ }
+
+ void adminLeave(String userId, String groupId) {
+ realm.admin().users().get(userId).leaveGroup(groupId);
+ }
+
+ String groupName(String groupId) {
+ return realm.admin().groups().group(groupId).toRepresentation().getName();
+ }
+
+ boolean groupExists(String groupId) {
+ try {
+ realm.admin().groups().group(groupId).toRepresentation();
+ return true;
+ } catch (NotFoundException e) {
+ return false;
+ }
+ }
+
+ void assertMembers(String groupId, String... expected) {
+ Set actual = realm.admin().groups().group(groupId).members(0, 1000).stream()
+ .map(UserRepresentation::getId)
+ .collect(Collectors.toSet());
+ assertEquals(Set.of(expected), actual);
+ }
+
+ static void put(ScimClient client, Group group, String... memberIds) {
+ client.groups().update(group(group.getId(), group.getDisplayName(), memberIds));
+ }
+
+ static Group group(String id, String displayName, String... memberIds) {
+ Group group = new Group();
+ group.setId(id);
+ group.setDisplayName(displayName);
+ group.setMembers(new ArrayList<>());
+
+ for (String memberId : memberIds) {
+ Member member = new Member();
+ member.setValue(memberId);
+ group.addMember(member);
+ }
+
+ return group;
+ }
+
+ static void patch(ScimClient client, String groupId, PatchOperation... operations) {
+ PatchRequest request = PatchRequest.create().build();
+ request.setOperations(new ArrayList<>(List.of(operations)));
+ client.groups().patch(groupId, request);
+ }
+
+ static String members(String... ids) {
+ return Set.of(ids).stream().map(id -> "{\"value\":\"" + id + "\"}").collect(Collectors.joining(",", "[", "]"));
+ }
+
+ static Set memberIds(Group group) {
+ return group.getMembers() == null ? Set.of() : group.getMembers().stream().map(Member::getValue).collect(Collectors.toSet());
+ }
+
+ static ScimClientException assertStatus(int status, Runnable request) {
+ try {
+ request.run();
+ } catch (ScimClientException sce) {
+ assertNotNull(sce.getError(), "expected a SCIM error body");
+ assertEquals(status, sce.getError().getStatusInt(), () -> "detail: " + sce.getError().getDetail());
+ return sce;
+ }
+ fail("expected HTTP " + status);
+ return null;
+ }
+
+ static void assertManagedByAnotherClient(Runnable request) {
+ ScimClientException sce = assertStatus(403, request);
+ assertEquals(MANAGED_BY_ANOTHER_CLIENT, sce.getError().getDetail());
+ }
+
+ static void assertMutability(Runnable request) {
+ ScimClientException sce = assertStatus(400, request);
+ assertEquals("mutability", sce.getError().getScimType());
+ }
+}
diff --git a/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipTest.java b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipTest.java
new file mode 100644
index 000000000000..9078146d20d7
--- /dev/null
+++ b/scim/tests/base/src/test/java/org/keycloak/tests/scim/tck/GroupOwnershipTest.java
@@ -0,0 +1,433 @@
+/*
+ * 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.tests.scim.tck;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+import org.keycloak.models.utils.KeycloakModelUtils;
+import org.keycloak.representations.idm.AdminEventRepresentation;
+import org.keycloak.representations.idm.UserRepresentation;
+import org.keycloak.scim.client.ScimClient;
+import org.keycloak.scim.client.ScimClientException;
+import org.keycloak.scim.protocol.request.PatchRequest.PatchOperation;
+import org.keycloak.scim.resource.group.Group;
+import org.keycloak.scim.resource.group.Member;
+import org.keycloak.testframework.annotations.InjectAdminEvents;
+import org.keycloak.testframework.annotations.InjectRealm;
+import org.keycloak.testframework.annotations.KeycloakIntegrationTest;
+import org.keycloak.testframework.events.AdminEvents;
+import org.keycloak.testframework.realm.ManagedRealm;
+import org.keycloak.testframework.scim.client.annotations.InjectScimClient;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.keycloak.tests.scim.tck.GroupOwnershipSupport.assertManagedByAnotherClient;
+import static org.keycloak.tests.scim.tck.GroupOwnershipSupport.assertStatus;
+import static org.keycloak.tests.scim.tck.GroupOwnershipSupport.group;
+import static org.keycloak.tests.scim.tck.GroupOwnershipSupport.memberIds;
+import static org.keycloak.tests.scim.tck.GroupOwnershipSupport.members;
+import static org.keycloak.tests.scim.tck.GroupOwnershipSupport.patch;
+import static org.keycloak.tests.scim.tck.GroupOwnershipSupport.put;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Groups owned by the SCIM client that created them. One directory behaves like an Okta app built with the App
+ * Integration Wizard (full member list on PUT), the other like Microsoft Entra ID (PATCH add and remove).
+ */
+@KeycloakIntegrationTest(config = GroupOwnershipServerConfig.class)
+public class GroupOwnershipTest {
+
+ @InjectRealm(config = GroupOwnershipRealmConfig.class)
+ ManagedRealm realm;
+
+ @InjectScimClient(clientId = "okta-directory")
+ ScimClient okta;
+
+ @InjectScimClient(clientId = "entra-directory")
+ ScimClient entra;
+
+ @InjectAdminEvents
+ AdminEvents adminEvents;
+
+ GroupOwnershipSupport support;
+
+ @BeforeEach
+ public void setUp() {
+ support = new GroupOwnershipSupport(realm);
+ }
+
+ @Test
+ public void testCreateWithMembersMakesTheCallerOwner() {
+ String alice = support.createUser();
+ adminEvents.clear();
+
+ Group group = support.createGroup(okta, alice);
+ support.assertMembers(group.getId(), alice);
+ // The create request URI ends at the collection, so the event path needs the new group id as well.
+ assertEquals(List.of("CREATE scim/v2/Groups/" + group.getId() + "/" + alice), membershipEventPaths());
+
+ // Okta owns the group: Entra cannot write to it, Okta can.
+ assertManagedByAnotherClient(() -> put(entra, group));
+ put(okta, group);
+ support.assertMembers(group.getId());
+ }
+
+ @Test
+ public void testCreateWithAnUnknownMemberCreatesNothing() {
+ String alice = support.createUser();
+ String name = "owned-" + KeycloakModelUtils.generateId();
+
+ assertStatus(400, () -> okta.groups().create(group(null, name, alice, KeycloakModelUtils.generateId())));
+ assertTrue(realm.admin().groups().query(name).stream().noneMatch(g -> name.equals(g.getName())));
+ }
+
+ @Test
+ public void testOwnerPutAddsAndRemovesMembers() {
+ String alice = support.createUser();
+ String bob = support.createUser();
+ String carol = support.createUser();
+ Group group = support.createGroup(okta);
+
+ put(okta, group, alice, bob);
+ support.assertMembers(group.getId(), alice, bob);
+
+ put(okta, group, bob, carol);
+ support.assertMembers(group.getId(), bob, carol);
+
+ put(okta, group);
+ support.assertMembers(group.getId());
+ }
+
+ @Test
+ public void testOwnerPutRemovesMembersAnAdministratorAdded() {
+ String alice = support.createUser();
+ String manual = support.createUser();
+ Group group = support.createGroup(okta, alice);
+
+ // An administrator may change an owned group. The owner's next full list overwrites that change.
+ support.adminJoin(manual, group.getId());
+ support.assertMembers(group.getId(), alice, manual);
+
+ put(okta, group, alice);
+ support.assertMembers(group.getId(), alice);
+ }
+
+ @Test
+ public void testOwnerPatchAddAndRemove() {
+ String alice = support.createUser();
+ String bob = support.createUser();
+ String carol = support.createUser();
+ String id = support.createGroup(entra).getId();
+
+ patch(entra, id, new PatchOperation("Add", "members", members(alice, bob, carol)));
+ support.assertMembers(id, alice, bob, carol);
+
+ // remove by filter
+ patch(entra, id, new PatchOperation("Remove", "members[value eq \"" + alice + "\"]", null));
+ support.assertMembers(id, bob, carol);
+
+ // remove by value list, as Microsoft Entra ID sends it
+ patch(entra, id, new PatchOperation("Remove", "members", members(bob)));
+ support.assertMembers(id, carol);
+
+ // an empty value list removes nobody
+ patch(entra, id, new PatchOperation("Remove", "members", "[]"));
+ support.assertMembers(id, carol);
+
+ // a filter with or
+ patch(entra, id, new PatchOperation("Add", "members", members(alice)));
+ patch(entra, id, new PatchOperation("remove", "members[value eq \"" + alice + "\" or value eq \"" + carol + "\"]", null));
+ support.assertMembers(id);
+
+ // parentheses around the same or, which the shared filter parser accepts
+ patch(entra, id, new PatchOperation("Add", "members", members(alice, carol)));
+ patch(entra, id, new PatchOperation("remove", "members[(value eq \"" + alice + "\" or value eq \"" + carol + "\")]", null));
+ support.assertMembers(id);
+
+ // remove without a filter or value removes everyone
+ patch(entra, id, new PatchOperation("Add", "members", members(alice, bob)));
+ patch(entra, id, new PatchOperation("Remove", "members", null));
+ support.assertMembers(id);
+ }
+
+ @Test
+ public void testOwnerPatchReplace() {
+ String alice = support.createUser();
+ String bob = support.createUser();
+ String carol = support.createUser();
+ String id = support.createGroup(okta, alice).getId();
+
+ patch(okta, id, new PatchOperation("Replace", "members", members(bob)));
+ support.assertMembers(id, bob);
+
+ // no path, members in the value
+ patch(okta, id, new PatchOperation("Replace", null, "{\"members\":" + members(alice, carol) + "}"));
+ support.assertMembers(id, alice, carol);
+
+ // RFC 7644 section 3.5.2: the schema URN as the path targets the group itself, like no path
+ patch(okta, id, new PatchOperation("Replace", Group.SCHEMA, "{\"members\":" + members(bob) + "}"));
+ support.assertMembers(id, bob);
+
+ patch(okta, id, new PatchOperation("Add", Group.SCHEMA, "{\"members\":" + members(carol) + "}"));
+ support.assertMembers(id, bob, carol);
+
+ // replace together with another attribute
+ String renamed = "owned-renamed-" + KeycloakModelUtils.generateId();
+ patch(okta, id, new PatchOperation("Replace", null, "{\"displayName\":\"" + renamed + "\",\"members\":[]}"));
+ support.assertMembers(id);
+ assertEquals(renamed, support.groupName(id));
+ }
+
+ @Test
+ public void testOwnerPatchWithoutMembersKeepsThem() {
+ String alice = support.createUser();
+ String id = support.createGroup(okta, alice).getId();
+ String renamed = "owned-renamed-" + KeycloakModelUtils.generateId();
+
+ patch(okta, id, new PatchOperation("Replace", null, "{\"displayName\":\"" + renamed + "\"}"));
+ assertEquals(renamed, support.groupName(id));
+ support.assertMembers(id, alice);
+ }
+
+ // Service accounts and administrators are never removed by an owner's write
+ @Test
+ public void testProtectedMembersLeftOutOfAFullListAreKept() {
+ String serviceAccount = support.createServiceAccountUser();
+ String admin = support.createAdminUser();
+ String alice = support.createUser();
+ String bob = support.createUser();
+ Group group = support.createGroup(okta, bob);
+ support.adminJoin(serviceAccount, group.getId());
+ support.adminJoin(admin, group.getId());
+
+ // The full list leaves both out: they stay, and the rest of the request is applied.
+ put(okta, group, alice);
+ support.assertMembers(group.getId(), serviceAccount, admin, alice);
+
+ patch(okta, group.getId(), new PatchOperation("Replace", "members", members()));
+ support.assertMembers(group.getId(), serviceAccount, admin);
+
+ patch(okta, group.getId(), new PatchOperation("Add", "members", members(alice)));
+ patch(okta, group.getId(), new PatchOperation("Remove", "members", null));
+ support.assertMembers(group.getId(), serviceAccount, admin);
+
+ // Listing a protected member who is already in the group changes nothing and is accepted.
+ put(okta, group, admin, alice);
+ support.assertMembers(group.getId(), serviceAccount, admin, alice);
+ }
+
+ @Test
+ public void testNamingAProtectedMemberIsRefused() {
+ String serviceAccount = support.createServiceAccountUser();
+ String admin = support.createAdminUser();
+ String otherAdmin = support.createAdminUser();
+ String alice = support.createUser();
+ Group group = support.createGroup(okta, alice);
+ support.adminJoin(admin, group.getId());
+
+ // Adding one who is not a member, through a full list or PATCH add, is refused as without owners.
+ assertStatus(400, () -> put(okta, group, alice, serviceAccount));
+ assertStatus(403, () -> put(okta, group, alice, admin, otherAdmin));
+ assertStatus(400, () -> patch(okta, group.getId(), new PatchOperation("Add", "members", members(serviceAccount))));
+ assertStatus(403, () -> patch(okta, group.getId(), new PatchOperation("Add", "members", members(otherAdmin))));
+
+ // Naming one in a PATCH add or remove is refused even when they are a member.
+ assertStatus(403, () -> patch(okta, group.getId(), new PatchOperation("Add", "members", members(admin))));
+ assertStatus(403, () -> patch(okta, group.getId(), new PatchOperation("Remove", "members[value eq \"" + admin + "\"]", null)));
+ assertStatus(403, () -> patch(okta, group.getId(), new PatchOperation("Remove", "members", members(admin))));
+
+ support.assertMembers(group.getId(), alice, admin);
+ }
+
+ @Test
+ public void testAnUnknownMemberRejectsTheWholeRequest() {
+ String alice = support.createUser();
+ String bob = support.createUser();
+ String missing = KeycloakModelUtils.generateId();
+ Group group = support.createGroup(okta, bob);
+ String name = group.getDisplayName();
+
+ // PUT with one unknown member: no rename, nobody added, nobody removed.
+ Group renamed = group(group.getId(), "owned-renamed-" + KeycloakModelUtils.generateId(), alice, missing);
+ assertStatus(400, () -> okta.groups().update(renamed));
+ support.assertMembers(group.getId(), bob);
+ assertEquals(name, support.groupName(group.getId()));
+
+ // PUT with a member without a value.
+ Group blank = group(group.getId(), name, alice);
+ blank.addMember(new Member());
+ assertStatus(400, () -> okta.groups().update(blank));
+ support.assertMembers(group.getId(), bob);
+
+ // PATCH where the bad member comes after a rename and a good one.
+ assertStatus(400, () -> patch(okta, group.getId(),
+ new PatchOperation("replace", "displayName", "owned-renamed-" + KeycloakModelUtils.generateId()),
+ new PatchOperation("Add", "members", members(alice)),
+ new PatchOperation("Add", "members", members(missing))));
+ support.assertMembers(group.getId(), bob);
+ assertEquals(name, support.groupName(group.getId()));
+
+ // PATCH replace with an unknown member removes nobody.
+ assertStatus(400, () -> patch(okta, group.getId(), new PatchOperation("Replace", "members", members(alice, missing))));
+ assertStatus(400, () -> patch(okta, group.getId(), new PatchOperation("Remove", "members[value eq \"" + missing + "\"]", null)));
+ support.assertMembers(group.getId(), bob);
+ }
+
+ // A read of an owned group shows every member, to every client, without being asked for them.
+ @Test
+ public void testReadShowsEveryMemberToEveryClient() {
+ String alice = support.createUser();
+ String manual = support.createUser();
+ Group group = support.createGroup(okta, alice);
+ support.adminJoin(manual, group.getId());
+
+ assertEquals(Set.of(alice, manual), memberIds(okta.groups().get(group.getId())));
+ assertEquals(Set.of(alice, manual), memberIds(entra.groups().get(group.getId())));
+ assertEquals(Set.of(alice, manual), memberIds(entra.groups().get(group.getId(), List.of("displayName", "members"))));
+
+ // A list filtered by name, which is how a directory looks a group up, shows the same.
+ List listed = entra.groups().getAll("displayName eq \"" + group.getDisplayName() + "\"").getResources();
+ assertEquals(1, listed.size());
+ assertEquals(Set.of(alice, manual), memberIds(listed.get(0)));
+
+ // Excluding members, or asking only for other attributes, leaves them out.
+ assertEquals(Set.of(), memberIds(okta.groups().get(group.getId(), null, List.of("members"))));
+ assertEquals(Set.of(), memberIds(okta.groups().get(group.getId(), List.of("displayName"))));
+ }
+
+ // The live Okta run of 14 November 2026: after each full-list PUT, Okta read the group back and sent a second PUT
+ // built from what it read. A read without members would make the second PUT empty the group.
+ @Test
+ public void testOktaFollowUpPutBuiltFromTheReadKeepsItsMembers() {
+ String alice = support.createUser();
+ String bob = support.createUser();
+ Group group = support.createGroup(okta, alice, bob);
+
+ put(okta, group, alice);
+ Set seen = new HashSet<>(memberIds(okta.groups().get(group.getId())));
+ seen.remove(bob);
+ put(okta, group, seen.toArray(String[]::new));
+ support.assertMembers(group.getId(), alice);
+
+ put(okta, group, alice, bob);
+ seen = new HashSet<>(memberIds(okta.groups().get(group.getId())));
+ seen.add(bob);
+ put(okta, group, seen.toArray(String[]::new));
+ support.assertMembers(group.getId(), alice, bob);
+ }
+
+ @Test
+ public void testMembershipEventsOnlyForJoinsAndLeaves() {
+ String alice = support.createUser();
+ Group group = support.createGroup(okta);
+
+ adminEvents.clear();
+ put(okta, group, alice);
+ assertEquals(List.of("CREATE scim/v2/Groups/" + group.getId() + "/" + alice), membershipEventPaths());
+
+ put(okta, group, alice);
+ assertEquals(List.of(), membershipEventPaths());
+
+ put(okta, group);
+ assertEquals(List.of("DELETE scim/v2/Groups/" + group.getId() + "/" + alice), membershipEventPaths());
+ }
+
+ // Two full lists for the same group at the same time: both succeed, and the group ends with one of them.
+ @Test
+ public void testConcurrentOwnerPutsEndConsistent() throws Exception {
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+
+ try {
+ for (int i = 0; i < 15; i++) {
+ String alice = support.createUser();
+ String bob = support.createUser();
+ String carol = support.createUser();
+ Group group = support.createGroup(okta, alice);
+
+ CountDownLatch start = new CountDownLatch(1);
+ Future> first = executor.submit(gated(start, () -> put(okta, group, alice, bob)));
+ Future> second = executor.submit(gated(start, () -> put(okta, group, carol)));
+ start.countDown();
+ first.get(60, TimeUnit.SECONDS);
+ second.get(60, TimeUnit.SECONDS);
+
+ Set actual = realm.admin().groups().group(group.getId()).members(0, 1000).stream()
+ .map(UserRepresentation::getId)
+ .collect(Collectors.toSet());
+ assertTrue(actual.equals(Set.of(alice, bob)) || actual.equals(Set.of(carol)), "unexpected members " + actual);
+ }
+ } finally {
+ executor.shutdownNow();
+ }
+ }
+
+ // An administrator removes a member while the owner drops it. Both requests must succeed.
+ @Test
+ public void testAdministratorRemovalRacingOwnerDropBothSucceed() throws Exception {
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+
+ try {
+ for (int i = 0; i < 15; i++) {
+ String bob = support.createUser();
+ Group group = support.createGroup(okta, bob);
+
+ CountDownLatch start = new CountDownLatch(1);
+ Future> adminRemoves = executor.submit(gated(start, () -> support.adminLeave(bob, group.getId())));
+ Future> oktaDrops = executor.submit(gated(start, () -> put(okta, group)));
+ start.countDown();
+ adminRemoves.get(60, TimeUnit.SECONDS);
+ oktaDrops.get(60, TimeUnit.SECONDS);
+
+ support.assertMembers(group.getId());
+ assertFalse(support.groupName(group.getId()).isBlank());
+ }
+ } finally {
+ executor.shutdownNow();
+ }
+ }
+
+ private List membershipEventPaths() {
+ List events = new ArrayList<>();
+ for (AdminEventRepresentation event = adminEvents.poll(); event != null; event = adminEvents.poll()) {
+ if ("GROUP_MEMBERSHIP".equals(event.getResourceType())) {
+ events.add(event.getOperationType() + " " + event.getResourcePath());
+ }
+ }
+ return events;
+ }
+
+ private static Callable gated(CountDownLatch start, Runnable request) {
+ return () -> {
+ start.await();
+ try {
+ request.run();
+ } catch (ScimClientException sce) {
+ throw new AssertionError("concurrent request failed: "
+ + (sce.getError() == null ? "no error body" : sce.getError().getStatusInt() + " " + sce.getError().getDetail()), sce);
+ }
+ return null;
+ };
+ }
+}