authentik.rbac.field_rules
1from dataclasses import dataclass, field 2from typing import Any 3 4from django.db.models import Model 5from django.db.models.constants import LOOKUP_SEP 6from django.http import HttpRequest 7from django.utils.translation import gettext_lazy as _ 8from djangoql.ast import Name, Node 9from rest_framework.exceptions import ValidationError 10from rest_framework.fields import ( 11 BooleanField, 12 CharField, 13 ChoiceField, 14 DecimalField, 15 DictField, 16 Field, 17 FloatField, 18 IntegerField, 19 JSONField, 20 ListField, 21 MultipleChoiceField, 22) 23from rest_framework.relations import ManyRelatedField 24from rest_framework.serializers import ListSerializer 25from structlog.stdlib import get_logger 26 27LOGGER = get_logger() 28MISSING = object() 29ABSENT_KEY = "authentik-hidden-key" 30 31 32# .... don't ask 33EMPTY_VALUES: tuple[tuple[tuple[type[Field], ...], type], ...] = ( 34 ((ListSerializer, ListField, ManyRelatedField, MultipleChoiceField), list), 35 ((DictField, JSONField), dict), 36 ((BooleanField,), bool), 37 ((IntegerField, FloatField, DecimalField), int), 38 ((CharField, ChoiceField), str), 39) 40 41 42@dataclass 43class FieldRules: 44 """ 45 This class deals with the fine details of some fields being hidden from users so those users 46 can't gain knowledge of the value of those fields (in case they are defined by authentik), or 47 even of their existence (in case they are defined by an admin). 48 49 Hidden fields can be 50 - whole fields, e.g. `email`, or 51 - fields within a JSON field, e.g. `attributes.salary` 52 53 This class is necessarily brittle and exact. Any change to it MUST be exhaustively tested. 54 """ 55 56 hidden: set[str] = field(default_factory=set) 57 readonly: set[str] = field(default_factory=set) 58 59 def __bool__(self) -> bool: 60 return bool(self.hidden or self.readonly) 61 62 @property 63 def hidden_whole_fields(self) -> set[str]: 64 return set(path for path in self.hidden if "." not in path and "[" not in path) 65 66 def hide(self, data: dict, fields: dict[str, Field]) -> dict: 67 for path in self.hidden: 68 if path in self.hidden_whole_fields: 69 if path in data: 70 data[path] = self.empty_value(fields.get(path)) 71 else: 72 data = FieldRules.remove_path(data, path.split(".")) 73 return data 74 75 def unknown_fields(self, fields: dict[str, Field]) -> set[str]: 76 """Fields paths start with that the serializer does not have, likely typos""" 77 paths = self.hidden | self.readonly 78 return { 79 FieldRules.parse_segment(FieldRules.split_path(path)[0])[0] for path in paths 80 } - set(fields) 81 82 @staticmethod 83 def without_selectors(paths: set[str]) -> set[str]: 84 return set( 85 ".".join(FieldRules.parse_segment(segment)[0] for segment in path.split(".")) 86 for path in paths 87 ) 88 89 @staticmethod 90 def accepts_input(path: str, fields: dict[str, Field]) -> bool: 91 field = FieldRules.split_path(path)[0] 92 return "[" not in path and not (field in fields and fields[field].read_only) 93 94 def restrict_input(self, data: Any, instance: Model | None, fields: dict[str, Field]) -> Any: 95 """Drop hidden input, keep stored values of protected keys, and refuse read-only changes""" 96 if not hasattr(data, "copy"): 97 return data 98 data = data.copy() 99 errors = {} 100 for path in self.hidden: 101 field, keys = FieldRules.split_path(path) 102 if field not in data or not self.accepts_input(path, fields): 103 continue 104 if keys: 105 if isinstance(data[field], dict): 106 data[field] = FieldRules.set_path( 107 data[field], keys, self.stored_value(instance, field, keys) 108 ) 109 elif instance is not None and field in fields and not fields[field].read_only: 110 data[field] = fields[field].to_representation(fields[field].get_attribute(instance)) 111 else: 112 del data[field] 113 for path in self.readonly - self.hidden: 114 field, keys = FieldRules.split_path(path) 115 if field not in data or not self.accepts_input(path, fields): 116 continue 117 if keys: 118 if not isinstance(data[field], dict): 119 continue 120 stored = self.stored_value(instance, field, keys) 121 given = FieldRules.get_path(data[field], keys) 122 if ( 123 given is MISSING 124 or given == stored 125 or (stored is MISSING and FieldRules.is_empty(given)) 126 ): 127 data[field] = FieldRules.set_path(data[field], keys, stored) 128 continue 129 else: 130 current = ( 131 MISSING 132 if instance is None or field not in fields 133 else fields[field].to_representation(fields[field].get_attribute(instance)) 134 ) 135 if data[field] == current or ( 136 current is MISSING and FieldRules.is_empty(data[field]) 137 ): 138 del data[field] 139 continue 140 errors[path] = _("You cannot change this value.") 141 if errors: 142 raise ValidationError(errors) 143 return data 144 145 def refuse_hidden_parameters(self, request: HttpRequest, view: Any): 146 """Ordering or filtering by a hidden field would reveal its values""" 147 hidden = self.hidden_whole_fields 148 if not hidden: 149 return 150 base_filters = getattr(getattr(view, "filterset_class", None), "base_filters", {}) 151 refused = [ 152 field 153 for term in request.query_params.get("ordering", "").split(",") 154 if (field := self.ordered_field(term)) in hidden 155 ] 156 for param in request.query_params: 157 field_name = getattr(base_filters.get(param), "field_name", None) or param 158 if field_name.split(LOOKUP_SEP)[0] in hidden: 159 refused.append(param) 160 if refused: 161 raise ValidationError({param: _("This field is hidden from you.") for param in refused}) 162 163 @staticmethod 164 def ordered_field(term: str) -> str: 165 """ 166 The model field an `ordering` term sorts by, without 167 - the `-` DRF reads as descending 168 - a `__` path into related models 169 """ 170 term = term.strip() 171 if term.startswith("-"): 172 term = term[1:] 173 return term.split(LOOKUP_SEP)[0] 174 175 def guard_search(self, node: Node): 176 """Refuse searches by hidden fields, and make hidden JSON keys match as if absent""" 177 if isinstance(node, Name): 178 if node.parts[0] in self.hidden_whole_fields: 179 raise ValidationError({"search": _("This field is hidden from you.")}) 180 path = ".".join(node.parts) 181 for hidden in self.hidden - self.hidden_whole_fields: 182 if path == hidden or path.startswith(f"{hidden}."): 183 node.parts = [node.parts[0], ABSENT_KEY] 184 return 185 for value in vars(node).values(): 186 if isinstance(value, Node): 187 self.guard_search(value) 188 189 @staticmethod 190 def stored_value(instance: Model | None, field: str, keys: list[str]) -> Any: 191 if instance is None: 192 return MISSING 193 return FieldRules.get_path(getattr(instance, field, None), keys) 194 195 @staticmethod 196 def empty_value(field: Field | None) -> Any: 197 """What a hidden field shows, keeping the field and its type""" 198 for field_types, empty in EMPTY_VALUES: 199 if isinstance(field, field_types): 200 return empty() 201 return None 202 203 @staticmethod 204 def split_path(path: str) -> tuple[str, list[str]]: 205 field, *keys = path.split(".") 206 return field, keys 207 208 @staticmethod 209 def get_path(value: Any, keys: list[str]) -> Any: 210 for key in keys: 211 if not isinstance(value, dict) or key not in value: 212 return MISSING 213 value = value[key] 214 return value 215 216 @staticmethod 217 def set_path(value: dict, keys: list[str], new: Any) -> dict: 218 """A copy of `value` with the key path set to `new`, or removed if `new` is MISSING""" 219 copy = dict(value) 220 key = keys[0] 221 rest = keys[1:] 222 if not rest: 223 if new is MISSING: 224 copy.pop(key, None) 225 else: 226 copy[key] = new 227 return copy 228 inner = copy.get(key) 229 if not isinstance(inner, dict): 230 if new is MISSING: 231 return copy 232 inner = {} 233 copy[key] = FieldRules.set_path(inner, rest, new) 234 return copy 235 236 @staticmethod 237 def parse_segment(segment: str) -> tuple[str, str | None]: 238 """`name`, or `name[pk=<pk>]` selecting by primary key""" 239 name, bracket, selector = segment.partition("[pk=") 240 if not bracket or not selector.endswith("]"): 241 return segment, None 242 return name, selector[:-1] 243 244 @staticmethod 245 def remove_path(value: Any, segments: list[str]) -> Any: 246 """A copy of `value` without what the path names. `name` is a key, `name[pk=<pk>]` only the 247 objects under it with that primary key, and lists on the way apply the rest to each item""" 248 if isinstance(value, list): 249 return [FieldRules.remove_path(item, segments) for item in value] 250 name, pk = FieldRules.parse_segment(segments[0]) 251 if not isinstance(value, dict) or name not in value: 252 return value 253 copy = dict(value) 254 rest = segments[1:] 255 target = value[name] 256 if pk is None: 257 if rest: 258 copy[name] = FieldRules.remove_path(target, rest) 259 else: 260 del copy[name] 261 return copy 262 263 def selected(item: Any) -> bool: 264 return isinstance(item, dict) and str(item.get("pk")) == pk 265 266 if isinstance(target, list): 267 if rest: 268 copy[name] = [ 269 FieldRules.remove_path(item, rest) if selected(item) else item 270 for item in target 271 ] 272 else: 273 copy[name] = [item for item in target if not selected(item)] 274 elif selected(target): 275 if rest: 276 copy[name] = FieldRules.remove_path(target, rest) 277 else: 278 del copy[name] 279 return copy 280 281 @staticmethod 282 def is_empty(value: Any) -> bool: 283 return value is None or value in ("", 0, False) or value in ({}, [])
43@dataclass 44class FieldRules: 45 """ 46 This class deals with the fine details of some fields being hidden from users so those users 47 can't gain knowledge of the value of those fields (in case they are defined by authentik), or 48 even of their existence (in case they are defined by an admin). 49 50 Hidden fields can be 51 - whole fields, e.g. `email`, or 52 - fields within a JSON field, e.g. `attributes.salary` 53 54 This class is necessarily brittle and exact. Any change to it MUST be exhaustively tested. 55 """ 56 57 hidden: set[str] = field(default_factory=set) 58 readonly: set[str] = field(default_factory=set) 59 60 def __bool__(self) -> bool: 61 return bool(self.hidden or self.readonly) 62 63 @property 64 def hidden_whole_fields(self) -> set[str]: 65 return set(path for path in self.hidden if "." not in path and "[" not in path) 66 67 def hide(self, data: dict, fields: dict[str, Field]) -> dict: 68 for path in self.hidden: 69 if path in self.hidden_whole_fields: 70 if path in data: 71 data[path] = self.empty_value(fields.get(path)) 72 else: 73 data = FieldRules.remove_path(data, path.split(".")) 74 return data 75 76 def unknown_fields(self, fields: dict[str, Field]) -> set[str]: 77 """Fields paths start with that the serializer does not have, likely typos""" 78 paths = self.hidden | self.readonly 79 return { 80 FieldRules.parse_segment(FieldRules.split_path(path)[0])[0] for path in paths 81 } - set(fields) 82 83 @staticmethod 84 def without_selectors(paths: set[str]) -> set[str]: 85 return set( 86 ".".join(FieldRules.parse_segment(segment)[0] for segment in path.split(".")) 87 for path in paths 88 ) 89 90 @staticmethod 91 def accepts_input(path: str, fields: dict[str, Field]) -> bool: 92 field = FieldRules.split_path(path)[0] 93 return "[" not in path and not (field in fields and fields[field].read_only) 94 95 def restrict_input(self, data: Any, instance: Model | None, fields: dict[str, Field]) -> Any: 96 """Drop hidden input, keep stored values of protected keys, and refuse read-only changes""" 97 if not hasattr(data, "copy"): 98 return data 99 data = data.copy() 100 errors = {} 101 for path in self.hidden: 102 field, keys = FieldRules.split_path(path) 103 if field not in data or not self.accepts_input(path, fields): 104 continue 105 if keys: 106 if isinstance(data[field], dict): 107 data[field] = FieldRules.set_path( 108 data[field], keys, self.stored_value(instance, field, keys) 109 ) 110 elif instance is not None and field in fields and not fields[field].read_only: 111 data[field] = fields[field].to_representation(fields[field].get_attribute(instance)) 112 else: 113 del data[field] 114 for path in self.readonly - self.hidden: 115 field, keys = FieldRules.split_path(path) 116 if field not in data or not self.accepts_input(path, fields): 117 continue 118 if keys: 119 if not isinstance(data[field], dict): 120 continue 121 stored = self.stored_value(instance, field, keys) 122 given = FieldRules.get_path(data[field], keys) 123 if ( 124 given is MISSING 125 or given == stored 126 or (stored is MISSING and FieldRules.is_empty(given)) 127 ): 128 data[field] = FieldRules.set_path(data[field], keys, stored) 129 continue 130 else: 131 current = ( 132 MISSING 133 if instance is None or field not in fields 134 else fields[field].to_representation(fields[field].get_attribute(instance)) 135 ) 136 if data[field] == current or ( 137 current is MISSING and FieldRules.is_empty(data[field]) 138 ): 139 del data[field] 140 continue 141 errors[path] = _("You cannot change this value.") 142 if errors: 143 raise ValidationError(errors) 144 return data 145 146 def refuse_hidden_parameters(self, request: HttpRequest, view: Any): 147 """Ordering or filtering by a hidden field would reveal its values""" 148 hidden = self.hidden_whole_fields 149 if not hidden: 150 return 151 base_filters = getattr(getattr(view, "filterset_class", None), "base_filters", {}) 152 refused = [ 153 field 154 for term in request.query_params.get("ordering", "").split(",") 155 if (field := self.ordered_field(term)) in hidden 156 ] 157 for param in request.query_params: 158 field_name = getattr(base_filters.get(param), "field_name", None) or param 159 if field_name.split(LOOKUP_SEP)[0] in hidden: 160 refused.append(param) 161 if refused: 162 raise ValidationError({param: _("This field is hidden from you.") for param in refused}) 163 164 @staticmethod 165 def ordered_field(term: str) -> str: 166 """ 167 The model field an `ordering` term sorts by, without 168 - the `-` DRF reads as descending 169 - a `__` path into related models 170 """ 171 term = term.strip() 172 if term.startswith("-"): 173 term = term[1:] 174 return term.split(LOOKUP_SEP)[0] 175 176 def guard_search(self, node: Node): 177 """Refuse searches by hidden fields, and make hidden JSON keys match as if absent""" 178 if isinstance(node, Name): 179 if node.parts[0] in self.hidden_whole_fields: 180 raise ValidationError({"search": _("This field is hidden from you.")}) 181 path = ".".join(node.parts) 182 for hidden in self.hidden - self.hidden_whole_fields: 183 if path == hidden or path.startswith(f"{hidden}."): 184 node.parts = [node.parts[0], ABSENT_KEY] 185 return 186 for value in vars(node).values(): 187 if isinstance(value, Node): 188 self.guard_search(value) 189 190 @staticmethod 191 def stored_value(instance: Model | None, field: str, keys: list[str]) -> Any: 192 if instance is None: 193 return MISSING 194 return FieldRules.get_path(getattr(instance, field, None), keys) 195 196 @staticmethod 197 def empty_value(field: Field | None) -> Any: 198 """What a hidden field shows, keeping the field and its type""" 199 for field_types, empty in EMPTY_VALUES: 200 if isinstance(field, field_types): 201 return empty() 202 return None 203 204 @staticmethod 205 def split_path(path: str) -> tuple[str, list[str]]: 206 field, *keys = path.split(".") 207 return field, keys 208 209 @staticmethod 210 def get_path(value: Any, keys: list[str]) -> Any: 211 for key in keys: 212 if not isinstance(value, dict) or key not in value: 213 return MISSING 214 value = value[key] 215 return value 216 217 @staticmethod 218 def set_path(value: dict, keys: list[str], new: Any) -> dict: 219 """A copy of `value` with the key path set to `new`, or removed if `new` is MISSING""" 220 copy = dict(value) 221 key = keys[0] 222 rest = keys[1:] 223 if not rest: 224 if new is MISSING: 225 copy.pop(key, None) 226 else: 227 copy[key] = new 228 return copy 229 inner = copy.get(key) 230 if not isinstance(inner, dict): 231 if new is MISSING: 232 return copy 233 inner = {} 234 copy[key] = FieldRules.set_path(inner, rest, new) 235 return copy 236 237 @staticmethod 238 def parse_segment(segment: str) -> tuple[str, str | None]: 239 """`name`, or `name[pk=<pk>]` selecting by primary key""" 240 name, bracket, selector = segment.partition("[pk=") 241 if not bracket or not selector.endswith("]"): 242 return segment, None 243 return name, selector[:-1] 244 245 @staticmethod 246 def remove_path(value: Any, segments: list[str]) -> Any: 247 """A copy of `value` without what the path names. `name` is a key, `name[pk=<pk>]` only the 248 objects under it with that primary key, and lists on the way apply the rest to each item""" 249 if isinstance(value, list): 250 return [FieldRules.remove_path(item, segments) for item in value] 251 name, pk = FieldRules.parse_segment(segments[0]) 252 if not isinstance(value, dict) or name not in value: 253 return value 254 copy = dict(value) 255 rest = segments[1:] 256 target = value[name] 257 if pk is None: 258 if rest: 259 copy[name] = FieldRules.remove_path(target, rest) 260 else: 261 del copy[name] 262 return copy 263 264 def selected(item: Any) -> bool: 265 return isinstance(item, dict) and str(item.get("pk")) == pk 266 267 if isinstance(target, list): 268 if rest: 269 copy[name] = [ 270 FieldRules.remove_path(item, rest) if selected(item) else item 271 for item in target 272 ] 273 else: 274 copy[name] = [item for item in target if not selected(item)] 275 elif selected(target): 276 if rest: 277 copy[name] = FieldRules.remove_path(target, rest) 278 else: 279 del copy[name] 280 return copy 281 282 @staticmethod 283 def is_empty(value: Any) -> bool: 284 return value is None or value in ("", 0, False) or value in ({}, [])
This class deals with the fine details of some fields being hidden from users so those users can't gain knowledge of the value of those fields (in case they are defined by authentik), or even of their existence (in case they are defined by an admin).
Hidden fields can be
- whole fields, e.g.
email, or - fields within a JSON field, e.g.
attributes.salary
This class is necessarily brittle and exact. Any change to it MUST be exhaustively tested.
76 def unknown_fields(self, fields: dict[str, Field]) -> set[str]: 77 """Fields paths start with that the serializer does not have, likely typos""" 78 paths = self.hidden | self.readonly 79 return { 80 FieldRules.parse_segment(FieldRules.split_path(path)[0])[0] for path in paths 81 } - set(fields)
Fields paths start with that the serializer does not have, likely typos
95 def restrict_input(self, data: Any, instance: Model | None, fields: dict[str, Field]) -> Any: 96 """Drop hidden input, keep stored values of protected keys, and refuse read-only changes""" 97 if not hasattr(data, "copy"): 98 return data 99 data = data.copy() 100 errors = {} 101 for path in self.hidden: 102 field, keys = FieldRules.split_path(path) 103 if field not in data or not self.accepts_input(path, fields): 104 continue 105 if keys: 106 if isinstance(data[field], dict): 107 data[field] = FieldRules.set_path( 108 data[field], keys, self.stored_value(instance, field, keys) 109 ) 110 elif instance is not None and field in fields and not fields[field].read_only: 111 data[field] = fields[field].to_representation(fields[field].get_attribute(instance)) 112 else: 113 del data[field] 114 for path in self.readonly - self.hidden: 115 field, keys = FieldRules.split_path(path) 116 if field not in data or not self.accepts_input(path, fields): 117 continue 118 if keys: 119 if not isinstance(data[field], dict): 120 continue 121 stored = self.stored_value(instance, field, keys) 122 given = FieldRules.get_path(data[field], keys) 123 if ( 124 given is MISSING 125 or given == stored 126 or (stored is MISSING and FieldRules.is_empty(given)) 127 ): 128 data[field] = FieldRules.set_path(data[field], keys, stored) 129 continue 130 else: 131 current = ( 132 MISSING 133 if instance is None or field not in fields 134 else fields[field].to_representation(fields[field].get_attribute(instance)) 135 ) 136 if data[field] == current or ( 137 current is MISSING and FieldRules.is_empty(data[field]) 138 ): 139 del data[field] 140 continue 141 errors[path] = _("You cannot change this value.") 142 if errors: 143 raise ValidationError(errors) 144 return data
Drop hidden input, keep stored values of protected keys, and refuse read-only changes
164 @staticmethod 165 def ordered_field(term: str) -> str: 166 """ 167 The model field an `ordering` term sorts by, without 168 - the `-` DRF reads as descending 169 - a `__` path into related models 170 """ 171 term = term.strip() 172 if term.startswith("-"): 173 term = term[1:] 174 return term.split(LOOKUP_SEP)[0]
The model field an ordering term sorts by, without
- the
-DRF reads as descending - a
__path into related models
176 def guard_search(self, node: Node): 177 """Refuse searches by hidden fields, and make hidden JSON keys match as if absent""" 178 if isinstance(node, Name): 179 if node.parts[0] in self.hidden_whole_fields: 180 raise ValidationError({"search": _("This field is hidden from you.")}) 181 path = ".".join(node.parts) 182 for hidden in self.hidden - self.hidden_whole_fields: 183 if path == hidden or path.startswith(f"{hidden}."): 184 node.parts = [node.parts[0], ABSENT_KEY] 185 return 186 for value in vars(node).values(): 187 if isinstance(value, Node): 188 self.guard_search(value)
Refuse searches by hidden fields, and make hidden JSON keys match as if absent
196 @staticmethod 197 def empty_value(field: Field | None) -> Any: 198 """What a hidden field shows, keeping the field and its type""" 199 for field_types, empty in EMPTY_VALUES: 200 if isinstance(field, field_types): 201 return empty() 202 return None
What a hidden field shows, keeping the field and its type
217 @staticmethod 218 def set_path(value: dict, keys: list[str], new: Any) -> dict: 219 """A copy of `value` with the key path set to `new`, or removed if `new` is MISSING""" 220 copy = dict(value) 221 key = keys[0] 222 rest = keys[1:] 223 if not rest: 224 if new is MISSING: 225 copy.pop(key, None) 226 else: 227 copy[key] = new 228 return copy 229 inner = copy.get(key) 230 if not isinstance(inner, dict): 231 if new is MISSING: 232 return copy 233 inner = {} 234 copy[key] = FieldRules.set_path(inner, rest, new) 235 return copy
A copy of value with the key path set to new, or removed if new is MISSING
237 @staticmethod 238 def parse_segment(segment: str) -> tuple[str, str | None]: 239 """`name`, or `name[pk=<pk>]` selecting by primary key""" 240 name, bracket, selector = segment.partition("[pk=") 241 if not bracket or not selector.endswith("]"): 242 return segment, None 243 return name, selector[:-1]
name, or name[pk=<pk>] selecting by primary key
245 @staticmethod 246 def remove_path(value: Any, segments: list[str]) -> Any: 247 """A copy of `value` without what the path names. `name` is a key, `name[pk=<pk>]` only the 248 objects under it with that primary key, and lists on the way apply the rest to each item""" 249 if isinstance(value, list): 250 return [FieldRules.remove_path(item, segments) for item in value] 251 name, pk = FieldRules.parse_segment(segments[0]) 252 if not isinstance(value, dict) or name not in value: 253 return value 254 copy = dict(value) 255 rest = segments[1:] 256 target = value[name] 257 if pk is None: 258 if rest: 259 copy[name] = FieldRules.remove_path(target, rest) 260 else: 261 del copy[name] 262 return copy 263 264 def selected(item: Any) -> bool: 265 return isinstance(item, dict) and str(item.get("pk")) == pk 266 267 if isinstance(target, list): 268 if rest: 269 copy[name] = [ 270 FieldRules.remove_path(item, rest) if selected(item) else item 271 for item in target 272 ] 273 else: 274 copy[name] = [item for item in target if not selected(item)] 275 elif selected(target): 276 if rest: 277 copy[name] = FieldRules.remove_path(target, rest) 278 else: 279 del copy[name] 280 return copy
A copy of value without what the path names. name is a key, name[pk=<pk>] only the
objects under it with that primary key, and lists on the way apply the rest to each item