authentik.sources.scim.views.v2.base

SCIM Utils

  1"""SCIM Utils"""
  2
  3from typing import Any
  4from uuid import UUID
  5
  6from django.core.exceptions import FieldError
  7from django.core.paginator import Page, Paginator
  8from django.db.models import Q, QuerySet
  9from django.http import HttpRequest
 10from rest_framework.parsers import JSONParser
 11from rest_framework.permissions import IsAuthenticated
 12from rest_framework.renderers import JSONRenderer
 13from rest_framework.request import Request
 14from rest_framework.response import Response
 15from rest_framework.views import APIView
 16from scim2_filter_parser.parser import SCIMParserError
 17from scim2_filter_parser.transpilers.django_q_object import get_query
 18from structlog import BoundLogger
 19from structlog.stdlib import get_logger
 20
 21from authentik.admin.utils import get_system_settings
 22from authentik.core.models import Group, User
 23from authentik.core.sources.mapper import SourceMapper
 24from authentik.lib.sync.mapper import PropertyMappingManager
 25from authentik.sources.scim.models import SCIMSource
 26from authentik.sources.scim.views.v2.auth import SCIMTokenAuth
 27from authentik.sources.scim.views.v2.exceptions import SCIMInvalidFilterError, SCIMNotFoundError
 28
 29SCIM_CONTENT_TYPE = "application/scim+json"
 30
 31
 32class SCIMParser(JSONParser):
 33    """SCIM clients use a custom content type"""
 34
 35    media_type = SCIM_CONTENT_TYPE
 36
 37
 38class SCIMRenderer(JSONRenderer):
 39    """SCIM clients also expect a custom content type"""
 40
 41    media_type = SCIM_CONTENT_TYPE
 42
 43
 44class SCIMView(APIView):
 45    """Base class for SCIM Views"""
 46
 47    source: SCIMSource
 48    logger: BoundLogger
 49
 50    permission_classes = [IsAuthenticated]
 51    parser_classes = [SCIMParser, JSONParser]
 52    renderer_classes = [SCIMRenderer]
 53
 54    def setup(self, request: HttpRequest, *args: Any, **kwargs: Any) -> None:
 55        self.logger = get_logger().bind()
 56        super().setup(request, *args, **kwargs)
 57
 58    def get_authenticators(self):
 59        return [SCIMTokenAuth(self)]
 60
 61    def remove_excluded_attributes(self, data: dict):
 62        """Remove attributes specified in excludedAttributes"""
 63        excluded: str = self.request.query_params.get("excludedAttributes", "")
 64        for key in excluded.split(","):
 65            data.pop(key.strip(), None)
 66        return data
 67
 68    def filter_parse(self, request: Request) -> Q:
 69        """Parse the `filter` query parameter into a Q object"""
 70        path = request.query_params.get("filter")
 71        if not path:
 72            return Q()
 73        attr_map = {}
 74        if self.model == User:
 75            attr_map = {
 76                ("id", None, None): "user__uuid",
 77                ("userName", None, None): "user__username",
 78                ("active", None, None): "user__is_active",
 79                ("name", "familyName", None): "attributes__familyName",
 80                ("externalId", None, None): "external_id",
 81            }
 82        elif self.model == Group:
 83            attr_map = {
 84                ("id", None, None): "group__group_uuid",
 85                ("displayName", None, None): "group__name",
 86                # `members` is a many-to-many relation, so it has to be filtered on a
 87                # concrete field of the related user instead of on the relation itself
 88                ("members", None, None): "group__users__uuid",
 89                ("externalId", None, None): "external_id",
 90            }
 91        try:
 92            query = get_query(path, attr_map)
 93        except (SCIMParserError, ValueError) as exc:
 94            self.logger.debug("Failed to parse filter", filter=path, exc=exc)
 95            raise SCIMInvalidFilterError("Invalid filter.") from exc
 96        if query is None:
 97            # None is returned when none of the attributes in the filter can be mapped
 98            # to a field, in which case we can't return any meaningful result
 99            self.logger.debug("Failed to map filter to any field", filter=path)
100            raise SCIMInvalidFilterError("Unsupported filter attribute.")
101        return query
102
103    def filter_query(self, request: Request, query: QuerySet) -> QuerySet:
104        """Apply the `filter` query parameter to `query`"""
105        parsed = self.filter_parse(request)
106        try:
107            return query.filter(parsed)
108        except FieldError as exc:
109            self.logger.debug("Failed to apply filter", filter=parsed, exc=exc)
110            raise SCIMInvalidFilterError("Unsupported filter.") from exc
111
112    def paginate_query(self, query: QuerySet) -> Page:
113        per_page = int(get_system_settings().pagination_default_page_size)
114        start_index = 1
115        try:
116            start_index = int(self.request.query_params.get("startIndex", 1))
117        except ValueError:
118            pass
119        paginator = Paginator(query, per_page=per_page)
120        page = paginator.page(int(max(start_index / per_page, 1)))
121        return page
122
123
124class SCIMObjectView(SCIMView):
125    """Base SCIM View for object management"""
126
127    mapper: SourceMapper
128    manager: PropertyMappingManager
129
130    model: type[User | Group]
131
132    def initial(self, request: Request, *args, **kwargs) -> None:
133        super().initial(request, *args, **kwargs)
134        # This needs to happen after authentication has happened, because we don't have
135        # a source attribute before
136        self.mapper = SourceMapper(self.source)
137        self.manager = self.mapper.get_manager(self.model, ["data"])
138        for key, value in kwargs.items():
139            if key.endswith("_id"):
140                try:
141                    UUID(value)
142                except ValueError:
143                    raise SCIMNotFoundError("Invalid ID") from None
144
145    def build_object_properties(self, data: dict[str, Any]) -> dict[str, Any | dict[str, Any]]:
146        return self.mapper.build_object_properties(
147            object_type=self.model,
148            manager=self.manager,
149            user=None,
150            request=self.request,
151            data=data,
152        )
153
154
155class SCIMRootView(SCIMView):
156    """Root SCIM View"""
157
158    def dispatch(self, request: Request, *args, **kwargs) -> Response:
159        return Response({"message": "Use this base-URL with a SCIM-compatible system."})
SCIM_CONTENT_TYPE = 'application/scim+json'
class SCIMParser(rest_framework.parsers.JSONParser):
33class SCIMParser(JSONParser):
34    """SCIM clients use a custom content type"""
35
36    media_type = SCIM_CONTENT_TYPE

SCIM clients use a custom content type

media_type = 'application/scim+json'
class SCIMRenderer(rest_framework.renderers.JSONRenderer):
39class SCIMRenderer(JSONRenderer):
40    """SCIM clients also expect a custom content type"""
41
42    media_type = SCIM_CONTENT_TYPE

SCIM clients also expect a custom content type

media_type = 'application/scim+json'
class SCIMView(rest_framework.views.APIView):
 45class SCIMView(APIView):
 46    """Base class for SCIM Views"""
 47
 48    source: SCIMSource
 49    logger: BoundLogger
 50
 51    permission_classes = [IsAuthenticated]
 52    parser_classes = [SCIMParser, JSONParser]
 53    renderer_classes = [SCIMRenderer]
 54
 55    def setup(self, request: HttpRequest, *args: Any, **kwargs: Any) -> None:
 56        self.logger = get_logger().bind()
 57        super().setup(request, *args, **kwargs)
 58
 59    def get_authenticators(self):
 60        return [SCIMTokenAuth(self)]
 61
 62    def remove_excluded_attributes(self, data: dict):
 63        """Remove attributes specified in excludedAttributes"""
 64        excluded: str = self.request.query_params.get("excludedAttributes", "")
 65        for key in excluded.split(","):
 66            data.pop(key.strip(), None)
 67        return data
 68
 69    def filter_parse(self, request: Request) -> Q:
 70        """Parse the `filter` query parameter into a Q object"""
 71        path = request.query_params.get("filter")
 72        if not path:
 73            return Q()
 74        attr_map = {}
 75        if self.model == User:
 76            attr_map = {
 77                ("id", None, None): "user__uuid",
 78                ("userName", None, None): "user__username",
 79                ("active", None, None): "user__is_active",
 80                ("name", "familyName", None): "attributes__familyName",
 81                ("externalId", None, None): "external_id",
 82            }
 83        elif self.model == Group:
 84            attr_map = {
 85                ("id", None, None): "group__group_uuid",
 86                ("displayName", None, None): "group__name",
 87                # `members` is a many-to-many relation, so it has to be filtered on a
 88                # concrete field of the related user instead of on the relation itself
 89                ("members", None, None): "group__users__uuid",
 90                ("externalId", None, None): "external_id",
 91            }
 92        try:
 93            query = get_query(path, attr_map)
 94        except (SCIMParserError, ValueError) as exc:
 95            self.logger.debug("Failed to parse filter", filter=path, exc=exc)
 96            raise SCIMInvalidFilterError("Invalid filter.") from exc
 97        if query is None:
 98            # None is returned when none of the attributes in the filter can be mapped
 99            # to a field, in which case we can't return any meaningful result
100            self.logger.debug("Failed to map filter to any field", filter=path)
101            raise SCIMInvalidFilterError("Unsupported filter attribute.")
102        return query
103
104    def filter_query(self, request: Request, query: QuerySet) -> QuerySet:
105        """Apply the `filter` query parameter to `query`"""
106        parsed = self.filter_parse(request)
107        try:
108            return query.filter(parsed)
109        except FieldError as exc:
110            self.logger.debug("Failed to apply filter", filter=parsed, exc=exc)
111            raise SCIMInvalidFilterError("Unsupported filter.") from exc
112
113    def paginate_query(self, query: QuerySet) -> Page:
114        per_page = int(get_system_settings().pagination_default_page_size)
115        start_index = 1
116        try:
117            start_index = int(self.request.query_params.get("startIndex", 1))
118        except ValueError:
119            pass
120        paginator = Paginator(query, per_page=per_page)
121        page = paginator.page(int(max(start_index / per_page, 1)))
122        return page

Base class for SCIM Views

logger: structlog._generic.BoundLogger
permission_classes = [<class 'rest_framework.permissions.IsAuthenticated'>]
parser_classes = [<class 'SCIMParser'>, <class 'rest_framework.parsers.JSONParser'>]
renderer_classes = [<class 'SCIMRenderer'>]
def setup( self, request: django.http.request.HttpRequest, *args: Any, **kwargs: Any) -> None:
55    def setup(self, request: HttpRequest, *args: Any, **kwargs: Any) -> None:
56        self.logger = get_logger().bind()
57        super().setup(request, *args, **kwargs)

Initialize attributes shared by all view methods.

def get_authenticators(self):
59    def get_authenticators(self):
60        return [SCIMTokenAuth(self)]

Instantiates and returns the list of authenticators that this view can use.

def remove_excluded_attributes(self, data: dict):
62    def remove_excluded_attributes(self, data: dict):
63        """Remove attributes specified in excludedAttributes"""
64        excluded: str = self.request.query_params.get("excludedAttributes", "")
65        for key in excluded.split(","):
66            data.pop(key.strip(), None)
67        return data

Remove attributes specified in excludedAttributes

def filter_parse( self, request: rest_framework.request.Request) -> django.db.models.query_utils.Q:
 69    def filter_parse(self, request: Request) -> Q:
 70        """Parse the `filter` query parameter into a Q object"""
 71        path = request.query_params.get("filter")
 72        if not path:
 73            return Q()
 74        attr_map = {}
 75        if self.model == User:
 76            attr_map = {
 77                ("id", None, None): "user__uuid",
 78                ("userName", None, None): "user__username",
 79                ("active", None, None): "user__is_active",
 80                ("name", "familyName", None): "attributes__familyName",
 81                ("externalId", None, None): "external_id",
 82            }
 83        elif self.model == Group:
 84            attr_map = {
 85                ("id", None, None): "group__group_uuid",
 86                ("displayName", None, None): "group__name",
 87                # `members` is a many-to-many relation, so it has to be filtered on a
 88                # concrete field of the related user instead of on the relation itself
 89                ("members", None, None): "group__users__uuid",
 90                ("externalId", None, None): "external_id",
 91            }
 92        try:
 93            query = get_query(path, attr_map)
 94        except (SCIMParserError, ValueError) as exc:
 95            self.logger.debug("Failed to parse filter", filter=path, exc=exc)
 96            raise SCIMInvalidFilterError("Invalid filter.") from exc
 97        if query is None:
 98            # None is returned when none of the attributes in the filter can be mapped
 99            # to a field, in which case we can't return any meaningful result
100            self.logger.debug("Failed to map filter to any field", filter=path)
101            raise SCIMInvalidFilterError("Unsupported filter attribute.")
102        return query

Parse the filter query parameter into a Q object

def filter_query( self, request: rest_framework.request.Request, query: django.db.models.query.QuerySet) -> django.db.models.query.QuerySet:
104    def filter_query(self, request: Request, query: QuerySet) -> QuerySet:
105        """Apply the `filter` query parameter to `query`"""
106        parsed = self.filter_parse(request)
107        try:
108            return query.filter(parsed)
109        except FieldError as exc:
110            self.logger.debug("Failed to apply filter", filter=parsed, exc=exc)
111            raise SCIMInvalidFilterError("Unsupported filter.") from exc

Apply the filter query parameter to query

def paginate_query( self, query: django.db.models.query.QuerySet) -> django.core.paginator.Page:
113    def paginate_query(self, query: QuerySet) -> Page:
114        per_page = int(get_system_settings().pagination_default_page_size)
115        start_index = 1
116        try:
117            start_index = int(self.request.query_params.get("startIndex", 1))
118        except ValueError:
119            pass
120        paginator = Paginator(query, per_page=per_page)
121        page = paginator.page(int(max(start_index / per_page, 1)))
122        return page
class SCIMObjectView(SCIMView):
125class SCIMObjectView(SCIMView):
126    """Base SCIM View for object management"""
127
128    mapper: SourceMapper
129    manager: PropertyMappingManager
130
131    model: type[User | Group]
132
133    def initial(self, request: Request, *args, **kwargs) -> None:
134        super().initial(request, *args, **kwargs)
135        # This needs to happen after authentication has happened, because we don't have
136        # a source attribute before
137        self.mapper = SourceMapper(self.source)
138        self.manager = self.mapper.get_manager(self.model, ["data"])
139        for key, value in kwargs.items():
140            if key.endswith("_id"):
141                try:
142                    UUID(value)
143                except ValueError:
144                    raise SCIMNotFoundError("Invalid ID") from None
145
146    def build_object_properties(self, data: dict[str, Any]) -> dict[str, Any | dict[str, Any]]:
147        return self.mapper.build_object_properties(
148            object_type=self.model,
149            manager=self.manager,
150            user=None,
151            request=self.request,
152            data=data,
153        )

Base SCIM View for object management

def initial(self, request: rest_framework.request.Request, *args, **kwargs) -> None:
133    def initial(self, request: Request, *args, **kwargs) -> None:
134        super().initial(request, *args, **kwargs)
135        # This needs to happen after authentication has happened, because we don't have
136        # a source attribute before
137        self.mapper = SourceMapper(self.source)
138        self.manager = self.mapper.get_manager(self.model, ["data"])
139        for key, value in kwargs.items():
140            if key.endswith("_id"):
141                try:
142                    UUID(value)
143                except ValueError:
144                    raise SCIMNotFoundError("Invalid ID") from None

Runs anything that needs to occur prior to calling the method handler.

def build_object_properties( self, data: dict[str, typing.Any]) -> dict[str, typing.Any | dict[str, typing.Any]]:
146    def build_object_properties(self, data: dict[str, Any]) -> dict[str, Any | dict[str, Any]]:
147        return self.mapper.build_object_properties(
148            object_type=self.model,
149            manager=self.manager,
150            user=None,
151            request=self.request,
152            data=data,
153        )
class SCIMRootView(SCIMView):
156class SCIMRootView(SCIMView):
157    """Root SCIM View"""
158
159    def dispatch(self, request: Request, *args, **kwargs) -> Response:
160        return Response({"message": "Use this base-URL with a SCIM-compatible system."})

Root SCIM View

def dispatch( self, request: rest_framework.request.Request, *args, **kwargs) -> rest_framework.response.Response:
159    def dispatch(self, request: Request, *args, **kwargs) -> Response:
160        return Response({"message": "Use this base-URL with a SCIM-compatible system."})

Dispatch the incoming request to the appropriate handler method.

This method implements the core request/response lifecycle for Django REST Framework views:

  1. Wraps the incoming Django HttpRequest in a REST framework Request.
  2. Performs content negotiation, authentication, permission, and throttling checks.
  3. Resolves and calls the appropriate HTTP method handler (e.g. get(), post(), put()).
  4. Handles any exceptions raised during processing and converts them into appropriate Response objects.
  5. Finalizes and returns the response with proper rendering and headers applied.