authentik.rbac.api.permission_checks
1from django.core.cache import cache 2from django.utils.translation import gettext_lazy as _ 3from drf_spectacular.utils import extend_schema, extend_schema_field 4from rest_framework.exceptions import ValidationError 5from rest_framework.fields import CharField, DictField, ListField, SerializerMethodField 6from rest_framework.permissions import IsAuthenticated 7from rest_framework.request import Request 8from rest_framework.response import Response 9from rest_framework.viewsets import ModelViewSet, ViewSet 10 11from authentik.core.api.used_by import UsedByMixin 12from authentik.core.api.utils import ModelSerializer, PassiveSerializer 13from authentik.rbac.endpoint_checks import EndpointChecks 14from authentik.rbac.endpoints import FUNCTIONS, Endpoints 15from authentik.rbac.evaluator import PermissionCheckEvaluator 16from authentik.rbac.models import PermissionCheck 17 18 19class PermissionCheckSerializer(ModelSerializer): 20 def validate_expression(self, expression: str) -> str: 21 try: 22 functions = PermissionCheckEvaluator.defined_functions(expression) 23 except SyntaxError as exc: 24 raise ValidationError(str(exc)) from None 25 if not functions: 26 raise ValidationError( 27 _("Define at least one of {functions}.").format(functions=", ".join(FUNCTIONS)) 28 ) 29 return expression 30 31 def validate_endpoints(self, bindings: list[str]) -> list[str]: 32 for binding in bindings: 33 if binding not in Endpoints.hookable(): 34 raise ValidationError(_("Unknown endpoint {id}.").format(id=binding)) 35 taken = { 36 endpoint 37 for check_endpoints in PermissionCheck.objects.filter(endpoints__overlap=bindings) 38 .exclude(pk=getattr(self.instance, "pk", None)) 39 .values_list("endpoints", flat=True) 40 for endpoint in check_endpoints 41 } 42 if overlap := taken.intersection(bindings): 43 raise ValidationError( 44 _("Already bound to another check: {ids}.").format(ids=", ".join(sorted(overlap))) 45 ) 46 return bindings 47 48 def validate(self, attrs: dict) -> dict: 49 """Make sure each endpoint runs at least one function""" 50 expression = attrs.get("expression", getattr(self.instance, "expression", "")) 51 functions = PermissionCheckEvaluator.defined_functions(expression) 52 endpoints = Endpoints.hookable() 53 for binding in attrs.get("endpoints", getattr(self.instance, "endpoints", [])): 54 if binding in endpoints and not functions.intersection(endpoints[binding].functions): 55 raise ValidationError( 56 {"endpoints": _("{id} runs no functions defined for it.").format(id=binding)} 57 ) 58 return attrs 59 60 unknown_endpoints = SerializerMethodField() 61 unknown_fields = SerializerMethodField() 62 63 @extend_schema_field(ListField(child=CharField())) 64 def get_unknown_endpoints(self, check: PermissionCheck) -> list[str]: 65 """Bound endpoints that no longer exist, for example after an upgrade renamed them""" 66 return [endpoint for endpoint in check.endpoints if endpoint not in Endpoints.hookable()] 67 68 @extend_schema_field(DictField(child=ListField(child=CharField()))) 69 def get_unknown_fields(self, check: PermissionCheck) -> dict[str, list[str]]: 70 keys = { 71 EndpointChecks.unknown_fields_key(check, endpoint): endpoint 72 for endpoint in check.endpoints 73 } 74 return {keys[key]: fields for key, fields in cache.get_many(list(keys)).items()} 75 76 class Meta: 77 model = PermissionCheck 78 fields = ["pk", "name", "expression", "endpoints", "unknown_endpoints", "unknown_fields"] 79 80 81class EndpointSerializer(PassiveSerializer): 82 id = CharField() 83 functions = ListField(child=CharField()) 84 85 86class PermissionCheckViewSet(UsedByMixin, ModelViewSet): 87 queryset = PermissionCheck.objects.all() 88 serializer_class = PermissionCheckSerializer 89 search_fields = ["name", "endpoints"] 90 ordering = ["name"] 91 filterset_fields = ["name"] 92 93 94class EndpointViewSet(ViewSet): 95 permission_classes = [IsAuthenticated] 96 97 @extend_schema(responses={200: EndpointSerializer(many=True)}) 98 def list(self, request: Request) -> Response: 99 endpoints = sorted(Endpoints.hookable().values(), key=lambda endpoint: endpoint.id) 100 return Response(EndpointSerializer(endpoints, many=True).data)
20class PermissionCheckSerializer(ModelSerializer): 21 def validate_expression(self, expression: str) -> str: 22 try: 23 functions = PermissionCheckEvaluator.defined_functions(expression) 24 except SyntaxError as exc: 25 raise ValidationError(str(exc)) from None 26 if not functions: 27 raise ValidationError( 28 _("Define at least one of {functions}.").format(functions=", ".join(FUNCTIONS)) 29 ) 30 return expression 31 32 def validate_endpoints(self, bindings: list[str]) -> list[str]: 33 for binding in bindings: 34 if binding not in Endpoints.hookable(): 35 raise ValidationError(_("Unknown endpoint {id}.").format(id=binding)) 36 taken = { 37 endpoint 38 for check_endpoints in PermissionCheck.objects.filter(endpoints__overlap=bindings) 39 .exclude(pk=getattr(self.instance, "pk", None)) 40 .values_list("endpoints", flat=True) 41 for endpoint in check_endpoints 42 } 43 if overlap := taken.intersection(bindings): 44 raise ValidationError( 45 _("Already bound to another check: {ids}.").format(ids=", ".join(sorted(overlap))) 46 ) 47 return bindings 48 49 def validate(self, attrs: dict) -> dict: 50 """Make sure each endpoint runs at least one function""" 51 expression = attrs.get("expression", getattr(self.instance, "expression", "")) 52 functions = PermissionCheckEvaluator.defined_functions(expression) 53 endpoints = Endpoints.hookable() 54 for binding in attrs.get("endpoints", getattr(self.instance, "endpoints", [])): 55 if binding in endpoints and not functions.intersection(endpoints[binding].functions): 56 raise ValidationError( 57 {"endpoints": _("{id} runs no functions defined for it.").format(id=binding)} 58 ) 59 return attrs 60 61 unknown_endpoints = SerializerMethodField() 62 unknown_fields = SerializerMethodField() 63 64 @extend_schema_field(ListField(child=CharField())) 65 def get_unknown_endpoints(self, check: PermissionCheck) -> list[str]: 66 """Bound endpoints that no longer exist, for example after an upgrade renamed them""" 67 return [endpoint for endpoint in check.endpoints if endpoint not in Endpoints.hookable()] 68 69 @extend_schema_field(DictField(child=ListField(child=CharField()))) 70 def get_unknown_fields(self, check: PermissionCheck) -> dict[str, list[str]]: 71 keys = { 72 EndpointChecks.unknown_fields_key(check, endpoint): endpoint 73 for endpoint in check.endpoints 74 } 75 return {keys[key]: fields for key, fields in cache.get_many(list(keys)).items()} 76 77 class Meta: 78 model = PermissionCheck 79 fields = ["pk", "name", "expression", "endpoints", "unknown_endpoints", "unknown_fields"]
A ModelSerializer is just a regular Serializer, except that:
- A set of default fields are automatically populated.
- A set of default validators are automatically populated.
- Default
.create()and.update()implementations are provided.
The process of automatically determining a set of serializer fields based on the model fields is reasonably complex, but you almost certainly don't need to dig into the implementation.
If the ModelSerializer class doesn't generate the set of fields that
you need you should either declare the extra/differing fields explicitly on
the serializer class, or simply use a Serializer class.
21 def validate_expression(self, expression: str) -> str: 22 try: 23 functions = PermissionCheckEvaluator.defined_functions(expression) 24 except SyntaxError as exc: 25 raise ValidationError(str(exc)) from None 26 if not functions: 27 raise ValidationError( 28 _("Define at least one of {functions}.").format(functions=", ".join(FUNCTIONS)) 29 ) 30 return expression
32 def validate_endpoints(self, bindings: list[str]) -> list[str]: 33 for binding in bindings: 34 if binding not in Endpoints.hookable(): 35 raise ValidationError(_("Unknown endpoint {id}.").format(id=binding)) 36 taken = { 37 endpoint 38 for check_endpoints in PermissionCheck.objects.filter(endpoints__overlap=bindings) 39 .exclude(pk=getattr(self.instance, "pk", None)) 40 .values_list("endpoints", flat=True) 41 for endpoint in check_endpoints 42 } 43 if overlap := taken.intersection(bindings): 44 raise ValidationError( 45 _("Already bound to another check: {ids}.").format(ids=", ".join(sorted(overlap))) 46 ) 47 return bindings
49 def validate(self, attrs: dict) -> dict: 50 """Make sure each endpoint runs at least one function""" 51 expression = attrs.get("expression", getattr(self.instance, "expression", "")) 52 functions = PermissionCheckEvaluator.defined_functions(expression) 53 endpoints = Endpoints.hookable() 54 for binding in attrs.get("endpoints", getattr(self.instance, "endpoints", [])): 55 if binding in endpoints and not functions.intersection(endpoints[binding].functions): 56 raise ValidationError( 57 {"endpoints": _("{id} runs no functions defined for it.").format(id=binding)} 58 ) 59 return attrs
Make sure each endpoint runs at least one function
64 @extend_schema_field(ListField(child=CharField())) 65 def get_unknown_endpoints(self, check: PermissionCheck) -> list[str]: 66 """Bound endpoints that no longer exist, for example after an upgrade renamed them""" 67 return [endpoint for endpoint in check.endpoints if endpoint not in Endpoints.hookable()]
Bound endpoints that no longer exist, for example after an upgrade renamed them
69 @extend_schema_field(DictField(child=ListField(child=CharField()))) 70 def get_unknown_fields(self, check: PermissionCheck) -> dict[str, list[str]]: 71 keys = { 72 EndpointChecks.unknown_fields_key(check, endpoint): endpoint 73 for endpoint in check.endpoints 74 } 75 return {keys[key]: fields for key, fields in cache.get_many(list(keys)).items()}
77 class Meta: 78 model = PermissionCheck 79 fields = ["pk", "name", "expression", "endpoints", "unknown_endpoints", "unknown_fields"]
82class EndpointSerializer(PassiveSerializer): 83 id = CharField() 84 functions = ListField(child=CharField())
Base serializer class which doesn't implement create/update methods
Inherited Members
87class PermissionCheckViewSet(UsedByMixin, ModelViewSet): 88 queryset = PermissionCheck.objects.all() 89 serializer_class = PermissionCheckSerializer 90 search_fields = ["name", "endpoints"] 91 ordering = ["name"] 92 filterset_fields = ["name"]
Mixin to add a used_by endpoint to return a list of all objects using this object
Inherited Members
95class EndpointViewSet(ViewSet): 96 permission_classes = [IsAuthenticated] 97 98 @extend_schema(responses={200: EndpointSerializer(many=True)}) 99 def list(self, request: Request) -> Response: 100 endpoints = sorted(Endpoints.hookable().values(), key=lambda endpoint: endpoint.id) 101 return Response(EndpointSerializer(endpoints, many=True).data)
The base ViewSet class does not provide any actions by default.