authentik.events.tasks
Event notification tasks
1"""Event notification tasks""" 2 3from uuid import UUID 4 5from django.db.models import Prefetch, Q, QuerySet 6from django.utils.translation import gettext_lazy as _ 7from dramatiq.actor import actor 8from guardian.shortcuts import get_anonymous_user 9from structlog.stdlib import get_logger 10 11from authentik.core.models import User 12from authentik.events.models import ( 13 Event, 14 Notification, 15 NotificationRule, 16 NotificationTransport, 17) 18from authentik.lib.utils.db import chunked_queryset 19from authentik.policies.engine import PolicyEngine 20from authentik.policies.models import PolicyBinding, PolicyEngineMode 21from authentik.tasks.middleware import CurrentTask 22 23LOGGER = get_logger() 24 25 26class PrefetchedPolicyEngine(PolicyEngine): 27 """Policy engine evaluating a pre-fetched list of bindings instead of querying them""" 28 29 def __init__(self, pbm: NotificationRule, user: User, bindings: list[PolicyBinding]): 30 super().__init__(pbm, user) 31 self.__bindings = bindings 32 33 def bindings(self): 34 return self.__bindings 35 36 37@actor(description=_("Dispatch new event notifications.")) 38def event_trigger_dispatch(event_uuid: UUID): 39 """Check all NotificationRules against an event in one pass""" 40 _evaluate_rules(event_uuid, NotificationRule.objects.all()) 41 42 43@actor( 44 description=_( 45 "Check if policies attached to NotificationRule match event " 46 "and dispatch notification tasks." 47 ) 48) 49def event_trigger_handler(event_uuid: UUID, trigger_name: str): 50 """Check if policies attached to NotificationRule match event""" 51 # only kept for messages enqueued before upgrading, remove in a later release 52 _evaluate_rules(event_uuid, NotificationRule.objects.filter(name=trigger_name)) 53 54 55def _evaluate_rules(event_uuid: UUID, rules: QuerySet[NotificationRule]): 56 self = CurrentTask.get_task() 57 58 event: Event = Event.objects.filter(event_uuid=event_uuid).first() 59 if not event: 60 self.warning("event doesn't exist yet or anymore", event_uuid=event_uuid) 61 return 62 63 if "policy_uuid" in event.context: 64 policy_uuid = event.context["policy_uuid"] 65 if PolicyBinding.objects.filter( 66 target__in=NotificationRule.objects.all().values_list("pbm_uuid", flat=True), 67 policy=policy_uuid, 68 ).exists(): 69 # If policy that caused this event to be created is attached 70 # to *any* NotificationRule, we return early. 71 # This is the most effective way to prevent infinite loops. 72 LOGGER.debug("e(trigger): attempting to prevent infinite loop", event_uuid=event_uuid) 73 return 74 75 rules = rules.prefetch_related( 76 Prefetch( 77 "bindings", 78 queryset=PolicyBinding.objects.filter(enabled=True) 79 .select_related("user", "group") 80 .order_by("order"), 81 to_attr="enabled_bindings", 82 ), 83 # Resolves policy subclasses for all bindings in one query 84 "enabled_bindings__policy", 85 "transports", 86 ) 87 # Rules without bindings never match (empty_result is False below) 88 rules = [rule for rule in rules if rule.enabled_bindings] 89 if not rules: 90 return 91 92 user = User.objects.filter(pk=event.user.get("pk")).first() or get_anonymous_user() 93 count = 0 94 for trigger in rules: 95 LOGGER.debug("e(trigger): checking if trigger applies", trigger=trigger) 96 policy_engine = PrefetchedPolicyEngine(trigger, user, trigger.enabled_bindings) 97 policy_engine.mode = PolicyEngineMode.MODE_ANY 98 policy_engine.empty_result = False 99 policy_engine.use_cache = False 100 policy_engine.request.obj = event 101 policy_engine.request.context["event"] = event 102 policy_engine.build() 103 if not policy_engine.result.passing: 104 continue 105 106 LOGGER.debug("e(trigger): event trigger matched", trigger=trigger) 107 # Create the notification objects 108 for transport in trigger.transports.all(): 109 for destination in trigger.destination_users(event): 110 notification_transport.send_with_options( 111 args=( 112 transport.pk, 113 event.pk, 114 destination.pk, 115 trigger.pk, 116 ), 117 rel_obj=transport, 118 ) 119 count += 1 120 if transport.send_once: 121 break 122 self.info(f"Created {count} notification tasks") 123 124 125@actor(description=_("Send notification.")) 126def notification_transport(transport_pk: int, event_pk: str, user_pk: int, trigger_pk: str): 127 """Send notification over specified transport""" 128 event = Event.objects.filter(pk=event_pk).first() 129 if not event: 130 return 131 user = User.objects.filter(pk=user_pk).first() 132 if not user: 133 return 134 trigger = NotificationRule.objects.filter(pk=trigger_pk).first() 135 if not trigger: 136 return 137 notification = Notification( 138 severity=trigger.severity, 139 body=event.summary, 140 event=event, 141 user=user, 142 hyperlink=event.hyperlink, 143 hyperlink_label=event.hyperlink_label, 144 ) 145 transport: NotificationTransport = NotificationTransport.objects.filter(pk=transport_pk).first() 146 if not transport: 147 return 148 transport.send(notification) 149 150 151@actor(description=_("Cleanup events for GDPR compliance.")) 152def gdpr_cleanup(user_pk: int): 153 """cleanup events from gdpr_compliance""" 154 events = Event.objects.filter(user__pk=user_pk) 155 LOGGER.debug("GDPR cleanup, removing events from user", events=events.count()) 156 for event in chunked_queryset(events): 157 event.delete() 158 159 160@actor(description=_("Cleanup seen notifications and notifications whose event expired.")) 161def notification_cleanup(): 162 """Cleanup seen notifications and notifications whose event expired.""" 163 self = CurrentTask.get_task() 164 notifications = Notification.objects.filter(Q(event=None) | Q(seen=True)) 165 amount = notifications.count() 166 notifications.delete() 167 LOGGER.debug("Expired notifications", amount=amount) 168 self.info(f"Expired {amount} Notifications")
LOGGER =
<BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
27class PrefetchedPolicyEngine(PolicyEngine): 28 """Policy engine evaluating a pre-fetched list of bindings instead of querying them""" 29 30 def __init__(self, pbm: NotificationRule, user: User, bindings: list[PolicyBinding]): 31 super().__init__(pbm, user) 32 self.__bindings = bindings 33 34 def bindings(self): 35 return self.__bindings
Policy engine evaluating a pre-fetched list of bindings instead of querying them
PrefetchedPolicyEngine( pbm: authentik.events.models.NotificationRule, user: authentik.core.models.User, bindings: list[authentik.policies.models.PolicyBinding])
event_trigger_dispatch =
Actor(<function event_trigger_dispatch>, queue_name='default', actor_name='event_trigger_dispatch')
Check all NotificationRules against an event in one pass
event_trigger_handler =
Actor(<function event_trigger_handler>, queue_name='default', actor_name='event_trigger_handler')
Check if policies attached to NotificationRule match event
notification_transport =
Actor(<function notification_transport>, queue_name='default', actor_name='notification_transport')
Send notification over specified transport
gdpr_cleanup =
Actor(<function gdpr_cleanup>, queue_name='default', actor_name='gdpr_cleanup')
cleanup events from gdpr_compliance
notification_cleanup =
Actor(<function notification_cleanup>, queue_name='default', actor_name='notification_cleanup')
Cleanup seen notifications and notifications whose event expired.