authentik.root.middleware

Dynamically set SameSite depending if the upstream connection is TLS or not

  1"""Dynamically set SameSite depending if the upstream connection is TLS or not"""
  2
  3from collections.abc import Callable
  4from ipaddress import ip_address
  5from time import perf_counter, time
  6from typing import Any
  7
  8from channels.exceptions import DenyConnection
  9from django.conf import settings
 10from django.contrib.sessions.backends.base import UpdateError
 11from django.contrib.sessions.exceptions import SessionInterrupted
 12from django.contrib.sessions.middleware import SessionMiddleware as UpstreamSessionMiddleware
 13from django.http.request import HttpRequest
 14from django.http.response import HttpResponse, HttpResponseServerError
 15from django.middleware.csrf import CSRF_SESSION_KEY
 16from django.middleware.csrf import CsrfViewMiddleware as UpstreamCsrfViewMiddleware
 17from django.utils.cache import patch_vary_headers
 18from django.utils.http import http_date
 19from jwt import PyJWTError, decode, encode
 20from structlog.stdlib import get_logger
 21
 22from authentik.core import user_switching
 23from authentik.core.models import Token, TokenIntents, User, UserTypes
 24from authentik.lib.config import CONFIG
 25from authentik.lib.tracing import active_tracer
 26from authentik.lib.utils.crypto import get_cookie_signing_key
 27from authentik.lib.utils.errors import exception_to_dict
 28
 29LOGGER = get_logger("authentik.asgi")
 30ACR_AUTHENTIK_SESSION = "goauthentik.io/core/default"
 31SIGNING_HASH = get_cookie_signing_key()
 32
 33
 34class LivenessMiddleware:
 35    """Short-circuit liveness probe requests to bypass database and tenant middleware."""
 36
 37    get_response: Callable[[HttpRequest], HttpResponse]
 38
 39    def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]):
 40        self.get_response = get_response
 41
 42    def __call__(self, request: HttpRequest) -> HttpResponse:
 43        if request.path == "/-/health/live/":
 44            return HttpResponse(status=200)
 45        return self.get_response(request)
 46
 47
 48class SessionMiddleware(UpstreamSessionMiddleware):
 49    """Dynamically set SameSite depending if the upstream connection is TLS or not"""
 50
 51    @staticmethod
 52    def is_secure(request: HttpRequest) -> bool:
 53        """Check if request is TLS'd or localhost"""
 54        if request.is_secure():
 55            return True
 56        host, _, _ = request.get_host().partition(":")
 57        if host == "localhost" and settings.DEBUG:
 58            # Since go does not consider localhost with http a secure origin
 59            # we can't set the secure flag.
 60            user_agent = request.META.get("HTTP_USER_AGENT", "")
 61            if user_agent.startswith("goauthentik.io/outpost/") or (
 62                "safari" in user_agent.lower() and "chrome" not in user_agent.lower()
 63            ):
 64                return False
 65            return True
 66        return False
 67
 68    @staticmethod
 69    def decode_session_key(key: str | None) -> str | None:
 70        """Decode raw session cookie, and parse JWT"""
 71        # We need to support the standard django format of just a session key
 72        # for testing setups, where the session is directly set
 73        session_key = key if settings.TEST else None
 74        try:
 75            session_payload = decode(key, SIGNING_HASH, algorithms=["HS256"])
 76            session_key = session_payload["sid"]
 77        except KeyError, PyJWTError:
 78            pass
 79        return session_key
 80
 81    @staticmethod
 82    def encode_session(session_key: str, user: User):
 83        payload = {
 84            "sid": session_key,
 85            "iss": "authentik",
 86            "sub": "anonymous",
 87            "authenticated": user.is_authenticated,
 88            "acr": ACR_AUTHENTIK_SESSION,
 89        }
 90        if user.is_authenticated:
 91            payload["sub"] = user.uid
 92        value = encode(payload=payload, key=SIGNING_HASH)
 93        if settings.TEST:
 94            value = session_key
 95        return value
 96
 97    def process_request(self, request: HttpRequest):
 98        raw_session = request.COOKIES.get(settings.SESSION_COOKIE_NAME)
 99        session_key = SessionMiddleware.decode_session_key(raw_session)
100        request.user_switching_token = user_switching.decode_cookie(
101            request.COOKIES.get(settings.USER_SWITCHING_COOKIE_NAME)
102        )
103        request.user_switching_token_needs_update = False
104        request.session = self.SessionStore(
105            session_key,
106            last_ip=ClientIPMiddleware.get_client_ip(request),
107            last_user_agent=request.META.get("HTTP_USER_AGENT", ""),
108        )
109
110    def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse:
111        """
112        If request.session was modified, or if the configuration is to save the
113        session every time, save the changes and set a session cookie or delete
114        the session cookie if the session has been emptied.
115        """
116        try:
117            user_switching.reconcile_session(request)
118            accessed = request.session.accessed
119            modified = request.session.modified or settings.SESSION_SAVE_EVERY_REQUEST
120            expiry_extended = request.session.expiry_extended
121            empty = request.session.is_empty()
122        except AttributeError:
123            return response
124        # Set SameSite based on whether or not the request is secure
125        secure = SessionMiddleware.is_secure(request)
126        same_site = "None" if secure else "Lax"
127        # First check if we need to delete this cookie.
128        # The session should be deleted only if the session is entirely empty.
129        if settings.SESSION_COOKIE_NAME in request.COOKIES and empty:
130            response.delete_cookie(
131                settings.SESSION_COOKIE_NAME,
132                path=settings.SESSION_COOKIE_PATH,
133                domain=settings.SESSION_COOKIE_DOMAIN,
134                samesite=same_site,
135            )
136            patch_vary_headers(response, ("Cookie",))
137        else:
138            if accessed:
139                patch_vary_headers(response, ("Cookie",))
140            if (modified or expiry_extended) and not empty:
141                if request.session.get_expire_at_browser_close():
142                    max_age = None
143                    expires = None
144                else:
145                    max_age = request.session.get_expiry_age()
146                    expires_time = time() + max_age
147                    expires = http_date(expires_time)
148                # Save the session data and refresh the client cookie.
149                # Skip session save for 500 responses, refs #3881.
150                if response.status_code != HttpResponseServerError.status_code:
151                    try:
152                        if modified:
153                            request.session.save()
154                        else:
155                            request.session.save_expiry()
156                    except UpdateError:
157                        raise SessionInterrupted(
158                            "The request's session was deleted before the "
159                            "request completed. The user may have logged "
160                            "out in a concurrent request, for example."
161                        ) from None
162                    response.set_cookie(
163                        settings.SESSION_COOKIE_NAME,
164                        SessionMiddleware.encode_session(request.session.session_key, request.user),
165                        max_age=max_age,
166                        expires=expires,
167                        domain=settings.SESSION_COOKIE_DOMAIN,
168                        path=settings.SESSION_COOKIE_PATH,
169                        secure=secure,
170                        httponly=settings.SESSION_COOKIE_HTTPONLY or None,
171                        samesite=same_site,
172                    )
173        # Keep the user-switching cookie longer-lived than the sessions it groups.
174        # It is intentionally not deleted with the session cookie.
175        if request.user_switching_token and request.user_switching_token_needs_update:
176            response.set_cookie(
177                settings.USER_SWITCHING_COOKIE_NAME,
178                user_switching.encode_cookie(request.user_switching_token),
179                max_age=settings.USER_SWITCHING_COOKIE_AGE,
180                domain=settings.SESSION_COOKIE_DOMAIN,
181                path=settings.SESSION_COOKIE_PATH,
182                secure=secure,
183                samesite=same_site,
184            )
185        return response
186
187
188class CsrfViewMiddleware(UpstreamCsrfViewMiddleware):
189    """Dynamically set secure depending if the upstream connection is TLS or not"""
190
191    def _set_csrf_cookie(self, request: HttpRequest, response: HttpResponse):
192        if settings.CSRF_USE_SESSIONS:
193            if request.session.get(CSRF_SESSION_KEY) != request.META["CSRF_COOKIE"]:
194                request.session[CSRF_SESSION_KEY] = request.META["CSRF_COOKIE"]
195        else:
196            secure = SessionMiddleware.is_secure(request)
197            response.set_cookie(
198                settings.CSRF_COOKIE_NAME,
199                request.META["CSRF_COOKIE"],
200                max_age=settings.CSRF_COOKIE_AGE,
201                domain=settings.CSRF_COOKIE_DOMAIN,
202                path=settings.CSRF_COOKIE_PATH,
203                secure=secure,
204                httponly=settings.CSRF_COOKIE_HTTPONLY,
205                samesite=settings.CSRF_COOKIE_SAMESITE,
206            )
207            # Set the Vary header since content varies with the CSRF cookie.
208            patch_vary_headers(response, ("Cookie",))
209
210
211class ClientIPMiddleware:
212    """Set a "known-good" client IP on the request, by default based off of x-forwarded-for
213    which is set by the go proxy, but also allowing the remote IP to be overridden by an outpost
214    for protocols like LDAP"""
215
216    get_response: Callable[[HttpRequest], HttpResponse]
217    outpost_remote_ip_header = "HTTP_X_AUTHENTIK_REMOTE_IP"
218    outpost_token_header = "HTTP_X_AUTHENTIK_OUTPOST_TOKEN"  # nosec
219    default_ip = "255.255.255.255"
220
221    request_attr_client_ip = "client_ip"
222    request_attr_outpost_user = "outpost_user"
223
224    def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]):
225        self.get_response = get_response
226        self.logger = get_logger().bind()
227
228    def _get_client_ip_from_meta(self, meta: dict[str, Any]) -> str:
229        """Attempt to get the client's IP by checking common HTTP Headers.
230        Returns none if no IP Could be found
231
232        No additional validation is done here as requests are expected to only arrive here
233        via the go proxy, which deals with validating these headers for us"""
234        headers = (
235            "HTTP_X_FORWARDED_FOR",
236            "REMOTE_ADDR",
237        )
238        try:
239            for _header in headers:
240                if _header in meta:
241                    ips: list[str] = meta.get(_header).split(",")
242                    # Ensure the IP parses as a valid IP
243                    return str(ip_address(ips[0].strip()))
244            return self.default_ip
245        except ValueError as exc:
246            self.logger.debug("Invalid remote IP", exc=exc)
247            return self.default_ip
248
249    # FIXME: this should probably not be in `root` but rather in a middleware in `outposts`
250    # but for now it's fine
251    def _get_outpost_override_ip(self, request: HttpRequest) -> str | None:
252        """Get the actual remote IP when set by an outpost. Only
253        allowed when the request is authenticated, by an outpost internal service account"""
254        if (
255            self.outpost_remote_ip_header not in request.META
256            or self.outpost_token_header not in request.META
257        ):
258            return None
259        delegated_ip = request.META[self.outpost_remote_ip_header]
260        token = (
261            Token.objects.filter(
262                key=request.META.get(self.outpost_token_header), intent=TokenIntents.INTENT_API
263            )
264            .select_related("user")
265            .first()
266        )
267        if not token:
268            LOGGER.warning("Attempted remote-ip override without token", delegated_ip=delegated_ip)
269            return None
270        user: User = token.user
271        if user.type != UserTypes.INTERNAL_SERVICE_ACCOUNT:
272            LOGGER.warning(
273                "Remote-IP override: user doesn't have permission",
274                user=user,
275                delegated_ip=delegated_ip,
276            )
277            return None
278        # Update the current span to include the correct client IP
279        active_tracer().set_tag("client.address", delegated_ip)
280        # Set the outpost service account on the request
281        setattr(request, self.request_attr_outpost_user, user)
282        try:
283            return str(ip_address(delegated_ip))
284        except ValueError as exc:
285            self.logger.debug("Invalid remote IP from Outpost", exc=exc)
286            return None
287
288    def _get_client_ip(self, request: HttpRequest | None) -> str:
289        """Attempt to get the client's IP by checking common HTTP Headers.
290        Returns none if no IP Could be found"""
291        if not request:
292            return self.default_ip
293        override = self._get_outpost_override_ip(request)
294        if override:
295            return override
296        return self._get_client_ip_from_meta(request.META)
297
298    @staticmethod
299    def get_outpost_user(request: HttpRequest) -> User | None:
300        """Get outpost user that authenticated this request"""
301        return getattr(request, ClientIPMiddleware.request_attr_outpost_user, None)
302
303    @staticmethod
304    def get_client_ip(request: HttpRequest) -> str:
305        """Get correct client IP, including any overrides from outposts that
306        have the permission to do so"""
307        if request and not hasattr(request, ClientIPMiddleware.request_attr_client_ip):
308            ClientIPMiddleware(lambda request: request).set_ip(request)
309        return getattr(
310            request, ClientIPMiddleware.request_attr_client_ip, ClientIPMiddleware.default_ip
311        )
312
313    def set_ip(self, request: HttpRequest):
314        """Set the IP"""
315        setattr(request, self.request_attr_client_ip, self._get_client_ip(request))
316
317    def __call__(self, request: HttpRequest) -> HttpResponse:
318        self.set_ip(request)
319        return self.get_response(request)
320
321
322class ChannelsLoggingMiddleware:
323    """Logging middleware for channels"""
324
325    def __init__(self, inner):
326        self.inner = inner
327
328    async def __call__(self, scope, receive, send):
329        self.log(scope)
330        try:
331            return await self.inner(scope, receive, send)
332        except DenyConnection:
333            return await send({"type": "websocket.close"})
334        except Exception as exc:
335            if settings.DEBUG or settings.TEST:
336                raise exc
337            LOGGER.warning("Exception in ASGI application", exc=exception_to_dict(exc))
338            return await send({"type": "websocket.close"})
339
340    def log(self, scope: dict, **kwargs):
341        """Log request"""
342        headers = dict(scope.get("headers", {}))
343        # Header values are raw bytes and aren't guaranteed to be UTF-8
344        LOGGER.info(
345            scope["path"],
346            scheme="ws",
347            remote=headers.get(b"x-forwarded-for", b"").decode(errors="backslashreplace"),
348            user_agent=headers.get(b"user-agent", b"").decode(errors="backslashreplace"),
349            **kwargs,
350        )
351
352
353class LoggingMiddleware:
354    """Logger middleware"""
355
356    get_response: Callable[[HttpRequest], HttpResponse]
357
358    def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]):
359        self.get_response = get_response
360        headers = CONFIG.get("log.http_headers", [])
361        if isinstance(headers, str):
362            headers = headers.split(",")
363        self.headers_to_log = headers
364
365    def __call__(self, request: HttpRequest) -> HttpResponse:
366        start = perf_counter()
367        response = self.get_response(request)
368        status_code = response.status_code
369        kwargs = {
370            "request_id": getattr(request, "request_id", None),
371        }
372        kwargs.update(getattr(response, "ak_context", {}))
373        self.log(request, status_code, int((perf_counter() - start) * 1000), **kwargs)
374        return response
375
376    def log(self, request: HttpRequest, status_code: int, runtime: int, **kwargs):
377        """Log request"""
378        # Those are logged by the server above
379        if request.path in ("/-/metrics/", "/-/health/ready/"):
380            return
381        for header in self.headers_to_log:
382            header_value = request.headers.get(header)
383            if not header_value:
384                continue
385            kwargs[header.lower().replace("-", "_")] = header_value
386        LOGGER.info(
387            request.get_full_path(),
388            remote=ClientIPMiddleware.get_client_ip(request),
389            method=request.method,
390            scheme=request.scheme,
391            status=status_code,
392            runtime=runtime,
393            **kwargs,
394        )
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=('authentik.asgi',))>
ACR_AUTHENTIK_SESSION = 'goauthentik.io/core/default'
SIGNING_HASH = '6753e8efcd13b07f5d24a07f7db28ce2ad6ddd09dee3a4e9b72717f75d5cb81b9ff8402428f1bbf5d418f6a4586f3af21eeaa81e47fc223e18aa540ced2156b4'
class LivenessMiddleware:
35class LivenessMiddleware:
36    """Short-circuit liveness probe requests to bypass database and tenant middleware."""
37
38    get_response: Callable[[HttpRequest], HttpResponse]
39
40    def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]):
41        self.get_response = get_response
42
43    def __call__(self, request: HttpRequest) -> HttpResponse:
44        if request.path == "/-/health/live/":
45            return HttpResponse(status=200)
46        return self.get_response(request)

Short-circuit liveness probe requests to bypass database and tenant middleware.

LivenessMiddleware( get_response: Callable[[django.http.request.HttpRequest], django.http.response.HttpResponse])
40    def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]):
41        self.get_response = get_response
get_response: Callable[[django.http.request.HttpRequest], django.http.response.HttpResponse]
class SessionMiddleware(django.contrib.sessions.middleware.SessionMiddleware):
 49class SessionMiddleware(UpstreamSessionMiddleware):
 50    """Dynamically set SameSite depending if the upstream connection is TLS or not"""
 51
 52    @staticmethod
 53    def is_secure(request: HttpRequest) -> bool:
 54        """Check if request is TLS'd or localhost"""
 55        if request.is_secure():
 56            return True
 57        host, _, _ = request.get_host().partition(":")
 58        if host == "localhost" and settings.DEBUG:
 59            # Since go does not consider localhost with http a secure origin
 60            # we can't set the secure flag.
 61            user_agent = request.META.get("HTTP_USER_AGENT", "")
 62            if user_agent.startswith("goauthentik.io/outpost/") or (
 63                "safari" in user_agent.lower() and "chrome" not in user_agent.lower()
 64            ):
 65                return False
 66            return True
 67        return False
 68
 69    @staticmethod
 70    def decode_session_key(key: str | None) -> str | None:
 71        """Decode raw session cookie, and parse JWT"""
 72        # We need to support the standard django format of just a session key
 73        # for testing setups, where the session is directly set
 74        session_key = key if settings.TEST else None
 75        try:
 76            session_payload = decode(key, SIGNING_HASH, algorithms=["HS256"])
 77            session_key = session_payload["sid"]
 78        except KeyError, PyJWTError:
 79            pass
 80        return session_key
 81
 82    @staticmethod
 83    def encode_session(session_key: str, user: User):
 84        payload = {
 85            "sid": session_key,
 86            "iss": "authentik",
 87            "sub": "anonymous",
 88            "authenticated": user.is_authenticated,
 89            "acr": ACR_AUTHENTIK_SESSION,
 90        }
 91        if user.is_authenticated:
 92            payload["sub"] = user.uid
 93        value = encode(payload=payload, key=SIGNING_HASH)
 94        if settings.TEST:
 95            value = session_key
 96        return value
 97
 98    def process_request(self, request: HttpRequest):
 99        raw_session = request.COOKIES.get(settings.SESSION_COOKIE_NAME)
100        session_key = SessionMiddleware.decode_session_key(raw_session)
101        request.user_switching_token = user_switching.decode_cookie(
102            request.COOKIES.get(settings.USER_SWITCHING_COOKIE_NAME)
103        )
104        request.user_switching_token_needs_update = False
105        request.session = self.SessionStore(
106            session_key,
107            last_ip=ClientIPMiddleware.get_client_ip(request),
108            last_user_agent=request.META.get("HTTP_USER_AGENT", ""),
109        )
110
111    def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse:
112        """
113        If request.session was modified, or if the configuration is to save the
114        session every time, save the changes and set a session cookie or delete
115        the session cookie if the session has been emptied.
116        """
117        try:
118            user_switching.reconcile_session(request)
119            accessed = request.session.accessed
120            modified = request.session.modified or settings.SESSION_SAVE_EVERY_REQUEST
121            expiry_extended = request.session.expiry_extended
122            empty = request.session.is_empty()
123        except AttributeError:
124            return response
125        # Set SameSite based on whether or not the request is secure
126        secure = SessionMiddleware.is_secure(request)
127        same_site = "None" if secure else "Lax"
128        # First check if we need to delete this cookie.
129        # The session should be deleted only if the session is entirely empty.
130        if settings.SESSION_COOKIE_NAME in request.COOKIES and empty:
131            response.delete_cookie(
132                settings.SESSION_COOKIE_NAME,
133                path=settings.SESSION_COOKIE_PATH,
134                domain=settings.SESSION_COOKIE_DOMAIN,
135                samesite=same_site,
136            )
137            patch_vary_headers(response, ("Cookie",))
138        else:
139            if accessed:
140                patch_vary_headers(response, ("Cookie",))
141            if (modified or expiry_extended) and not empty:
142                if request.session.get_expire_at_browser_close():
143                    max_age = None
144                    expires = None
145                else:
146                    max_age = request.session.get_expiry_age()
147                    expires_time = time() + max_age
148                    expires = http_date(expires_time)
149                # Save the session data and refresh the client cookie.
150                # Skip session save for 500 responses, refs #3881.
151                if response.status_code != HttpResponseServerError.status_code:
152                    try:
153                        if modified:
154                            request.session.save()
155                        else:
156                            request.session.save_expiry()
157                    except UpdateError:
158                        raise SessionInterrupted(
159                            "The request's session was deleted before the "
160                            "request completed. The user may have logged "
161                            "out in a concurrent request, for example."
162                        ) from None
163                    response.set_cookie(
164                        settings.SESSION_COOKIE_NAME,
165                        SessionMiddleware.encode_session(request.session.session_key, request.user),
166                        max_age=max_age,
167                        expires=expires,
168                        domain=settings.SESSION_COOKIE_DOMAIN,
169                        path=settings.SESSION_COOKIE_PATH,
170                        secure=secure,
171                        httponly=settings.SESSION_COOKIE_HTTPONLY or None,
172                        samesite=same_site,
173                    )
174        # Keep the user-switching cookie longer-lived than the sessions it groups.
175        # It is intentionally not deleted with the session cookie.
176        if request.user_switching_token and request.user_switching_token_needs_update:
177            response.set_cookie(
178                settings.USER_SWITCHING_COOKIE_NAME,
179                user_switching.encode_cookie(request.user_switching_token),
180                max_age=settings.USER_SWITCHING_COOKIE_AGE,
181                domain=settings.SESSION_COOKIE_DOMAIN,
182                path=settings.SESSION_COOKIE_PATH,
183                secure=secure,
184                samesite=same_site,
185            )
186        return response

Dynamically set SameSite depending if the upstream connection is TLS or not

@staticmethod
def is_secure(request: django.http.request.HttpRequest) -> bool:
52    @staticmethod
53    def is_secure(request: HttpRequest) -> bool:
54        """Check if request is TLS'd or localhost"""
55        if request.is_secure():
56            return True
57        host, _, _ = request.get_host().partition(":")
58        if host == "localhost" and settings.DEBUG:
59            # Since go does not consider localhost with http a secure origin
60            # we can't set the secure flag.
61            user_agent = request.META.get("HTTP_USER_AGENT", "")
62            if user_agent.startswith("goauthentik.io/outpost/") or (
63                "safari" in user_agent.lower() and "chrome" not in user_agent.lower()
64            ):
65                return False
66            return True
67        return False

Check if request is TLS'd or localhost

@staticmethod
def decode_session_key(key: str | None) -> str | None:
69    @staticmethod
70    def decode_session_key(key: str | None) -> str | None:
71        """Decode raw session cookie, and parse JWT"""
72        # We need to support the standard django format of just a session key
73        # for testing setups, where the session is directly set
74        session_key = key if settings.TEST else None
75        try:
76            session_payload = decode(key, SIGNING_HASH, algorithms=["HS256"])
77            session_key = session_payload["sid"]
78        except KeyError, PyJWTError:
79            pass
80        return session_key

Decode raw session cookie, and parse JWT

@staticmethod
def encode_session(session_key: str, user: authentik.core.models.User):
82    @staticmethod
83    def encode_session(session_key: str, user: User):
84        payload = {
85            "sid": session_key,
86            "iss": "authentik",
87            "sub": "anonymous",
88            "authenticated": user.is_authenticated,
89            "acr": ACR_AUTHENTIK_SESSION,
90        }
91        if user.is_authenticated:
92            payload["sub"] = user.uid
93        value = encode(payload=payload, key=SIGNING_HASH)
94        if settings.TEST:
95            value = session_key
96        return value
def process_request(self, request: django.http.request.HttpRequest):
 98    def process_request(self, request: HttpRequest):
 99        raw_session = request.COOKIES.get(settings.SESSION_COOKIE_NAME)
100        session_key = SessionMiddleware.decode_session_key(raw_session)
101        request.user_switching_token = user_switching.decode_cookie(
102            request.COOKIES.get(settings.USER_SWITCHING_COOKIE_NAME)
103        )
104        request.user_switching_token_needs_update = False
105        request.session = self.SessionStore(
106            session_key,
107            last_ip=ClientIPMiddleware.get_client_ip(request),
108            last_user_agent=request.META.get("HTTP_USER_AGENT", ""),
109        )
def process_response( self, request: django.http.request.HttpRequest, response: django.http.response.HttpResponse) -> django.http.response.HttpResponse:
111    def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse:
112        """
113        If request.session was modified, or if the configuration is to save the
114        session every time, save the changes and set a session cookie or delete
115        the session cookie if the session has been emptied.
116        """
117        try:
118            user_switching.reconcile_session(request)
119            accessed = request.session.accessed
120            modified = request.session.modified or settings.SESSION_SAVE_EVERY_REQUEST
121            expiry_extended = request.session.expiry_extended
122            empty = request.session.is_empty()
123        except AttributeError:
124            return response
125        # Set SameSite based on whether or not the request is secure
126        secure = SessionMiddleware.is_secure(request)
127        same_site = "None" if secure else "Lax"
128        # First check if we need to delete this cookie.
129        # The session should be deleted only if the session is entirely empty.
130        if settings.SESSION_COOKIE_NAME in request.COOKIES and empty:
131            response.delete_cookie(
132                settings.SESSION_COOKIE_NAME,
133                path=settings.SESSION_COOKIE_PATH,
134                domain=settings.SESSION_COOKIE_DOMAIN,
135                samesite=same_site,
136            )
137            patch_vary_headers(response, ("Cookie",))
138        else:
139            if accessed:
140                patch_vary_headers(response, ("Cookie",))
141            if (modified or expiry_extended) and not empty:
142                if request.session.get_expire_at_browser_close():
143                    max_age = None
144                    expires = None
145                else:
146                    max_age = request.session.get_expiry_age()
147                    expires_time = time() + max_age
148                    expires = http_date(expires_time)
149                # Save the session data and refresh the client cookie.
150                # Skip session save for 500 responses, refs #3881.
151                if response.status_code != HttpResponseServerError.status_code:
152                    try:
153                        if modified:
154                            request.session.save()
155                        else:
156                            request.session.save_expiry()
157                    except UpdateError:
158                        raise SessionInterrupted(
159                            "The request's session was deleted before the "
160                            "request completed. The user may have logged "
161                            "out in a concurrent request, for example."
162                        ) from None
163                    response.set_cookie(
164                        settings.SESSION_COOKIE_NAME,
165                        SessionMiddleware.encode_session(request.session.session_key, request.user),
166                        max_age=max_age,
167                        expires=expires,
168                        domain=settings.SESSION_COOKIE_DOMAIN,
169                        path=settings.SESSION_COOKIE_PATH,
170                        secure=secure,
171                        httponly=settings.SESSION_COOKIE_HTTPONLY or None,
172                        samesite=same_site,
173                    )
174        # Keep the user-switching cookie longer-lived than the sessions it groups.
175        # It is intentionally not deleted with the session cookie.
176        if request.user_switching_token and request.user_switching_token_needs_update:
177            response.set_cookie(
178                settings.USER_SWITCHING_COOKIE_NAME,
179                user_switching.encode_cookie(request.user_switching_token),
180                max_age=settings.USER_SWITCHING_COOKIE_AGE,
181                domain=settings.SESSION_COOKIE_DOMAIN,
182                path=settings.SESSION_COOKIE_PATH,
183                secure=secure,
184                samesite=same_site,
185            )
186        return response

If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie or delete the session cookie if the session has been emptied.

class CsrfViewMiddleware(django.middleware.csrf.CsrfViewMiddleware):
189class CsrfViewMiddleware(UpstreamCsrfViewMiddleware):
190    """Dynamically set secure depending if the upstream connection is TLS or not"""
191
192    def _set_csrf_cookie(self, request: HttpRequest, response: HttpResponse):
193        if settings.CSRF_USE_SESSIONS:
194            if request.session.get(CSRF_SESSION_KEY) != request.META["CSRF_COOKIE"]:
195                request.session[CSRF_SESSION_KEY] = request.META["CSRF_COOKIE"]
196        else:
197            secure = SessionMiddleware.is_secure(request)
198            response.set_cookie(
199                settings.CSRF_COOKIE_NAME,
200                request.META["CSRF_COOKIE"],
201                max_age=settings.CSRF_COOKIE_AGE,
202                domain=settings.CSRF_COOKIE_DOMAIN,
203                path=settings.CSRF_COOKIE_PATH,
204                secure=secure,
205                httponly=settings.CSRF_COOKIE_HTTPONLY,
206                samesite=settings.CSRF_COOKIE_SAMESITE,
207            )
208            # Set the Vary header since content varies with the CSRF cookie.
209            patch_vary_headers(response, ("Cookie",))

Dynamically set secure depending if the upstream connection is TLS or not

class ClientIPMiddleware:
212class ClientIPMiddleware:
213    """Set a "known-good" client IP on the request, by default based off of x-forwarded-for
214    which is set by the go proxy, but also allowing the remote IP to be overridden by an outpost
215    for protocols like LDAP"""
216
217    get_response: Callable[[HttpRequest], HttpResponse]
218    outpost_remote_ip_header = "HTTP_X_AUTHENTIK_REMOTE_IP"
219    outpost_token_header = "HTTP_X_AUTHENTIK_OUTPOST_TOKEN"  # nosec
220    default_ip = "255.255.255.255"
221
222    request_attr_client_ip = "client_ip"
223    request_attr_outpost_user = "outpost_user"
224
225    def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]):
226        self.get_response = get_response
227        self.logger = get_logger().bind()
228
229    def _get_client_ip_from_meta(self, meta: dict[str, Any]) -> str:
230        """Attempt to get the client's IP by checking common HTTP Headers.
231        Returns none if no IP Could be found
232
233        No additional validation is done here as requests are expected to only arrive here
234        via the go proxy, which deals with validating these headers for us"""
235        headers = (
236            "HTTP_X_FORWARDED_FOR",
237            "REMOTE_ADDR",
238        )
239        try:
240            for _header in headers:
241                if _header in meta:
242                    ips: list[str] = meta.get(_header).split(",")
243                    # Ensure the IP parses as a valid IP
244                    return str(ip_address(ips[0].strip()))
245            return self.default_ip
246        except ValueError as exc:
247            self.logger.debug("Invalid remote IP", exc=exc)
248            return self.default_ip
249
250    # FIXME: this should probably not be in `root` but rather in a middleware in `outposts`
251    # but for now it's fine
252    def _get_outpost_override_ip(self, request: HttpRequest) -> str | None:
253        """Get the actual remote IP when set by an outpost. Only
254        allowed when the request is authenticated, by an outpost internal service account"""
255        if (
256            self.outpost_remote_ip_header not in request.META
257            or self.outpost_token_header not in request.META
258        ):
259            return None
260        delegated_ip = request.META[self.outpost_remote_ip_header]
261        token = (
262            Token.objects.filter(
263                key=request.META.get(self.outpost_token_header), intent=TokenIntents.INTENT_API
264            )
265            .select_related("user")
266            .first()
267        )
268        if not token:
269            LOGGER.warning("Attempted remote-ip override without token", delegated_ip=delegated_ip)
270            return None
271        user: User = token.user
272        if user.type != UserTypes.INTERNAL_SERVICE_ACCOUNT:
273            LOGGER.warning(
274                "Remote-IP override: user doesn't have permission",
275                user=user,
276                delegated_ip=delegated_ip,
277            )
278            return None
279        # Update the current span to include the correct client IP
280        active_tracer().set_tag("client.address", delegated_ip)
281        # Set the outpost service account on the request
282        setattr(request, self.request_attr_outpost_user, user)
283        try:
284            return str(ip_address(delegated_ip))
285        except ValueError as exc:
286            self.logger.debug("Invalid remote IP from Outpost", exc=exc)
287            return None
288
289    def _get_client_ip(self, request: HttpRequest | None) -> str:
290        """Attempt to get the client's IP by checking common HTTP Headers.
291        Returns none if no IP Could be found"""
292        if not request:
293            return self.default_ip
294        override = self._get_outpost_override_ip(request)
295        if override:
296            return override
297        return self._get_client_ip_from_meta(request.META)
298
299    @staticmethod
300    def get_outpost_user(request: HttpRequest) -> User | None:
301        """Get outpost user that authenticated this request"""
302        return getattr(request, ClientIPMiddleware.request_attr_outpost_user, None)
303
304    @staticmethod
305    def get_client_ip(request: HttpRequest) -> str:
306        """Get correct client IP, including any overrides from outposts that
307        have the permission to do so"""
308        if request and not hasattr(request, ClientIPMiddleware.request_attr_client_ip):
309            ClientIPMiddleware(lambda request: request).set_ip(request)
310        return getattr(
311            request, ClientIPMiddleware.request_attr_client_ip, ClientIPMiddleware.default_ip
312        )
313
314    def set_ip(self, request: HttpRequest):
315        """Set the IP"""
316        setattr(request, self.request_attr_client_ip, self._get_client_ip(request))
317
318    def __call__(self, request: HttpRequest) -> HttpResponse:
319        self.set_ip(request)
320        return self.get_response(request)

Set a "known-good" client IP on the request, by default based off of x-forwarded-for which is set by the go proxy, but also allowing the remote IP to be overridden by an outpost for protocols like LDAP

ClientIPMiddleware( get_response: Callable[[django.http.request.HttpRequest], django.http.response.HttpResponse])
225    def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]):
226        self.get_response = get_response
227        self.logger = get_logger().bind()
get_response: Callable[[django.http.request.HttpRequest], django.http.response.HttpResponse]
outpost_remote_ip_header = 'HTTP_X_AUTHENTIK_REMOTE_IP'
outpost_token_header = 'HTTP_X_AUTHENTIK_OUTPOST_TOKEN'
default_ip = '255.255.255.255'
request_attr_client_ip = 'client_ip'
request_attr_outpost_user = 'outpost_user'
logger
@staticmethod
def get_outpost_user( request: django.http.request.HttpRequest) -> authentik.core.models.User | None:
299    @staticmethod
300    def get_outpost_user(request: HttpRequest) -> User | None:
301        """Get outpost user that authenticated this request"""
302        return getattr(request, ClientIPMiddleware.request_attr_outpost_user, None)

Get outpost user that authenticated this request

@staticmethod
def get_client_ip(request: django.http.request.HttpRequest) -> str:
304    @staticmethod
305    def get_client_ip(request: HttpRequest) -> str:
306        """Get correct client IP, including any overrides from outposts that
307        have the permission to do so"""
308        if request and not hasattr(request, ClientIPMiddleware.request_attr_client_ip):
309            ClientIPMiddleware(lambda request: request).set_ip(request)
310        return getattr(
311            request, ClientIPMiddleware.request_attr_client_ip, ClientIPMiddleware.default_ip
312        )

Get correct client IP, including any overrides from outposts that have the permission to do so

def set_ip(self, request: django.http.request.HttpRequest):
314    def set_ip(self, request: HttpRequest):
315        """Set the IP"""
316        setattr(request, self.request_attr_client_ip, self._get_client_ip(request))

Set the IP

class ChannelsLoggingMiddleware:
323class ChannelsLoggingMiddleware:
324    """Logging middleware for channels"""
325
326    def __init__(self, inner):
327        self.inner = inner
328
329    async def __call__(self, scope, receive, send):
330        self.log(scope)
331        try:
332            return await self.inner(scope, receive, send)
333        except DenyConnection:
334            return await send({"type": "websocket.close"})
335        except Exception as exc:
336            if settings.DEBUG or settings.TEST:
337                raise exc
338            LOGGER.warning("Exception in ASGI application", exc=exception_to_dict(exc))
339            return await send({"type": "websocket.close"})
340
341    def log(self, scope: dict, **kwargs):
342        """Log request"""
343        headers = dict(scope.get("headers", {}))
344        # Header values are raw bytes and aren't guaranteed to be UTF-8
345        LOGGER.info(
346            scope["path"],
347            scheme="ws",
348            remote=headers.get(b"x-forwarded-for", b"").decode(errors="backslashreplace"),
349            user_agent=headers.get(b"user-agent", b"").decode(errors="backslashreplace"),
350            **kwargs,
351        )

Logging middleware for channels

ChannelsLoggingMiddleware(inner)
326    def __init__(self, inner):
327        self.inner = inner
inner
def log(self, scope: dict, **kwargs):
341    def log(self, scope: dict, **kwargs):
342        """Log request"""
343        headers = dict(scope.get("headers", {}))
344        # Header values are raw bytes and aren't guaranteed to be UTF-8
345        LOGGER.info(
346            scope["path"],
347            scheme="ws",
348            remote=headers.get(b"x-forwarded-for", b"").decode(errors="backslashreplace"),
349            user_agent=headers.get(b"user-agent", b"").decode(errors="backslashreplace"),
350            **kwargs,
351        )

Log request

class LoggingMiddleware:
354class LoggingMiddleware:
355    """Logger middleware"""
356
357    get_response: Callable[[HttpRequest], HttpResponse]
358
359    def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]):
360        self.get_response = get_response
361        headers = CONFIG.get("log.http_headers", [])
362        if isinstance(headers, str):
363            headers = headers.split(",")
364        self.headers_to_log = headers
365
366    def __call__(self, request: HttpRequest) -> HttpResponse:
367        start = perf_counter()
368        response = self.get_response(request)
369        status_code = response.status_code
370        kwargs = {
371            "request_id": getattr(request, "request_id", None),
372        }
373        kwargs.update(getattr(response, "ak_context", {}))
374        self.log(request, status_code, int((perf_counter() - start) * 1000), **kwargs)
375        return response
376
377    def log(self, request: HttpRequest, status_code: int, runtime: int, **kwargs):
378        """Log request"""
379        # Those are logged by the server above
380        if request.path in ("/-/metrics/", "/-/health/ready/"):
381            return
382        for header in self.headers_to_log:
383            header_value = request.headers.get(header)
384            if not header_value:
385                continue
386            kwargs[header.lower().replace("-", "_")] = header_value
387        LOGGER.info(
388            request.get_full_path(),
389            remote=ClientIPMiddleware.get_client_ip(request),
390            method=request.method,
391            scheme=request.scheme,
392            status=status_code,
393            runtime=runtime,
394            **kwargs,
395        )

Logger middleware

LoggingMiddleware( get_response: Callable[[django.http.request.HttpRequest], django.http.response.HttpResponse])
359    def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]):
360        self.get_response = get_response
361        headers = CONFIG.get("log.http_headers", [])
362        if isinstance(headers, str):
363            headers = headers.split(",")
364        self.headers_to_log = headers
get_response: Callable[[django.http.request.HttpRequest], django.http.response.HttpResponse]
headers_to_log
def log( self, request: django.http.request.HttpRequest, status_code: int, runtime: int, **kwargs):
377    def log(self, request: HttpRequest, status_code: int, runtime: int, **kwargs):
378        """Log request"""
379        # Those are logged by the server above
380        if request.path in ("/-/metrics/", "/-/health/ready/"):
381            return
382        for header in self.headers_to_log:
383            header_value = request.headers.get(header)
384            if not header_value:
385                continue
386            kwargs[header.lower().replace("-", "_")] = header_value
387        LOGGER.info(
388            request.get_full_path(),
389            remote=ClientIPMiddleware.get_client_ip(request),
390            method=request.method,
391            scheme=request.scheme,
392            status=status_code,
393            runtime=runtime,
394            **kwargs,
395        )

Log request