authentik.enterprise.requests.api.apps
1from http import HTTPMethod 2from uuid import UUID 3 4from django.db.models import Q, QuerySet 5from django_filters.rest_framework import DjangoFilterBackend 6from drf_spectacular.utils import extend_schema 7from rest_framework.decorators import action 8from rest_framework.fields import CharField 9from rest_framework.request import Request 10from rest_framework.response import Response 11 12from authentik.api.ordering import NullsAwareOrderingFilter 13from authentik.api.pagination import Pagination 14from authentik.api.search.ql import QLSearch 15from authentik.core.api.applications import ApplicationSerializer 16from authentik.core.api.utils import MetaNameSerializer, PassiveSerializer 17from authentik.core.apps import AppAccessWithoutBindings 18from authentik.core.models import Application, ApplicationEntitlement, User 19from authentik.enterprise.requests.models import RequestRuleBinding, RequestRuleChildBinding 20from authentik.policies.engine import ListPolicyEngine 21from authentik.policies.models import ( 22 PolicyBinding, 23 PolicyBindingModel, 24 RequestableChildModel, 25 RequestableModel, 26) 27 28REQUESTABLE_FILTER_BACKENDS = [QLSearch, DjangoFilterBackend, NullsAwareOrderingFilter] 29 30 31def granting_rule_bindings( 32 pbms: QuerySet[PolicyBindingModel] | list[PolicyBindingModel] | list[UUID], 33 user: User, 34 request: Request, 35) -> QuerySet[RequestRuleBinding]: 36 """The RequestRuleBinding(s) that make any of `pbms` requestable by `user`, i.e. 37 `user` passes the rule's own PolicyBindings. `pbms` may be model instances or their 38 `pbm_uuid`s.""" 39 rule_bindings = RequestRuleBinding.objects.filter( 40 Q(target__in=pbms) | Q(related__in=pbms) 41 ).distinct() 42 if not rule_bindings.exists(): 43 return rule_bindings 44 engine = ListPolicyEngine(rule_bindings, user, request) 45 engine.empty_result = AppAccessWithoutBindings.get() 46 return engine.build().result 47 48 49def user_can_request(pbm: RequestableModel, user: User, request: Request) -> bool: 50 """Whether `user` is eligible to request access to `pbm`, per the 51 RequestRule(s) attached to it.""" 52 return granting_rule_bindings([pbm], user, request).exists() 53 54 55def _requestable( 56 base: QuerySet[RequestableModel | RequestableChildModel], request: Request 57) -> QuerySet[RequestableModel]: 58 """every unique object of the viewset's own model which the current user is eligible to 59 request, direct or child related.""" 60 # RequestRuleBinding.target/related point at the PolicyBindingModel base table's own pk, 61 # which can diverge from a subclass's `.pk` -- same caveat as ListPolicyEngine.build(). 62 target_field = PolicyBinding._meta.get_field("target").target_field.attname 63 candidates = list( 64 base.filter(Q(request_rules__isnull=False) | Q(request_rule_child_bindings__isnull=False)) 65 .values_list(target_field, flat=True) 66 .distinct() 67 ) 68 if not candidates: 69 return base.none() 70 # A rule binding's verdict depends only on (binding, user), never on which object 71 # prompted the question, so every candidate is resolved in a single policy pass. 72 granting = list(granting_rule_bindings(candidates, request.user, request)) 73 granted = {binding.target_id for binding in granting} 74 granted |= set( 75 RequestRuleChildBinding.objects.filter( 76 binding__in=granting, target__in=candidates 77 ).values_list("target_id", flat=True) 78 ) 79 return base.filter(**{f"{target_field}__in": granted}) 80 81 82class RequestableTargetSerializer(MetaNameSerializer, PassiveSerializer): 83 """Generic representation of a single request target: whatever was actually 84 requested (an Application, an Application Entitlement, ...), always paired with the 85 parent it belongs to, so the UI/audit trail has that context even when the 86 request itself was scoped narrower than the whole app.""" 87 88 pbm_uuid = CharField(source="pk", read_only=True) 89 label = CharField(source="requestable_label", read_only=True) 90 parent = ApplicationSerializer(source="requestable_parent", read_only=True, allow_null=True) 91 92 93class ApplicationsRequestableMixin: 94 queryset: QuerySet[Application] 95 96 @extend_schema( 97 responses={ 98 200: ApplicationSerializer(many=True), 99 }, 100 ) 101 @action(methods=[HTTPMethod.GET], detail=False, filter_backends=REQUESTABLE_FILTER_BACKENDS) 102 def requestable(self, request: Request) -> Response: 103 """List applications which the current user can request access to""" 104 paginator: Pagination = self.paginator 105 paginated = paginator.paginate_queryset( 106 _requestable(self.filter_queryset(self.get_queryset()), request), request 107 ) 108 serializer = self.get_serializer(paginated, many=True) 109 return self.get_paginated_response(serializer.data) 110 111 112class ApplicationEntitlementsRequestableMixin: 113 queryset: QuerySet[ApplicationEntitlement] 114 115 @extend_schema( 116 responses={ 117 200: RequestableTargetSerializer(many=True), 118 }, 119 ) 120 @action(methods=[HTTPMethod.GET], detail=False, filter_backends=REQUESTABLE_FILTER_BACKENDS) 121 def requestable(self, request: Request) -> Response: 122 """List application entitlements which the current user can request access to""" 123 paginator: Pagination = self.paginator 124 paginated = paginator.paginate_queryset( 125 _requestable(self.filter_queryset(self.get_queryset()), request), request 126 ) 127 serializer = RequestableTargetSerializer(paginated, many=True) 128 return self.get_paginated_response(serializer.data)
REQUESTABLE_FILTER_BACKENDS =
[<class 'authentik.api.search.ql.QLSearch'>, <class 'django_filters.rest_framework.backends.DjangoFilterBackend'>, <class 'authentik.api.ordering.NullsAwareOrderingFilter'>]
def
granting_rule_bindings( pbms: django.db.models.query.QuerySet | list[authentik.policies.models.PolicyBindingModel] | list[uuid.UUID], user: authentik.core.models.User, request: rest_framework.request.Request) -> django.db.models.query.QuerySet:
32def granting_rule_bindings( 33 pbms: QuerySet[PolicyBindingModel] | list[PolicyBindingModel] | list[UUID], 34 user: User, 35 request: Request, 36) -> QuerySet[RequestRuleBinding]: 37 """The RequestRuleBinding(s) that make any of `pbms` requestable by `user`, i.e. 38 `user` passes the rule's own PolicyBindings. `pbms` may be model instances or their 39 `pbm_uuid`s.""" 40 rule_bindings = RequestRuleBinding.objects.filter( 41 Q(target__in=pbms) | Q(related__in=pbms) 42 ).distinct() 43 if not rule_bindings.exists(): 44 return rule_bindings 45 engine = ListPolicyEngine(rule_bindings, user, request) 46 engine.empty_result = AppAccessWithoutBindings.get() 47 return engine.build().result
The RequestRuleBinding(s) that make any of pbms requestable by user, i.e.
user passes the rule's own PolicyBindings. pbms may be model instances or their
pbm_uuids.
def
user_can_request( pbm: authentik.policies.models.RequestableModel, user: authentik.core.models.User, request: rest_framework.request.Request) -> bool:
50def user_can_request(pbm: RequestableModel, user: User, request: Request) -> bool: 51 """Whether `user` is eligible to request access to `pbm`, per the 52 RequestRule(s) attached to it.""" 53 return granting_rule_bindings([pbm], user, request).exists()
Whether user is eligible to request access to pbm, per the
RequestRule(s) attached to it.
class
RequestableTargetSerializer(authentik.core.api.utils.MetaNameSerializer, authentik.core.api.utils.PassiveSerializer):
83class RequestableTargetSerializer(MetaNameSerializer, PassiveSerializer): 84 """Generic representation of a single request target: whatever was actually 85 requested (an Application, an Application Entitlement, ...), always paired with the 86 parent it belongs to, so the UI/audit trail has that context even when the 87 request itself was scoped narrower than the whole app.""" 88 89 pbm_uuid = CharField(source="pk", read_only=True) 90 label = CharField(source="requestable_label", read_only=True) 91 parent = ApplicationSerializer(source="requestable_parent", read_only=True, allow_null=True)
Generic representation of a single request target: whatever was actually requested (an Application, an Application Entitlement, ...), always paired with the parent it belongs to, so the UI/audit trail has that context even when the request itself was scoped narrower than the whole app.
class
ApplicationsRequestableMixin:
94class ApplicationsRequestableMixin: 95 queryset: QuerySet[Application] 96 97 @extend_schema( 98 responses={ 99 200: ApplicationSerializer(many=True), 100 }, 101 ) 102 @action(methods=[HTTPMethod.GET], detail=False, filter_backends=REQUESTABLE_FILTER_BACKENDS) 103 def requestable(self, request: Request) -> Response: 104 """List applications which the current user can request access to""" 105 paginator: Pagination = self.paginator 106 paginated = paginator.paginate_queryset( 107 _requestable(self.filter_queryset(self.get_queryset()), request), request 108 ) 109 serializer = self.get_serializer(paginated, many=True) 110 return self.get_paginated_response(serializer.data)
@extend_schema(responses={200: ApplicationSerializer(many=True)})
@action(methods=[HTTPMethod.GET], detail=False, filter_backends=REQUESTABLE_FILTER_BACKENDS)
def
requestable( self, request: rest_framework.request.Request) -> rest_framework.response.Response:
97 @extend_schema( 98 responses={ 99 200: ApplicationSerializer(many=True), 100 }, 101 ) 102 @action(methods=[HTTPMethod.GET], detail=False, filter_backends=REQUESTABLE_FILTER_BACKENDS) 103 def requestable(self, request: Request) -> Response: 104 """List applications which the current user can request access to""" 105 paginator: Pagination = self.paginator 106 paginated = paginator.paginate_queryset( 107 _requestable(self.filter_queryset(self.get_queryset()), request), request 108 ) 109 serializer = self.get_serializer(paginated, many=True) 110 return self.get_paginated_response(serializer.data)
List applications which the current user can request access to
class
ApplicationEntitlementsRequestableMixin:
113class ApplicationEntitlementsRequestableMixin: 114 queryset: QuerySet[ApplicationEntitlement] 115 116 @extend_schema( 117 responses={ 118 200: RequestableTargetSerializer(many=True), 119 }, 120 ) 121 @action(methods=[HTTPMethod.GET], detail=False, filter_backends=REQUESTABLE_FILTER_BACKENDS) 122 def requestable(self, request: Request) -> Response: 123 """List application entitlements which the current user can request access to""" 124 paginator: Pagination = self.paginator 125 paginated = paginator.paginate_queryset( 126 _requestable(self.filter_queryset(self.get_queryset()), request), request 127 ) 128 serializer = RequestableTargetSerializer(paginated, many=True) 129 return self.get_paginated_response(serializer.data)
@extend_schema(responses={200: RequestableTargetSerializer(many=True)})
@action(methods=[HTTPMethod.GET], detail=False, filter_backends=REQUESTABLE_FILTER_BACKENDS)
def
requestable( self, request: rest_framework.request.Request) -> rest_framework.response.Response:
116 @extend_schema( 117 responses={ 118 200: RequestableTargetSerializer(many=True), 119 }, 120 ) 121 @action(methods=[HTTPMethod.GET], detail=False, filter_backends=REQUESTABLE_FILTER_BACKENDS) 122 def requestable(self, request: Request) -> Response: 123 """List application entitlements which the current user can request access to""" 124 paginator: Pagination = self.paginator 125 paginated = paginator.paginate_queryset( 126 _requestable(self.filter_queryset(self.get_queryset()), request), request 127 ) 128 serializer = RequestableTargetSerializer(paginated, many=True) 129 return self.get_paginated_response(serializer.data)
List application entitlements which the current user can request access to