authentik.events.middleware

Events middleware

  1"""Events middleware"""
  2
  3from collections.abc import Callable
  4from contextlib import contextmanager
  5from contextvars import ContextVar
  6from threading import Thread
  7from typing import Any
  8
  9from django.conf import settings
 10from django.contrib.sessions.models import Session
 11from django.core.exceptions import SuspiciousOperation
 12from django.db.models import Model
 13from django.db.models.signals import m2m_changed, post_save, pre_delete
 14from django.http import HttpRequest, HttpResponse
 15from django_postgres_cache.models import CacheEntry
 16from structlog.stdlib import BoundLogger, get_logger
 17
 18from authentik.blueprints.v1.importer import excluded_models
 19from authentik.core.models import Group, User
 20from authentik.events.models import Event, EventAction, Notification
 21from authentik.events.utils import model_to_dict
 22from authentik.lib.middleware import SignalMiddleware
 23from authentik.lib.models import InternallyManagedMixin
 24from authentik.lib.tracing.exceptions import should_ignore_exception
 25from authentik.lib.utils.errors import exception_to_dict
 26from authentik.stages.authenticator_static.models import StaticToken
 27
 28IGNORED_MODELS = tuple(
 29    excluded_models()
 30    + (
 31        Event,
 32        Notification,
 33        StaticToken,
 34        Session,
 35        CacheEntry,
 36    )
 37)
 38
 39_CTX_OVERWRITE_USER = ContextVar[User | None]("authentik_events_log_overwrite_user", default=None)
 40_CTX_IGNORE = ContextVar[bool]("authentik_events_log_ignore", default=False)
 41
 42
 43def should_log_model(model: Model) -> bool:
 44    """Return true if operation on `model` should be logged"""
 45    return model.__class__ not in IGNORED_MODELS and not isinstance(model, InternallyManagedMixin)
 46
 47
 48def should_log_m2m(model: Model) -> bool:
 49    """Return true if m2m operation should be logged"""
 50    if model.__class__ in [User, Group]:
 51        return True
 52    return False
 53
 54
 55@contextmanager
 56def audit_overwrite_user(user: User):
 57    """Overwrite user being logged for model AuditMiddleware. Commonly used
 58    for example in flows where a pending user is given, but the request is not authenticated yet"""
 59    _CTX_OVERWRITE_USER.set(user)
 60    try:
 61        yield
 62    finally:
 63        _CTX_OVERWRITE_USER.set(None)
 64
 65
 66@contextmanager
 67def audit_ignore():
 68    """Ignore model operations in the block. Useful for objects which need to be modified
 69    but are not excluded (e.g. WebAuthn devices)"""
 70    _CTX_IGNORE.set(True)
 71    try:
 72        yield
 73    finally:
 74        _CTX_IGNORE.set(False)
 75
 76
 77def is_audit_ignored() -> bool:
 78    """Return true if the current operation should be ignored for auditing"""
 79    return _CTX_IGNORE.get()
 80
 81
 82class EventNewThread(Thread):
 83    """Create Event in background thread"""
 84
 85    action: str
 86    request: HttpRequest
 87    kwargs: dict[str, Any]
 88    user: User | None = None
 89
 90    def __init__(self, action: str, request: HttpRequest, user: User | None = None, **kwargs):
 91        super().__init__()
 92        self.action = action
 93        self.request = request
 94        self.user = user
 95        self.kwargs = kwargs
 96
 97    def run(self):
 98        Event.new(self.action, **self.kwargs).from_http(self.request, user=self.user)
 99
100
101class AuditMiddleware(SignalMiddleware):
102    """Log creation/update/deletion of models during a request"""
103
104    signal_handlers = {
105        post_save: "post_save_handler",
106        pre_delete: "pre_delete_handler",
107        m2m_changed: "m2m_changed_handler",
108    }
109
110    anonymous_user: User = None
111    logger: BoundLogger
112
113    def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]):
114        super().__init__(get_response)
115        self.logger = get_logger().bind()
116
117    def _ensure_fallback_user(self):
118        """Defer fetching anonymous user until we have to"""
119        if self.anonymous_user:
120            return
121        from guardian.shortcuts import get_anonymous_user
122
123        self.anonymous_user = get_anonymous_user()
124
125    def get_user(self, request: HttpRequest) -> User:
126        user = _CTX_OVERWRITE_USER.get()
127        if user:
128            return user
129        user = getattr(request, "user", self.anonymous_user)
130        if not user.is_authenticated:
131            self._ensure_fallback_user()
132            return self.anonymous_user
133        return user
134
135    def is_current_request(self, request: HttpRequest) -> bool:
136        """Only handle signals for the request this middleware is currently handling"""
137        current_request = self.current_request()
138        return current_request is not None and request.request_id == current_request.request_id
139
140    def process_exception(self, request: HttpRequest, exception: Exception):
141        """Create an event for unhandled exceptions"""
142        if settings.DEBUG:
143            return
144        # Special case for SuspiciousOperation, we have a special event action for that
145        if isinstance(exception, SuspiciousOperation):
146            thread = EventNewThread(
147                EventAction.SUSPICIOUS_REQUEST,
148                request,
149                message=str(exception),
150                exception=exception_to_dict(exception),
151            )
152            thread.run()
153        elif not should_ignore_exception(exception):
154            thread = EventNewThread(
155                EventAction.SYSTEM_EXCEPTION,
156                request,
157                message=str(exception),
158                exception=exception_to_dict(exception),
159            )
160            thread.run()
161
162    def post_save_handler(
163        self,
164        request: HttpRequest,
165        sender,
166        instance: Model,
167        created: bool,
168        thread_kwargs: dict | None = None,
169        **_,
170    ):
171        """Signal handler for all object's post_save"""
172        if not should_log_model(instance):
173            return
174        if _CTX_IGNORE.get():
175            return
176        if not self.is_current_request(request):
177            return
178        user = self.get_user(request)
179
180        action = EventAction.MODEL_CREATED if created else EventAction.MODEL_UPDATED
181        thread = EventNewThread(action, request, user=user, model=model_to_dict(instance))
182        thread.kwargs.update(thread_kwargs or {})
183        thread.run()
184
185    def pre_delete_handler(self, request: HttpRequest, sender, instance: Model, **_):
186        """Signal handler for all object's pre_delete"""
187        if not should_log_model(instance):  # pragma: no cover
188            return
189        if _CTX_IGNORE.get():
190            return
191        if not self.is_current_request(request):
192            return
193        user = self.get_user(request)
194
195        EventNewThread(
196            EventAction.MODEL_DELETED,
197            request,
198            user=user,
199            model=model_to_dict(instance),
200        ).run()
201
202    def m2m_changed_handler(
203        self,
204        request: HttpRequest,
205        sender,
206        instance: Model,
207        action: str,
208        thread_kwargs: dict | None = None,
209        **_,
210    ):
211        """Signal handler for all object's m2m_changed"""
212        if action not in ["pre_add", "pre_remove", "post_clear"]:
213            return
214        if not should_log_m2m(instance):
215            return
216        if _CTX_IGNORE.get():
217            return
218        if not self.is_current_request(request):
219            return
220        user = self.get_user(request)
221
222        EventNewThread(
223            EventAction.MODEL_UPDATED,
224            request,
225            user=user,
226            model=model_to_dict(instance),
227            **(thread_kwargs or {}),
228        ).run()
IGNORED_MODELS = (<class 'django.contrib.auth.models.User'>, <class 'django.contrib.auth.models.Group'>, <class 'django.contrib.contenttypes.models.ContentType'>, <class 'django.contrib.auth.models.Permission'>, <class 'guardian.models.RoleObjectPermission'>, <class 'authentik.core.models.Provider'>, <class 'authentik.core.models.Source'>, <class 'authentik.core.models.PropertyMapping'>, <class 'authentik.core.models.UserSourceConnection'>, <class 'authentik.core.models.GroupSourceConnection'>, <class 'authentik.flows.models.Stage'>, <class 'authentik.outposts.models.OutpostServiceConnection'>, <class 'authentik.policies.models.Policy'>, <class 'authentik.policies.models.PolicyBindingModel'>, <class 'authentik.endpoints.models.Connector'>, <class 'authentik.core.models.Session'>, <class 'authentik.core.models.AuthenticatedSession'>, <class 'authentik.events.models.Event'>, <class 'authentik.events.models.Notification'>, <class 'authentik.stages.authenticator_static.models.StaticToken'>, <class 'django.contrib.sessions.models.Session'>, <class 'django_postgres_cache.models.CacheEntry'>)
def should_log_model(model: django.db.models.base.Model) -> bool:
44def should_log_model(model: Model) -> bool:
45    """Return true if operation on `model` should be logged"""
46    return model.__class__ not in IGNORED_MODELS and not isinstance(model, InternallyManagedMixin)

Return true if operation on model should be logged

def should_log_m2m(model: django.db.models.base.Model) -> bool:
49def should_log_m2m(model: Model) -> bool:
50    """Return true if m2m operation should be logged"""
51    if model.__class__ in [User, Group]:
52        return True
53    return False

Return true if m2m operation should be logged

@contextmanager
def audit_overwrite_user(user: authentik.core.models.User):
56@contextmanager
57def audit_overwrite_user(user: User):
58    """Overwrite user being logged for model AuditMiddleware. Commonly used
59    for example in flows where a pending user is given, but the request is not authenticated yet"""
60    _CTX_OVERWRITE_USER.set(user)
61    try:
62        yield
63    finally:
64        _CTX_OVERWRITE_USER.set(None)

Overwrite user being logged for model AuditMiddleware. Commonly used for example in flows where a pending user is given, but the request is not authenticated yet

@contextmanager
def audit_ignore():
67@contextmanager
68def audit_ignore():
69    """Ignore model operations in the block. Useful for objects which need to be modified
70    but are not excluded (e.g. WebAuthn devices)"""
71    _CTX_IGNORE.set(True)
72    try:
73        yield
74    finally:
75        _CTX_IGNORE.set(False)

Ignore model operations in the block. Useful for objects which need to be modified but are not excluded (e.g. WebAuthn devices)

def is_audit_ignored() -> bool:
78def is_audit_ignored() -> bool:
79    """Return true if the current operation should be ignored for auditing"""
80    return _CTX_IGNORE.get()

Return true if the current operation should be ignored for auditing

class EventNewThread(threading.Thread):
83class EventNewThread(Thread):
84    """Create Event in background thread"""
85
86    action: str
87    request: HttpRequest
88    kwargs: dict[str, Any]
89    user: User | None = None
90
91    def __init__(self, action: str, request: HttpRequest, user: User | None = None, **kwargs):
92        super().__init__()
93        self.action = action
94        self.request = request
95        self.user = user
96        self.kwargs = kwargs
97
98    def run(self):
99        Event.new(self.action, **self.kwargs).from_http(self.request, user=self.user)

Create Event in background thread

EventNewThread( action: str, request: django.http.request.HttpRequest, user: authentik.core.models.User | None = None, **kwargs)
91    def __init__(self, action: str, request: HttpRequest, user: User | None = None, **kwargs):
92        super().__init__()
93        self.action = action
94        self.request = request
95        self.user = user
96        self.kwargs = kwargs

This constructor should always be called with keyword arguments. Arguments are:

group should be None; reserved for future extension when a ThreadGroup class is implemented.

target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.

name is the thread name. By default, a unique name is constructed of the form "Thread-N" where N is a small decimal number.

args is a list or tuple of arguments for the target invocation. Defaults to ().

kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.

context is the contextvars.Context value to use for the thread. The default value is None, which means to check sys.flags.thread_inherit_context. If that flag is true, use a copy of the context of the caller. If false, use an empty context. To explicitly start with an empty context, pass a new instance of contextvars.Context(). To explicitly start with a copy of the current context, pass the value from contextvars.copy_context().

If a subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread.

action: str
request: django.http.request.HttpRequest
kwargs: dict[str, typing.Any]
user: authentik.core.models.User | None = None
def run(self):
98    def run(self):
99        Event.new(self.action, **self.kwargs).from_http(self.request, user=self.user)

Method representing the thread's activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object's constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

class AuditMiddleware(authentik.lib.middleware.SignalMiddleware):
102class AuditMiddleware(SignalMiddleware):
103    """Log creation/update/deletion of models during a request"""
104
105    signal_handlers = {
106        post_save: "post_save_handler",
107        pre_delete: "pre_delete_handler",
108        m2m_changed: "m2m_changed_handler",
109    }
110
111    anonymous_user: User = None
112    logger: BoundLogger
113
114    def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]):
115        super().__init__(get_response)
116        self.logger = get_logger().bind()
117
118    def _ensure_fallback_user(self):
119        """Defer fetching anonymous user until we have to"""
120        if self.anonymous_user:
121            return
122        from guardian.shortcuts import get_anonymous_user
123
124        self.anonymous_user = get_anonymous_user()
125
126    def get_user(self, request: HttpRequest) -> User:
127        user = _CTX_OVERWRITE_USER.get()
128        if user:
129            return user
130        user = getattr(request, "user", self.anonymous_user)
131        if not user.is_authenticated:
132            self._ensure_fallback_user()
133            return self.anonymous_user
134        return user
135
136    def is_current_request(self, request: HttpRequest) -> bool:
137        """Only handle signals for the request this middleware is currently handling"""
138        current_request = self.current_request()
139        return current_request is not None and request.request_id == current_request.request_id
140
141    def process_exception(self, request: HttpRequest, exception: Exception):
142        """Create an event for unhandled exceptions"""
143        if settings.DEBUG:
144            return
145        # Special case for SuspiciousOperation, we have a special event action for that
146        if isinstance(exception, SuspiciousOperation):
147            thread = EventNewThread(
148                EventAction.SUSPICIOUS_REQUEST,
149                request,
150                message=str(exception),
151                exception=exception_to_dict(exception),
152            )
153            thread.run()
154        elif not should_ignore_exception(exception):
155            thread = EventNewThread(
156                EventAction.SYSTEM_EXCEPTION,
157                request,
158                message=str(exception),
159                exception=exception_to_dict(exception),
160            )
161            thread.run()
162
163    def post_save_handler(
164        self,
165        request: HttpRequest,
166        sender,
167        instance: Model,
168        created: bool,
169        thread_kwargs: dict | None = None,
170        **_,
171    ):
172        """Signal handler for all object's post_save"""
173        if not should_log_model(instance):
174            return
175        if _CTX_IGNORE.get():
176            return
177        if not self.is_current_request(request):
178            return
179        user = self.get_user(request)
180
181        action = EventAction.MODEL_CREATED if created else EventAction.MODEL_UPDATED
182        thread = EventNewThread(action, request, user=user, model=model_to_dict(instance))
183        thread.kwargs.update(thread_kwargs or {})
184        thread.run()
185
186    def pre_delete_handler(self, request: HttpRequest, sender, instance: Model, **_):
187        """Signal handler for all object's pre_delete"""
188        if not should_log_model(instance):  # pragma: no cover
189            return
190        if _CTX_IGNORE.get():
191            return
192        if not self.is_current_request(request):
193            return
194        user = self.get_user(request)
195
196        EventNewThread(
197            EventAction.MODEL_DELETED,
198            request,
199            user=user,
200            model=model_to_dict(instance),
201        ).run()
202
203    def m2m_changed_handler(
204        self,
205        request: HttpRequest,
206        sender,
207        instance: Model,
208        action: str,
209        thread_kwargs: dict | None = None,
210        **_,
211    ):
212        """Signal handler for all object's m2m_changed"""
213        if action not in ["pre_add", "pre_remove", "post_clear"]:
214            return
215        if not should_log_m2m(instance):
216            return
217        if _CTX_IGNORE.get():
218            return
219        if not self.is_current_request(request):
220            return
221        user = self.get_user(request)
222
223        EventNewThread(
224            EventAction.MODEL_UPDATED,
225            request,
226            user=user,
227            model=model_to_dict(instance),
228            **(thread_kwargs or {}),
229        ).run()

Log creation/update/deletion of models during a request

AuditMiddleware( get_response: Callable[[django.http.request.HttpRequest], django.http.response.HttpResponse])
114    def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]):
115        super().__init__(get_response)
116        self.logger = get_logger().bind()
signal_handlers = {<django.db.models.signals.ModelSignal object>: 'post_save_handler', <django.db.models.signals.ModelSignal object>: 'pre_delete_handler', <django.db.models.signals.ModelSignal object>: 'm2m_changed_handler'}
anonymous_user: authentik.core.models.User = None
logger: structlog.stdlib.BoundLogger
def get_user( self, request: django.http.request.HttpRequest) -> authentik.core.models.User:
126    def get_user(self, request: HttpRequest) -> User:
127        user = _CTX_OVERWRITE_USER.get()
128        if user:
129            return user
130        user = getattr(request, "user", self.anonymous_user)
131        if not user.is_authenticated:
132            self._ensure_fallback_user()
133            return self.anonymous_user
134        return user
def is_current_request(self, request: django.http.request.HttpRequest) -> bool:
136    def is_current_request(self, request: HttpRequest) -> bool:
137        """Only handle signals for the request this middleware is currently handling"""
138        current_request = self.current_request()
139        return current_request is not None and request.request_id == current_request.request_id

Only handle signals for the request this middleware is currently handling

def process_exception(self, request: django.http.request.HttpRequest, exception: Exception):
141    def process_exception(self, request: HttpRequest, exception: Exception):
142        """Create an event for unhandled exceptions"""
143        if settings.DEBUG:
144            return
145        # Special case for SuspiciousOperation, we have a special event action for that
146        if isinstance(exception, SuspiciousOperation):
147            thread = EventNewThread(
148                EventAction.SUSPICIOUS_REQUEST,
149                request,
150                message=str(exception),
151                exception=exception_to_dict(exception),
152            )
153            thread.run()
154        elif not should_ignore_exception(exception):
155            thread = EventNewThread(
156                EventAction.SYSTEM_EXCEPTION,
157                request,
158                message=str(exception),
159                exception=exception_to_dict(exception),
160            )
161            thread.run()

Create an event for unhandled exceptions

def post_save_handler( self, request: django.http.request.HttpRequest, sender, instance: django.db.models.base.Model, created: bool, thread_kwargs: dict | None = None, **_):
163    def post_save_handler(
164        self,
165        request: HttpRequest,
166        sender,
167        instance: Model,
168        created: bool,
169        thread_kwargs: dict | None = None,
170        **_,
171    ):
172        """Signal handler for all object's post_save"""
173        if not should_log_model(instance):
174            return
175        if _CTX_IGNORE.get():
176            return
177        if not self.is_current_request(request):
178            return
179        user = self.get_user(request)
180
181        action = EventAction.MODEL_CREATED if created else EventAction.MODEL_UPDATED
182        thread = EventNewThread(action, request, user=user, model=model_to_dict(instance))
183        thread.kwargs.update(thread_kwargs or {})
184        thread.run()

Signal handler for all object's post_save

def pre_delete_handler( self, request: django.http.request.HttpRequest, sender, instance: django.db.models.base.Model, **_):
186    def pre_delete_handler(self, request: HttpRequest, sender, instance: Model, **_):
187        """Signal handler for all object's pre_delete"""
188        if not should_log_model(instance):  # pragma: no cover
189            return
190        if _CTX_IGNORE.get():
191            return
192        if not self.is_current_request(request):
193            return
194        user = self.get_user(request)
195
196        EventNewThread(
197            EventAction.MODEL_DELETED,
198            request,
199            user=user,
200            model=model_to_dict(instance),
201        ).run()

Signal handler for all object's pre_delete

def m2m_changed_handler( self, request: django.http.request.HttpRequest, sender, instance: django.db.models.base.Model, action: str, thread_kwargs: dict | None = None, **_):
203    def m2m_changed_handler(
204        self,
205        request: HttpRequest,
206        sender,
207        instance: Model,
208        action: str,
209        thread_kwargs: dict | None = None,
210        **_,
211    ):
212        """Signal handler for all object's m2m_changed"""
213        if action not in ["pre_add", "pre_remove", "post_clear"]:
214            return
215        if not should_log_m2m(instance):
216            return
217        if _CTX_IGNORE.get():
218            return
219        if not self.is_current_request(request):
220            return
221        user = self.get_user(request)
222
223        EventNewThread(
224            EventAction.MODEL_UPDATED,
225            request,
226            user=user,
227            model=model_to_dict(instance),
228            **(thread_kwargs or {}),
229        ).run()

Signal handler for all object's m2m_changed