authentik.sources.ldap.sync.users

Sync LDAP Users into authentik

  1"""Sync LDAP Users into authentik"""
  2
  3from collections.abc import Generator
  4from typing import Any
  5
  6from django.core.exceptions import FieldError
  7from django.db.utils import IntegrityError
  8from ldap3 import ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES, SUBTREE
  9
 10from authentik.core.expression.exceptions import (
 11    PropertyMappingExpressionException,
 12    SkipObjectException,
 13)
 14from authentik.core.models import User
 15from authentik.core.sources.mapper import SourceMapper
 16from authentik.core.sources.matcher import Action
 17from authentik.events.models import Event, EventAction
 18from authentik.lib.sync.outgoing.exceptions import StopSync
 19from authentik.lib.utils.errors import exception_to_dict
 20from authentik.sources.ldap.models import (
 21    LDAP_UNIQUENESS,
 22    LDAPSource,
 23    UserLDAPSourceConnection,
 24    flatten,
 25)
 26from authentik.sources.ldap.sync.base import BaseLDAPSynchronizer
 27from authentik.sources.ldap.sync.vendor.freeipa import FreeIPA
 28from authentik.sources.ldap.sync.vendor.ms_ad import MicrosoftActiveDirectory
 29from authentik.tasks.models import Task
 30
 31
 32class UserLDAPSynchronizer(BaseLDAPSynchronizer):
 33    """Sync LDAP Users into authentik"""
 34
 35    def __init__(self, source: LDAPSource, task: Task):
 36        super().__init__(source, task)
 37        self.mapper = SourceMapper(source)
 38        self.manager = self.mapper.get_manager(User, ["ldap", "dn"])
 39
 40    @staticmethod
 41    def name() -> str:
 42        return "users"
 43
 44    def get_objects(self, **kwargs) -> Generator:
 45        if not self._source.sync_users:
 46            self._task.info("User syncing is disabled for this Source")
 47            return iter(())
 48        return self.search_paginator(
 49            search_base=self.base_dn_users,
 50            search_filter=self._source.user_object_filter,
 51            search_scope=SUBTREE,
 52            attributes=[
 53                ALL_ATTRIBUTES,
 54                ALL_OPERATIONAL_ATTRIBUTES,
 55                self._source.object_uniqueness_field,
 56            ],
 57            **kwargs,
 58        )
 59
 60    @staticmethod
 61    def get_account_properties(
 62        attributes: dict[str, Any],
 63        syncers: tuple[MicrosoftActiveDirectory, FreeIPA],
 64    ) -> dict[str, bool]:
 65        """Combine directory restrictions, leaving unmapped account status unchanged."""
 66        # Evaluate every handler so one cannot override another's restriction or hide an error.
 67        account_states = [
 68            state
 69            for syncer in syncers
 70            if (state := syncer.get_account_active(attributes)) is not None
 71        ]
 72        if not account_states:
 73            return {}
 74        return {"is_active": all(account_states)}
 75
 76    def sync(self, page_data: list) -> int:
 77        """Iterate over all LDAP Users and create authentik_core.User instances"""
 78        if not self._source.sync_users:
 79            self._task.info("User syncing is disabled for this Source")
 80            return -1
 81        user_count = 0
 82
 83        ms_ad_syncer = MicrosoftActiveDirectory(self._source, self._task)
 84        freeipa_syncer = FreeIPA(self._source, self._task)
 85
 86        for user in page_data:
 87            if (attributes := self.get_attributes(user)) is None:
 88                continue
 89            user_dn = flatten(user.get("entryDN", user.get("dn")))
 90            if not (uniq := self.get_identifier(attributes)):
 91                self._task.info(
 92                    f"Uniqueness field not found/not set in attributes: '{user_dn}'",
 93                    attributes=list(attributes.keys()),
 94                    dn=user_dn,
 95                )
 96                continue
 97            try:
 98                defaults = {
 99                    k: flatten(v)
100                    for k, v in self.mapper.build_object_properties(
101                        object_type=User,
102                        manager=self.manager,
103                        user=None,
104                        request=None,
105                        dn=user_dn,
106                        ldap=attributes,
107                    ).items()
108                }
109                defaults.update(
110                    self.get_account_properties(attributes, (ms_ad_syncer, freeipa_syncer))
111                )
112                self._logger.debug("Writing user with attributes", attributes=defaults)
113                if "username" not in defaults:
114                    raise IntegrityError("Username was not set by propertymappings")
115                action, connection = self.matcher.get_user_action(uniq, defaults)
116                created = False
117                if action == Action.ENROLL:
118                    # Legacy fallback, in case the user only has an `ldap_uniq` attribute set, but
119                    # no source connection exists yet
120                    legacy_user = User.objects.filter(
121                        **{
122                            f"attributes__{LDAP_UNIQUENESS}": uniq,
123                        }
124                    ).first()
125                    if legacy_user and LDAP_UNIQUENESS in legacy_user.attributes:
126                        connection = UserLDAPSourceConnection(
127                            source=self._source,
128                            user=legacy_user,
129                            identifier=legacy_user.attributes.get(LDAP_UNIQUENESS),
130                        )
131                        ak_user = legacy_user
132                        # Switch the action to update the attributes
133                        action = Action.AUTH
134                    else:
135                        ak_user = User.objects.create(**defaults)
136                        created = True
137                        connection.user = ak_user
138                    connection.save()
139
140                if action in (Action.AUTH, Action.LINK):
141                    ak_user = connection.user
142                    ak_user.update_attributes(defaults)
143                    connection.save()
144                elif action == Action.DENY:
145                    continue
146            except PropertyMappingExpressionException as exc:
147                raise StopSync(exc, None, exc.mapping) from exc
148            except SkipObjectException:
149                continue
150            except (IntegrityError, FieldError, TypeError, AttributeError) as exc:
151                self._logger.debug("failed to create user", exc=exc)
152                Event.new(
153                    EventAction.CONFIGURATION_ERROR,
154                    message=(
155                        "Failed to create user; "
156                        "To merge new user with existing user, connect it via the LDAP Source's "
157                        "'Synced Users' tab."
158                    ),
159                    exception=exception_to_dict(exc),
160                    source=self._source,
161                    dn=user_dn,
162                ).save()
163            else:
164                self._logger.debug("Synced User", user=ak_user.username, created=created)
165                user_count += 1
166                ms_ad_syncer.sync(attributes, ak_user, created)
167                freeipa_syncer.sync(attributes, ak_user, created)
168        return user_count
class UserLDAPSynchronizer(authentik.sources.ldap.sync.base.BaseLDAPSynchronizer):
 33class UserLDAPSynchronizer(BaseLDAPSynchronizer):
 34    """Sync LDAP Users into authentik"""
 35
 36    def __init__(self, source: LDAPSource, task: Task):
 37        super().__init__(source, task)
 38        self.mapper = SourceMapper(source)
 39        self.manager = self.mapper.get_manager(User, ["ldap", "dn"])
 40
 41    @staticmethod
 42    def name() -> str:
 43        return "users"
 44
 45    def get_objects(self, **kwargs) -> Generator:
 46        if not self._source.sync_users:
 47            self._task.info("User syncing is disabled for this Source")
 48            return iter(())
 49        return self.search_paginator(
 50            search_base=self.base_dn_users,
 51            search_filter=self._source.user_object_filter,
 52            search_scope=SUBTREE,
 53            attributes=[
 54                ALL_ATTRIBUTES,
 55                ALL_OPERATIONAL_ATTRIBUTES,
 56                self._source.object_uniqueness_field,
 57            ],
 58            **kwargs,
 59        )
 60
 61    @staticmethod
 62    def get_account_properties(
 63        attributes: dict[str, Any],
 64        syncers: tuple[MicrosoftActiveDirectory, FreeIPA],
 65    ) -> dict[str, bool]:
 66        """Combine directory restrictions, leaving unmapped account status unchanged."""
 67        # Evaluate every handler so one cannot override another's restriction or hide an error.
 68        account_states = [
 69            state
 70            for syncer in syncers
 71            if (state := syncer.get_account_active(attributes)) is not None
 72        ]
 73        if not account_states:
 74            return {}
 75        return {"is_active": all(account_states)}
 76
 77    def sync(self, page_data: list) -> int:
 78        """Iterate over all LDAP Users and create authentik_core.User instances"""
 79        if not self._source.sync_users:
 80            self._task.info("User syncing is disabled for this Source")
 81            return -1
 82        user_count = 0
 83
 84        ms_ad_syncer = MicrosoftActiveDirectory(self._source, self._task)
 85        freeipa_syncer = FreeIPA(self._source, self._task)
 86
 87        for user in page_data:
 88            if (attributes := self.get_attributes(user)) is None:
 89                continue
 90            user_dn = flatten(user.get("entryDN", user.get("dn")))
 91            if not (uniq := self.get_identifier(attributes)):
 92                self._task.info(
 93                    f"Uniqueness field not found/not set in attributes: '{user_dn}'",
 94                    attributes=list(attributes.keys()),
 95                    dn=user_dn,
 96                )
 97                continue
 98            try:
 99                defaults = {
100                    k: flatten(v)
101                    for k, v in self.mapper.build_object_properties(
102                        object_type=User,
103                        manager=self.manager,
104                        user=None,
105                        request=None,
106                        dn=user_dn,
107                        ldap=attributes,
108                    ).items()
109                }
110                defaults.update(
111                    self.get_account_properties(attributes, (ms_ad_syncer, freeipa_syncer))
112                )
113                self._logger.debug("Writing user with attributes", attributes=defaults)
114                if "username" not in defaults:
115                    raise IntegrityError("Username was not set by propertymappings")
116                action, connection = self.matcher.get_user_action(uniq, defaults)
117                created = False
118                if action == Action.ENROLL:
119                    # Legacy fallback, in case the user only has an `ldap_uniq` attribute set, but
120                    # no source connection exists yet
121                    legacy_user = User.objects.filter(
122                        **{
123                            f"attributes__{LDAP_UNIQUENESS}": uniq,
124                        }
125                    ).first()
126                    if legacy_user and LDAP_UNIQUENESS in legacy_user.attributes:
127                        connection = UserLDAPSourceConnection(
128                            source=self._source,
129                            user=legacy_user,
130                            identifier=legacy_user.attributes.get(LDAP_UNIQUENESS),
131                        )
132                        ak_user = legacy_user
133                        # Switch the action to update the attributes
134                        action = Action.AUTH
135                    else:
136                        ak_user = User.objects.create(**defaults)
137                        created = True
138                        connection.user = ak_user
139                    connection.save()
140
141                if action in (Action.AUTH, Action.LINK):
142                    ak_user = connection.user
143                    ak_user.update_attributes(defaults)
144                    connection.save()
145                elif action == Action.DENY:
146                    continue
147            except PropertyMappingExpressionException as exc:
148                raise StopSync(exc, None, exc.mapping) from exc
149            except SkipObjectException:
150                continue
151            except (IntegrityError, FieldError, TypeError, AttributeError) as exc:
152                self._logger.debug("failed to create user", exc=exc)
153                Event.new(
154                    EventAction.CONFIGURATION_ERROR,
155                    message=(
156                        "Failed to create user; "
157                        "To merge new user with existing user, connect it via the LDAP Source's "
158                        "'Synced Users' tab."
159                    ),
160                    exception=exception_to_dict(exc),
161                    source=self._source,
162                    dn=user_dn,
163                ).save()
164            else:
165                self._logger.debug("Synced User", user=ak_user.username, created=created)
166                user_count += 1
167                ms_ad_syncer.sync(attributes, ak_user, created)
168                freeipa_syncer.sync(attributes, ak_user, created)
169        return user_count

Sync LDAP Users into authentik

UserLDAPSynchronizer( source: authentik.sources.ldap.models.LDAPSource, task: authentik.tasks.models.Task)
36    def __init__(self, source: LDAPSource, task: Task):
37        super().__init__(source, task)
38        self.mapper = SourceMapper(source)
39        self.manager = self.mapper.get_manager(User, ["ldap", "dn"])
mapper
manager
@staticmethod
def name() -> str:
41    @staticmethod
42    def name() -> str:
43        return "users"

UI name for the type of object this class synchronizes

def get_objects(self, **kwargs) -> Generator:
45    def get_objects(self, **kwargs) -> Generator:
46        if not self._source.sync_users:
47            self._task.info("User syncing is disabled for this Source")
48            return iter(())
49        return self.search_paginator(
50            search_base=self.base_dn_users,
51            search_filter=self._source.user_object_filter,
52            search_scope=SUBTREE,
53            attributes=[
54                ALL_ATTRIBUTES,
55                ALL_OPERATIONAL_ATTRIBUTES,
56                self._source.object_uniqueness_field,
57            ],
58            **kwargs,
59        )

Get objects from LDAP, implemented in subclass

@staticmethod
def get_account_properties( attributes: dict[str, typing.Any], syncers: tuple[authentik.sources.ldap.sync.vendor.ms_ad.MicrosoftActiveDirectory, authentik.sources.ldap.sync.vendor.freeipa.FreeIPA]) -> dict[str, bool]:
61    @staticmethod
62    def get_account_properties(
63        attributes: dict[str, Any],
64        syncers: tuple[MicrosoftActiveDirectory, FreeIPA],
65    ) -> dict[str, bool]:
66        """Combine directory restrictions, leaving unmapped account status unchanged."""
67        # Evaluate every handler so one cannot override another's restriction or hide an error.
68        account_states = [
69            state
70            for syncer in syncers
71            if (state := syncer.get_account_active(attributes)) is not None
72        ]
73        if not account_states:
74            return {}
75        return {"is_active": all(account_states)}

Combine directory restrictions, leaving unmapped account status unchanged.

def sync(self, page_data: list) -> int:
 77    def sync(self, page_data: list) -> int:
 78        """Iterate over all LDAP Users and create authentik_core.User instances"""
 79        if not self._source.sync_users:
 80            self._task.info("User syncing is disabled for this Source")
 81            return -1
 82        user_count = 0
 83
 84        ms_ad_syncer = MicrosoftActiveDirectory(self._source, self._task)
 85        freeipa_syncer = FreeIPA(self._source, self._task)
 86
 87        for user in page_data:
 88            if (attributes := self.get_attributes(user)) is None:
 89                continue
 90            user_dn = flatten(user.get("entryDN", user.get("dn")))
 91            if not (uniq := self.get_identifier(attributes)):
 92                self._task.info(
 93                    f"Uniqueness field not found/not set in attributes: '{user_dn}'",
 94                    attributes=list(attributes.keys()),
 95                    dn=user_dn,
 96                )
 97                continue
 98            try:
 99                defaults = {
100                    k: flatten(v)
101                    for k, v in self.mapper.build_object_properties(
102                        object_type=User,
103                        manager=self.manager,
104                        user=None,
105                        request=None,
106                        dn=user_dn,
107                        ldap=attributes,
108                    ).items()
109                }
110                defaults.update(
111                    self.get_account_properties(attributes, (ms_ad_syncer, freeipa_syncer))
112                )
113                self._logger.debug("Writing user with attributes", attributes=defaults)
114                if "username" not in defaults:
115                    raise IntegrityError("Username was not set by propertymappings")
116                action, connection = self.matcher.get_user_action(uniq, defaults)
117                created = False
118                if action == Action.ENROLL:
119                    # Legacy fallback, in case the user only has an `ldap_uniq` attribute set, but
120                    # no source connection exists yet
121                    legacy_user = User.objects.filter(
122                        **{
123                            f"attributes__{LDAP_UNIQUENESS}": uniq,
124                        }
125                    ).first()
126                    if legacy_user and LDAP_UNIQUENESS in legacy_user.attributes:
127                        connection = UserLDAPSourceConnection(
128                            source=self._source,
129                            user=legacy_user,
130                            identifier=legacy_user.attributes.get(LDAP_UNIQUENESS),
131                        )
132                        ak_user = legacy_user
133                        # Switch the action to update the attributes
134                        action = Action.AUTH
135                    else:
136                        ak_user = User.objects.create(**defaults)
137                        created = True
138                        connection.user = ak_user
139                    connection.save()
140
141                if action in (Action.AUTH, Action.LINK):
142                    ak_user = connection.user
143                    ak_user.update_attributes(defaults)
144                    connection.save()
145                elif action == Action.DENY:
146                    continue
147            except PropertyMappingExpressionException as exc:
148                raise StopSync(exc, None, exc.mapping) from exc
149            except SkipObjectException:
150                continue
151            except (IntegrityError, FieldError, TypeError, AttributeError) as exc:
152                self._logger.debug("failed to create user", exc=exc)
153                Event.new(
154                    EventAction.CONFIGURATION_ERROR,
155                    message=(
156                        "Failed to create user; "
157                        "To merge new user with existing user, connect it via the LDAP Source's "
158                        "'Synced Users' tab."
159                    ),
160                    exception=exception_to_dict(exc),
161                    source=self._source,
162                    dn=user_dn,
163                ).save()
164            else:
165                self._logger.debug("Synced User", user=ak_user.username, created=created)
166                user_count += 1
167                ms_ad_syncer.sync(attributes, ak_user, created)
168                freeipa_syncer.sync(attributes, ak_user, created)
169        return user_count

Iterate over all LDAP Users and create authentik_core.User instances