authentik.rbac.endpoints

API endpoints permission checks can be bound to

  1"""API endpoints permission checks can be bound to"""
  2
  3from collections.abc import Iterator
  4from dataclasses import dataclass
  5from functools import cache
  6from typing import TYPE_CHECKING
  7
  8from django.urls import URLPattern
  9from rest_framework.request import Request
 10
 11if TYPE_CHECKING:
 12    from rest_framework.viewsets import ViewSet
 13
 14RBAC_FUNC_HAS_PERMISSION = "has_permission"
 15RBAC_FUNC_HAS_OBJECT_PERMISSION = "has_object_permission"
 16RBAC_FUNC_NARROW_LIST = "narrow_list"
 17RBAC_FUNC_WIDEN_LIST = "widen_list"
 18RBAC_FUNC_ALTER_RESPONSE = "alter_response"
 19RBAC_FUNC_HIDDEN_FIELDS = "hidden_fields"
 20RBAC_FUNC_READONLY_FIELDS = "readonly_fields"
 21FUNCTIONS = (
 22    RBAC_FUNC_HAS_PERMISSION,
 23    RBAC_FUNC_HAS_OBJECT_PERMISSION,
 24    RBAC_FUNC_NARROW_LIST,
 25    RBAC_FUNC_WIDEN_LIST,
 26    RBAC_FUNC_ALTER_RESPONSE,
 27    RBAC_FUNC_HIDDEN_FIELDS,
 28    RBAC_FUNC_READONLY_FIELDS,
 29)
 30
 31API_PREFIX = "api/v3/"
 32FIELD_ACTIONS = {"list", "retrieve", "create", "update", "partial_update"}
 33WRITE_ACTIONS = {"create", "update", "partial_update"}
 34
 35
 36@dataclass
 37class Endpoint:
 38    id: str
 39    functions: tuple[str, ...]
 40
 41
 42class Endpoints:
 43    """
 44    Technical note: many functions here have late imports to avoid circular dependencies, because
 45    the API's URLs import this module through the views they route to.
 46    """
 47
 48    @staticmethod
 49    @cache
 50    def router_prefixes() -> dict[type, str]:
 51        from authentik.api.v3.urls import router
 52
 53        return {viewset: prefix for prefix, viewset, basename in router.registry}
 54
 55    @classmethod
 56    def endpoint_id(cls, request: Request, action: str | None = None) -> str | None:
 57        """`<router prefix>:<action>` for viewsets and `<path>:<method>` for other views, or
 58        with `action` the id of that action of the requested viewset"""
 59        match = getattr(request, "resolver_match", None)
 60        if match is None:
 61            return None
 62        if prefix := cls.router_prefixes().get(getattr(match.func, "cls", None)):
 63            action = action or getattr(match.func, "actions", {}).get(request.method.lower())
 64            return f"{prefix}:{action}" if action else None
 65        route = match.route or ""
 66        if action or not route.startswith(API_PREFIX):
 67            return None
 68        return f"{route.removeprefix(API_PREFIX).strip('/')}:{request.method.lower()}"
 69
 70    @classmethod
 71    def viewset_for(cls, endpoint: str) -> type[ViewSet]:
 72        prefix = endpoint.rsplit(":", 1)[0]
 73        return next(viewset for viewset, path in cls.router_prefixes().items() if path == prefix)
 74
 75    @classmethod
 76    @cache
 77    def hookable(cls) -> dict[str, Endpoint]:
 78        """Every endpoint to which permission checks can be bound, by id"""
 79        from authentik.api.v3.urls import _other_urls, router
 80
 81        routes = [pattern for pattern in router.urls if hasattr(pattern.callback, "actions")]
 82        endpoints = [endpoint for pattern in routes for endpoint in cls.from_route(pattern)]
 83        endpoints += [endpoint for pattern in _other_urls for endpoint in cls.from_view(pattern)]
 84        return {endpoint.id: endpoint for endpoint in endpoints}
 85
 86    @classmethod
 87    def from_route(cls, pattern: URLPattern) -> Iterator[Endpoint]:
 88        view = pattern.callback
 89        viewset = view.cls
 90        options = view.initkwargs
 91        prefix = cls.router_prefixes()[viewset]
 92        permission_classes = options.get("permission_classes", viewset.permission_classes)
 93        backends = options.get("filter_backends", getattr(viewset, "filter_backends", ()))
 94        for action in dict.fromkeys(view.actions.values()):
 95            if not cls.is_hookable(permission_classes, getattr(viewset, action)):
 96                continue
 97            functions = [RBAC_FUNC_HAS_PERMISSION]
 98            if options.get("detail"):
 99                functions.append(RBAC_FUNC_HAS_OBJECT_PERMISSION)
100            if action == "list" and any(
101                issubclass(backend, cls.list_filters()) for backend in backends
102            ):
103                functions += [RBAC_FUNC_NARROW_LIST, RBAC_FUNC_WIDEN_LIST]
104            if action in FIELD_ACTIONS and getattr(viewset, "queryset", None) is not None:
105                functions.append(RBAC_FUNC_HIDDEN_FIELDS)
106                if action in WRITE_ACTIONS:
107                    functions.append(RBAC_FUNC_READONLY_FIELDS)
108            functions.append(RBAC_FUNC_ALTER_RESPONSE)
109            yield Endpoint(f"{prefix}:{action}", tuple(functions))
110
111    @classmethod
112    def from_view(cls, pattern: URLPattern) -> Iterator[Endpoint]:
113        """The endpoints of a view outside the router, one per HTTP method"""
114        view = getattr(pattern.callback, "cls", None)
115        if view is None or not cls.is_hookable(view.permission_classes, None):
116            return
117        path = str(pattern.pattern).strip("/")
118        functions = (RBAC_FUNC_HAS_PERMISSION, RBAC_FUNC_ALTER_RESPONSE)
119        for method in view.http_method_names:
120            if method != "options" and hasattr(view, method):
121                yield Endpoint(f"{path}:{method}", functions)
122
123    @staticmethod
124    def is_hookable(permission_classes: list, handler) -> bool:
125        from authentik.rbac.permissions import ObjectPermissions
126
127        return getattr(handler, "permission_requirements", None) is not None or any(
128            isinstance(cls, type) and issubclass(cls, ObjectPermissions)
129            for cls in permission_classes
130        )
131
132    @staticmethod
133    def list_filters() -> tuple[type, ...]:
134        """The filters that run narrow_list and widen_list"""
135        from authentik.rbac.filters import ObjectFilter, SecretKeyFilter
136
137        return ObjectFilter, SecretKeyFilter
RBAC_FUNC_HAS_PERMISSION = 'has_permission'
RBAC_FUNC_HAS_OBJECT_PERMISSION = 'has_object_permission'
RBAC_FUNC_NARROW_LIST = 'narrow_list'
RBAC_FUNC_WIDEN_LIST = 'widen_list'
RBAC_FUNC_ALTER_RESPONSE = 'alter_response'
RBAC_FUNC_HIDDEN_FIELDS = 'hidden_fields'
RBAC_FUNC_READONLY_FIELDS = 'readonly_fields'
FUNCTIONS = ('has_permission', 'has_object_permission', 'narrow_list', 'widen_list', 'alter_response', 'hidden_fields', 'readonly_fields')
API_PREFIX = 'api/v3/'
FIELD_ACTIONS = {'retrieve', 'list', 'create', 'partial_update', 'update'}
WRITE_ACTIONS = {'create', 'partial_update', 'update'}
@dataclass
class Endpoint:
37@dataclass
38class Endpoint:
39    id: str
40    functions: tuple[str, ...]
Endpoint(id: str, functions: tuple[str, ...])
id: str
functions: tuple[str, ...]
class Endpoints:
 43class Endpoints:
 44    """
 45    Technical note: many functions here have late imports to avoid circular dependencies, because
 46    the API's URLs import this module through the views they route to.
 47    """
 48
 49    @staticmethod
 50    @cache
 51    def router_prefixes() -> dict[type, str]:
 52        from authentik.api.v3.urls import router
 53
 54        return {viewset: prefix for prefix, viewset, basename in router.registry}
 55
 56    @classmethod
 57    def endpoint_id(cls, request: Request, action: str | None = None) -> str | None:
 58        """`<router prefix>:<action>` for viewsets and `<path>:<method>` for other views, or
 59        with `action` the id of that action of the requested viewset"""
 60        match = getattr(request, "resolver_match", None)
 61        if match is None:
 62            return None
 63        if prefix := cls.router_prefixes().get(getattr(match.func, "cls", None)):
 64            action = action or getattr(match.func, "actions", {}).get(request.method.lower())
 65            return f"{prefix}:{action}" if action else None
 66        route = match.route or ""
 67        if action or not route.startswith(API_PREFIX):
 68            return None
 69        return f"{route.removeprefix(API_PREFIX).strip('/')}:{request.method.lower()}"
 70
 71    @classmethod
 72    def viewset_for(cls, endpoint: str) -> type[ViewSet]:
 73        prefix = endpoint.rsplit(":", 1)[0]
 74        return next(viewset for viewset, path in cls.router_prefixes().items() if path == prefix)
 75
 76    @classmethod
 77    @cache
 78    def hookable(cls) -> dict[str, Endpoint]:
 79        """Every endpoint to which permission checks can be bound, by id"""
 80        from authentik.api.v3.urls import _other_urls, router
 81
 82        routes = [pattern for pattern in router.urls if hasattr(pattern.callback, "actions")]
 83        endpoints = [endpoint for pattern in routes for endpoint in cls.from_route(pattern)]
 84        endpoints += [endpoint for pattern in _other_urls for endpoint in cls.from_view(pattern)]
 85        return {endpoint.id: endpoint for endpoint in endpoints}
 86
 87    @classmethod
 88    def from_route(cls, pattern: URLPattern) -> Iterator[Endpoint]:
 89        view = pattern.callback
 90        viewset = view.cls
 91        options = view.initkwargs
 92        prefix = cls.router_prefixes()[viewset]
 93        permission_classes = options.get("permission_classes", viewset.permission_classes)
 94        backends = options.get("filter_backends", getattr(viewset, "filter_backends", ()))
 95        for action in dict.fromkeys(view.actions.values()):
 96            if not cls.is_hookable(permission_classes, getattr(viewset, action)):
 97                continue
 98            functions = [RBAC_FUNC_HAS_PERMISSION]
 99            if options.get("detail"):
100                functions.append(RBAC_FUNC_HAS_OBJECT_PERMISSION)
101            if action == "list" and any(
102                issubclass(backend, cls.list_filters()) for backend in backends
103            ):
104                functions += [RBAC_FUNC_NARROW_LIST, RBAC_FUNC_WIDEN_LIST]
105            if action in FIELD_ACTIONS and getattr(viewset, "queryset", None) is not None:
106                functions.append(RBAC_FUNC_HIDDEN_FIELDS)
107                if action in WRITE_ACTIONS:
108                    functions.append(RBAC_FUNC_READONLY_FIELDS)
109            functions.append(RBAC_FUNC_ALTER_RESPONSE)
110            yield Endpoint(f"{prefix}:{action}", tuple(functions))
111
112    @classmethod
113    def from_view(cls, pattern: URLPattern) -> Iterator[Endpoint]:
114        """The endpoints of a view outside the router, one per HTTP method"""
115        view = getattr(pattern.callback, "cls", None)
116        if view is None or not cls.is_hookable(view.permission_classes, None):
117            return
118        path = str(pattern.pattern).strip("/")
119        functions = (RBAC_FUNC_HAS_PERMISSION, RBAC_FUNC_ALTER_RESPONSE)
120        for method in view.http_method_names:
121            if method != "options" and hasattr(view, method):
122                yield Endpoint(f"{path}:{method}", functions)
123
124    @staticmethod
125    def is_hookable(permission_classes: list, handler) -> bool:
126        from authentik.rbac.permissions import ObjectPermissions
127
128        return getattr(handler, "permission_requirements", None) is not None or any(
129            isinstance(cls, type) and issubclass(cls, ObjectPermissions)
130            for cls in permission_classes
131        )
132
133    @staticmethod
134    def list_filters() -> tuple[type, ...]:
135        """The filters that run narrow_list and widen_list"""
136        from authentik.rbac.filters import ObjectFilter, SecretKeyFilter
137
138        return ObjectFilter, SecretKeyFilter

Technical note: many functions here have late imports to avoid circular dependencies, because the API's URLs import this module through the views they route to.

@staticmethod
@cache
def router_prefixes() -> dict[type, str]:
49    @staticmethod
50    @cache
51    def router_prefixes() -> dict[type, str]:
52        from authentik.api.v3.urls import router
53
54        return {viewset: prefix for prefix, viewset, basename in router.registry}
@classmethod
def endpoint_id( cls, request: rest_framework.request.Request, action: str | None = None) -> str | None:
56    @classmethod
57    def endpoint_id(cls, request: Request, action: str | None = None) -> str | None:
58        """`<router prefix>:<action>` for viewsets and `<path>:<method>` for other views, or
59        with `action` the id of that action of the requested viewset"""
60        match = getattr(request, "resolver_match", None)
61        if match is None:
62            return None
63        if prefix := cls.router_prefixes().get(getattr(match.func, "cls", None)):
64            action = action or getattr(match.func, "actions", {}).get(request.method.lower())
65            return f"{prefix}:{action}" if action else None
66        route = match.route or ""
67        if action or not route.startswith(API_PREFIX):
68            return None
69        return f"{route.removeprefix(API_PREFIX).strip('/')}:{request.method.lower()}"

<router prefix>:<action> for viewsets and <path>:<method> for other views, or with action the id of that action of the requested viewset

@classmethod
def viewset_for(unknown):
71    @classmethod
72    def viewset_for(cls, endpoint: str) -> type[ViewSet]:
73        prefix = endpoint.rsplit(":", 1)[0]
74        return next(viewset for viewset, path in cls.router_prefixes().items() if path == prefix)
@classmethod
@cache
def hookable(cls) -> dict[str, Endpoint]:
76    @classmethod
77    @cache
78    def hookable(cls) -> dict[str, Endpoint]:
79        """Every endpoint to which permission checks can be bound, by id"""
80        from authentik.api.v3.urls import _other_urls, router
81
82        routes = [pattern for pattern in router.urls if hasattr(pattern.callback, "actions")]
83        endpoints = [endpoint for pattern in routes for endpoint in cls.from_route(pattern)]
84        endpoints += [endpoint for pattern in _other_urls for endpoint in cls.from_view(pattern)]
85        return {endpoint.id: endpoint for endpoint in endpoints}

Every endpoint to which permission checks can be bound, by id

@classmethod
def from_route( cls, pattern: django.urls.resolvers.URLPattern) -> Iterator[Endpoint]:
 87    @classmethod
 88    def from_route(cls, pattern: URLPattern) -> Iterator[Endpoint]:
 89        view = pattern.callback
 90        viewset = view.cls
 91        options = view.initkwargs
 92        prefix = cls.router_prefixes()[viewset]
 93        permission_classes = options.get("permission_classes", viewset.permission_classes)
 94        backends = options.get("filter_backends", getattr(viewset, "filter_backends", ()))
 95        for action in dict.fromkeys(view.actions.values()):
 96            if not cls.is_hookable(permission_classes, getattr(viewset, action)):
 97                continue
 98            functions = [RBAC_FUNC_HAS_PERMISSION]
 99            if options.get("detail"):
100                functions.append(RBAC_FUNC_HAS_OBJECT_PERMISSION)
101            if action == "list" and any(
102                issubclass(backend, cls.list_filters()) for backend in backends
103            ):
104                functions += [RBAC_FUNC_NARROW_LIST, RBAC_FUNC_WIDEN_LIST]
105            if action in FIELD_ACTIONS and getattr(viewset, "queryset", None) is not None:
106                functions.append(RBAC_FUNC_HIDDEN_FIELDS)
107                if action in WRITE_ACTIONS:
108                    functions.append(RBAC_FUNC_READONLY_FIELDS)
109            functions.append(RBAC_FUNC_ALTER_RESPONSE)
110            yield Endpoint(f"{prefix}:{action}", tuple(functions))
@classmethod
def from_view( cls, pattern: django.urls.resolvers.URLPattern) -> Iterator[Endpoint]:
112    @classmethod
113    def from_view(cls, pattern: URLPattern) -> Iterator[Endpoint]:
114        """The endpoints of a view outside the router, one per HTTP method"""
115        view = getattr(pattern.callback, "cls", None)
116        if view is None or not cls.is_hookable(view.permission_classes, None):
117            return
118        path = str(pattern.pattern).strip("/")
119        functions = (RBAC_FUNC_HAS_PERMISSION, RBAC_FUNC_ALTER_RESPONSE)
120        for method in view.http_method_names:
121            if method != "options" and hasattr(view, method):
122                yield Endpoint(f"{path}:{method}", functions)

The endpoints of a view outside the router, one per HTTP method

@staticmethod
def is_hookable(permission_classes: list, handler) -> bool:
124    @staticmethod
125    def is_hookable(permission_classes: list, handler) -> bool:
126        from authentik.rbac.permissions import ObjectPermissions
127
128        return getattr(handler, "permission_requirements", None) is not None or any(
129            isinstance(cls, type) and issubclass(cls, ObjectPermissions)
130            for cls in permission_classes
131        )
@staticmethod
def list_filters() -> tuple[type, ...]:
133    @staticmethod
134    def list_filters() -> tuple[type, ...]:
135        """The filters that run narrow_list and widen_list"""
136        from authentik.rbac.filters import ObjectFilter, SecretKeyFilter
137
138        return ObjectFilter, SecretKeyFilter

The filters that run narrow_list and widen_list