authentik.sources.scim.patch.processor
1from copy import deepcopy 2from typing import Any 3 4from authentik.providers.scim.clients.schema import PatchOp, PatchOperation 5from authentik.sources.scim.constants import SCIM_URN_USER_ENTERPRISE 6from authentik.sources.scim.patch.parser import SCIMPathParser 7 8 9class SCIMPatchProcessor: 10 """Processes SCIM patch operations on Python dictionaries""" 11 12 def __init__(self): 13 self.parser = SCIMPathParser() 14 15 def apply_patches(self, data: dict[str, Any], patches: list[PatchOperation]) -> dict[str, Any]: 16 """Apply a list of patch operations to the data, returning the 17 patched data without modifying the input 18 (the SCIM source views compare the result against the stored 19 attributes to decide whether to persist anything)""" 20 result = deepcopy(data) 21 22 for _patch in patches: 23 patch = PatchOperation.model_validate(_patch) 24 if patch.path is None: 25 # Handle operations with no path - value contains attribute paths as keys 26 self._apply_bulk_operation(result, patch.op, patch.value) 27 elif patch.op == PatchOp.add: 28 self._apply_add(result, patch.path, patch.value) 29 elif patch.op == PatchOp.remove: 30 self._apply_remove(result, patch.path) 31 elif patch.op == PatchOp.replace: 32 self._apply_replace(result, patch.path, patch.value) 33 34 return result 35 36 def _apply_bulk_operation( 37 self, data: dict[str, Any], operation: PatchOp, value: dict[str, Any] 38 ): 39 """Apply bulk operations when path is None""" 40 if not isinstance(value, dict): 41 return 42 for path, val in value.items(): 43 if operation == PatchOp.add: 44 self._apply_add(data, path, val) 45 elif operation == PatchOp.remove: 46 self._apply_remove(data, path) 47 elif operation == PatchOp.replace: 48 self._apply_replace(data, path, val) 49 50 def _apply_add(self, data: dict[str, Any], path: str, value: Any): 51 """Apply ADD operation""" 52 components = self.parser.parse_path(path) 53 54 if len(components) == 1 and not components[0]["filter"]: 55 # Simple path 56 attr = components[0]["attribute"] 57 if components[0]["sub_attribute"]: 58 if attr not in data: 59 data[attr] = {} 60 # Somewhat hacky workaround for the manager attribute of the enterprise schema 61 # ideally we'd do this based on the schema 62 if attr == SCIM_URN_USER_ENTERPRISE and components[0]["sub_attribute"] == "manager": 63 data[attr][components[0]["sub_attribute"]] = {"value": value} 64 else: 65 data[attr][components[0]["sub_attribute"]] = value 66 elif attr in data: 67 data[attr].append(value) 68 else: 69 data[attr] = value 70 else: 71 # Complex path with filters 72 self._navigate_and_modify(data, components, value, "add") 73 74 def _apply_remove(self, data: dict[str, Any], path: str): 75 """Apply REMOVE operation""" 76 components = self.parser.parse_path(path) 77 78 if len(components) == 1 and not components[0]["filter"]: 79 # Simple path 80 attr = components[0]["attribute"] 81 if components[0]["sub_attribute"]: 82 if attr in data and isinstance(data[attr], dict): 83 data[attr].pop(components[0]["sub_attribute"], None) 84 else: 85 data.pop(attr, None) 86 else: 87 # Complex path with filters 88 self._navigate_and_modify(data, components, None, "remove") 89 90 def _apply_replace(self, data: dict[str, Any], path: str, value: Any): 91 """Apply REPLACE operation""" 92 components = self.parser.parse_path(path) 93 94 if len(components) == 1 and not components[0]["filter"]: 95 # Simple path 96 attr = components[0]["attribute"] 97 if components[0]["sub_attribute"]: 98 if attr not in data: 99 data[attr] = {} 100 # Somewhat hacky workaround for the manager attribute of the enterprise schema 101 # ideally we'd do this based on the schema 102 if attr == SCIM_URN_USER_ENTERPRISE and components[0]["sub_attribute"] == "manager": 103 data[attr][components[0]["sub_attribute"]] = {"value": value} 104 else: 105 data[attr][components[0]["sub_attribute"]] = value 106 else: 107 data[attr] = value 108 else: 109 # Complex path with filters 110 self._navigate_and_modify(data, components, value, "replace") 111 112 def _navigate_and_modify( # noqa PLR0912 113 self, data: dict[str, Any], components: list[dict[str, Any]], value: Any, operation: str 114 ): 115 """Navigate through complex paths and apply modifications""" 116 current = data 117 118 for i, component in enumerate(components): 119 attr = component["attribute"] 120 filter_expr = component["filter"] 121 sub_attr = component["sub_attribute"] 122 123 if filter_expr: 124 # Handle array with filter 125 if attr not in current: 126 if operation == "add": 127 current[attr] = [] 128 else: 129 return 130 131 if not isinstance(current[attr], list): 132 return 133 134 # Find matching items 135 matching_items = [] 136 for item in current[attr]: 137 if self._matches_filter(item, filter_expr): 138 matching_items.append(item) 139 140 if not matching_items and operation == "add": 141 # Create new item if none match (only for simple comparison filters) 142 if filter_expr.get("type", "comparison") == "comparison": 143 new_item = {filter_expr["attribute"]: filter_expr["value"]} 144 current[attr].append(new_item) 145 matching_items = [new_item] 146 147 # Apply operation to matching items 148 for item in matching_items: 149 if sub_attr: 150 if operation in {"add", "replace"}: 151 item[sub_attr] = value 152 elif operation == "remove": 153 item.pop(sub_attr, None) 154 elif operation in {"add", "replace"}: 155 if isinstance(value, dict): 156 item.update(value) 157 else: 158 # If value is not a dict, we can't merge it 159 pass 160 elif operation == "remove": 161 # Remove the entire item 162 if item in current[attr]: 163 current[attr].remove(item) 164 # Handle simple attribute 165 elif i == len(components) - 1: 166 # Last component 167 if sub_attr: 168 if attr not in current: 169 current[attr] = {} 170 if operation in {"add", "replace"}: 171 current[attr][sub_attr] = value 172 elif operation == "remove": 173 current[attr].pop(sub_attr, None) 174 elif operation in {"add", "replace"}: 175 current[attr] = value 176 elif operation == "remove": 177 current.pop(attr, None) 178 else: 179 # Navigate deeper 180 if attr not in current: 181 current[attr] = {} 182 current = current[attr] 183 184 def _matches_filter(self, item: dict[str, Any], filter_expr: dict[str, Any]) -> bool: 185 """Check if an item matches the filter expression""" 186 if not filter_expr: 187 return True 188 189 filter_type = filter_expr.get("type", "comparison") 190 191 if filter_type == "comparison": 192 return self._matches_comparison(item, filter_expr) 193 elif filter_type == "logical": 194 return self._matches_logical(item, filter_expr) 195 196 return False 197 198 def _matches_comparison( # noqa PLR0912 199 self, item: dict[str, Any], filter_expr: dict[str, Any] 200 ) -> bool: 201 """Check if an item matches a comparison filter""" 202 attr = filter_expr["attribute"] 203 operator = filter_expr["operator"] 204 expected_value = filter_expr["value"] 205 206 if attr not in item: 207 return False 208 209 actual_value = item[attr] 210 211 if operator == "eq": 212 return actual_value == expected_value 213 elif operator == "ne": 214 return actual_value != expected_value 215 elif operator == "co": 216 return str(expected_value) in str(actual_value) 217 elif operator == "sw": 218 return str(actual_value).startswith(str(expected_value)) 219 elif operator == "ew": 220 return str(actual_value).endswith(str(expected_value)) 221 elif operator == "gt": 222 return actual_value > expected_value 223 elif operator == "lt": 224 return actual_value < expected_value 225 elif operator == "ge": 226 return actual_value >= expected_value 227 elif operator == "le": 228 return actual_value <= expected_value 229 elif operator == "pr": 230 return actual_value is not None 231 232 return False 233 234 def _matches_logical(self, item: dict[str, Any], filter_expr: dict[str, Any]) -> bool: 235 """Check if an item matches a logical filter expression""" 236 operator = filter_expr["operator"] 237 238 if operator == "and": 239 left_result = self._matches_filter(item, filter_expr["left"]) 240 right_result = self._matches_filter(item, filter_expr["right"]) 241 return left_result and right_result 242 elif operator == "or": 243 left_result = self._matches_filter(item, filter_expr["left"]) 244 right_result = self._matches_filter(item, filter_expr["right"]) 245 return left_result or right_result 246 elif operator == "not": 247 operand_result = self._matches_filter(item, filter_expr["operand"]) 248 return not operand_result 249 250 return False
class
SCIMPatchProcessor:
10class SCIMPatchProcessor: 11 """Processes SCIM patch operations on Python dictionaries""" 12 13 def __init__(self): 14 self.parser = SCIMPathParser() 15 16 def apply_patches(self, data: dict[str, Any], patches: list[PatchOperation]) -> dict[str, Any]: 17 """Apply a list of patch operations to the data, returning the 18 patched data without modifying the input 19 (the SCIM source views compare the result against the stored 20 attributes to decide whether to persist anything)""" 21 result = deepcopy(data) 22 23 for _patch in patches: 24 patch = PatchOperation.model_validate(_patch) 25 if patch.path is None: 26 # Handle operations with no path - value contains attribute paths as keys 27 self._apply_bulk_operation(result, patch.op, patch.value) 28 elif patch.op == PatchOp.add: 29 self._apply_add(result, patch.path, patch.value) 30 elif patch.op == PatchOp.remove: 31 self._apply_remove(result, patch.path) 32 elif patch.op == PatchOp.replace: 33 self._apply_replace(result, patch.path, patch.value) 34 35 return result 36 37 def _apply_bulk_operation( 38 self, data: dict[str, Any], operation: PatchOp, value: dict[str, Any] 39 ): 40 """Apply bulk operations when path is None""" 41 if not isinstance(value, dict): 42 return 43 for path, val in value.items(): 44 if operation == PatchOp.add: 45 self._apply_add(data, path, val) 46 elif operation == PatchOp.remove: 47 self._apply_remove(data, path) 48 elif operation == PatchOp.replace: 49 self._apply_replace(data, path, val) 50 51 def _apply_add(self, data: dict[str, Any], path: str, value: Any): 52 """Apply ADD operation""" 53 components = self.parser.parse_path(path) 54 55 if len(components) == 1 and not components[0]["filter"]: 56 # Simple path 57 attr = components[0]["attribute"] 58 if components[0]["sub_attribute"]: 59 if attr not in data: 60 data[attr] = {} 61 # Somewhat hacky workaround for the manager attribute of the enterprise schema 62 # ideally we'd do this based on the schema 63 if attr == SCIM_URN_USER_ENTERPRISE and components[0]["sub_attribute"] == "manager": 64 data[attr][components[0]["sub_attribute"]] = {"value": value} 65 else: 66 data[attr][components[0]["sub_attribute"]] = value 67 elif attr in data: 68 data[attr].append(value) 69 else: 70 data[attr] = value 71 else: 72 # Complex path with filters 73 self._navigate_and_modify(data, components, value, "add") 74 75 def _apply_remove(self, data: dict[str, Any], path: str): 76 """Apply REMOVE operation""" 77 components = self.parser.parse_path(path) 78 79 if len(components) == 1 and not components[0]["filter"]: 80 # Simple path 81 attr = components[0]["attribute"] 82 if components[0]["sub_attribute"]: 83 if attr in data and isinstance(data[attr], dict): 84 data[attr].pop(components[0]["sub_attribute"], None) 85 else: 86 data.pop(attr, None) 87 else: 88 # Complex path with filters 89 self._navigate_and_modify(data, components, None, "remove") 90 91 def _apply_replace(self, data: dict[str, Any], path: str, value: Any): 92 """Apply REPLACE operation""" 93 components = self.parser.parse_path(path) 94 95 if len(components) == 1 and not components[0]["filter"]: 96 # Simple path 97 attr = components[0]["attribute"] 98 if components[0]["sub_attribute"]: 99 if attr not in data: 100 data[attr] = {} 101 # Somewhat hacky workaround for the manager attribute of the enterprise schema 102 # ideally we'd do this based on the schema 103 if attr == SCIM_URN_USER_ENTERPRISE and components[0]["sub_attribute"] == "manager": 104 data[attr][components[0]["sub_attribute"]] = {"value": value} 105 else: 106 data[attr][components[0]["sub_attribute"]] = value 107 else: 108 data[attr] = value 109 else: 110 # Complex path with filters 111 self._navigate_and_modify(data, components, value, "replace") 112 113 def _navigate_and_modify( # noqa PLR0912 114 self, data: dict[str, Any], components: list[dict[str, Any]], value: Any, operation: str 115 ): 116 """Navigate through complex paths and apply modifications""" 117 current = data 118 119 for i, component in enumerate(components): 120 attr = component["attribute"] 121 filter_expr = component["filter"] 122 sub_attr = component["sub_attribute"] 123 124 if filter_expr: 125 # Handle array with filter 126 if attr not in current: 127 if operation == "add": 128 current[attr] = [] 129 else: 130 return 131 132 if not isinstance(current[attr], list): 133 return 134 135 # Find matching items 136 matching_items = [] 137 for item in current[attr]: 138 if self._matches_filter(item, filter_expr): 139 matching_items.append(item) 140 141 if not matching_items and operation == "add": 142 # Create new item if none match (only for simple comparison filters) 143 if filter_expr.get("type", "comparison") == "comparison": 144 new_item = {filter_expr["attribute"]: filter_expr["value"]} 145 current[attr].append(new_item) 146 matching_items = [new_item] 147 148 # Apply operation to matching items 149 for item in matching_items: 150 if sub_attr: 151 if operation in {"add", "replace"}: 152 item[sub_attr] = value 153 elif operation == "remove": 154 item.pop(sub_attr, None) 155 elif operation in {"add", "replace"}: 156 if isinstance(value, dict): 157 item.update(value) 158 else: 159 # If value is not a dict, we can't merge it 160 pass 161 elif operation == "remove": 162 # Remove the entire item 163 if item in current[attr]: 164 current[attr].remove(item) 165 # Handle simple attribute 166 elif i == len(components) - 1: 167 # Last component 168 if sub_attr: 169 if attr not in current: 170 current[attr] = {} 171 if operation in {"add", "replace"}: 172 current[attr][sub_attr] = value 173 elif operation == "remove": 174 current[attr].pop(sub_attr, None) 175 elif operation in {"add", "replace"}: 176 current[attr] = value 177 elif operation == "remove": 178 current.pop(attr, None) 179 else: 180 # Navigate deeper 181 if attr not in current: 182 current[attr] = {} 183 current = current[attr] 184 185 def _matches_filter(self, item: dict[str, Any], filter_expr: dict[str, Any]) -> bool: 186 """Check if an item matches the filter expression""" 187 if not filter_expr: 188 return True 189 190 filter_type = filter_expr.get("type", "comparison") 191 192 if filter_type == "comparison": 193 return self._matches_comparison(item, filter_expr) 194 elif filter_type == "logical": 195 return self._matches_logical(item, filter_expr) 196 197 return False 198 199 def _matches_comparison( # noqa PLR0912 200 self, item: dict[str, Any], filter_expr: dict[str, Any] 201 ) -> bool: 202 """Check if an item matches a comparison filter""" 203 attr = filter_expr["attribute"] 204 operator = filter_expr["operator"] 205 expected_value = filter_expr["value"] 206 207 if attr not in item: 208 return False 209 210 actual_value = item[attr] 211 212 if operator == "eq": 213 return actual_value == expected_value 214 elif operator == "ne": 215 return actual_value != expected_value 216 elif operator == "co": 217 return str(expected_value) in str(actual_value) 218 elif operator == "sw": 219 return str(actual_value).startswith(str(expected_value)) 220 elif operator == "ew": 221 return str(actual_value).endswith(str(expected_value)) 222 elif operator == "gt": 223 return actual_value > expected_value 224 elif operator == "lt": 225 return actual_value < expected_value 226 elif operator == "ge": 227 return actual_value >= expected_value 228 elif operator == "le": 229 return actual_value <= expected_value 230 elif operator == "pr": 231 return actual_value is not None 232 233 return False 234 235 def _matches_logical(self, item: dict[str, Any], filter_expr: dict[str, Any]) -> bool: 236 """Check if an item matches a logical filter expression""" 237 operator = filter_expr["operator"] 238 239 if operator == "and": 240 left_result = self._matches_filter(item, filter_expr["left"]) 241 right_result = self._matches_filter(item, filter_expr["right"]) 242 return left_result and right_result 243 elif operator == "or": 244 left_result = self._matches_filter(item, filter_expr["left"]) 245 right_result = self._matches_filter(item, filter_expr["right"]) 246 return left_result or right_result 247 elif operator == "not": 248 operand_result = self._matches_filter(item, filter_expr["operand"]) 249 return not operand_result 250 251 return False
Processes SCIM patch operations on Python dictionaries
def
apply_patches( self, data: dict[str, typing.Any], patches: list[authentik.providers.scim.clients.schema.PatchOperation]) -> dict[str, typing.Any]:
16 def apply_patches(self, data: dict[str, Any], patches: list[PatchOperation]) -> dict[str, Any]: 17 """Apply a list of patch operations to the data, returning the 18 patched data without modifying the input 19 (the SCIM source views compare the result against the stored 20 attributes to decide whether to persist anything)""" 21 result = deepcopy(data) 22 23 for _patch in patches: 24 patch = PatchOperation.model_validate(_patch) 25 if patch.path is None: 26 # Handle operations with no path - value contains attribute paths as keys 27 self._apply_bulk_operation(result, patch.op, patch.value) 28 elif patch.op == PatchOp.add: 29 self._apply_add(result, patch.path, patch.value) 30 elif patch.op == PatchOp.remove: 31 self._apply_remove(result, patch.path) 32 elif patch.op == PatchOp.replace: 33 self._apply_replace(result, patch.path, patch.value) 34 35 return result
Apply a list of patch operations to the data, returning the patched data without modifying the input (the SCIM source views compare the result against the stored attributes to decide whether to persist anything)