Source code for smarter.lib.django.middleware.csrf

"""
ASGI-safe dynamic CSRF middleware for Django.

This module extends :class:`django.middleware.csrf.CsrfViewMiddleware`
to support request-scoped trusted origins while preserving full
compatibility with Django's supported middleware lifecycle.

The implementation intentionally relies only on officially supported
extension points and avoids custom async adaptation logic.

Key Features
============

- Fully compatible with ASGI and WSGI
- Dynamic request-scoped CSRF trusted origins
- Stateless request processing
- LLMClient-aware CSRF bypass support
- Internal network bypass support
- Local development environment bypass
- Compatibility with Django admin and authentication middleware
- Compatible with sync views, async views, and Channels

Design Constraints
==================

This middleware intentionally avoids several patterns that commonly
introduce concurrency bugs or unsupported Django behavior:

- Does not mutate ``request.user``
- Overrides ``__call__`` only to let amnesty paths skip the check
- Does not use ``markcoroutinefunction``
- Does not manually manage async adaptation
- Does not persist middleware state across requests
- Does not mutate ``settings.CSRF_TRUSTED_ORIGINS``

Concurrency Safety
==================

All trusted origin computation is request-scoped.

Dynamic CSRF origin lists are created fresh for each request and are
never written back to Django settings or shared global state.

Temporary compatibility overrides required by Django internals are
strictly limited to the duration of ``process_view()`` execution and
are restored immediately afterward.

Behavior
========

For each request, the middleware:

#. Evaluates feature-flag enablement via Django Waffle
#. Applies environment-specific bypass rules
#. Applies internal network bypass rules
#. Applies llmclient-specific CSRF bypass logic
#. Dynamically computes trusted origins
#. Delegates CSRF validation to Django's built-in middleware

If CSRF validation fails, detailed structured logging is emitted
containing request metadata for diagnostics.

Dynamic Trusted Origins
=======================

Dynamic origins are derived from the active request and may include:

- llmclient-specific origins
- configuration endpoints
- environment-specific origins

The middleware never mutates:

- ``settings.CSRF_TRUSTED_ORIGINS``
- Django global middleware configuration
- shared process state

Django Compatibility
====================

This middleware preserves compatibility with Django internals by
maintaining the expected behavior of:

- ``csrf_trusted_origins_hosts``
- ``allowed_origins_exact``
- ``allowed_origin_subdomains``

These properties are exposed using Django-compatible interfaces while
still avoiding persistent mutation of global settings.

Classes
=======

.. autosummary::
   :toctree: generated/

   SmarterCsrfViewMiddleware

Dependencies
============

- Django
- Django Waffle

Logging
=======

Middleware lifecycle events, bypass conditions, dynamic origin
generation, and CSRF validation failures are logged using the
application's structured logging framework.

Notes
=====

This middleware depends on behavior provided by
:class:`smarter.lib.django.request.SmarterRequestMixin`.

Because Django's native CSRF middleware already supports both sync
and async execution models, this implementation avoids introducing
custom coroutine wrappers or async middleware adaptation logic.

Warnings
========

Although temporary reassignment of Django internal CSRF origin
structures occurs during request processing, the original values are
always restored immediately after validation completes.

This behavior is intentionally scoped to the request lifecycle and is
designed to preserve compatibility with Django's internal CSRF
validation flow.
"""

from collections import defaultdict
from urllib.parse import urlparse

from django.conf import settings
from django.http import HttpRequest, HttpResponseForbidden
from django.http.response import HttpResponseBase
from django.middleware.csrf import CsrfViewMiddleware, get_token
from django.utils.functional import cached_property

from smarter.common.conf import smarter_settings
from smarter.common.const import SmarterEnvironments
from smarter.common.mixins.helper_mixin import SmarterHelperMixin
from smarter.lib import logging
from smarter.lib.django import waffle
from smarter.lib.django.request import SmarterRequestMixin
from smarter.lib.django.waffle import SmarterWaffleSwitches

logger = logging.getSmarterLogger(__name__, any_switches=[SmarterWaffleSwitches.MIDDLEWARE_LOGGING])

CSRF_SAFE_METHODS = frozenset(("GET", "HEAD", "OPTIONS", "TRACE"))
"""The methods whose requests Django's CSRF check always accepts."""

LLMCLIENT_REQUEST_KIND_ATTRIBUTE = "_smarter_csrf_llmclient_request_kind"
"""The request attribute that holds :meth:`SmarterCsrfViewMiddleware.llmclient_request_kind`."""


if waffle.switch_is_active(SmarterWaffleSwitches.ENABLE_MIDDLEWARE_CSRF):
    logger.debug(
        "is %s",
        SmarterHelperMixin().formatted_state_ready,
    )
else:
    logger.debug(
        "is %s. Enable with Django waffle in the admin console.",
        SmarterHelperMixin().formatted_state_not_ready,
    )


[docs] class SmarterCsrfViewMiddleware(CsrfViewMiddleware, SmarterRequestMixin): """ ASGI-safe CSRF middleware. Extends Django's CsrfViewMiddleware while preserving all Django request lifecycle invariants. """
[docs] def __init__(self, get_response): """ Initialize Django's CSRF middleware, then this instance's :class:`SmarterRequestMixin`. :param get_response: The next handler in the middleware chain. """ super().__init__(get_response) # initialize request mixin WITHOUT fake users/admin state SmarterRequestMixin.__init__(self)
def __call__(self, request): """ Skip the CSRF middleware for an amnesty path, or run Django's middleware lifecycle. An amnesty path, e.g. a health check, goes straight to the next handler. Every other request goes through Django's ``__call__``, which calls :meth:`process_view` and :meth:`process_response`. :param request: The incoming request. :returns: The response. """ if self.deserves_amnesty(request.path): return self.get_response(request) return super().__call__(request) @cached_property def formatted_class_name(self) -> str: """Return the formatted class name for logging. It names the instance, not a request. """ class_name = f"{__name__}.{self.__class__.__name__}[{id(self)}]" return self.formatted_text(class_name)
[docs] def get_dynamic_trusted_origins( self, request: HttpRequest, ) -> list[str]: """ Return one request's trusted origins: ``CSRF_TRUSTED_ORIGINS``, plus its own origin for an LLMClient. The list is a fresh copy for each request, and Django's settings are never changed. An LLMClient or configuration api request adds its own origin, e.g. ``https://example.com``. A failure to classify the request is logged, and the settings' origins are returned. :param request: The request. :returns: A new list of trusted origins. """ origins = list(settings.CSRF_TRUSTED_ORIGINS) try: is_llmclient, is_config = self.llmclient_request_kind(request) if is_llmclient or is_config: origin = request.build_absolute_uri("/").rstrip("/") if origin not in origins: origins.append(origin) # pylint: disable=broad-except except Exception as exc: logger.exception( "failed building dynamic CSRF origins: %s", exc, ) return origins
[docs] def llmclient_request_kind(self, request: HttpRequest) -> tuple[bool, bool]: """ Return whether the request is for an LLMClient, and whether it is for a configuration api. The middleware is one instance shared by every request, so the request is classified by its own :class:`SmarterRequestMixin`, never by this instance's, and the result is kept on the request, never on the middleware. A request that can't be classified is neither, so it gets the full CSRF check. :param request: The request. :returns: ``(is_llmclient, is_config)``. """ kind = getattr(request, LLMCLIENT_REQUEST_KIND_ATTRIBUTE, None) if kind is None: try: srm = SmarterRequestMixin(request) kind = (bool(srm.is_llmclient), bool(srm.is_config)) # pylint: disable=broad-except except Exception as exc: logger.warning( "could not classify %s: %s", request.path, exc, ) kind = (False, False) setattr(request, LLMCLIENT_REQUEST_KIND_ATTRIBUTE, kind) return kind
@cached_property def csrf_trusted_origins_hosts(self) -> list[str]: """ The hosts of ``CSRF_TRUSTED_ORIGINS``, without a leading wildcard, as Django's internals expect. :meth:`process_view` swaps it for the request's own list while Django checks the request, so that the settings are never changed. :returns: The trusted hosts, e.g. ``.example.com`` for ``https://*.example.com``. """ return [urlparse(origin).netloc.lstrip("*") for origin in settings.CSRF_TRUSTED_ORIGINS] @cached_property def allowed_origins_exact(self) -> set[str]: """ The ``CSRF_TRUSTED_ORIGINS`` without a wildcard, which must match an origin exactly. :returns: The set of exact origins. """ return {origin for origin in settings.CSRF_TRUSTED_ORIGINS if "*" not in origin} @cached_property def allowed_origin_subdomains(self) -> defaultdict[str, list[str]]: """ The wildcard ``CSRF_TRUSTED_ORIGINS``, as a dict of scheme to the domains whose subdomains are trusted. For example, ``https://*.example.com`` adds ``.example.com`` to the ``https`` list. :returns: A dict of scheme to the list of trusted parent domains. """ allowed_origin_subdomains = defaultdict(list) for origin in settings.CSRF_TRUSTED_ORIGINS: if "*" not in origin: continue parsed = urlparse(origin) domain = parsed.netloc.lstrip("*") allowed_origin_subdomains[parsed.scheme].append(domain) return allowed_origin_subdomains
[docs] def process_response(self, request: HttpRequest, response: HttpResponseBase) -> HttpResponseBase: """ Renew the CSRF cookie on a signed-in user's console pages, then let Django set it. ``get_token()`` keeps the current token when the request has one, or makes a new one when the cookie has expired, and marks the cookie for update, so that Django's ``process_response()`` sends it again with a fresh ``CSRF_COOKIE_AGE``. :param request: The request. :param response: The view's response. :returns: The response, with the ``csrftoken`` cookie when it was renewed. """ if self.renews_csrf_cookie(request, response): get_token(request) return super().process_response(request, response)
[docs] def process_view( self, request: HttpRequest, callback, callback_args, callback_kwargs, ): """ Check a request's CSRF token and origin, unless one of the bypass rules applies. Amnesty paths, a disabled ``ENABLE_MIDDLEWARE_CSRF`` switch, the local environment, health checks, internal hosts and, with ``CSRF_SUPPRESS_FOR_LLM_CLIENTS`` on, LLMClient requests skip the check. Every other request is checked by Django, against the trusted origins of :meth:`get_dynamic_trusted_origins`, which replace this instance's origin lists only until Django's check returns. A rejected request is logged at ERROR. This hook never calls ``self.get_response(request)``: it returns None, and Django calls the view. :param request: The request. :param callback: The view function. :param callback_args: The view's positional arguments. :param callback_kwargs: The view's keyword arguments. :returns: None to let the request through, or Django's ``403`` response. """ if self.deserves_amnesty(request.path): return None if not waffle.switch_is_active(SmarterWaffleSwitches.ENABLE_MIDDLEWARE_CSRF): return None if smarter_settings.environment == SmarterEnvironments.LOCAL: return None path = request.path.strip("/") if path in getattr(self, "amnesty_urls", []): # health check bypass return None host = request.get_host() if host.startswith(tuple(smarter_settings.platform_internal_ip_prefixes)): # internal IP bypass return None if request.method in CSRF_SAFE_METHODS: # Django never checks the origin of a safe request, so it needs no classification. return super().process_view(request, callback, callback_args, callback_kwargs) # # LLMClient bypass # is_llmclient, _ = self.llmclient_request_kind(request) if is_llmclient and waffle.switch_is_active(SmarterWaffleSwitches.CSRF_SUPPRESS_FOR_LLM_CLIENTS): logger.info( "llmclient CSRF bypass: %s", request.path, ) return None dynamic_origins = self.get_dynamic_trusted_origins(request) original_exact = self.allowed_origins_exact original_subdomains = self.allowed_origin_subdomains original_hosts = self.csrf_trusted_origins_hosts try: self.csrf_trusted_origins_hosts = [urlparse(origin).netloc.lstrip("*") for origin in dynamic_origins] self.allowed_origins_exact = {origin for origin in dynamic_origins if "*" not in origin} allowed_subdomains = defaultdict(list) for origin in dynamic_origins: if "*" not in origin: continue parsed = urlparse(origin) domain = parsed.netloc.lstrip("*") allowed_subdomains[parsed.scheme].append(domain) self.allowed_origin_subdomains = allowed_subdomains response = super().process_view(request, callback, callback_args, callback_kwargs) finally: self.allowed_origins_exact = original_exact self.allowed_origin_subdomains = original_subdomains self.csrf_trusted_origins_hosts = original_hosts if isinstance(response, HttpResponseForbidden): logger.error( ( "CSRF validation failed " "| path=%s " "| method=%s " "| origin=%s " "| referer=%s " "| remote_addr=%s " "| user_agent=%s" ), request.path, request.method, request.META.get("HTTP_ORIGIN"), request.META.get("HTTP_REFERER"), request.META.get("REMOTE_ADDR"), request.META.get("HTTP_USER_AGENT"), ) return response