authentik.core.tasks

authentik core tasks

 1"""authentik core tasks"""
 2
 3from contextlib import contextmanager
 4from datetime import datetime, timedelta
 5
 6from django.utils.timezone import now
 7from django.utils.translation import gettext_lazy as _
 8from django_channels_postgres.models import GroupChannel, Message
 9from django_postgres_cache.tasks import clear_expired_cache
10from dramatiq.actor import actor
11from structlog.stdlib import get_logger
12
13from authentik.core.models import (
14    USER_ATTRIBUTE_EXPIRES,
15    USER_ATTRIBUTE_GENERATED,
16    User,
17)
18from authentik.lib.models import ExpiringModel
19from authentik.lib.sync.models import Sync
20from authentik.lib.utils.db import chunked_queryset, delete_in_batches
21from authentik.tasks.middleware import CurrentTask
22
23LOGGER = get_logger()
24
25
26@actor(description=_("Remove expired objects."))
27def clean_expired_models():
28    self = CurrentTask.get_task()
29    errors: list[Exception] = []
30
31    @contextmanager
32    def isolated(name: str):
33        """A failure to clean up one kind of object must not prevent the cleanup of the
34        others. The first error is raised again once everything has been attempted."""
35        try:
36            yield
37        except Exception as exc:  # noqa: BLE001
38            LOGGER.warning("Failed to expire models", model=name, exc=exc)
39            self.warning(f"Failed to expire {name}: {exc}")
40            errors.append(exc)
41
42    for cls in ExpiringModel.__subclasses__():
43        with isolated(cls._meta.verbose_name_plural):
44            objects = cls.objects.including_expired().filter(expiring=True)
45            amount = 0
46            # Separate queries, because with an OR Postgres can no longer stop the index scan
47            # at now() and filters every row once fewer than a batch's worth have expired.
48            for expired in (objects.filter(expires__lte=now()), objects.filter(expires=None)):
49                if cls.expire_action is ExpiringModel.expire_action:
50                    amount += delete_in_batches(expired, order_by="expires")
51                else:
52                    amount += expired.count()
53                    for obj in chunked_queryset(expired):
54                        obj.expire_action()
55            LOGGER.debug("Expired models", model=cls, amount=amount)
56            self.info(f"Expired {amount} {cls._meta.verbose_name_plural}")
57    with isolated("cache entries"):
58        clear_expired_cache()
59    for cls in [Message, GroupChannel]:
60        with isolated(cls._meta.verbose_name_plural):
61            amount = delete_in_batches(cls.objects.filter(expires__lt=now()), order_by="expires")
62            LOGGER.debug("Expired models", model=cls, amount=amount)
63            self.info(f"Expired {amount} {cls._meta.verbose_name_plural}")
64    for cls in Sync.__subclasses__():
65        with isolated(cls._meta.verbose_name_plural):
66            amount = cls.cleanup()
67            LOGGER.debug("Expired models", model=cls, amount=amount)
68    if errors:
69        raise errors[0]
70
71
72@actor(description=_("Remove temporary users created by SAML Sources."))
73def clean_temporary_users():
74    self = CurrentTask.get_task()
75    _now = datetime.now()
76    deleted_users = 0
77    for user in User.objects.filter(**{f"attributes__{USER_ATTRIBUTE_GENERATED}": True}):
78        if not user.attributes.get(USER_ATTRIBUTE_EXPIRES):
79            continue
80        delta: timedelta = _now - datetime.fromtimestamp(
81            user.attributes.get(USER_ATTRIBUTE_EXPIRES)
82        )
83        if delta.total_seconds() > 0:
84            LOGGER.debug("User is expired and will be deleted.", user=user, delta=delta)
85            user.delete()
86            deleted_users += 1
87    self.info(f"Successfully deleted {deleted_users} users.")
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>