authentik.core.api.applications

Application API Views

  1"""Application API Views"""
  2
  3from collections.abc import Iterator
  4from copy import copy
  5
  6from django.core.cache import cache
  7from django.db.models import Case, Prefetch, QuerySet
  8from django.db.models.expressions import When
  9from django.db.models.manager import BaseManager
 10from django.shortcuts import get_object_or_404
 11from django.utils.translation import gettext as _
 12from django_filters.rest_framework import DjangoFilterBackend
 13from drf_spectacular.types import OpenApiTypes
 14from drf_spectacular.utils import OpenApiParameter, extend_schema
 15from guardian.shortcuts import get_objects_for_user
 16from rest_framework.decorators import action
 17from rest_framework.exceptions import ValidationError
 18from rest_framework.fields import CharField, ReadOnlyField, SerializerMethodField
 19from rest_framework.request import Request
 20from rest_framework.response import Response
 21from rest_framework.serializers import ListSerializer
 22from rest_framework.viewsets import ModelViewSet
 23from structlog.stdlib import get_logger
 24
 25from authentik.admin.files.manager import get_file_manager
 26from authentik.admin.files.usage import FileUsage
 27from authentik.api.ordering import NullsAwareOrderingFilter
 28from authentik.api.pagination import Pagination
 29from authentik.api.search.ql import QLSearch
 30from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
 31from authentik.core.api.providers import ProviderSerializer
 32from authentik.core.api.used_by import UsedByMixin
 33from authentik.core.api.users import UserSerializer
 34from authentik.core.api.utils import ModelSerializer, ThemedUrlsSerializer
 35from authentik.core.apps import AppAccessWithoutBindings
 36from authentik.core.models import Application, Provider, User
 37from authentik.events.logs import LogEventSerializer, capture_logs
 38from authentik.lib.config import CONFIG
 39from authentik.lib.utils.reflection import ConditionalInheritance
 40from authentik.policies.api.exec import PolicyTestResultSerializer
 41from authentik.policies.engine import ListPolicyEngine, PolicyEngine
 42from authentik.policies.types import CACHE_PREFIX, PolicyResult
 43from authentik.root.middleware import ClientIPMiddleware
 44
 45LOGGER = get_logger()
 46
 47
 48def user_app_cache_key(
 49    user_pk: str,
 50    client_ip: str | None = None,
 51    page_number: int | None = None,
 52    only_with_launch_url: bool = False,
 53) -> str:
 54    """Cache key where application list for user is saved"""
 55    key = f"{CACHE_PREFIX}app_access/{user_pk}"
 56    if only_with_launch_url:
 57        key += "/launch"
 58    if client_ip:
 59        key += f"/{client_ip}"
 60    if page_number:
 61        key += f"/{page_number}"
 62    return key
 63
 64
 65class ApplicationListSerializer(ListSerializer):
 66    """Applications, with the cached URLs of all their icons read in one query"""
 67
 68    def to_representation(self, data):
 69        applications = list(data.all() if isinstance(data, BaseManager) else data)
 70        with get_file_manager(FileUsage.MEDIA).prefetch_urls(
 71            application.meta_icon for application in applications
 72        ):
 73            return super().to_representation(applications)
 74
 75
 76class ApplicationSerializer(ModelSerializer):
 77    """Application Serializer"""
 78
 79    launch_url = SerializerMethodField()
 80    provider_obj = ProviderSerializer(
 81        source="get_provider",
 82        required=False,
 83        read_only=True,
 84        allow_null=True,
 85    )
 86    backchannel_providers_obj = ProviderSerializer(
 87        source="backchannel_providers", required=False, read_only=True, many=True
 88    )
 89
 90    meta_icon_url = ReadOnlyField(source="get_meta_icon")
 91    meta_icon_themed_urls = ThemedUrlsSerializer(
 92        source="get_meta_icon_themed_urls", read_only=True, allow_null=True
 93    )
 94
 95    def get_launch_url(self, app: Application) -> str | None:
 96        """Format the launch URL for the user given as `for_user` in the context, or else the
 97        requesting user"""
 98        user = self.context.get("for_user") or getattr(self.context.get("request"), "user", None)
 99        if not user:
100            return app.get_launch_url()
101        return app.get_launch_url(user, user_data=lambda: self._get_user_data(user))
102
103    def _get_user_data(self, user: User) -> dict:
104        """`user` serialized, once for all applications in the response"""
105        if "_cached_user_data" not in self.context:
106            self.context["_cached_user_data"] = UserSerializer(instance=user).data
107        return self.context["_cached_user_data"]
108
109    def validate_slug(self, slug: str) -> str:
110        if slug in Application.reserved_slugs:
111            raise ValidationError(
112                _("The slug '{slug}' is reserved and cannot be used for applications.").format(
113                    slug=slug
114                )
115            )
116        return slug
117
118    def __init__(self, *args, **kwargs) -> None:
119        super().__init__(*args, **kwargs)
120        if SERIALIZER_CONTEXT_BLUEPRINT in self.context:
121            self.fields["icon"] = CharField(source="meta_icon", required=False)
122
123    class Meta:
124        model = Application
125        list_serializer_class = ApplicationListSerializer
126        fields = [
127            "pk",
128            "pbm_uuid",
129            "name",
130            "slug",
131            "provider",
132            "provider_obj",
133            "backchannel_providers",
134            "backchannel_providers_obj",
135            "launch_url",
136            "open_in_new_tab",
137            "meta_launch_url",
138            "meta_icon",
139            "meta_icon_url",
140            "meta_icon_themed_urls",
141            "meta_description",
142            "meta_publisher",
143            "policy_engine_mode",
144            "group",
145            "meta_hide",
146        ]
147        extra_kwargs = {
148            "pbm_uuid": {"read_only": True},
149            "backchannel_providers": {"required": False},
150        }
151
152
153class ApplicationViewSet(
154    ConditionalInheritance("authentik.enterprise.requests.api.apps.ApplicationsRequestableMixin"),
155    UsedByMixin,
156    ModelViewSet,
157):
158    """Application Viewset"""
159
160    # ProviderSerializer reads each provider's concrete type, property mappings, application and
161    # backchannel application. A provider's application is prefetched rather than selected, as
162    # select_subclasses() returns the subclass instances and not the selected base rows.
163    queryset = Application.objects.with_provider().prefetch_related(
164        "provider__property_mappings",
165        "provider__backchannel_application",
166        Prefetch(
167            "backchannel_providers",
168            queryset=Provider.objects.select_subclasses().prefetch_related(
169                "application", "property_mappings"
170            ),
171        ),
172    )
173    serializer_class = ApplicationSerializer
174    search_fields = [
175        "name",
176        "slug",
177        "meta_launch_url",
178        "meta_description",
179        "meta_publisher",
180        "group",
181    ]
182    filterset_fields = [
183        "name",
184        "slug",
185        "meta_launch_url",
186        "meta_description",
187        "meta_publisher",
188        "group",
189    ]
190    lookup_field = "slug"
191    ordering = ["name"]
192
193    def _get_allowed_applications(
194        self, paginated_apps: Iterator[Application], user: User | None = None
195    ) -> list[Application]:
196        apps = list(paginated_apps)
197        if not apps:
198            return []
199        request = self.request._request
200        if user:
201            request = copy(request)
202            request.user = user
203        engine = ListPolicyEngine(
204            Application.objects.filter(pk__in=[app.pk for app in apps]), request.user, request
205        )
206        engine.empty_result = AppAccessWithoutBindings.get()
207        engine.build()
208        passing_pks = set(engine.result.values_list("pk", flat=True))
209        # Filter (rather than re-fetch from engine.result) to preserve the original
210        # pagination order and the prefetching already applied by get_queryset().
211        return [app for app in apps if app.pk in passing_pks]
212
213    def _expand_applications(self, applications: list[Application]) -> QuerySet[Application]:
214        """
215        Re-fetch with proper prefetching for serialization
216        Cached applications don't have prefetched relationships, causing N+1 queries
217        during serialization when get_provider() is called
218        """
219        if not applications:
220            return self.get_queryset().none()
221        pks = [app.pk for app in applications]
222        return (
223            self.get_queryset()
224            .filter(pk__in=pks)
225            .order_by(Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(pks)]))
226        )
227
228    def _filter_applications_with_launch_url(
229        self, paginated_apps: QuerySet[Application]
230    ) -> list[Application]:
231        applications = []
232        for app in paginated_apps:
233            if app.get_launch_url():
234                applications.append(app)
235        return applications
236
237    @extend_schema(
238        parameters=[
239            OpenApiParameter(
240                name="for_user",
241                location=OpenApiParameter.QUERY,
242                type=OpenApiTypes.INT,
243            )
244        ],
245        responses={
246            200: PolicyTestResultSerializer(),
247        },
248    )
249    @action(detail=True, methods=["GET"])
250    def check_access(self, request: Request, slug: str) -> Response:
251        """Check access to a single application by slug"""
252        # Don't use self.get_object as that checks for view_application permission
253        # which the user might not have, even if they have access
254        application = get_object_or_404(Application, slug=slug)
255        # If the current user is superuser, they can set `for_user`
256        for_user = request.user
257        if request.user.is_superuser and "for_user" in request.query_params:
258            try:
259                for_user = User.objects.filter(pk=request.query_params.get("for_user")).first()
260            except ValueError:
261                raise ValidationError({"for_user": "for_user must be numerical"}) from None
262            if not for_user:
263                raise ValidationError({"for_user": "User not found"})
264        engine = PolicyEngine(application, for_user, request)
265        engine.empty_result = AppAccessWithoutBindings.get()
266        engine.use_cache = False
267        with capture_logs() as logs:
268            engine.build()
269            result = engine.result
270        response = PolicyTestResultSerializer(PolicyResult(False))
271        if result.passing:
272            response = PolicyTestResultSerializer(PolicyResult(True))
273        if request.user.is_superuser:
274            log_messages = []
275            for log in logs:
276                if log.attributes.get("process", "") == "PolicyProcess":
277                    continue
278                log_messages.append(LogEventSerializer(log).data)
279            result.log_messages = log_messages
280            response = PolicyTestResultSerializer(result)
281        return Response(response.data)
282
283    @extend_schema(
284        parameters=[
285            OpenApiParameter(
286                name="for_user",
287                location=OpenApiParameter.QUERY,
288                type=OpenApiTypes.INT,
289            ),
290            OpenApiParameter(
291                name="only_with_launch_url",
292                location=OpenApiParameter.QUERY,
293                type=OpenApiTypes.BOOL,
294            ),
295        ],
296        responses={
297            200: ApplicationSerializer(many=True),
298        },
299        operation_id="core_applications_accessible_list",
300    )
301    @action(
302        methods=["GET"],
303        detail=False,
304        url_path="@accessible",
305        # Access is decided by policies below, so skip the RBAC ObjectFilter
306        filter_backends=[QLSearch, DjangoFilterBackend, NullsAwareOrderingFilter],
307    )
308    def accessible(self, request: Request) -> Response:
309        """List applications the user passes policies for, regardless of RBAC permissions"""
310        should_cache = request.query_params.get("search", "") == ""
311
312        only_with_launch_url = (
313            str(request.query_params.get("only_with_launch_url", "false")).lower()
314        ) == "true"
315
316        queryset = self.filter_queryset(self.get_queryset())
317        queryset = queryset.exclude(meta_hide=True)
318        if only_with_launch_url:
319            # Pre-filter at DB level to skip expensive per-app policy evaluation
320            # for apps that can never appear in the launcher (no meta_launch_url
321            # and no provider, so no possible launch URL).
322            queryset = queryset.exclude(meta_launch_url="", provider__isnull=True)
323        paginator: Pagination = self.paginator
324
325        if "for_user" in request.query_params:
326            try:
327                for_user: int = int(request.query_params.get("for_user", 0))
328                for_user = (
329                    get_objects_for_user(request.user, "authentik_core.view_user_applications")
330                    .filter(pk=for_user)
331                    .first()
332                )
333                if not for_user:
334                    raise ValidationError({"for_user": "User not found"})
335            except ValueError as exc:
336                raise ValidationError from exc
337            # Evaluate the full candidate set so counts and page boundaries reflect
338            # applications this user can access, rather than all applications.
339            allowed_applications = self._get_allowed_applications(queryset, user=for_user)
340            paginated_apps = paginator.paginate_queryset(allowed_applications, request)
341
342            serializer = self.get_serializer(
343                paginated_apps,
344                many=True,
345                context={**self.get_serializer_context(), "for_user": for_user},
346            )
347            return self.get_paginated_response(serializer.data)
348
349        paginated_apps = paginator.paginate_queryset(queryset, request)
350        allowed_applications = []
351        if not should_cache:
352            allowed_applications = self._get_allowed_applications(paginated_apps)
353        if should_cache:
354            client_ip = ClientIPMiddleware.get_client_ip(self.request)
355            allowed_applications = cache.get(
356                user_app_cache_key(
357                    self.request.user.pk, client_ip, paginator.page.number, only_with_launch_url
358                )
359            )
360            if allowed_applications:
361                # Re-fetch cached applications since pickled instances lose prefetched
362                # relationships, causing N+1 queries during serialization
363                allowed_applications = self._expand_applications(allowed_applications)
364            else:
365                LOGGER.debug("Caching allowed application list", page=paginator.page.number)
366                allowed_applications = self._get_allowed_applications(paginated_apps)
367                cache.set(
368                    user_app_cache_key(
369                        self.request.user.pk, client_ip, paginator.page.number, only_with_launch_url
370                    ),
371                    allowed_applications,
372                    timeout=CONFIG.get_int("cache.timeout_application_policies", 86400),
373                )
374
375        if only_with_launch_url:
376            allowed_applications = self._filter_applications_with_launch_url(allowed_applications)
377
378        serializer = self.get_serializer(allowed_applications, many=True)
379        return self.get_paginated_response(serializer.data)
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
def user_app_cache_key( user_pk: str, client_ip: str | None = None, page_number: int | None = None, only_with_launch_url: bool = False) -> str:
49def user_app_cache_key(
50    user_pk: str,
51    client_ip: str | None = None,
52    page_number: int | None = None,
53    only_with_launch_url: bool = False,
54) -> str:
55    """Cache key where application list for user is saved"""
56    key = f"{CACHE_PREFIX}app_access/{user_pk}"
57    if only_with_launch_url:
58        key += "/launch"
59    if client_ip:
60        key += f"/{client_ip}"
61    if page_number:
62        key += f"/{page_number}"
63    return key

Cache key where application list for user is saved

class ApplicationListSerializer(rest_framework.serializers.ListSerializer):
66class ApplicationListSerializer(ListSerializer):
67    """Applications, with the cached URLs of all their icons read in one query"""
68
69    def to_representation(self, data):
70        applications = list(data.all() if isinstance(data, BaseManager) else data)
71        with get_file_manager(FileUsage.MEDIA).prefetch_urls(
72            application.meta_icon for application in applications
73        ):
74            return super().to_representation(applications)

Applications, with the cached URLs of all their icons read in one query

def to_representation(self, data):
69    def to_representation(self, data):
70        applications = list(data.all() if isinstance(data, BaseManager) else data)
71        with get_file_manager(FileUsage.MEDIA).prefetch_urls(
72            application.meta_icon for application in applications
73        ):
74            return super().to_representation(applications)

List of object instances -> List of dicts of primitive datatypes.

class ApplicationSerializer(authentik.core.api.utils.ModelSerializer):
 77class ApplicationSerializer(ModelSerializer):
 78    """Application Serializer"""
 79
 80    launch_url = SerializerMethodField()
 81    provider_obj = ProviderSerializer(
 82        source="get_provider",
 83        required=False,
 84        read_only=True,
 85        allow_null=True,
 86    )
 87    backchannel_providers_obj = ProviderSerializer(
 88        source="backchannel_providers", required=False, read_only=True, many=True
 89    )
 90
 91    meta_icon_url = ReadOnlyField(source="get_meta_icon")
 92    meta_icon_themed_urls = ThemedUrlsSerializer(
 93        source="get_meta_icon_themed_urls", read_only=True, allow_null=True
 94    )
 95
 96    def get_launch_url(self, app: Application) -> str | None:
 97        """Format the launch URL for the user given as `for_user` in the context, or else the
 98        requesting user"""
 99        user = self.context.get("for_user") or getattr(self.context.get("request"), "user", None)
100        if not user:
101            return app.get_launch_url()
102        return app.get_launch_url(user, user_data=lambda: self._get_user_data(user))
103
104    def _get_user_data(self, user: User) -> dict:
105        """`user` serialized, once for all applications in the response"""
106        if "_cached_user_data" not in self.context:
107            self.context["_cached_user_data"] = UserSerializer(instance=user).data
108        return self.context["_cached_user_data"]
109
110    def validate_slug(self, slug: str) -> str:
111        if slug in Application.reserved_slugs:
112            raise ValidationError(
113                _("The slug '{slug}' is reserved and cannot be used for applications.").format(
114                    slug=slug
115                )
116            )
117        return slug
118
119    def __init__(self, *args, **kwargs) -> None:
120        super().__init__(*args, **kwargs)
121        if SERIALIZER_CONTEXT_BLUEPRINT in self.context:
122            self.fields["icon"] = CharField(source="meta_icon", required=False)
123
124    class Meta:
125        model = Application
126        list_serializer_class = ApplicationListSerializer
127        fields = [
128            "pk",
129            "pbm_uuid",
130            "name",
131            "slug",
132            "provider",
133            "provider_obj",
134            "backchannel_providers",
135            "backchannel_providers_obj",
136            "launch_url",
137            "open_in_new_tab",
138            "meta_launch_url",
139            "meta_icon",
140            "meta_icon_url",
141            "meta_icon_themed_urls",
142            "meta_description",
143            "meta_publisher",
144            "policy_engine_mode",
145            "group",
146            "meta_hide",
147        ]
148        extra_kwargs = {
149            "pbm_uuid": {"read_only": True},
150            "backchannel_providers": {"required": False},
151        }

Application Serializer

ApplicationSerializer(*args, **kwargs)
119    def __init__(self, *args, **kwargs) -> None:
120        super().__init__(*args, **kwargs)
121        if SERIALIZER_CONTEXT_BLUEPRINT in self.context:
122            self.fields["icon"] = CharField(source="meta_icon", required=False)
launch_url
provider_obj
backchannel_providers_obj
meta_icon_url
meta_icon_themed_urls
def get_launch_url(self, app: authentik.core.models.Application) -> str | None:
 96    def get_launch_url(self, app: Application) -> str | None:
 97        """Format the launch URL for the user given as `for_user` in the context, or else the
 98        requesting user"""
 99        user = self.context.get("for_user") or getattr(self.context.get("request"), "user", None)
100        if not user:
101            return app.get_launch_url()
102        return app.get_launch_url(user, user_data=lambda: self._get_user_data(user))

Format the launch URL for the user given as for_user in the context, or else the requesting user

def validate_slug(self, slug: str) -> str:
110    def validate_slug(self, slug: str) -> str:
111        if slug in Application.reserved_slugs:
112            raise ValidationError(
113                _("The slug '{slug}' is reserved and cannot be used for applications.").format(
114                    slug=slug
115                )
116            )
117        return slug
class ApplicationSerializer.Meta:
124    class Meta:
125        model = Application
126        list_serializer_class = ApplicationListSerializer
127        fields = [
128            "pk",
129            "pbm_uuid",
130            "name",
131            "slug",
132            "provider",
133            "provider_obj",
134            "backchannel_providers",
135            "backchannel_providers_obj",
136            "launch_url",
137            "open_in_new_tab",
138            "meta_launch_url",
139            "meta_icon",
140            "meta_icon_url",
141            "meta_icon_themed_urls",
142            "meta_description",
143            "meta_publisher",
144            "policy_engine_mode",
145            "group",
146            "meta_hide",
147        ]
148        extra_kwargs = {
149            "pbm_uuid": {"read_only": True},
150            "backchannel_providers": {"required": False},
151        }
list_serializer_class = <class 'ApplicationListSerializer'>
fields = ['pk', 'pbm_uuid', 'name', 'slug', 'provider', 'provider_obj', 'backchannel_providers', 'backchannel_providers_obj', 'launch_url', 'open_in_new_tab', 'meta_launch_url', 'meta_icon', 'meta_icon_url', 'meta_icon_themed_urls', 'meta_description', 'meta_publisher', 'policy_engine_mode', 'group', 'meta_hide']
extra_kwargs = {'pbm_uuid': {'read_only': True}, 'backchannel_providers': {'required': False}}
class ApplicationViewSet(authentik.enterprise.requests.api.apps.ApplicationsRequestableMixin, authentik.core.api.used_by.UsedByMixin, rest_framework.viewsets.ModelViewSet):
154class ApplicationViewSet(
155    ConditionalInheritance("authentik.enterprise.requests.api.apps.ApplicationsRequestableMixin"),
156    UsedByMixin,
157    ModelViewSet,
158):
159    """Application Viewset"""
160
161    # ProviderSerializer reads each provider's concrete type, property mappings, application and
162    # backchannel application. A provider's application is prefetched rather than selected, as
163    # select_subclasses() returns the subclass instances and not the selected base rows.
164    queryset = Application.objects.with_provider().prefetch_related(
165        "provider__property_mappings",
166        "provider__backchannel_application",
167        Prefetch(
168            "backchannel_providers",
169            queryset=Provider.objects.select_subclasses().prefetch_related(
170                "application", "property_mappings"
171            ),
172        ),
173    )
174    serializer_class = ApplicationSerializer
175    search_fields = [
176        "name",
177        "slug",
178        "meta_launch_url",
179        "meta_description",
180        "meta_publisher",
181        "group",
182    ]
183    filterset_fields = [
184        "name",
185        "slug",
186        "meta_launch_url",
187        "meta_description",
188        "meta_publisher",
189        "group",
190    ]
191    lookup_field = "slug"
192    ordering = ["name"]
193
194    def _get_allowed_applications(
195        self, paginated_apps: Iterator[Application], user: User | None = None
196    ) -> list[Application]:
197        apps = list(paginated_apps)
198        if not apps:
199            return []
200        request = self.request._request
201        if user:
202            request = copy(request)
203            request.user = user
204        engine = ListPolicyEngine(
205            Application.objects.filter(pk__in=[app.pk for app in apps]), request.user, request
206        )
207        engine.empty_result = AppAccessWithoutBindings.get()
208        engine.build()
209        passing_pks = set(engine.result.values_list("pk", flat=True))
210        # Filter (rather than re-fetch from engine.result) to preserve the original
211        # pagination order and the prefetching already applied by get_queryset().
212        return [app for app in apps if app.pk in passing_pks]
213
214    def _expand_applications(self, applications: list[Application]) -> QuerySet[Application]:
215        """
216        Re-fetch with proper prefetching for serialization
217        Cached applications don't have prefetched relationships, causing N+1 queries
218        during serialization when get_provider() is called
219        """
220        if not applications:
221            return self.get_queryset().none()
222        pks = [app.pk for app in applications]
223        return (
224            self.get_queryset()
225            .filter(pk__in=pks)
226            .order_by(Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(pks)]))
227        )
228
229    def _filter_applications_with_launch_url(
230        self, paginated_apps: QuerySet[Application]
231    ) -> list[Application]:
232        applications = []
233        for app in paginated_apps:
234            if app.get_launch_url():
235                applications.append(app)
236        return applications
237
238    @extend_schema(
239        parameters=[
240            OpenApiParameter(
241                name="for_user",
242                location=OpenApiParameter.QUERY,
243                type=OpenApiTypes.INT,
244            )
245        ],
246        responses={
247            200: PolicyTestResultSerializer(),
248        },
249    )
250    @action(detail=True, methods=["GET"])
251    def check_access(self, request: Request, slug: str) -> Response:
252        """Check access to a single application by slug"""
253        # Don't use self.get_object as that checks for view_application permission
254        # which the user might not have, even if they have access
255        application = get_object_or_404(Application, slug=slug)
256        # If the current user is superuser, they can set `for_user`
257        for_user = request.user
258        if request.user.is_superuser and "for_user" in request.query_params:
259            try:
260                for_user = User.objects.filter(pk=request.query_params.get("for_user")).first()
261            except ValueError:
262                raise ValidationError({"for_user": "for_user must be numerical"}) from None
263            if not for_user:
264                raise ValidationError({"for_user": "User not found"})
265        engine = PolicyEngine(application, for_user, request)
266        engine.empty_result = AppAccessWithoutBindings.get()
267        engine.use_cache = False
268        with capture_logs() as logs:
269            engine.build()
270            result = engine.result
271        response = PolicyTestResultSerializer(PolicyResult(False))
272        if result.passing:
273            response = PolicyTestResultSerializer(PolicyResult(True))
274        if request.user.is_superuser:
275            log_messages = []
276            for log in logs:
277                if log.attributes.get("process", "") == "PolicyProcess":
278                    continue
279                log_messages.append(LogEventSerializer(log).data)
280            result.log_messages = log_messages
281            response = PolicyTestResultSerializer(result)
282        return Response(response.data)
283
284    @extend_schema(
285        parameters=[
286            OpenApiParameter(
287                name="for_user",
288                location=OpenApiParameter.QUERY,
289                type=OpenApiTypes.INT,
290            ),
291            OpenApiParameter(
292                name="only_with_launch_url",
293                location=OpenApiParameter.QUERY,
294                type=OpenApiTypes.BOOL,
295            ),
296        ],
297        responses={
298            200: ApplicationSerializer(many=True),
299        },
300        operation_id="core_applications_accessible_list",
301    )
302    @action(
303        methods=["GET"],
304        detail=False,
305        url_path="@accessible",
306        # Access is decided by policies below, so skip the RBAC ObjectFilter
307        filter_backends=[QLSearch, DjangoFilterBackend, NullsAwareOrderingFilter],
308    )
309    def accessible(self, request: Request) -> Response:
310        """List applications the user passes policies for, regardless of RBAC permissions"""
311        should_cache = request.query_params.get("search", "") == ""
312
313        only_with_launch_url = (
314            str(request.query_params.get("only_with_launch_url", "false")).lower()
315        ) == "true"
316
317        queryset = self.filter_queryset(self.get_queryset())
318        queryset = queryset.exclude(meta_hide=True)
319        if only_with_launch_url:
320            # Pre-filter at DB level to skip expensive per-app policy evaluation
321            # for apps that can never appear in the launcher (no meta_launch_url
322            # and no provider, so no possible launch URL).
323            queryset = queryset.exclude(meta_launch_url="", provider__isnull=True)
324        paginator: Pagination = self.paginator
325
326        if "for_user" in request.query_params:
327            try:
328                for_user: int = int(request.query_params.get("for_user", 0))
329                for_user = (
330                    get_objects_for_user(request.user, "authentik_core.view_user_applications")
331                    .filter(pk=for_user)
332                    .first()
333                )
334                if not for_user:
335                    raise ValidationError({"for_user": "User not found"})
336            except ValueError as exc:
337                raise ValidationError from exc
338            # Evaluate the full candidate set so counts and page boundaries reflect
339            # applications this user can access, rather than all applications.
340            allowed_applications = self._get_allowed_applications(queryset, user=for_user)
341            paginated_apps = paginator.paginate_queryset(allowed_applications, request)
342
343            serializer = self.get_serializer(
344                paginated_apps,
345                many=True,
346                context={**self.get_serializer_context(), "for_user": for_user},
347            )
348            return self.get_paginated_response(serializer.data)
349
350        paginated_apps = paginator.paginate_queryset(queryset, request)
351        allowed_applications = []
352        if not should_cache:
353            allowed_applications = self._get_allowed_applications(paginated_apps)
354        if should_cache:
355            client_ip = ClientIPMiddleware.get_client_ip(self.request)
356            allowed_applications = cache.get(
357                user_app_cache_key(
358                    self.request.user.pk, client_ip, paginator.page.number, only_with_launch_url
359                )
360            )
361            if allowed_applications:
362                # Re-fetch cached applications since pickled instances lose prefetched
363                # relationships, causing N+1 queries during serialization
364                allowed_applications = self._expand_applications(allowed_applications)
365            else:
366                LOGGER.debug("Caching allowed application list", page=paginator.page.number)
367                allowed_applications = self._get_allowed_applications(paginated_apps)
368                cache.set(
369                    user_app_cache_key(
370                        self.request.user.pk, client_ip, paginator.page.number, only_with_launch_url
371                    ),
372                    allowed_applications,
373                    timeout=CONFIG.get_int("cache.timeout_application_policies", 86400),
374                )
375
376        if only_with_launch_url:
377            allowed_applications = self._filter_applications_with_launch_url(allowed_applications)
378
379        serializer = self.get_serializer(allowed_applications, many=True)
380        return self.get_paginated_response(serializer.data)

Application Viewset

queryset = <ApplicationQuerySet []>
serializer_class = <class 'ApplicationSerializer'>
search_fields = ['name', 'slug', 'meta_launch_url', 'meta_description', 'meta_publisher', 'group']
filterset_fields = ['name', 'slug', 'meta_launch_url', 'meta_description', 'meta_publisher', 'group']
lookup_field = 'slug'
ordering = ['name']
@extend_schema(parameters=[OpenApiParameter(name='for_user', location=OpenApiParameter.QUERY, type=OpenApiTypes.INT)], responses={200: PolicyTestResultSerializer()})
@action(detail=True, methods=['GET'])
def check_access( self, request: rest_framework.request.Request, slug: str) -> rest_framework.response.Response:
238    @extend_schema(
239        parameters=[
240            OpenApiParameter(
241                name="for_user",
242                location=OpenApiParameter.QUERY,
243                type=OpenApiTypes.INT,
244            )
245        ],
246        responses={
247            200: PolicyTestResultSerializer(),
248        },
249    )
250    @action(detail=True, methods=["GET"])
251    def check_access(self, request: Request, slug: str) -> Response:
252        """Check access to a single application by slug"""
253        # Don't use self.get_object as that checks for view_application permission
254        # which the user might not have, even if they have access
255        application = get_object_or_404(Application, slug=slug)
256        # If the current user is superuser, they can set `for_user`
257        for_user = request.user
258        if request.user.is_superuser and "for_user" in request.query_params:
259            try:
260                for_user = User.objects.filter(pk=request.query_params.get("for_user")).first()
261            except ValueError:
262                raise ValidationError({"for_user": "for_user must be numerical"}) from None
263            if not for_user:
264                raise ValidationError({"for_user": "User not found"})
265        engine = PolicyEngine(application, for_user, request)
266        engine.empty_result = AppAccessWithoutBindings.get()
267        engine.use_cache = False
268        with capture_logs() as logs:
269            engine.build()
270            result = engine.result
271        response = PolicyTestResultSerializer(PolicyResult(False))
272        if result.passing:
273            response = PolicyTestResultSerializer(PolicyResult(True))
274        if request.user.is_superuser:
275            log_messages = []
276            for log in logs:
277                if log.attributes.get("process", "") == "PolicyProcess":
278                    continue
279                log_messages.append(LogEventSerializer(log).data)
280            result.log_messages = log_messages
281            response = PolicyTestResultSerializer(result)
282        return Response(response.data)

Check access to a single application by slug

@extend_schema(parameters=[OpenApiParameter(name='for_user', location=OpenApiParameter.QUERY, type=OpenApiTypes.INT), OpenApiParameter(name='only_with_launch_url', location=OpenApiParameter.QUERY, type=OpenApiTypes.BOOL)], responses={200: ApplicationSerializer(many=True)}, operation_id='core_applications_accessible_list')
@action(methods=['GET'], detail=False, url_path='@accessible', filter_backends=[QLSearch, DjangoFilterBackend, NullsAwareOrderingFilter])
def accessible( self, request: rest_framework.request.Request) -> rest_framework.response.Response:
284    @extend_schema(
285        parameters=[
286            OpenApiParameter(
287                name="for_user",
288                location=OpenApiParameter.QUERY,
289                type=OpenApiTypes.INT,
290            ),
291            OpenApiParameter(
292                name="only_with_launch_url",
293                location=OpenApiParameter.QUERY,
294                type=OpenApiTypes.BOOL,
295            ),
296        ],
297        responses={
298            200: ApplicationSerializer(many=True),
299        },
300        operation_id="core_applications_accessible_list",
301    )
302    @action(
303        methods=["GET"],
304        detail=False,
305        url_path="@accessible",
306        # Access is decided by policies below, so skip the RBAC ObjectFilter
307        filter_backends=[QLSearch, DjangoFilterBackend, NullsAwareOrderingFilter],
308    )
309    def accessible(self, request: Request) -> Response:
310        """List applications the user passes policies for, regardless of RBAC permissions"""
311        should_cache = request.query_params.get("search", "") == ""
312
313        only_with_launch_url = (
314            str(request.query_params.get("only_with_launch_url", "false")).lower()
315        ) == "true"
316
317        queryset = self.filter_queryset(self.get_queryset())
318        queryset = queryset.exclude(meta_hide=True)
319        if only_with_launch_url:
320            # Pre-filter at DB level to skip expensive per-app policy evaluation
321            # for apps that can never appear in the launcher (no meta_launch_url
322            # and no provider, so no possible launch URL).
323            queryset = queryset.exclude(meta_launch_url="", provider__isnull=True)
324        paginator: Pagination = self.paginator
325
326        if "for_user" in request.query_params:
327            try:
328                for_user: int = int(request.query_params.get("for_user", 0))
329                for_user = (
330                    get_objects_for_user(request.user, "authentik_core.view_user_applications")
331                    .filter(pk=for_user)
332                    .first()
333                )
334                if not for_user:
335                    raise ValidationError({"for_user": "User not found"})
336            except ValueError as exc:
337                raise ValidationError from exc
338            # Evaluate the full candidate set so counts and page boundaries reflect
339            # applications this user can access, rather than all applications.
340            allowed_applications = self._get_allowed_applications(queryset, user=for_user)
341            paginated_apps = paginator.paginate_queryset(allowed_applications, request)
342
343            serializer = self.get_serializer(
344                paginated_apps,
345                many=True,
346                context={**self.get_serializer_context(), "for_user": for_user},
347            )
348            return self.get_paginated_response(serializer.data)
349
350        paginated_apps = paginator.paginate_queryset(queryset, request)
351        allowed_applications = []
352        if not should_cache:
353            allowed_applications = self._get_allowed_applications(paginated_apps)
354        if should_cache:
355            client_ip = ClientIPMiddleware.get_client_ip(self.request)
356            allowed_applications = cache.get(
357                user_app_cache_key(
358                    self.request.user.pk, client_ip, paginator.page.number, only_with_launch_url
359                )
360            )
361            if allowed_applications:
362                # Re-fetch cached applications since pickled instances lose prefetched
363                # relationships, causing N+1 queries during serialization
364                allowed_applications = self._expand_applications(allowed_applications)
365            else:
366                LOGGER.debug("Caching allowed application list", page=paginator.page.number)
367                allowed_applications = self._get_allowed_applications(paginated_apps)
368                cache.set(
369                    user_app_cache_key(
370                        self.request.user.pk, client_ip, paginator.page.number, only_with_launch_url
371                    ),
372                    allowed_applications,
373                    timeout=CONFIG.get_int("cache.timeout_application_policies", 86400),
374                )
375
376        if only_with_launch_url:
377            allowed_applications = self._filter_applications_with_launch_url(allowed_applications)
378
379        serializer = self.get_serializer(allowed_applications, many=True)
380        return self.get_paginated_response(serializer.data)

List applications the user passes policies for, regardless of RBAC permissions

name = None
description = None
suffix = None
detail = None
basename = None