authentik.enterprise.middleware

Enterprise middleware

  1"""Enterprise middleware"""
  2
  3from collections.abc import Callable
  4from re import Pattern, compile
  5
  6from django.http import HttpRequest, HttpResponse, JsonResponse
  7from django.urls import URLResolver, get_resolver
  8from structlog.stdlib import BoundLogger, get_logger
  9
 10from authentik.core.api.users import UserViewSet
 11from authentik.enterprise.api import LicenseViewSet
 12from authentik.enterprise.license import LicenseKey
 13from authentik.enterprise.models import LicenseUsageStatus
 14from authentik.flows.views.executor import FlowExecutorView
 15
 16# Views which are always allowed, even in read-only mode
 17ALWAYS_ALLOWED_VIEWS = (
 18    # Always allow requests to manage licenses
 19    LicenseViewSet,
 20    # Flow executor is mounted as an API path but explicitly allowed
 21    FlowExecutorView,
 22    # Always allow making changes to users, even in case the license has been exceeded
 23    UserViewSet,
 24)
 25
 26
 27def _build_paths(
 28    resolver: URLResolver, prefix: str, in_api: bool = False
 29) -> tuple[list[str], list[str]]:
 30    """Walk the URL tree and return regexes of API mountpoints and of allowed API endpoints"""
 31    api_paths, allowed_paths = [], []
 32    for entry in resolver.url_patterns:
 33        regex = prefix + entry.pattern.regex.pattern.removeprefix("^")
 34        if isinstance(entry, URLResolver):
 35            is_api = entry.app_name == "authentik_api"
 36            if is_api and not in_api:
 37                api_paths.append(regex)
 38            sub_api, sub_allowed = _build_paths(entry, regex, in_api or is_api)
 39            api_paths.extend(sub_api)
 40            allowed_paths.extend(sub_allowed)
 41            continue
 42        view = getattr(entry.callback, "view_class", getattr(entry.callback, "cls", None))
 43        if in_api and view in ALWAYS_ALLOWED_VIEWS:
 44            allowed_paths.append(regex)
 45    return api_paths, allowed_paths
 46
 47
 48_NAMED_GROUP = compile(r"\(\?P<\w+>")
 49
 50
 51def _combine(regexes: list[str]) -> Pattern:
 52    """Combine regexes into a single alternation; named groups are dropped as
 53    they'd clash across alternatives. An empty list never matches."""
 54    if not regexes:
 55        return compile(r"(?!)")
 56    return compile("|".join(f"(?:{_NAMED_GROUP.sub('(?:', regex)})" for regex in regexes))
 57
 58
 59_root = get_resolver()
 60_api_paths, _allowed_paths = _build_paths(_root, _root.pattern.regex.pattern)
 61API_PATHS = _combine(_api_paths)
 62ALLOWED_PATHS = _combine(_allowed_paths)
 63SAFE_METHODS = frozenset(["GET", "HEAD", "OPTIONS", "TRACE"])
 64
 65
 66class EnterpriseMiddleware:
 67    """Enterprise middleware"""
 68
 69    get_response: Callable[[HttpRequest], HttpResponse]
 70    logger: BoundLogger
 71
 72    def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]):
 73        self.get_response = get_response
 74        self.logger = get_logger().bind()
 75
 76    def __call__(self, request: HttpRequest) -> HttpResponse:
 77        if not self.is_request_allowed(request):
 78            self.logger.warning("Refusing request due to expired/invalid license")
 79            return JsonResponse(
 80                {
 81                    "detail": "Request denied due to expired/invalid license.",
 82                    "code": "denied_license",
 83                },
 84                status=400,
 85            )
 86        return self.get_response(request)
 87
 88    def is_request_allowed(self, request: HttpRequest) -> bool:
 89        """Check if a specific request is allowed"""
 90        if self.is_request_always_allowed(request):
 91            return True
 92        cached_status = LicenseKey.cached_summary()
 93        if not cached_status:
 94            return True
 95        if cached_status.status == LicenseUsageStatus.READ_ONLY:
 96            return False
 97        return True
 98
 99    def is_request_always_allowed(self, request: HttpRequest):
100        """Check if a request is always allowed"""
101        # Always allow "safe" methods
102        if request.method in SAFE_METHODS:
103            return True
104        # Only apply these restrictions to the API
105        if not API_PATHS.match(request.path_info):
106            return True
107        return ALLOWED_PATHS.match(request.path_info) is not None
API_PATHS = re.compile('(?:^/api/)')
ALLOWED_PATHS = re.compile('(?:^/api/v3/flows/executor/(?:[-a-zA-Z0-9_]+)/\\Z)|(?:^/api/v3/core/users/$)|(?:^/api/v3/core/users/account_lockdown/$)|(?:^/api/v3/core/users/export/$)|(?:^/api/v3/core/users/impersonate_end/$)|(?:^)
SAFE_METHODS = frozenset({'HEAD', 'TRACE', 'GET', 'OPTIONS'})
class EnterpriseMiddleware:
 67class EnterpriseMiddleware:
 68    """Enterprise middleware"""
 69
 70    get_response: Callable[[HttpRequest], HttpResponse]
 71    logger: BoundLogger
 72
 73    def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]):
 74        self.get_response = get_response
 75        self.logger = get_logger().bind()
 76
 77    def __call__(self, request: HttpRequest) -> HttpResponse:
 78        if not self.is_request_allowed(request):
 79            self.logger.warning("Refusing request due to expired/invalid license")
 80            return JsonResponse(
 81                {
 82                    "detail": "Request denied due to expired/invalid license.",
 83                    "code": "denied_license",
 84                },
 85                status=400,
 86            )
 87        return self.get_response(request)
 88
 89    def is_request_allowed(self, request: HttpRequest) -> bool:
 90        """Check if a specific request is allowed"""
 91        if self.is_request_always_allowed(request):
 92            return True
 93        cached_status = LicenseKey.cached_summary()
 94        if not cached_status:
 95            return True
 96        if cached_status.status == LicenseUsageStatus.READ_ONLY:
 97            return False
 98        return True
 99
100    def is_request_always_allowed(self, request: HttpRequest):
101        """Check if a request is always allowed"""
102        # Always allow "safe" methods
103        if request.method in SAFE_METHODS:
104            return True
105        # Only apply these restrictions to the API
106        if not API_PATHS.match(request.path_info):
107            return True
108        return ALLOWED_PATHS.match(request.path_info) is not None

Enterprise middleware

EnterpriseMiddleware( get_response: Callable[[django.http.request.HttpRequest], django.http.response.HttpResponse])
73    def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]):
74        self.get_response = get_response
75        self.logger = get_logger().bind()
get_response: Callable[[django.http.request.HttpRequest], django.http.response.HttpResponse]
logger: structlog.stdlib.BoundLogger
def is_request_allowed(self, request: django.http.request.HttpRequest) -> bool:
89    def is_request_allowed(self, request: HttpRequest) -> bool:
90        """Check if a specific request is allowed"""
91        if self.is_request_always_allowed(request):
92            return True
93        cached_status = LicenseKey.cached_summary()
94        if not cached_status:
95            return True
96        if cached_status.status == LicenseUsageStatus.READ_ONLY:
97            return False
98        return True

Check if a specific request is allowed

def is_request_always_allowed(self, request: django.http.request.HttpRequest):
100    def is_request_always_allowed(self, request: HttpRequest):
101        """Check if a request is always allowed"""
102        # Always allow "safe" methods
103        if request.method in SAFE_METHODS:
104            return True
105        # Only apply these restrictions to the API
106        if not API_PATHS.match(request.path_info):
107            return True
108        return ALLOWED_PATHS.match(request.path_info) is not None

Check if a request is always allowed