authentik.events.utils

event utilities

  1"""event utilities"""
  2
  3import re
  4from copy import copy
  5from dataclasses import asdict, is_dataclass
  6from datetime import date, datetime, time, timedelta
  7from enum import Enum
  8from pathlib import Path
  9from types import GeneratorType, NoneType
 10from typing import Any
 11from uuid import UUID
 12
 13from django.contrib.auth.models import AnonymousUser
 14from django.core.handlers.wsgi import WSGIRequest
 15from django.core.serializers.json import DjangoJSONEncoder
 16from django.db import models
 17from django.db.models.base import Model
 18from django.http.request import HttpRequest
 19from django.utils import timezone
 20from django.views.debug import SafeExceptionReporterFilter
 21from geoip2.models import ASN, City
 22from guardian.conf import settings
 23from guardian.shortcuts import get_anonymous_user
 24
 25from authentik.blueprints.v1.common import YAMLTag
 26from authentik.core.models import User, UserTypes
 27from authentik.events.context_processors.asn import ASN_CONTEXT_PROCESSOR
 28from authentik.events.context_processors.geoip import GEOIP_CONTEXT_PROCESSOR
 29from authentik.policies.types import PolicyRequest
 30
 31# Special keys which are *not* cleaned, even when the default filter
 32# is matched
 33ALLOWED_SPECIAL_KEYS = re.compile(
 34    r"passing|password_change_date|^auth_method(_args)?$|^revoke_tokens$",
 35    flags=re.I,
 36)
 37
 38
 39def cleanse_str(raw: Any) -> str:
 40    return str(raw).replace("\u0000", "")
 41
 42
 43def cleanse_item(key: str, value: Any) -> Any:
 44    """Cleanse a single item"""
 45    if isinstance(value, dict):
 46        return cleanse_dict(value)
 47    if isinstance(value, list | tuple | set):
 48        return type(value)(cleanse_item(key, item) for item in value)
 49    try:
 50        if not SafeExceptionReporterFilter.hidden_settings.search(key):
 51            return value
 52        if ALLOWED_SPECIAL_KEYS.search(key):
 53            return value
 54        return SafeExceptionReporterFilter.cleansed_substitute
 55    except TypeError:  # pragma: no cover
 56        return value
 57
 58
 59def cleanse_dict(source: dict[Any, Any]) -> dict[Any, Any]:
 60    """Cleanse a dictionary, recursively"""
 61    final_dict = {}
 62    for key, value in source.items():
 63        new_value = cleanse_item(key, value)
 64        if new_value is not ...:
 65            final_dict[key] = new_value
 66    return final_dict
 67
 68
 69def model_to_dict(model: Model) -> dict[str, Any]:
 70    """Convert model to dict"""
 71    name = cleanse_str(model)
 72    if hasattr(model, "name"):
 73        name = model.name
 74    return {
 75        "app": model._meta.app_label,
 76        "model_name": model._meta.model_name,
 77        "pk": model.pk,
 78        "name": name,
 79    }
 80
 81
 82def get_user(user: User | AnonymousUser) -> dict[str, Any]:
 83    """Convert user object to dictionary"""
 84    if isinstance(user, AnonymousUser):
 85        try:
 86            user = get_anonymous_user()
 87        except User.DoesNotExist:
 88            return {}
 89    user_data = {
 90        "username": user.username,
 91        "pk": user.pk,
 92        "email": user.email,
 93    }
 94    if user.username == settings.ANONYMOUS_USER_NAME:
 95        user_data["is_anonymous"] = True
 96    # Actions performed by an actor are recorded on behalf of its parent, so the
 97    # audit log always ties the activity back to a responsible human.
 98    if getattr(user, "type", None) == UserTypes.SERVICE_ACCOUNT and hasattr(user, "actor"):
 99        user_data["is_agent"] = True
100        # An actor without an owner acts for itself, so there is nobody to attribute to
101        if user.actor.parent:
102            user_data["on_behalf_of"] = get_user(user.actor.parent)
103    return user_data
104
105
106def sanitize_item(value: Any) -> Any:  # noqa: PLR0911, PLR0912
107    """Sanitize a single item, ensure it is JSON parsable"""
108    if is_dataclass(value):
109        # Because asdict calls `copy.deepcopy(obj)` on everything that's not tuple/dict,
110        # and deepcopy doesn't work with HttpRequest (neither django nor rest_framework).
111        # (more specifically doesn't work with ResolverMatch)
112        # rest_framework's custom Request class makes this more complicated as it also holds a
113        # thread lock.
114        # Since this class is mainly used for Events which already hold the http request context
115        # we just remove the http_request from the shallow policy request
116        # Currently, the only dataclass that actually holds an http request is a PolicyRequest
117        if isinstance(value, PolicyRequest) and value.http_request is not None:
118            value: PolicyRequest = copy(value)
119            value.http_request = None
120        value = asdict(value)
121    if isinstance(value, dict):
122        return sanitize_dict(value)
123    if isinstance(value, GeneratorType):
124        return sanitize_item(list(value))
125    if isinstance(value, list | tuple | set):
126        new_values = []
127        for item in value:
128            new_value = sanitize_item(item)
129            if new_value:
130                new_values.append(new_value)
131        return new_values
132    if isinstance(value, User | AnonymousUser):
133        return sanitize_dict(get_user(value))
134    if isinstance(value, models.Model):
135        return sanitize_dict(model_to_dict(value))
136    if isinstance(value, UUID):
137        return value.hex
138    if isinstance(value, HttpRequest | WSGIRequest):
139        return ...
140    if isinstance(value, City):
141        return GEOIP_CONTEXT_PROCESSOR.city_to_dict(value)
142    if isinstance(value, ASN):
143        return ASN_CONTEXT_PROCESSOR.asn_to_dict(value)
144    if isinstance(value, Path):
145        return cleanse_str(value)
146    if isinstance(value, Exception):
147        return cleanse_str(value)
148    if isinstance(value, YAMLTag):
149        return cleanse_str(value)
150    if isinstance(value, Enum):
151        return value.value
152    if isinstance(value, type):
153        return {
154            "type": value.__name__,
155            "module": value.__module__,
156        }
157    # See
158    # https://github.com/encode/django-rest-framework/blob/master/rest_framework/utils/encoders.py
159    # For Date Time string spec, see ECMA 262
160    # https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
161    if isinstance(value, datetime):
162        representation = value.isoformat()
163        if representation.endswith("+00:00"):
164            representation = representation[:-6] + "Z"
165        return representation
166    if isinstance(value, date):
167        return value.isoformat()
168    if isinstance(value, time):
169        if timezone and timezone.is_aware(value):
170            raise ValueError("JSON can't represent timezone-aware times.")
171        return value.isoformat()
172    if isinstance(value, timedelta):
173        return cleanse_str(value.total_seconds())
174    if callable(value):
175        return {
176            "type": "callable",
177            "name": value.__name__,
178            "module": value.__module__,
179        }
180    # List taken from the stdlib's JSON encoder (_make_iterencode, encoder.py:415)
181    if isinstance(value, bool | int | float | NoneType | list | tuple | dict):
182        return value
183    try:
184        return DjangoJSONEncoder().default(value)
185    except TypeError:
186        return cleanse_str(value)
187    return cleanse_str(value)
188
189
190def sanitize_dict(source: dict[Any, Any]) -> dict[Any, Any]:
191    """clean source of all Models that would interfere with the JSONField.
192    Models are replaced with a dictionary of {
193        app: str,
194        name: str,
195        pk: Any
196    }"""
197    final_dict = {}
198    for key, value in source.items():
199        new_value = sanitize_item(value)
200        if new_value is not ...:
201            final_dict[key] = new_value
202    return final_dict
ALLOWED_SPECIAL_KEYS = re.compile('passing|password_change_date|^auth_method(_args)?$|^revoke_tokens$', re.IGNORECASE)
def cleanse_str(raw: Any) -> str:
40def cleanse_str(raw: Any) -> str:
41    return str(raw).replace("\u0000", "")
def cleanse_item(key: str, value: Any) -> Any:
44def cleanse_item(key: str, value: Any) -> Any:
45    """Cleanse a single item"""
46    if isinstance(value, dict):
47        return cleanse_dict(value)
48    if isinstance(value, list | tuple | set):
49        return type(value)(cleanse_item(key, item) for item in value)
50    try:
51        if not SafeExceptionReporterFilter.hidden_settings.search(key):
52            return value
53        if ALLOWED_SPECIAL_KEYS.search(key):
54            return value
55        return SafeExceptionReporterFilter.cleansed_substitute
56    except TypeError:  # pragma: no cover
57        return value

Cleanse a single item

def cleanse_dict(source: dict[typing.Any, typing.Any]) -> dict[typing.Any, typing.Any]:
60def cleanse_dict(source: dict[Any, Any]) -> dict[Any, Any]:
61    """Cleanse a dictionary, recursively"""
62    final_dict = {}
63    for key, value in source.items():
64        new_value = cleanse_item(key, value)
65        if new_value is not ...:
66            final_dict[key] = new_value
67    return final_dict

Cleanse a dictionary, recursively

def model_to_dict(model: django.db.models.base.Model) -> dict[str, typing.Any]:
70def model_to_dict(model: Model) -> dict[str, Any]:
71    """Convert model to dict"""
72    name = cleanse_str(model)
73    if hasattr(model, "name"):
74        name = model.name
75    return {
76        "app": model._meta.app_label,
77        "model_name": model._meta.model_name,
78        "pk": model.pk,
79        "name": name,
80    }

Convert model to dict

def get_user( user: authentik.core.models.User | django.contrib.auth.models.AnonymousUser) -> dict[str, typing.Any]:
 83def get_user(user: User | AnonymousUser) -> dict[str, Any]:
 84    """Convert user object to dictionary"""
 85    if isinstance(user, AnonymousUser):
 86        try:
 87            user = get_anonymous_user()
 88        except User.DoesNotExist:
 89            return {}
 90    user_data = {
 91        "username": user.username,
 92        "pk": user.pk,
 93        "email": user.email,
 94    }
 95    if user.username == settings.ANONYMOUS_USER_NAME:
 96        user_data["is_anonymous"] = True
 97    # Actions performed by an actor are recorded on behalf of its parent, so the
 98    # audit log always ties the activity back to a responsible human.
 99    if getattr(user, "type", None) == UserTypes.SERVICE_ACCOUNT and hasattr(user, "actor"):
100        user_data["is_agent"] = True
101        # An actor without an owner acts for itself, so there is nobody to attribute to
102        if user.actor.parent:
103            user_data["on_behalf_of"] = get_user(user.actor.parent)
104    return user_data

Convert user object to dictionary

def sanitize_item(value: Any) -> Any:
107def sanitize_item(value: Any) -> Any:  # noqa: PLR0911, PLR0912
108    """Sanitize a single item, ensure it is JSON parsable"""
109    if is_dataclass(value):
110        # Because asdict calls `copy.deepcopy(obj)` on everything that's not tuple/dict,
111        # and deepcopy doesn't work with HttpRequest (neither django nor rest_framework).
112        # (more specifically doesn't work with ResolverMatch)
113        # rest_framework's custom Request class makes this more complicated as it also holds a
114        # thread lock.
115        # Since this class is mainly used for Events which already hold the http request context
116        # we just remove the http_request from the shallow policy request
117        # Currently, the only dataclass that actually holds an http request is a PolicyRequest
118        if isinstance(value, PolicyRequest) and value.http_request is not None:
119            value: PolicyRequest = copy(value)
120            value.http_request = None
121        value = asdict(value)
122    if isinstance(value, dict):
123        return sanitize_dict(value)
124    if isinstance(value, GeneratorType):
125        return sanitize_item(list(value))
126    if isinstance(value, list | tuple | set):
127        new_values = []
128        for item in value:
129            new_value = sanitize_item(item)
130            if new_value:
131                new_values.append(new_value)
132        return new_values
133    if isinstance(value, User | AnonymousUser):
134        return sanitize_dict(get_user(value))
135    if isinstance(value, models.Model):
136        return sanitize_dict(model_to_dict(value))
137    if isinstance(value, UUID):
138        return value.hex
139    if isinstance(value, HttpRequest | WSGIRequest):
140        return ...
141    if isinstance(value, City):
142        return GEOIP_CONTEXT_PROCESSOR.city_to_dict(value)
143    if isinstance(value, ASN):
144        return ASN_CONTEXT_PROCESSOR.asn_to_dict(value)
145    if isinstance(value, Path):
146        return cleanse_str(value)
147    if isinstance(value, Exception):
148        return cleanse_str(value)
149    if isinstance(value, YAMLTag):
150        return cleanse_str(value)
151    if isinstance(value, Enum):
152        return value.value
153    if isinstance(value, type):
154        return {
155            "type": value.__name__,
156            "module": value.__module__,
157        }
158    # See
159    # https://github.com/encode/django-rest-framework/blob/master/rest_framework/utils/encoders.py
160    # For Date Time string spec, see ECMA 262
161    # https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
162    if isinstance(value, datetime):
163        representation = value.isoformat()
164        if representation.endswith("+00:00"):
165            representation = representation[:-6] + "Z"
166        return representation
167    if isinstance(value, date):
168        return value.isoformat()
169    if isinstance(value, time):
170        if timezone and timezone.is_aware(value):
171            raise ValueError("JSON can't represent timezone-aware times.")
172        return value.isoformat()
173    if isinstance(value, timedelta):
174        return cleanse_str(value.total_seconds())
175    if callable(value):
176        return {
177            "type": "callable",
178            "name": value.__name__,
179            "module": value.__module__,
180        }
181    # List taken from the stdlib's JSON encoder (_make_iterencode, encoder.py:415)
182    if isinstance(value, bool | int | float | NoneType | list | tuple | dict):
183        return value
184    try:
185        return DjangoJSONEncoder().default(value)
186    except TypeError:
187        return cleanse_str(value)
188    return cleanse_str(value)

Sanitize a single item, ensure it is JSON parsable

def sanitize_dict(source: dict[typing.Any, typing.Any]) -> dict[typing.Any, typing.Any]:
191def sanitize_dict(source: dict[Any, Any]) -> dict[Any, Any]:
192    """clean source of all Models that would interfere with the JSONField.
193    Models are replaced with a dictionary of {
194        app: str,
195        name: str,
196        pk: Any
197    }"""
198    final_dict = {}
199    for key, value in source.items():
200        new_value = sanitize_item(value)
201        if new_value is not ...:
202            final_dict[key] = new_value
203    return final_dict

clean source of all Models that would interfere with the JSONField. Models are replaced with a dictionary of { app: str, name: str, pk: Any }