authentik.providers.scim.clients.groups
Group client
1"""Group client""" 2 3from copy import deepcopy 4from itertools import batched 5from typing import Any 6 7from django.db import transaction 8from django.db.models import QuerySet 9from pydantic import ValidationError 10 11from authentik.core.models import Group 12from authentik.lib.merge import MERGE_LIST_UNIQUE 13from authentik.lib.sync.mapper import PropertyMappingManager 14from authentik.lib.sync.outgoing.base import Direction 15from authentik.lib.sync.outgoing.exceptions import ( 16 NotFoundSyncException, 17 ObjectExistsSyncException, 18 StopSync, 19) 20from authentik.policies.utils import delete_none_values 21from authentik.providers.scim.clients.base import SCIMClient 22from authentik.providers.scim.clients.exceptions import SCIMRequestException 23from authentik.providers.scim.clients.schema import ( 24 SCIM_GROUP_SCHEMA, 25 GroupMember, 26 PatchOp, 27 PatchOperation, 28 PatchRequest, 29) 30from authentik.providers.scim.clients.schema import Group as SCIMGroupSchema 31from authentik.providers.scim.models import ( 32 SCIMCompatibilityMode, 33 SCIMMapping, 34 SCIMProvider, 35 SCIMProviderGroup, 36 SCIMProviderUser, 37) 38 39 40class SCIMGroupClient(SCIMClient[Group, SCIMProviderGroup, SCIMGroupSchema]): 41 """SCIM client for groups""" 42 43 connection_type = SCIMProviderGroup 44 connection_type_query = "group" 45 mapper: PropertyMappingManager 46 47 def __init__(self, provider: SCIMProvider): 48 super().__init__(provider) 49 self.mapper = PropertyMappingManager( 50 self.provider.property_mappings_group.all().order_by("name").select_subclasses(), 51 SCIMMapping, 52 ["group", "provider", "connection"], 53 ) 54 55 def _create_group_member(self, id: str) -> GroupMember: 56 member = GroupMember(value=id) 57 # https://developer.webex.com/admin/docs/api/v1/scim-2-groups/create-a-group 58 if self.provider.compatibility_mode == SCIMCompatibilityMode.WEBEX: 59 member.type = "user" 60 return member 61 62 def to_schema(self, obj: Group, connection: SCIMProviderGroup) -> SCIMGroupSchema: 63 """Convert authentik user into SCIM""" 64 raw_scim_group = super().to_schema(obj, connection) 65 try: 66 scim_group = SCIMGroupSchema.model_validate(delete_none_values(raw_scim_group)) 67 except ValidationError as exc: 68 raise StopSync(exc, obj) from exc 69 if SCIM_GROUP_SCHEMA not in scim_group.schemas: 70 scim_group.schemas.insert(0, SCIM_GROUP_SCHEMA) 71 # As this might be unset, we need to tell pydantic it's set so ensure the schemas 72 # are included, even if its just the defaults 73 scim_group.schemas = list(scim_group.schemas) 74 if not scim_group.externalId: 75 scim_group.externalId = str(obj.pk) 76 77 if not self._config.patch.supported: 78 users = list(obj.users.order_by("id").values_list("id", flat=True)) 79 member_ids = SCIMProviderUser.objects.filter( 80 provider=self.provider, user__pk__in=users 81 ).values_list("scim_id", flat=True) 82 # The member list is also sent when it is empty, as without PATCH that is the only 83 # way to remove the last member of a group 84 scim_group.members = [self._create_group_member(x) for x in member_ids] 85 else: 86 del scim_group.members 87 return scim_group 88 89 def delete(self, identifier: str): 90 """Delete group""" 91 SCIMProviderGroup.objects.filter(provider=self.provider, scim_id=identifier).delete() 92 return self._request("DELETE", f"/Groups/{identifier}") 93 94 def create(self, group: Group): 95 """Create group from scratch and create a connection object""" 96 scim_group = self.to_schema(group, None) 97 payload = scim_group.model_dump(mode="json", exclude_unset=True) 98 connection = None 99 with transaction.atomic(): 100 try: 101 response = self._request("POST", "/Groups", json=payload) 102 except ObjectExistsSyncException as exc: 103 remote_group = self.find_conflicting( 104 "/Groups", "displayName", scim_group.displayName 105 ) 106 if not remote_group: 107 raise exc 108 connection = SCIMProviderGroup.objects.create( 109 provider=self.provider, 110 group=group, 111 scim_id=remote_group["id"], 112 attributes=remote_group, 113 ) 114 else: 115 scim_id = response.get("id") 116 if not scim_id or scim_id == "": 117 raise StopSync("SCIM Response with missing or invalid `id`") 118 connection = SCIMProviderGroup.objects.create( 119 provider=self.provider, 120 group=group, 121 scim_id=scim_id, 122 attributes=payload | response, 123 ) 124 # Members are only sent separately when PATCH is supported, as to_schema otherwise 125 # includes them in the request above 126 if self._config.patch.supported: 127 users = list(group.users.order_by("id").values_list("id", flat=True)) 128 self._patch_add_users(connection, users) 129 return connection 130 131 @staticmethod 132 def _member_ids(group: dict[str, Any]) -> set[str]: 133 """Get the IDs of a serialized group's members""" 134 return {member["value"] for member in group.get("members") or [] if member.get("value")} 135 136 def diff(self, local_created: dict[str, Any], connection: SCIMProviderGroup): 137 """Check if a group is different than what we last wrote to the remote system. 138 Returns true if there is a difference in data.""" 139 local_known = connection.attributes 140 if "members" in local_created: 141 # Members are compared by ID, as the remote system may return them with additional 142 # attributes, and as merging lists cannot detect a removed member. A recorded state 143 # without a member list cannot prove the members are unchanged. 144 if "members" not in local_known: 145 return True 146 if self._member_ids(local_created) != self._member_ids(local_known): 147 return True 148 local_created = {key: value for key, value in local_created.items() if key != "members"} 149 local_updated = deepcopy(local_known) 150 MERGE_LIST_UNIQUE.merge(local_updated, local_created) 151 return self._json_encoder.encode(local_updated) != self._json_encoder.encode(local_known) 152 153 def update(self, group: Group, connection: SCIMProviderGroup): 154 """Update existing group""" 155 scim_group = self.to_schema(group, connection) 156 scim_group.id = connection.scim_id 157 payload = scim_group.model_dump(mode="json", exclude_unset=True) 158 if not self.diff(payload, connection): 159 self.logger.debug("Skipping group write as data has not changed") 160 return self.patch_compare_users(group) 161 try: 162 if self._config.patch.supported: 163 return self._update_patch(group, payload, connection) 164 return self._update_put(group, payload, connection) 165 except NotFoundSyncException: 166 # Resource missing is handled by self.write, which will re-create the group 167 raise 168 169 def _update_patch(self, group: Group, payload: dict[str, Any], connection: SCIMProviderGroup): 170 """Apply provider-specific PATCH requests""" 171 match connection.provider.compatibility_mode: 172 case SCIMCompatibilityMode.AWS: 173 self._update_patch_aws(payload, connection) 174 case _: 175 self._update_patch_general(payload, connection) 176 return self.patch_compare_users(group) 177 178 def _update_patch_aws(self, payload: dict[str, Any], connection: SCIMProviderGroup): 179 """Run PATCH requests for supported attributes""" 180 self._patch_chunked( 181 connection.scim_id, 182 *[ 183 PatchOperation( 184 op=PatchOp.replace, 185 path=attr, 186 value=payload[attr], 187 ) 188 for attr in ("displayName", "externalId") 189 ], 190 ) 191 192 def _update_patch_general(self, payload: dict[str, Any], connection: SCIMProviderGroup): 193 """Update a group via PATCH request""" 194 # Patch group's attributes instead of replacing it and re-adding users if we can 195 value = {key: value for key, value in payload.items() if key != "id"} 196 response = self._request( 197 "PATCH", 198 f"/Groups/{connection.scim_id}", 199 json=PatchRequest( 200 Operations=[ 201 PatchOperation( 202 op=PatchOp.replace, 203 path=None, 204 value=value, 205 ) 206 ] 207 ).model_dump( 208 mode="json", 209 exclude_unset=True, 210 exclude_none=True, 211 ), 212 ) 213 self._record_written_state(connection, payload, response) 214 215 def _record_written_state( 216 self, connection: SCIMProviderGroup, payload: dict[str, Any], response: dict[str, Any] 217 ): 218 """Remember what we wrote to the remote system, so that writes which would not change 219 anything can be skipped. The response takes precedence over the sent payload, but cannot 220 be recorded alone: servers may answer 204 No Content or omit attributes such as the 221 member list.""" 222 connection.attributes = payload | response 223 connection.save() 224 225 def _update_put(self, group: Group, payload: dict[str, Any], connection: SCIMProviderGroup): 226 """Update a group via PUT request""" 227 try: 228 response = self._request("PUT", f"/Groups/{connection.scim_id}", json=payload) 229 self._record_written_state(connection, payload, response) 230 return self.patch_compare_users(group) 231 except SCIMRequestException, ObjectExistsSyncException: 232 # Some providers don't support PUT on groups, so this is mainly a fix for the initial 233 # sync, send patch add requests for all the users the group currently has 234 return self._update_patch(group, payload, connection) 235 236 def update_group(self, group: Group, action: Direction, users_set: set[int]): 237 """Update a group, either using PUT to replace it or PATCH if supported""" 238 scim_group = SCIMProviderGroup.objects.filter(provider=self.provider, group=group).first() 239 if not scim_group: 240 self.logger.warning( 241 "could not sync group membership, group does not exist", group=group 242 ) 243 return 244 if self._config.patch.supported: 245 if action == Direction.add: 246 return self._patch_add_users(scim_group, users_set) 247 if action == Direction.remove: 248 return self._patch_remove_users(scim_group, users_set) 249 try: 250 return self.write(group) 251 except SCIMRequestException as exc: 252 if self._config.is_fallback: 253 # Assume that provider does not support PUT and also doesn't support 254 # ServiceProviderConfig, so try PATCH as a fallback 255 if action == Direction.add: 256 return self._patch_add_users(scim_group, users_set) 257 if action == Direction.remove: 258 return self._patch_remove_users(scim_group, users_set) 259 raise exc 260 261 def _patch_chunked( 262 self, 263 group_id: str, 264 *ops: PatchOperation, 265 ): 266 """Helper function that chunks patch requests based on the maxOperations attribute. 267 This is not strictly according to specs but there's nothing in the schema that allows the 268 us to know what the maximum patch operations per request should be.""" 269 chunk_size = self._config.bulk.maxOperations 270 if chunk_size < 1: 271 chunk_size = len(ops) 272 if len(ops) < 1: 273 return 274 for chunk in batched(ops, chunk_size, strict=False): 275 req = PatchRequest(Operations=list(chunk)) 276 self._request( 277 "PATCH", 278 f"/Groups/{group_id}", 279 json=req.model_dump(mode="json", exclude_none=True), 280 ) 281 282 def _patch_add_member(self, user_id: str) -> PatchOperation: 283 """Build a patch operation that adds a member to a group""" 284 return PatchOperation( 285 op=PatchOp.add, 286 path="members", 287 value=[ 288 self._create_group_member(user_id).model_dump( 289 mode="json", 290 exclude_unset=True, 291 ) 292 ], 293 ) 294 295 def _patch_remove_member(self, user_id: str) -> PatchOperation: 296 """Build a patch operation that removes a member from a group""" 297 return PatchOperation( 298 op=PatchOp.remove, 299 path=f'members[value eq "{user_id}"]', 300 ) 301 302 @transaction.atomic 303 def patch_compare_users(self, group: Group): 304 """Compare users with a SCIM group and add/remove any differences""" 305 # Get scim group first 306 scim_group = SCIMProviderGroup.objects.filter(provider=self.provider, group=group).first() 307 if not scim_group: 308 self.logger.warning( 309 "could not sync group membership, group does not exist", group=group 310 ) 311 return 312 # Get a list of all users in the authentik group 313 raw_users_should = list(group.users.order_by("id").values_list("id", flat=True)) 314 # Lookup the SCIM IDs of the users 315 users_should: list[str] = list( 316 SCIMProviderUser.objects.filter( 317 user__pk__in=raw_users_should, provider=self.provider 318 ).values_list("scim_id", flat=True) 319 ) 320 if len(raw_users_should) != len(users_should): 321 self.logger.warning( 322 "User count mismatch, not all users in the group are synced to SCIM yet.", 323 group=group, 324 ) 325 # Get current group status 326 current_group = SCIMGroupSchema.model_validate( 327 self._request("GET", f"/Groups/{scim_group.scim_id}") 328 ) 329 users_to_add = [] 330 users_to_remove = [] 331 # Check users currently in group and if they shouldn't be in the group and remove them 332 for user in current_group.members or []: 333 if user.value not in users_should: 334 users_to_remove.append(user.value) 335 # Check users that should be in the group and add them 336 existing_member_ids = {x.value for x in (current_group.members or [])} 337 for user in users_should: 338 if user not in existing_member_ids: 339 users_to_add.append(user) 340 # Only send request if we need to make changes 341 if len(users_to_add) < 1 and len(users_to_remove) < 1: 342 return 343 return self._patch_chunked( 344 scim_group.scim_id, 345 *[self._patch_add_member(x) for x in users_to_add], 346 *[self._patch_remove_member(x) for x in users_to_remove], 347 ) 348 349 def _patch_add_users(self, scim_group: SCIMProviderGroup, users_set: set[int]): 350 """Add users in users_set to group""" 351 if len(users_set) < 1: 352 return 353 user_ids = list( 354 SCIMProviderUser.objects.filter( 355 user__pk__in=users_set, provider=self.provider 356 ).values_list("scim_id", flat=True) 357 ) 358 if len(user_ids) < 1: 359 return 360 self._patch_chunked( 361 scim_group.scim_id, 362 *[self._patch_add_member(x) for x in user_ids], 363 ) 364 365 def _patch_remove_users(self, scim_group: SCIMProviderGroup, users_set: set[int]): 366 """Remove users in users_set from group""" 367 if len(users_set) < 1: 368 return 369 user_ids = list( 370 SCIMProviderUser.objects.filter( 371 user__pk__in=users_set, provider=self.provider 372 ).values_list("scim_id", flat=True) 373 ) 374 if len(user_ids) < 1: 375 return 376 self._patch_chunked( 377 scim_group.scim_id, 378 *[self._patch_remove_member(x) for x in user_ids], 379 ) 380 381 def discover(self): 382 groups = self.provider.get_object_qs(Group) 383 for group in self.paginate_resources("/Groups"): 384 try: 385 self._discover_group_single(group, groups) 386 except ValidationError: 387 self.logger.warning("failed to discover group", scim_group=group.get("externalId")) 388 389 def _discover_group_single(self, group: dict, groups: QuerySet[Group]): 390 scim_group = SCIMGroupSchema.model_validate(group) 391 if SCIMProviderGroup.objects.filter(scim_id=scim_group.id, provider=self.provider).exists(): 392 return 393 # Only adopt groups that this provider is configured to manage. 394 ak_group = groups.filter(name=scim_group.displayName).first() 395 if not ak_group: 396 return 397 SCIMProviderGroup.objects.create( 398 provider=self.provider, 399 group=ak_group, 400 scim_id=scim_group.id, 401 attributes=group, 402 )
class
SCIMGroupClient(authentik.providers.scim.clients.base.SCIMClient[authentik.core.models.Group, authentik.providers.scim.models.SCIMProviderGroup, authentik.providers.scim.clients.schema.Group]):
41class SCIMGroupClient(SCIMClient[Group, SCIMProviderGroup, SCIMGroupSchema]): 42 """SCIM client for groups""" 43 44 connection_type = SCIMProviderGroup 45 connection_type_query = "group" 46 mapper: PropertyMappingManager 47 48 def __init__(self, provider: SCIMProvider): 49 super().__init__(provider) 50 self.mapper = PropertyMappingManager( 51 self.provider.property_mappings_group.all().order_by("name").select_subclasses(), 52 SCIMMapping, 53 ["group", "provider", "connection"], 54 ) 55 56 def _create_group_member(self, id: str) -> GroupMember: 57 member = GroupMember(value=id) 58 # https://developer.webex.com/admin/docs/api/v1/scim-2-groups/create-a-group 59 if self.provider.compatibility_mode == SCIMCompatibilityMode.WEBEX: 60 member.type = "user" 61 return member 62 63 def to_schema(self, obj: Group, connection: SCIMProviderGroup) -> SCIMGroupSchema: 64 """Convert authentik user into SCIM""" 65 raw_scim_group = super().to_schema(obj, connection) 66 try: 67 scim_group = SCIMGroupSchema.model_validate(delete_none_values(raw_scim_group)) 68 except ValidationError as exc: 69 raise StopSync(exc, obj) from exc 70 if SCIM_GROUP_SCHEMA not in scim_group.schemas: 71 scim_group.schemas.insert(0, SCIM_GROUP_SCHEMA) 72 # As this might be unset, we need to tell pydantic it's set so ensure the schemas 73 # are included, even if its just the defaults 74 scim_group.schemas = list(scim_group.schemas) 75 if not scim_group.externalId: 76 scim_group.externalId = str(obj.pk) 77 78 if not self._config.patch.supported: 79 users = list(obj.users.order_by("id").values_list("id", flat=True)) 80 member_ids = SCIMProviderUser.objects.filter( 81 provider=self.provider, user__pk__in=users 82 ).values_list("scim_id", flat=True) 83 # The member list is also sent when it is empty, as without PATCH that is the only 84 # way to remove the last member of a group 85 scim_group.members = [self._create_group_member(x) for x in member_ids] 86 else: 87 del scim_group.members 88 return scim_group 89 90 def delete(self, identifier: str): 91 """Delete group""" 92 SCIMProviderGroup.objects.filter(provider=self.provider, scim_id=identifier).delete() 93 return self._request("DELETE", f"/Groups/{identifier}") 94 95 def create(self, group: Group): 96 """Create group from scratch and create a connection object""" 97 scim_group = self.to_schema(group, None) 98 payload = scim_group.model_dump(mode="json", exclude_unset=True) 99 connection = None 100 with transaction.atomic(): 101 try: 102 response = self._request("POST", "/Groups", json=payload) 103 except ObjectExistsSyncException as exc: 104 remote_group = self.find_conflicting( 105 "/Groups", "displayName", scim_group.displayName 106 ) 107 if not remote_group: 108 raise exc 109 connection = SCIMProviderGroup.objects.create( 110 provider=self.provider, 111 group=group, 112 scim_id=remote_group["id"], 113 attributes=remote_group, 114 ) 115 else: 116 scim_id = response.get("id") 117 if not scim_id or scim_id == "": 118 raise StopSync("SCIM Response with missing or invalid `id`") 119 connection = SCIMProviderGroup.objects.create( 120 provider=self.provider, 121 group=group, 122 scim_id=scim_id, 123 attributes=payload | response, 124 ) 125 # Members are only sent separately when PATCH is supported, as to_schema otherwise 126 # includes them in the request above 127 if self._config.patch.supported: 128 users = list(group.users.order_by("id").values_list("id", flat=True)) 129 self._patch_add_users(connection, users) 130 return connection 131 132 @staticmethod 133 def _member_ids(group: dict[str, Any]) -> set[str]: 134 """Get the IDs of a serialized group's members""" 135 return {member["value"] for member in group.get("members") or [] if member.get("value")} 136 137 def diff(self, local_created: dict[str, Any], connection: SCIMProviderGroup): 138 """Check if a group is different than what we last wrote to the remote system. 139 Returns true if there is a difference in data.""" 140 local_known = connection.attributes 141 if "members" in local_created: 142 # Members are compared by ID, as the remote system may return them with additional 143 # attributes, and as merging lists cannot detect a removed member. A recorded state 144 # without a member list cannot prove the members are unchanged. 145 if "members" not in local_known: 146 return True 147 if self._member_ids(local_created) != self._member_ids(local_known): 148 return True 149 local_created = {key: value for key, value in local_created.items() if key != "members"} 150 local_updated = deepcopy(local_known) 151 MERGE_LIST_UNIQUE.merge(local_updated, local_created) 152 return self._json_encoder.encode(local_updated) != self._json_encoder.encode(local_known) 153 154 def update(self, group: Group, connection: SCIMProviderGroup): 155 """Update existing group""" 156 scim_group = self.to_schema(group, connection) 157 scim_group.id = connection.scim_id 158 payload = scim_group.model_dump(mode="json", exclude_unset=True) 159 if not self.diff(payload, connection): 160 self.logger.debug("Skipping group write as data has not changed") 161 return self.patch_compare_users(group) 162 try: 163 if self._config.patch.supported: 164 return self._update_patch(group, payload, connection) 165 return self._update_put(group, payload, connection) 166 except NotFoundSyncException: 167 # Resource missing is handled by self.write, which will re-create the group 168 raise 169 170 def _update_patch(self, group: Group, payload: dict[str, Any], connection: SCIMProviderGroup): 171 """Apply provider-specific PATCH requests""" 172 match connection.provider.compatibility_mode: 173 case SCIMCompatibilityMode.AWS: 174 self._update_patch_aws(payload, connection) 175 case _: 176 self._update_patch_general(payload, connection) 177 return self.patch_compare_users(group) 178 179 def _update_patch_aws(self, payload: dict[str, Any], connection: SCIMProviderGroup): 180 """Run PATCH requests for supported attributes""" 181 self._patch_chunked( 182 connection.scim_id, 183 *[ 184 PatchOperation( 185 op=PatchOp.replace, 186 path=attr, 187 value=payload[attr], 188 ) 189 for attr in ("displayName", "externalId") 190 ], 191 ) 192 193 def _update_patch_general(self, payload: dict[str, Any], connection: SCIMProviderGroup): 194 """Update a group via PATCH request""" 195 # Patch group's attributes instead of replacing it and re-adding users if we can 196 value = {key: value for key, value in payload.items() if key != "id"} 197 response = self._request( 198 "PATCH", 199 f"/Groups/{connection.scim_id}", 200 json=PatchRequest( 201 Operations=[ 202 PatchOperation( 203 op=PatchOp.replace, 204 path=None, 205 value=value, 206 ) 207 ] 208 ).model_dump( 209 mode="json", 210 exclude_unset=True, 211 exclude_none=True, 212 ), 213 ) 214 self._record_written_state(connection, payload, response) 215 216 def _record_written_state( 217 self, connection: SCIMProviderGroup, payload: dict[str, Any], response: dict[str, Any] 218 ): 219 """Remember what we wrote to the remote system, so that writes which would not change 220 anything can be skipped. The response takes precedence over the sent payload, but cannot 221 be recorded alone: servers may answer 204 No Content or omit attributes such as the 222 member list.""" 223 connection.attributes = payload | response 224 connection.save() 225 226 def _update_put(self, group: Group, payload: dict[str, Any], connection: SCIMProviderGroup): 227 """Update a group via PUT request""" 228 try: 229 response = self._request("PUT", f"/Groups/{connection.scim_id}", json=payload) 230 self._record_written_state(connection, payload, response) 231 return self.patch_compare_users(group) 232 except SCIMRequestException, ObjectExistsSyncException: 233 # Some providers don't support PUT on groups, so this is mainly a fix for the initial 234 # sync, send patch add requests for all the users the group currently has 235 return self._update_patch(group, payload, connection) 236 237 def update_group(self, group: Group, action: Direction, users_set: set[int]): 238 """Update a group, either using PUT to replace it or PATCH if supported""" 239 scim_group = SCIMProviderGroup.objects.filter(provider=self.provider, group=group).first() 240 if not scim_group: 241 self.logger.warning( 242 "could not sync group membership, group does not exist", group=group 243 ) 244 return 245 if self._config.patch.supported: 246 if action == Direction.add: 247 return self._patch_add_users(scim_group, users_set) 248 if action == Direction.remove: 249 return self._patch_remove_users(scim_group, users_set) 250 try: 251 return self.write(group) 252 except SCIMRequestException as exc: 253 if self._config.is_fallback: 254 # Assume that provider does not support PUT and also doesn't support 255 # ServiceProviderConfig, so try PATCH as a fallback 256 if action == Direction.add: 257 return self._patch_add_users(scim_group, users_set) 258 if action == Direction.remove: 259 return self._patch_remove_users(scim_group, users_set) 260 raise exc 261 262 def _patch_chunked( 263 self, 264 group_id: str, 265 *ops: PatchOperation, 266 ): 267 """Helper function that chunks patch requests based on the maxOperations attribute. 268 This is not strictly according to specs but there's nothing in the schema that allows the 269 us to know what the maximum patch operations per request should be.""" 270 chunk_size = self._config.bulk.maxOperations 271 if chunk_size < 1: 272 chunk_size = len(ops) 273 if len(ops) < 1: 274 return 275 for chunk in batched(ops, chunk_size, strict=False): 276 req = PatchRequest(Operations=list(chunk)) 277 self._request( 278 "PATCH", 279 f"/Groups/{group_id}", 280 json=req.model_dump(mode="json", exclude_none=True), 281 ) 282 283 def _patch_add_member(self, user_id: str) -> PatchOperation: 284 """Build a patch operation that adds a member to a group""" 285 return PatchOperation( 286 op=PatchOp.add, 287 path="members", 288 value=[ 289 self._create_group_member(user_id).model_dump( 290 mode="json", 291 exclude_unset=True, 292 ) 293 ], 294 ) 295 296 def _patch_remove_member(self, user_id: str) -> PatchOperation: 297 """Build a patch operation that removes a member from a group""" 298 return PatchOperation( 299 op=PatchOp.remove, 300 path=f'members[value eq "{user_id}"]', 301 ) 302 303 @transaction.atomic 304 def patch_compare_users(self, group: Group): 305 """Compare users with a SCIM group and add/remove any differences""" 306 # Get scim group first 307 scim_group = SCIMProviderGroup.objects.filter(provider=self.provider, group=group).first() 308 if not scim_group: 309 self.logger.warning( 310 "could not sync group membership, group does not exist", group=group 311 ) 312 return 313 # Get a list of all users in the authentik group 314 raw_users_should = list(group.users.order_by("id").values_list("id", flat=True)) 315 # Lookup the SCIM IDs of the users 316 users_should: list[str] = list( 317 SCIMProviderUser.objects.filter( 318 user__pk__in=raw_users_should, provider=self.provider 319 ).values_list("scim_id", flat=True) 320 ) 321 if len(raw_users_should) != len(users_should): 322 self.logger.warning( 323 "User count mismatch, not all users in the group are synced to SCIM yet.", 324 group=group, 325 ) 326 # Get current group status 327 current_group = SCIMGroupSchema.model_validate( 328 self._request("GET", f"/Groups/{scim_group.scim_id}") 329 ) 330 users_to_add = [] 331 users_to_remove = [] 332 # Check users currently in group and if they shouldn't be in the group and remove them 333 for user in current_group.members or []: 334 if user.value not in users_should: 335 users_to_remove.append(user.value) 336 # Check users that should be in the group and add them 337 existing_member_ids = {x.value for x in (current_group.members or [])} 338 for user in users_should: 339 if user not in existing_member_ids: 340 users_to_add.append(user) 341 # Only send request if we need to make changes 342 if len(users_to_add) < 1 and len(users_to_remove) < 1: 343 return 344 return self._patch_chunked( 345 scim_group.scim_id, 346 *[self._patch_add_member(x) for x in users_to_add], 347 *[self._patch_remove_member(x) for x in users_to_remove], 348 ) 349 350 def _patch_add_users(self, scim_group: SCIMProviderGroup, users_set: set[int]): 351 """Add users in users_set to group""" 352 if len(users_set) < 1: 353 return 354 user_ids = list( 355 SCIMProviderUser.objects.filter( 356 user__pk__in=users_set, provider=self.provider 357 ).values_list("scim_id", flat=True) 358 ) 359 if len(user_ids) < 1: 360 return 361 self._patch_chunked( 362 scim_group.scim_id, 363 *[self._patch_add_member(x) for x in user_ids], 364 ) 365 366 def _patch_remove_users(self, scim_group: SCIMProviderGroup, users_set: set[int]): 367 """Remove users in users_set from group""" 368 if len(users_set) < 1: 369 return 370 user_ids = list( 371 SCIMProviderUser.objects.filter( 372 user__pk__in=users_set, provider=self.provider 373 ).values_list("scim_id", flat=True) 374 ) 375 if len(user_ids) < 1: 376 return 377 self._patch_chunked( 378 scim_group.scim_id, 379 *[self._patch_remove_member(x) for x in user_ids], 380 ) 381 382 def discover(self): 383 groups = self.provider.get_object_qs(Group) 384 for group in self.paginate_resources("/Groups"): 385 try: 386 self._discover_group_single(group, groups) 387 except ValidationError: 388 self.logger.warning("failed to discover group", scim_group=group.get("externalId")) 389 390 def _discover_group_single(self, group: dict, groups: QuerySet[Group]): 391 scim_group = SCIMGroupSchema.model_validate(group) 392 if SCIMProviderGroup.objects.filter(scim_id=scim_group.id, provider=self.provider).exists(): 393 return 394 # Only adopt groups that this provider is configured to manage. 395 ak_group = groups.filter(name=scim_group.displayName).first() 396 if not ak_group: 397 return 398 SCIMProviderGroup.objects.create( 399 provider=self.provider, 400 group=ak_group, 401 scim_id=scim_group.id, 402 attributes=group, 403 )
SCIM client for groups
SCIMGroupClient(provider: authentik.providers.scim.models.SCIMProvider)
connection_type =
<class 'authentik.providers.scim.models.SCIMProviderGroup'>
def
to_schema( self, obj: authentik.core.models.Group, connection: authentik.providers.scim.models.SCIMProviderGroup) -> authentik.providers.scim.clients.schema.Group:
63 def to_schema(self, obj: Group, connection: SCIMProviderGroup) -> SCIMGroupSchema: 64 """Convert authentik user into SCIM""" 65 raw_scim_group = super().to_schema(obj, connection) 66 try: 67 scim_group = SCIMGroupSchema.model_validate(delete_none_values(raw_scim_group)) 68 except ValidationError as exc: 69 raise StopSync(exc, obj) from exc 70 if SCIM_GROUP_SCHEMA not in scim_group.schemas: 71 scim_group.schemas.insert(0, SCIM_GROUP_SCHEMA) 72 # As this might be unset, we need to tell pydantic it's set so ensure the schemas 73 # are included, even if its just the defaults 74 scim_group.schemas = list(scim_group.schemas) 75 if not scim_group.externalId: 76 scim_group.externalId = str(obj.pk) 77 78 if not self._config.patch.supported: 79 users = list(obj.users.order_by("id").values_list("id", flat=True)) 80 member_ids = SCIMProviderUser.objects.filter( 81 provider=self.provider, user__pk__in=users 82 ).values_list("scim_id", flat=True) 83 # The member list is also sent when it is empty, as without PATCH that is the only 84 # way to remove the last member of a group 85 scim_group.members = [self._create_group_member(x) for x in member_ids] 86 else: 87 del scim_group.members 88 return scim_group
Convert authentik user into SCIM
def
delete(self, identifier: str):
90 def delete(self, identifier: str): 91 """Delete group""" 92 SCIMProviderGroup.objects.filter(provider=self.provider, scim_id=identifier).delete() 93 return self._request("DELETE", f"/Groups/{identifier}")
Delete group
95 def create(self, group: Group): 96 """Create group from scratch and create a connection object""" 97 scim_group = self.to_schema(group, None) 98 payload = scim_group.model_dump(mode="json", exclude_unset=True) 99 connection = None 100 with transaction.atomic(): 101 try: 102 response = self._request("POST", "/Groups", json=payload) 103 except ObjectExistsSyncException as exc: 104 remote_group = self.find_conflicting( 105 "/Groups", "displayName", scim_group.displayName 106 ) 107 if not remote_group: 108 raise exc 109 connection = SCIMProviderGroup.objects.create( 110 provider=self.provider, 111 group=group, 112 scim_id=remote_group["id"], 113 attributes=remote_group, 114 ) 115 else: 116 scim_id = response.get("id") 117 if not scim_id or scim_id == "": 118 raise StopSync("SCIM Response with missing or invalid `id`") 119 connection = SCIMProviderGroup.objects.create( 120 provider=self.provider, 121 group=group, 122 scim_id=scim_id, 123 attributes=payload | response, 124 ) 125 # Members are only sent separately when PATCH is supported, as to_schema otherwise 126 # includes them in the request above 127 if self._config.patch.supported: 128 users = list(group.users.order_by("id").values_list("id", flat=True)) 129 self._patch_add_users(connection, users) 130 return connection
Create group from scratch and create a connection object
def
diff( self, local_created: dict[str, typing.Any], connection: authentik.providers.scim.models.SCIMProviderGroup):
137 def diff(self, local_created: dict[str, Any], connection: SCIMProviderGroup): 138 """Check if a group is different than what we last wrote to the remote system. 139 Returns true if there is a difference in data.""" 140 local_known = connection.attributes 141 if "members" in local_created: 142 # Members are compared by ID, as the remote system may return them with additional 143 # attributes, and as merging lists cannot detect a removed member. A recorded state 144 # without a member list cannot prove the members are unchanged. 145 if "members" not in local_known: 146 return True 147 if self._member_ids(local_created) != self._member_ids(local_known): 148 return True 149 local_created = {key: value for key, value in local_created.items() if key != "members"} 150 local_updated = deepcopy(local_known) 151 MERGE_LIST_UNIQUE.merge(local_updated, local_created) 152 return self._json_encoder.encode(local_updated) != self._json_encoder.encode(local_known)
Check if a group is different than what we last wrote to the remote system. Returns true if there is a difference in data.
def
update( self, group: authentik.core.models.Group, connection: authentik.providers.scim.models.SCIMProviderGroup):
154 def update(self, group: Group, connection: SCIMProviderGroup): 155 """Update existing group""" 156 scim_group = self.to_schema(group, connection) 157 scim_group.id = connection.scim_id 158 payload = scim_group.model_dump(mode="json", exclude_unset=True) 159 if not self.diff(payload, connection): 160 self.logger.debug("Skipping group write as data has not changed") 161 return self.patch_compare_users(group) 162 try: 163 if self._config.patch.supported: 164 return self._update_patch(group, payload, connection) 165 return self._update_put(group, payload, connection) 166 except NotFoundSyncException: 167 # Resource missing is handled by self.write, which will re-create the group 168 raise
Update existing group
def
update_group( self, group: authentik.core.models.Group, action: authentik.lib.sync.outgoing.base.Direction, users_set: set[int]):
237 def update_group(self, group: Group, action: Direction, users_set: set[int]): 238 """Update a group, either using PUT to replace it or PATCH if supported""" 239 scim_group = SCIMProviderGroup.objects.filter(provider=self.provider, group=group).first() 240 if not scim_group: 241 self.logger.warning( 242 "could not sync group membership, group does not exist", group=group 243 ) 244 return 245 if self._config.patch.supported: 246 if action == Direction.add: 247 return self._patch_add_users(scim_group, users_set) 248 if action == Direction.remove: 249 return self._patch_remove_users(scim_group, users_set) 250 try: 251 return self.write(group) 252 except SCIMRequestException as exc: 253 if self._config.is_fallback: 254 # Assume that provider does not support PUT and also doesn't support 255 # ServiceProviderConfig, so try PATCH as a fallback 256 if action == Direction.add: 257 return self._patch_add_users(scim_group, users_set) 258 if action == Direction.remove: 259 return self._patch_remove_users(scim_group, users_set) 260 raise exc
Update a group, either using PUT to replace it or PATCH if supported
303 @transaction.atomic 304 def patch_compare_users(self, group: Group): 305 """Compare users with a SCIM group and add/remove any differences""" 306 # Get scim group first 307 scim_group = SCIMProviderGroup.objects.filter(provider=self.provider, group=group).first() 308 if not scim_group: 309 self.logger.warning( 310 "could not sync group membership, group does not exist", group=group 311 ) 312 return 313 # Get a list of all users in the authentik group 314 raw_users_should = list(group.users.order_by("id").values_list("id", flat=True)) 315 # Lookup the SCIM IDs of the users 316 users_should: list[str] = list( 317 SCIMProviderUser.objects.filter( 318 user__pk__in=raw_users_should, provider=self.provider 319 ).values_list("scim_id", flat=True) 320 ) 321 if len(raw_users_should) != len(users_should): 322 self.logger.warning( 323 "User count mismatch, not all users in the group are synced to SCIM yet.", 324 group=group, 325 ) 326 # Get current group status 327 current_group = SCIMGroupSchema.model_validate( 328 self._request("GET", f"/Groups/{scim_group.scim_id}") 329 ) 330 users_to_add = [] 331 users_to_remove = [] 332 # Check users currently in group and if they shouldn't be in the group and remove them 333 for user in current_group.members or []: 334 if user.value not in users_should: 335 users_to_remove.append(user.value) 336 # Check users that should be in the group and add them 337 existing_member_ids = {x.value for x in (current_group.members or [])} 338 for user in users_should: 339 if user not in existing_member_ids: 340 users_to_add.append(user) 341 # Only send request if we need to make changes 342 if len(users_to_add) < 1 and len(users_to_remove) < 1: 343 return 344 return self._patch_chunked( 345 scim_group.scim_id, 346 *[self._patch_add_member(x) for x in users_to_add], 347 *[self._patch_remove_member(x) for x in users_to_remove], 348 )
Compare users with a SCIM group and add/remove any differences
def
discover(self):
382 def discover(self): 383 groups = self.provider.get_object_qs(Group) 384 for group in self.paginate_resources("/Groups"): 385 try: 386 self._discover_group_single(group, groups) 387 except ValidationError: 388 self.logger.warning("failed to discover group", scim_group=group.get("externalId"))
Optional method. Can be used to implement a "discovery" where upon creation of this provider, this function will be called and can pre-link any users/groups in the remote system with the respective object in authentik based on a common identifier