authentik.sources.ldap.tasks

LDAP Sync tasks

  1"""LDAP Sync tasks"""
  2
  3from typing import TYPE_CHECKING
  4from uuid import uuid4
  5
  6from django.core.cache import cache
  7from django.utils.translation import gettext_lazy as _
  8from dramatiq.actor import actor
  9from dramatiq.composition import group
 10from dramatiq.message import Message
 11from structlog.stdlib import get_logger
 12
 13from authentik.lib.config import CONFIG
 14from authentik.lib.sync.incoming.models import SyncOutgoingTriggerMode
 15from authentik.lib.sync.outgoing.exceptions import StopSync
 16from authentik.lib.sync.outgoing.models import OutgoingSyncProvider
 17from authentik.lib.sync.outgoing.signals import sync_outgoing_inhibit_dispatch
 18from authentik.lib.utils.reflection import all_subclasses, class_to_path, path_to_class
 19from authentik.sources.ldap.models import LDAPSource
 20from authentik.tasks.middleware import CurrentTask
 21from authentik.tasks.models import Task
 22
 23if TYPE_CHECKING:
 24    from authentik.sources.ldap.sync.base import BaseLDAPSynchronizer
 25
 26LOGGER = get_logger()
 27CACHE_KEY_PREFIX = "goauthentik.io/sources/ldap/page/"
 28CACHE_KEY_STATUS = "goauthentik.io/sources/ldap/status/"
 29
 30
 31@actor(description=_("Check connectivity for LDAP source."))
 32def ldap_connectivity_check(pk: str | None = None):
 33    """Check connectivity for LDAP Sources"""
 34    timeout = 60 * 60 * 2
 35    source = LDAPSource.objects.filter(pk=pk, enabled=True).first()
 36    if not source:
 37        return
 38    status = source.check_connection()
 39    cache.set(CACHE_KEY_STATUS + source.slug, status, timeout=timeout)
 40
 41
 42@actor(
 43    # We take the configured hours timeout time by 3.5 as we run user and
 44    # group in parallel and then membership, then deletions, so 3x is to cover the serial tasks,
 45    # and 0.5x on top of that to give some more leeway
 46    time_limit=(60 * 60 * CONFIG.get_int("ldap.task_timeout_hours") * 1000) * 3.5,
 47    description=_("Sync LDAP source."),
 48)
 49def ldap_sync(source_pk: str):
 50    """Sync a single source"""
 51    # Sync classes pull in ldap3, only import them when an LDAP source is synced
 52    from authentik.sources.ldap.sync.forward_delete_groups import GroupLDAPForwardDeletion
 53    from authentik.sources.ldap.sync.forward_delete_users import UserLDAPForwardDeletion
 54    from authentik.sources.ldap.sync.groups import GroupLDAPSynchronizer
 55    from authentik.sources.ldap.sync.membership import (
 56        GroupHierarchyLDAPSynchronizer,
 57        MembershipLDAPSynchronizer,
 58    )
 59    from authentik.sources.ldap.sync.users import UserLDAPSynchronizer
 60
 61    task = CurrentTask.get_task()
 62    source: LDAPSource = LDAPSource.objects.filter(pk=source_pk, enabled=True).first()
 63    if not source:
 64        return
 65    with source.sync_lock as lock_acquired:
 66        if not lock_acquired:
 67            task.info("Synchronization is already running. Skipping")
 68            LOGGER.debug("Failed to acquire lock for LDAP sync, skipping task", source=source.slug)
 69            return
 70
 71        user_group_tasks = group(
 72            ldap_sync_paginator(task, source, UserLDAPSynchronizer)
 73            + ldap_sync_paginator(task, source, GroupLDAPSynchronizer)
 74        )
 75
 76        membership_tasks = group(
 77            ldap_sync_paginator(task, source, MembershipLDAPSynchronizer)
 78            + ldap_sync_paginator(task, source, GroupHierarchyLDAPSynchronizer)
 79        )
 80
 81        deletion_tasks = group(
 82            ldap_sync_paginator(task, source, UserLDAPForwardDeletion)
 83            + ldap_sync_paginator(task, source, GroupLDAPForwardDeletion),
 84        )
 85
 86        # User and group sync can happen at once, they have no dependencies on each other
 87        user_group_tasks.run().wait(
 88            timeout=60 * 60 * CONFIG.get_int("ldap.task_timeout_hours") * 1000
 89        )
 90        # Membership sync needs to run afterwards
 91        membership_tasks.run().wait(
 92            timeout=60 * 60 * CONFIG.get_int("ldap.task_timeout_hours") * 1000
 93        )
 94        # Finally, deletions. What we'd really like to do here is something like
 95        # ```
 96        # user_identifiers = <ldap query>
 97        # User.objects.exclude(
 98        #     usersourceconnection__identifier__in=user_uniqueness_identifiers,
 99        # ).delete()
100        # ```
101        # This runs into performance issues in large installations. So instead we spread the
102        # work out into three steps:
103        # 1. Get every object from the LDAP source.
104        # 2. Mark every object as "safe" in the database. This is quick, but any error could
105        #    mean deleting users which should not be deleted, so we do it immediately, in
106        #    large chunks, and only queue the deletion step afterwards.
107        # 3. Delete every unmarked item. This is slow, so we spread it over many tasks in
108        #    small chunks.
109        deletion_tasks.run().wait(
110            timeout=60 * 60 * CONFIG.get_int("ldap.task_timeout_hours") * 1000,
111        )
112
113    if source.sync_outgoing_trigger_mode == SyncOutgoingTriggerMode.DEFERRED_END:
114        for outgoing_sync_provider_cls in all_subclasses(OutgoingSyncProvider):
115            for provider in outgoing_sync_provider_cls.objects.all():
116                provider.sync_dispatch()
117
118
119def ldap_sync_paginator(
120    task: Task, source: LDAPSource, sync: type[BaseLDAPSynchronizer]
121) -> list[Message]:
122    """Return a list of task signatures with LDAP pagination data"""
123    sync_inst: BaseLDAPSynchronizer = sync(source, task)
124    messages = []
125    for page in sync_inst.get_objects():
126        page_uid = str(uuid4())
127        page_cache_key = CACHE_KEY_PREFIX + page_uid
128        cache.set(page_cache_key, page, 60 * 60 * CONFIG.get_int("ldap.task_timeout_hours"))
129        page_sync = ldap_sync_page.message_with_options(
130            args=(source.pk, class_to_path(sync), page_cache_key),
131            rel_obj=task.rel_obj,
132            uid=f"{source.slug}:{sync_inst.name()}:{page_uid}",
133        )
134        messages.append(page_sync)
135    return messages
136
137
138@actor(
139    time_limit=60 * 60 * CONFIG.get_int("ldap.task_timeout_hours") * 1000,
140    description=_("Sync page for LDAP source."),
141)
142def ldap_sync_page(source_pk: str, sync_class: str, page_cache_key: str):
143    """Synchronization of an LDAP Source"""
144    from ldap3.core.exceptions import LDAPException
145
146    self = CurrentTask.get_task()
147    source: LDAPSource = LDAPSource.objects.filter(pk=source_pk).first()
148    if not source:
149        # Because the source couldn't be found, we don't have a UID
150        # to set the state with
151        return
152    sync: type[BaseLDAPSynchronizer] = path_to_class(sync_class)
153    try:
154        sync_inst: BaseLDAPSynchronizer = sync(source, self)
155        page = cache.get(page_cache_key)
156        if not page:
157            error_message = (
158                f"Could not find page in cache: {page_cache_key}. "
159                + "Try increasing ldap.task_timeout_hours"
160            )
161            LOGGER.warning(error_message)
162            self.error(error_message)
163            return
164        cache.touch(page_cache_key)
165        if source.sync_outgoing_trigger_mode == SyncOutgoingTriggerMode.IMMEDIATE:
166            count = sync_inst.sync(page)
167        else:
168            with sync_outgoing_inhibit_dispatch():
169                count = sync_inst.sync(page)
170        self.info(f"Synced {count} objects.")
171        cache.delete(page_cache_key)
172    except (LDAPException, StopSync) as exc:
173        # No explicit event is created here as .error will do that
174        LOGGER.warning("Failed to sync LDAP", exc=exc, source=source)
175        self.error(exc)
176        raise exc
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
CACHE_KEY_PREFIX = 'goauthentik.io/sources/ldap/page/'
CACHE_KEY_STATUS = 'goauthentik.io/sources/ldap/status/'
ldap_connectivity_check = Actor(<function ldap_connectivity_check>, queue_name='default', actor_name='ldap_connectivity_check')

Check connectivity for LDAP Sources

ldap_sync = Actor(<function ldap_sync>, queue_name='default', actor_name='ldap_sync')

Sync a single source

def ldap_sync_paginator(unknown):
120def ldap_sync_paginator(
121    task: Task, source: LDAPSource, sync: type[BaseLDAPSynchronizer]
122) -> list[Message]:
123    """Return a list of task signatures with LDAP pagination data"""
124    sync_inst: BaseLDAPSynchronizer = sync(source, task)
125    messages = []
126    for page in sync_inst.get_objects():
127        page_uid = str(uuid4())
128        page_cache_key = CACHE_KEY_PREFIX + page_uid
129        cache.set(page_cache_key, page, 60 * 60 * CONFIG.get_int("ldap.task_timeout_hours"))
130        page_sync = ldap_sync_page.message_with_options(
131            args=(source.pk, class_to_path(sync), page_cache_key),
132            rel_obj=task.rel_obj,
133            uid=f"{source.slug}:{sync_inst.name()}:{page_uid}",
134        )
135        messages.append(page_sync)
136    return messages

Return a list of task signatures with LDAP pagination data

ldap_sync_page = Actor(<function ldap_sync_page>, queue_name='default', actor_name='ldap_sync_page')

Synchronization of an LDAP Source