authentik.rbac.endpoint_checks
Permission checks: admin-written Python that has the final say on API access
1"""Permission checks: admin-written Python that has the final say on API access""" 2 3from functools import cached_property 4from hashlib import sha256 5from json import dumps 6from typing import Any 7 8from django.core.cache import cache 9from django.db.models import Model, Q, QuerySet 10from django.utils.translation import gettext_lazy as _ 11from rest_framework.exceptions import APIException, PermissionDenied 12from rest_framework.request import Request 13from rest_framework.utils.encoders import JSONEncoder 14from structlog.stdlib import BoundLogger, get_logger 15 16from authentik.rbac.apps import EnableCustomPermissions 17from authentik.rbac.endpoints import ( 18 RBAC_FUNC_ALTER_RESPONSE, 19 RBAC_FUNC_HAS_OBJECT_PERMISSION, 20 RBAC_FUNC_HAS_PERMISSION, 21 RBAC_FUNC_HIDDEN_FIELDS, 22 RBAC_FUNC_NARROW_LIST, 23 RBAC_FUNC_READONLY_FIELDS, 24 RBAC_FUNC_WIDEN_LIST, 25 Endpoints, 26) 27from authentik.rbac.field_rules import FieldRules 28from authentik.rbac.models import PermissionCheck 29 30LOGGER = get_logger() 31REQUEST_ATTRIBUTE = "endpoint_checks" 32UNKNOWN_FIELDS_KEY = "goauthentik.io/rbac/permission_checks/{check}/{expression}/{endpoint}" 33UNKNOWN_FIELDS_TIMEOUT = 60 * 60 * 24 34 35 36class PermissionCheckSkipException(Exception): 37 """Raised by has_permission or has_object_permission to immediately grant access""" 38 39 40class PermissionCheckFailed(APIException): 41 default_detail = _("A permission check failed.") 42 43 44class EndpointChecks: 45 """The permission check bound to an endpoint, as it applies to one request""" 46 47 def __init__(self, request: Request, endpoint: str | None): 48 self.request = request 49 self.endpoint = endpoint 50 self.field_rules_by_object: dict[Any, FieldRules] = {} 51 self.reported_fields: set[str] = set() 52 53 @classmethod 54 def for_request(cls, request: Request, action: str | None = None) -> EndpointChecks: 55 return cls.for_endpoint(request, Endpoints.endpoint_id(request, action)) 56 57 @classmethod 58 def for_endpoint(cls, request: Request, endpoint: str | None) -> EndpointChecks: 59 checks = request.__dict__.setdefault(REQUEST_ATTRIBUTE, {}) 60 if endpoint not in checks: 61 checks[endpoint] = cls(request, endpoint) 62 return checks[endpoint] 63 64 @cached_property 65 def bound_check(self) -> PermissionCheck | None: 66 # The flag first, as the superuser check can cost a query 67 if not self.endpoint or not EnableCustomPermissions.get(): 68 return None 69 if PermissionCheck.skipped_for(self.request.user): 70 return None 71 return PermissionCheck.objects.filter(endpoints__contains=[self.endpoint]).first() 72 73 def defines(self, *functions: str) -> bool: 74 """Helper to determine whether the `EndpointCheck` defines all `functions`""" 75 if self.bound_check is None: 76 return False 77 endpoint = Endpoints.hookable().get(self.endpoint) 78 return endpoint is not None and any( 79 function in endpoint.functions and self.bound_check.defines(function) 80 for function in functions 81 ) 82 83 def has_permission(self, allowed: bool) -> bool: 84 """The final decision on the request, given whether authentik allows it""" 85 return self.final_decision(RBAC_FUNC_HAS_PERMISSION, allowed) 86 87 def has_object_permission(self, obj: Model, allowed: bool) -> bool: 88 """The final decision on one object, given whether authentik allows it""" 89 return self.final_decision(RBAC_FUNC_HAS_OBJECT_PERMISSION, allowed, obj) 90 91 def final_decision(self, function: str, allowed: bool, *objects: Model) -> bool: 92 """A check returning True keeps authentik's decision, False forbids, and 93 PermissionCheckSkipException grants""" 94 if not self.defines(function): 95 return allowed 96 try: 97 result = self.bound_check.run( 98 function, self.request, self.endpoint, self.request, *objects 99 ) 100 except PermissionCheckSkipException: 101 decision = True 102 except PermissionDenied as exc: 103 self.logger(function).info("Permission check denied", reason=str(exc.detail)) 104 raise 105 except Exception as exc: # noqa: BLE001 106 self.logger(function).warning("Permission check failed", exc=exc) 107 decision = False 108 else: 109 if not isinstance(result, bool): 110 self.logger(function).warning("Permission check did not return a bool") 111 decision = allowed if result is True else False 112 if decision != allowed: 113 self.logger(function).info("Permission check changed decision", decision=decision) 114 return decision 115 116 def filter_list(self, visible: QuerySet, everything: QuerySet) -> QuerySet: 117 """authentik's list `visible`, narrowed by narrow_list, plus what widen_list picks from 118 `everything` the endpoint can list""" 119 if self.defines(RBAC_FUNC_NARROW_LIST): 120 kept = self.run_list_function(RBAC_FUNC_NARROW_LIST, visible) 121 visible = visible.filter(pk__in=kept.values("pk")) 122 if self.defines(RBAC_FUNC_WIDEN_LIST): 123 added = self.run_list_function(RBAC_FUNC_WIDEN_LIST, everything) 124 visible = everything.filter( 125 Q(pk__in=visible.values("pk")) | Q(pk__in=added.values("pk")) 126 ) 127 return visible 128 129 def run_list_function(self, function: str, queryset: QuerySet) -> QuerySet: 130 try: 131 result = self.bound_check.run( 132 function, self.request, self.endpoint, self.request, queryset 133 ) 134 except PermissionDenied: 135 raise 136 except Exception as exc: # noqa: BLE001 137 self.logger(function).warning("Permission check failed", exc=exc) 138 raise PermissionDenied() from None 139 if not isinstance(result, QuerySet) or result.model is not queryset.model: 140 self.logger(function).warning("Permission check did not return a queryset of the model") 141 raise PermissionDenied() 142 return result 143 144 def field_rules(self, obj: Model | None = None) -> FieldRules: 145 """What hidden_fields and readonly_fields protect on one object, or with `obj=None` on 146 any object of the endpoint""" 147 if not self.defines(RBAC_FUNC_HIDDEN_FIELDS, RBAC_FUNC_READONLY_FIELDS): 148 return FieldRules() 149 key = None if obj is None else obj.pk 150 if key not in self.field_rules_by_object: 151 rules = FieldRules( 152 self.field_paths(RBAC_FUNC_HIDDEN_FIELDS, obj), 153 self.field_paths(RBAC_FUNC_READONLY_FIELDS, obj), 154 ) 155 if key is not None: 156 hidden = FieldRules.without_selectors(rules.hidden) 157 if not hidden <= FieldRules.without_selectors(self.field_rules().hidden): 158 self.logger(RBAC_FUNC_HIDDEN_FIELDS).warning( 159 "hidden_fields hides more on one object" 160 ) 161 raise PermissionCheckFailed() 162 self.field_rules_by_object[key] = rules 163 return self.field_rules_by_object[key] 164 165 def report_unknown_fields(self, fields: set[str]): 166 """Log fields that paths start with but the endpoint lacks, likely typos, and note them 167 for the check's form""" 168 new = fields - self.reported_fields 169 if not new or self.bound_check is None: 170 return 171 self.reported_fields |= new 172 self.logger(RBAC_FUNC_HIDDEN_FIELDS).warning( 173 "Field rules name fields the endpoint lacks", fields=new 174 ) 175 key = self.unknown_fields_key(self.bound_check, self.endpoint) 176 cache.set(key, sorted(set(cache.get(key, [])) | new), UNKNOWN_FIELDS_TIMEOUT) 177 178 @staticmethod 179 def unknown_fields_key(check: PermissionCheck, endpoint: str) -> str: 180 expression = sha256(check.expression.encode()).hexdigest()[:16] 181 return UNKNOWN_FIELDS_KEY.format(check=check.pk, expression=expression, endpoint=endpoint) 182 183 def field_paths(self, function: str, obj: Model | None) -> set[str]: 184 if not self.defines(function): 185 return set() 186 try: 187 paths = self.bound_check.run(function, self.request, self.endpoint, self.request, obj) 188 except PermissionDenied: 189 raise 190 except Exception as exc: # noqa: BLE001 191 self.logger(function).warning("Permission check failed", exc=exc) 192 raise PermissionCheckFailed() from None 193 if not isinstance(paths, set | list | tuple) or not all( 194 isinstance(path, str) for path in paths 195 ): 196 self.logger(function).warning("Permission check did not return a set of paths") 197 raise PermissionCheckFailed() 198 return set(paths) 199 200 def alter_response(self, data: Any) -> Any: 201 if not self.defines(RBAC_FUNC_ALTER_RESPONSE): 202 return data 203 try: 204 result = self.bound_check.run( 205 RBAC_FUNC_ALTER_RESPONSE, self.request, self.endpoint, self.request, data 206 ) 207 dumps(result, cls=JSONEncoder) 208 except PermissionDenied: 209 raise 210 except Exception as exc: # noqa: BLE001 211 self.logger(RBAC_FUNC_ALTER_RESPONSE).warning("Permission check failed", exc=exc) 212 raise PermissionCheckFailed() from None 213 return result 214 215 def logger(self, function: str) -> BoundLogger: 216 return LOGGER.bind( 217 check=self.bound_check.name, 218 function=function, 219 endpoint=self.endpoint, 220 user=self.request.user.username, 221 )
37class PermissionCheckSkipException(Exception): 38 """Raised by has_permission or has_object_permission to immediately grant access"""
Raised by has_permission or has_object_permission to immediately grant access
Base class for REST framework exceptions.
Subclasses should provide .status_code and .default_detail properties.
45class EndpointChecks: 46 """The permission check bound to an endpoint, as it applies to one request""" 47 48 def __init__(self, request: Request, endpoint: str | None): 49 self.request = request 50 self.endpoint = endpoint 51 self.field_rules_by_object: dict[Any, FieldRules] = {} 52 self.reported_fields: set[str] = set() 53 54 @classmethod 55 def for_request(cls, request: Request, action: str | None = None) -> EndpointChecks: 56 return cls.for_endpoint(request, Endpoints.endpoint_id(request, action)) 57 58 @classmethod 59 def for_endpoint(cls, request: Request, endpoint: str | None) -> EndpointChecks: 60 checks = request.__dict__.setdefault(REQUEST_ATTRIBUTE, {}) 61 if endpoint not in checks: 62 checks[endpoint] = cls(request, endpoint) 63 return checks[endpoint] 64 65 @cached_property 66 def bound_check(self) -> PermissionCheck | None: 67 # The flag first, as the superuser check can cost a query 68 if not self.endpoint or not EnableCustomPermissions.get(): 69 return None 70 if PermissionCheck.skipped_for(self.request.user): 71 return None 72 return PermissionCheck.objects.filter(endpoints__contains=[self.endpoint]).first() 73 74 def defines(self, *functions: str) -> bool: 75 """Helper to determine whether the `EndpointCheck` defines all `functions`""" 76 if self.bound_check is None: 77 return False 78 endpoint = Endpoints.hookable().get(self.endpoint) 79 return endpoint is not None and any( 80 function in endpoint.functions and self.bound_check.defines(function) 81 for function in functions 82 ) 83 84 def has_permission(self, allowed: bool) -> bool: 85 """The final decision on the request, given whether authentik allows it""" 86 return self.final_decision(RBAC_FUNC_HAS_PERMISSION, allowed) 87 88 def has_object_permission(self, obj: Model, allowed: bool) -> bool: 89 """The final decision on one object, given whether authentik allows it""" 90 return self.final_decision(RBAC_FUNC_HAS_OBJECT_PERMISSION, allowed, obj) 91 92 def final_decision(self, function: str, allowed: bool, *objects: Model) -> bool: 93 """A check returning True keeps authentik's decision, False forbids, and 94 PermissionCheckSkipException grants""" 95 if not self.defines(function): 96 return allowed 97 try: 98 result = self.bound_check.run( 99 function, self.request, self.endpoint, self.request, *objects 100 ) 101 except PermissionCheckSkipException: 102 decision = True 103 except PermissionDenied as exc: 104 self.logger(function).info("Permission check denied", reason=str(exc.detail)) 105 raise 106 except Exception as exc: # noqa: BLE001 107 self.logger(function).warning("Permission check failed", exc=exc) 108 decision = False 109 else: 110 if not isinstance(result, bool): 111 self.logger(function).warning("Permission check did not return a bool") 112 decision = allowed if result is True else False 113 if decision != allowed: 114 self.logger(function).info("Permission check changed decision", decision=decision) 115 return decision 116 117 def filter_list(self, visible: QuerySet, everything: QuerySet) -> QuerySet: 118 """authentik's list `visible`, narrowed by narrow_list, plus what widen_list picks from 119 `everything` the endpoint can list""" 120 if self.defines(RBAC_FUNC_NARROW_LIST): 121 kept = self.run_list_function(RBAC_FUNC_NARROW_LIST, visible) 122 visible = visible.filter(pk__in=kept.values("pk")) 123 if self.defines(RBAC_FUNC_WIDEN_LIST): 124 added = self.run_list_function(RBAC_FUNC_WIDEN_LIST, everything) 125 visible = everything.filter( 126 Q(pk__in=visible.values("pk")) | Q(pk__in=added.values("pk")) 127 ) 128 return visible 129 130 def run_list_function(self, function: str, queryset: QuerySet) -> QuerySet: 131 try: 132 result = self.bound_check.run( 133 function, self.request, self.endpoint, self.request, queryset 134 ) 135 except PermissionDenied: 136 raise 137 except Exception as exc: # noqa: BLE001 138 self.logger(function).warning("Permission check failed", exc=exc) 139 raise PermissionDenied() from None 140 if not isinstance(result, QuerySet) or result.model is not queryset.model: 141 self.logger(function).warning("Permission check did not return a queryset of the model") 142 raise PermissionDenied() 143 return result 144 145 def field_rules(self, obj: Model | None = None) -> FieldRules: 146 """What hidden_fields and readonly_fields protect on one object, or with `obj=None` on 147 any object of the endpoint""" 148 if not self.defines(RBAC_FUNC_HIDDEN_FIELDS, RBAC_FUNC_READONLY_FIELDS): 149 return FieldRules() 150 key = None if obj is None else obj.pk 151 if key not in self.field_rules_by_object: 152 rules = FieldRules( 153 self.field_paths(RBAC_FUNC_HIDDEN_FIELDS, obj), 154 self.field_paths(RBAC_FUNC_READONLY_FIELDS, obj), 155 ) 156 if key is not None: 157 hidden = FieldRules.without_selectors(rules.hidden) 158 if not hidden <= FieldRules.without_selectors(self.field_rules().hidden): 159 self.logger(RBAC_FUNC_HIDDEN_FIELDS).warning( 160 "hidden_fields hides more on one object" 161 ) 162 raise PermissionCheckFailed() 163 self.field_rules_by_object[key] = rules 164 return self.field_rules_by_object[key] 165 166 def report_unknown_fields(self, fields: set[str]): 167 """Log fields that paths start with but the endpoint lacks, likely typos, and note them 168 for the check's form""" 169 new = fields - self.reported_fields 170 if not new or self.bound_check is None: 171 return 172 self.reported_fields |= new 173 self.logger(RBAC_FUNC_HIDDEN_FIELDS).warning( 174 "Field rules name fields the endpoint lacks", fields=new 175 ) 176 key = self.unknown_fields_key(self.bound_check, self.endpoint) 177 cache.set(key, sorted(set(cache.get(key, [])) | new), UNKNOWN_FIELDS_TIMEOUT) 178 179 @staticmethod 180 def unknown_fields_key(check: PermissionCheck, endpoint: str) -> str: 181 expression = sha256(check.expression.encode()).hexdigest()[:16] 182 return UNKNOWN_FIELDS_KEY.format(check=check.pk, expression=expression, endpoint=endpoint) 183 184 def field_paths(self, function: str, obj: Model | None) -> set[str]: 185 if not self.defines(function): 186 return set() 187 try: 188 paths = self.bound_check.run(function, self.request, self.endpoint, self.request, obj) 189 except PermissionDenied: 190 raise 191 except Exception as exc: # noqa: BLE001 192 self.logger(function).warning("Permission check failed", exc=exc) 193 raise PermissionCheckFailed() from None 194 if not isinstance(paths, set | list | tuple) or not all( 195 isinstance(path, str) for path in paths 196 ): 197 self.logger(function).warning("Permission check did not return a set of paths") 198 raise PermissionCheckFailed() 199 return set(paths) 200 201 def alter_response(self, data: Any) -> Any: 202 if not self.defines(RBAC_FUNC_ALTER_RESPONSE): 203 return data 204 try: 205 result = self.bound_check.run( 206 RBAC_FUNC_ALTER_RESPONSE, self.request, self.endpoint, self.request, data 207 ) 208 dumps(result, cls=JSONEncoder) 209 except PermissionDenied: 210 raise 211 except Exception as exc: # noqa: BLE001 212 self.logger(RBAC_FUNC_ALTER_RESPONSE).warning("Permission check failed", exc=exc) 213 raise PermissionCheckFailed() from None 214 return result 215 216 def logger(self, function: str) -> BoundLogger: 217 return LOGGER.bind( 218 check=self.bound_check.name, 219 function=function, 220 endpoint=self.endpoint, 221 user=self.request.user.username, 222 )
The permission check bound to an endpoint, as it applies to one request
65 @cached_property 66 def bound_check(self) -> PermissionCheck | None: 67 # The flag first, as the superuser check can cost a query 68 if not self.endpoint or not EnableCustomPermissions.get(): 69 return None 70 if PermissionCheck.skipped_for(self.request.user): 71 return None 72 return PermissionCheck.objects.filter(endpoints__contains=[self.endpoint]).first()
74 def defines(self, *functions: str) -> bool: 75 """Helper to determine whether the `EndpointCheck` defines all `functions`""" 76 if self.bound_check is None: 77 return False 78 endpoint = Endpoints.hookable().get(self.endpoint) 79 return endpoint is not None and any( 80 function in endpoint.functions and self.bound_check.defines(function) 81 for function in functions 82 )
Helper to determine whether the EndpointCheck defines all functions
84 def has_permission(self, allowed: bool) -> bool: 85 """The final decision on the request, given whether authentik allows it""" 86 return self.final_decision(RBAC_FUNC_HAS_PERMISSION, allowed)
The final decision on the request, given whether authentik allows it
88 def has_object_permission(self, obj: Model, allowed: bool) -> bool: 89 """The final decision on one object, given whether authentik allows it""" 90 return self.final_decision(RBAC_FUNC_HAS_OBJECT_PERMISSION, allowed, obj)
The final decision on one object, given whether authentik allows it
92 def final_decision(self, function: str, allowed: bool, *objects: Model) -> bool: 93 """A check returning True keeps authentik's decision, False forbids, and 94 PermissionCheckSkipException grants""" 95 if not self.defines(function): 96 return allowed 97 try: 98 result = self.bound_check.run( 99 function, self.request, self.endpoint, self.request, *objects 100 ) 101 except PermissionCheckSkipException: 102 decision = True 103 except PermissionDenied as exc: 104 self.logger(function).info("Permission check denied", reason=str(exc.detail)) 105 raise 106 except Exception as exc: # noqa: BLE001 107 self.logger(function).warning("Permission check failed", exc=exc) 108 decision = False 109 else: 110 if not isinstance(result, bool): 111 self.logger(function).warning("Permission check did not return a bool") 112 decision = allowed if result is True else False 113 if decision != allowed: 114 self.logger(function).info("Permission check changed decision", decision=decision) 115 return decision
A check returning True keeps authentik's decision, False forbids, and PermissionCheckSkipException grants
117 def filter_list(self, visible: QuerySet, everything: QuerySet) -> QuerySet: 118 """authentik's list `visible`, narrowed by narrow_list, plus what widen_list picks from 119 `everything` the endpoint can list""" 120 if self.defines(RBAC_FUNC_NARROW_LIST): 121 kept = self.run_list_function(RBAC_FUNC_NARROW_LIST, visible) 122 visible = visible.filter(pk__in=kept.values("pk")) 123 if self.defines(RBAC_FUNC_WIDEN_LIST): 124 added = self.run_list_function(RBAC_FUNC_WIDEN_LIST, everything) 125 visible = everything.filter( 126 Q(pk__in=visible.values("pk")) | Q(pk__in=added.values("pk")) 127 ) 128 return visible
authentik's list visible, narrowed by narrow_list, plus what widen_list picks from
everything the endpoint can list
130 def run_list_function(self, function: str, queryset: QuerySet) -> QuerySet: 131 try: 132 result = self.bound_check.run( 133 function, self.request, self.endpoint, self.request, queryset 134 ) 135 except PermissionDenied: 136 raise 137 except Exception as exc: # noqa: BLE001 138 self.logger(function).warning("Permission check failed", exc=exc) 139 raise PermissionDenied() from None 140 if not isinstance(result, QuerySet) or result.model is not queryset.model: 141 self.logger(function).warning("Permission check did not return a queryset of the model") 142 raise PermissionDenied() 143 return result
145 def field_rules(self, obj: Model | None = None) -> FieldRules: 146 """What hidden_fields and readonly_fields protect on one object, or with `obj=None` on 147 any object of the endpoint""" 148 if not self.defines(RBAC_FUNC_HIDDEN_FIELDS, RBAC_FUNC_READONLY_FIELDS): 149 return FieldRules() 150 key = None if obj is None else obj.pk 151 if key not in self.field_rules_by_object: 152 rules = FieldRules( 153 self.field_paths(RBAC_FUNC_HIDDEN_FIELDS, obj), 154 self.field_paths(RBAC_FUNC_READONLY_FIELDS, obj), 155 ) 156 if key is not None: 157 hidden = FieldRules.without_selectors(rules.hidden) 158 if not hidden <= FieldRules.without_selectors(self.field_rules().hidden): 159 self.logger(RBAC_FUNC_HIDDEN_FIELDS).warning( 160 "hidden_fields hides more on one object" 161 ) 162 raise PermissionCheckFailed() 163 self.field_rules_by_object[key] = rules 164 return self.field_rules_by_object[key]
What hidden_fields and readonly_fields protect on one object, or with obj=None on
any object of the endpoint
166 def report_unknown_fields(self, fields: set[str]): 167 """Log fields that paths start with but the endpoint lacks, likely typos, and note them 168 for the check's form""" 169 new = fields - self.reported_fields 170 if not new or self.bound_check is None: 171 return 172 self.reported_fields |= new 173 self.logger(RBAC_FUNC_HIDDEN_FIELDS).warning( 174 "Field rules name fields the endpoint lacks", fields=new 175 ) 176 key = self.unknown_fields_key(self.bound_check, self.endpoint) 177 cache.set(key, sorted(set(cache.get(key, [])) | new), UNKNOWN_FIELDS_TIMEOUT)
Log fields that paths start with but the endpoint lacks, likely typos, and note them for the check's form
184 def field_paths(self, function: str, obj: Model | None) -> set[str]: 185 if not self.defines(function): 186 return set() 187 try: 188 paths = self.bound_check.run(function, self.request, self.endpoint, self.request, obj) 189 except PermissionDenied: 190 raise 191 except Exception as exc: # noqa: BLE001 192 self.logger(function).warning("Permission check failed", exc=exc) 193 raise PermissionCheckFailed() from None 194 if not isinstance(paths, set | list | tuple) or not all( 195 isinstance(path, str) for path in paths 196 ): 197 self.logger(function).warning("Permission check did not return a set of paths") 198 raise PermissionCheckFailed() 199 return set(paths)
201 def alter_response(self, data: Any) -> Any: 202 if not self.defines(RBAC_FUNC_ALTER_RESPONSE): 203 return data 204 try: 205 result = self.bound_check.run( 206 RBAC_FUNC_ALTER_RESPONSE, self.request, self.endpoint, self.request, data 207 ) 208 dumps(result, cls=JSONEncoder) 209 except PermissionDenied: 210 raise 211 except Exception as exc: # noqa: BLE001 212 self.logger(RBAC_FUNC_ALTER_RESPONSE).warning("Permission check failed", exc=exc) 213 raise PermissionCheckFailed() from None 214 return result