authentik.sources.ldap.sync.membership

Sync LDAP Users and groups into authentik

  1"""Sync LDAP Users and groups into authentik"""
  2
  3from collections.abc import Generator
  4from typing import Any
  5
  6from django.db.models import Q
  7from ldap3 import SUBTREE
  8from ldap3.utils.conv import escape_filter_chars
  9
 10from authentik.core.models import Group, User
 11from authentik.sources.ldap.models import (
 12    LDAP_DISTINGUISHED_NAME,
 13    GroupLDAPSourceConnection,
 14    LDAPSource,
 15)
 16from authentik.sources.ldap.sync.base import BaseLDAPSynchronizer
 17from authentik.tasks.models import Task
 18
 19
 20class BaseMembershipLDAPSynchronizer(BaseLDAPSynchronizer):
 21    """Sync membership of LDAP Users and Groups into authentik"""
 22
 23    group_cache: dict[str, Group]
 24
 25    def __init__(self, source: LDAPSource, task: Task):
 26        super().__init__(source, task)
 27        self.group_cache: dict[str, Group] = {}
 28
 29    @staticmethod
 30    def name() -> str:
 31        raise NotImplementedError
 32
 33    def get_objects(self, **kwargs) -> Generator:
 34        raise NotImplementedError
 35
 36    def sync(self, page_data: list) -> int:
 37        raise NotImplementedError
 38
 39    def get_group(self, group_dict: dict[str, Any]) -> Group | None:
 40        """Check if we fetched the group already, and if not cache it for later"""
 41        group_dn = group_dict.get("attributes", {}).get(LDAP_DISTINGUISHED_NAME, [])
 42        group_uniq = group_dict.get("attributes", {}).get(self._source.object_uniqueness_field, [])
 43        # group_uniq might be a single string or an array with (hopefully) a single string
 44        if isinstance(group_uniq, list):
 45            if len(group_uniq) < 1:
 46                self._task.info(
 47                    f"Group does not have a uniqueness attribute: '{group_dn}'",
 48                    group=group_dn,
 49                )
 50                return None
 51            group_uniq = group_uniq[0]
 52        if group_uniq not in self.group_cache:
 53            groups = GroupLDAPSourceConnection.objects.filter(identifier=group_uniq).select_related(
 54                "group"
 55            )
 56            if not groups.exists():
 57                if self._source.sync_groups:
 58                    self._task.info(
 59                        f"Group does not exist in our DB yet, run sync_groups first: '{group_dn}'",
 60                        group=group_dn,
 61                    )
 62                return None
 63            self.group_cache[group_uniq] = groups.first().group
 64        return self.group_cache[group_uniq]
 65
 66
 67class MembershipLDAPSynchronizer(BaseMembershipLDAPSynchronizer):
 68    """Sync membership of LDAP Users into authentik"""
 69
 70    @staticmethod
 71    def name() -> str:
 72        return "membership"
 73
 74    def get_objects(self, **kwargs) -> Generator:
 75        if not self._source.sync_groups:
 76            self._task.info("Group syncing is disabled for this Source")
 77            return iter(())
 78
 79        # If we are looking up groups from users, we don't need to fetch the group membership field
 80        attributes = [self._source.object_uniqueness_field, LDAP_DISTINGUISHED_NAME]
 81        if not self._source.lookup_groups_from_user:
 82            attributes.append(self._source.group_membership_field)
 83
 84        return self.search_paginator(
 85            search_base=self.base_dn_groups,
 86            search_filter=self._source.group_object_filter,
 87            search_scope=SUBTREE,
 88            attributes=attributes,
 89            **kwargs,
 90        )
 91
 92    def sync(self, page_data: list) -> int:
 93        """Iterate over all Users and assign Groups using memberOf Field"""
 94        if not self._source.sync_groups:
 95            self._task.info("Group syncing is disabled for this Source")
 96            return -1
 97        membership_count = 0
 98        for group_data in page_data:
 99            if self._source.lookup_groups_from_user:
100                group_dn = group_data.get("dn", {})
101                escaped_dn = escape_filter_chars(group_dn)
102                group_filter = f"({self._source.group_membership_field}={escaped_dn})"
103                group_members = self._source.connection().extend.standard.paged_search(
104                    search_base=self.base_dn_users,
105                    search_filter=group_filter,
106                    search_scope=SUBTREE,
107                    attributes=[self._source.object_uniqueness_field],
108                )
109                members = []
110                for group_member in group_members:
111                    group_member_dn = group_member.get("dn", {})
112                    members.append(group_member_dn)
113            else:
114                if (attributes := self.get_attributes(group_data)) is None:
115                    continue
116                members = attributes.get(self._source.group_membership_field, [])
117
118            group = self.get_group(group_data)
119            if not group:
120                continue
121
122            member_values = members + [[member] for member in members]
123            users = User.objects.filter(
124                Q(**{f"attributes__{self._source.user_membership_attribute}__in": member_values})
125                | Q(
126                    **{
127                        f"attributes__{self._source.user_membership_attribute}__isnull": True,
128                        "groups__in": [group],
129                    }
130                )
131            ).distinct()
132            membership_count += 1
133            membership_count += users.count()
134            group.users.set(users)
135            group.save()
136        self._logger.debug("Successfully updated group membership")
137        return membership_count
138
139
140class GroupHierarchyLDAPSynchronizer(BaseMembershipLDAPSynchronizer):
141    """Sync hierarchy of LDAP Groups into authentik"""
142
143    @staticmethod
144    def name() -> str:
145        return "group hierarchy"
146
147    def get_objects(self, **kwargs) -> Generator:
148        if not self._source.sync_groups:
149            self._task.info("Group syncing is disabled for this Source")
150            return iter(())
151        if not self._source.sync_group_hierarchy:
152            self._task.info("Group hierarchy syncing is disabled for this Source")
153            return iter(())
154
155        attributes = [
156            self._source.group_membership_field,
157            self._source.user_membership_attribute,
158            self._source.object_uniqueness_field,
159            LDAP_DISTINGUISHED_NAME,
160        ]
161
162        return self.search_paginator(
163            search_base=self.base_dn_groups,
164            search_filter=self._source.group_object_filter,
165            search_scope=SUBTREE,
166            attributes=attributes,
167            **kwargs,
168        )
169
170    def sync(self, page_data: list) -> int:
171        """Iterate over all Groups and assign their parents"""
172        if not self._source.sync_groups:
173            self._task.info("Group syncing is disabled for this Source")
174            return -1
175        if not self._source.sync_group_hierarchy:
176            self._task.info("Group hierarchy syncing is disabled for this Source")
177            return -1
178        count = 0
179        for group_data in page_data:
180            if (attributes := self.get_attributes(group_data)) is None:
181                continue
182            group = self.get_group(group_data)
183            if not group:
184                continue
185
186            # Deliberately WET
187            if self._source.lookup_groups_from_user:
188                parents_from_source_raw = attributes.get(self._source.group_membership_field, [])
189                parents_from_source = Group.objects.filter(
190                    **{
191                        (
192                            "attributes__" f"{self._source.user_membership_attribute}__in"
193                        ): parents_from_source_raw
194                    }
195                )
196                parents_not_from_source = group.parents.exclude(
197                    groupsourceconnection__source=self._source
198                )
199
200                count = len(parents_from_source)
201                group.parents.set(parents_from_source.union(parents_not_from_source))
202            else:
203                children_from_source_raw = attributes.get(self._source.group_membership_field, [])
204                children_from_source = Group.objects.filter(
205                    **{
206                        (
207                            "attributes__" f"{self._source.user_membership_attribute}__in"
208                        ): children_from_source_raw
209                    }
210                )
211                children_not_from_source = group.children.exclude(
212                    groupsourceconnection__source=self._source
213                )
214
215                count = len(children_from_source)
216                group.children.set(children_from_source.union(children_not_from_source))
217
218        self._logger.debug("Successfully updated group hierarchy")
219        return count
class BaseMembershipLDAPSynchronizer(authentik.sources.ldap.sync.base.BaseLDAPSynchronizer):
21class BaseMembershipLDAPSynchronizer(BaseLDAPSynchronizer):
22    """Sync membership of LDAP Users and Groups into authentik"""
23
24    group_cache: dict[str, Group]
25
26    def __init__(self, source: LDAPSource, task: Task):
27        super().__init__(source, task)
28        self.group_cache: dict[str, Group] = {}
29
30    @staticmethod
31    def name() -> str:
32        raise NotImplementedError
33
34    def get_objects(self, **kwargs) -> Generator:
35        raise NotImplementedError
36
37    def sync(self, page_data: list) -> int:
38        raise NotImplementedError
39
40    def get_group(self, group_dict: dict[str, Any]) -> Group | None:
41        """Check if we fetched the group already, and if not cache it for later"""
42        group_dn = group_dict.get("attributes", {}).get(LDAP_DISTINGUISHED_NAME, [])
43        group_uniq = group_dict.get("attributes", {}).get(self._source.object_uniqueness_field, [])
44        # group_uniq might be a single string or an array with (hopefully) a single string
45        if isinstance(group_uniq, list):
46            if len(group_uniq) < 1:
47                self._task.info(
48                    f"Group does not have a uniqueness attribute: '{group_dn}'",
49                    group=group_dn,
50                )
51                return None
52            group_uniq = group_uniq[0]
53        if group_uniq not in self.group_cache:
54            groups = GroupLDAPSourceConnection.objects.filter(identifier=group_uniq).select_related(
55                "group"
56            )
57            if not groups.exists():
58                if self._source.sync_groups:
59                    self._task.info(
60                        f"Group does not exist in our DB yet, run sync_groups first: '{group_dn}'",
61                        group=group_dn,
62                    )
63                return None
64            self.group_cache[group_uniq] = groups.first().group
65        return self.group_cache[group_uniq]

Sync membership of LDAP Users and Groups into authentik

BaseMembershipLDAPSynchronizer( source: authentik.sources.ldap.models.LDAPSource, task: authentik.tasks.models.Task)
26    def __init__(self, source: LDAPSource, task: Task):
27        super().__init__(source, task)
28        self.group_cache: dict[str, Group] = {}
group_cache: dict[str, authentik.core.models.Group]
@staticmethod
def name() -> str:
30    @staticmethod
31    def name() -> str:
32        raise NotImplementedError

UI name for the type of object this class synchronizes

def get_objects(self, **kwargs) -> Generator:
34    def get_objects(self, **kwargs) -> Generator:
35        raise NotImplementedError

Get objects from LDAP, implemented in subclass

def sync(self, page_data: list) -> int:
37    def sync(self, page_data: list) -> int:
38        raise NotImplementedError

Sync function, implemented in subclass

def get_group( self, group_dict: dict[str, typing.Any]) -> authentik.core.models.Group | None:
40    def get_group(self, group_dict: dict[str, Any]) -> Group | None:
41        """Check if we fetched the group already, and if not cache it for later"""
42        group_dn = group_dict.get("attributes", {}).get(LDAP_DISTINGUISHED_NAME, [])
43        group_uniq = group_dict.get("attributes", {}).get(self._source.object_uniqueness_field, [])
44        # group_uniq might be a single string or an array with (hopefully) a single string
45        if isinstance(group_uniq, list):
46            if len(group_uniq) < 1:
47                self._task.info(
48                    f"Group does not have a uniqueness attribute: '{group_dn}'",
49                    group=group_dn,
50                )
51                return None
52            group_uniq = group_uniq[0]
53        if group_uniq not in self.group_cache:
54            groups = GroupLDAPSourceConnection.objects.filter(identifier=group_uniq).select_related(
55                "group"
56            )
57            if not groups.exists():
58                if self._source.sync_groups:
59                    self._task.info(
60                        f"Group does not exist in our DB yet, run sync_groups first: '{group_dn}'",
61                        group=group_dn,
62                    )
63                return None
64            self.group_cache[group_uniq] = groups.first().group
65        return self.group_cache[group_uniq]

Check if we fetched the group already, and if not cache it for later

class MembershipLDAPSynchronizer(BaseMembershipLDAPSynchronizer):
 68class MembershipLDAPSynchronizer(BaseMembershipLDAPSynchronizer):
 69    """Sync membership of LDAP Users into authentik"""
 70
 71    @staticmethod
 72    def name() -> str:
 73        return "membership"
 74
 75    def get_objects(self, **kwargs) -> Generator:
 76        if not self._source.sync_groups:
 77            self._task.info("Group syncing is disabled for this Source")
 78            return iter(())
 79
 80        # If we are looking up groups from users, we don't need to fetch the group membership field
 81        attributes = [self._source.object_uniqueness_field, LDAP_DISTINGUISHED_NAME]
 82        if not self._source.lookup_groups_from_user:
 83            attributes.append(self._source.group_membership_field)
 84
 85        return self.search_paginator(
 86            search_base=self.base_dn_groups,
 87            search_filter=self._source.group_object_filter,
 88            search_scope=SUBTREE,
 89            attributes=attributes,
 90            **kwargs,
 91        )
 92
 93    def sync(self, page_data: list) -> int:
 94        """Iterate over all Users and assign Groups using memberOf Field"""
 95        if not self._source.sync_groups:
 96            self._task.info("Group syncing is disabled for this Source")
 97            return -1
 98        membership_count = 0
 99        for group_data in page_data:
100            if self._source.lookup_groups_from_user:
101                group_dn = group_data.get("dn", {})
102                escaped_dn = escape_filter_chars(group_dn)
103                group_filter = f"({self._source.group_membership_field}={escaped_dn})"
104                group_members = self._source.connection().extend.standard.paged_search(
105                    search_base=self.base_dn_users,
106                    search_filter=group_filter,
107                    search_scope=SUBTREE,
108                    attributes=[self._source.object_uniqueness_field],
109                )
110                members = []
111                for group_member in group_members:
112                    group_member_dn = group_member.get("dn", {})
113                    members.append(group_member_dn)
114            else:
115                if (attributes := self.get_attributes(group_data)) is None:
116                    continue
117                members = attributes.get(self._source.group_membership_field, [])
118
119            group = self.get_group(group_data)
120            if not group:
121                continue
122
123            member_values = members + [[member] for member in members]
124            users = User.objects.filter(
125                Q(**{f"attributes__{self._source.user_membership_attribute}__in": member_values})
126                | Q(
127                    **{
128                        f"attributes__{self._source.user_membership_attribute}__isnull": True,
129                        "groups__in": [group],
130                    }
131                )
132            ).distinct()
133            membership_count += 1
134            membership_count += users.count()
135            group.users.set(users)
136            group.save()
137        self._logger.debug("Successfully updated group membership")
138        return membership_count

Sync membership of LDAP Users into authentik

@staticmethod
def name() -> str:
71    @staticmethod
72    def name() -> str:
73        return "membership"

UI name for the type of object this class synchronizes

def get_objects(self, **kwargs) -> Generator:
75    def get_objects(self, **kwargs) -> Generator:
76        if not self._source.sync_groups:
77            self._task.info("Group syncing is disabled for this Source")
78            return iter(())
79
80        # If we are looking up groups from users, we don't need to fetch the group membership field
81        attributes = [self._source.object_uniqueness_field, LDAP_DISTINGUISHED_NAME]
82        if not self._source.lookup_groups_from_user:
83            attributes.append(self._source.group_membership_field)
84
85        return self.search_paginator(
86            search_base=self.base_dn_groups,
87            search_filter=self._source.group_object_filter,
88            search_scope=SUBTREE,
89            attributes=attributes,
90            **kwargs,
91        )

Get objects from LDAP, implemented in subclass

def sync(self, page_data: list) -> int:
 93    def sync(self, page_data: list) -> int:
 94        """Iterate over all Users and assign Groups using memberOf Field"""
 95        if not self._source.sync_groups:
 96            self._task.info("Group syncing is disabled for this Source")
 97            return -1
 98        membership_count = 0
 99        for group_data in page_data:
100            if self._source.lookup_groups_from_user:
101                group_dn = group_data.get("dn", {})
102                escaped_dn = escape_filter_chars(group_dn)
103                group_filter = f"({self._source.group_membership_field}={escaped_dn})"
104                group_members = self._source.connection().extend.standard.paged_search(
105                    search_base=self.base_dn_users,
106                    search_filter=group_filter,
107                    search_scope=SUBTREE,
108                    attributes=[self._source.object_uniqueness_field],
109                )
110                members = []
111                for group_member in group_members:
112                    group_member_dn = group_member.get("dn", {})
113                    members.append(group_member_dn)
114            else:
115                if (attributes := self.get_attributes(group_data)) is None:
116                    continue
117                members = attributes.get(self._source.group_membership_field, [])
118
119            group = self.get_group(group_data)
120            if not group:
121                continue
122
123            member_values = members + [[member] for member in members]
124            users = User.objects.filter(
125                Q(**{f"attributes__{self._source.user_membership_attribute}__in": member_values})
126                | Q(
127                    **{
128                        f"attributes__{self._source.user_membership_attribute}__isnull": True,
129                        "groups__in": [group],
130                    }
131                )
132            ).distinct()
133            membership_count += 1
134            membership_count += users.count()
135            group.users.set(users)
136            group.save()
137        self._logger.debug("Successfully updated group membership")
138        return membership_count

Iterate over all Users and assign Groups using memberOf Field

class GroupHierarchyLDAPSynchronizer(BaseMembershipLDAPSynchronizer):
141class GroupHierarchyLDAPSynchronizer(BaseMembershipLDAPSynchronizer):
142    """Sync hierarchy of LDAP Groups into authentik"""
143
144    @staticmethod
145    def name() -> str:
146        return "group hierarchy"
147
148    def get_objects(self, **kwargs) -> Generator:
149        if not self._source.sync_groups:
150            self._task.info("Group syncing is disabled for this Source")
151            return iter(())
152        if not self._source.sync_group_hierarchy:
153            self._task.info("Group hierarchy syncing is disabled for this Source")
154            return iter(())
155
156        attributes = [
157            self._source.group_membership_field,
158            self._source.user_membership_attribute,
159            self._source.object_uniqueness_field,
160            LDAP_DISTINGUISHED_NAME,
161        ]
162
163        return self.search_paginator(
164            search_base=self.base_dn_groups,
165            search_filter=self._source.group_object_filter,
166            search_scope=SUBTREE,
167            attributes=attributes,
168            **kwargs,
169        )
170
171    def sync(self, page_data: list) -> int:
172        """Iterate over all Groups and assign their parents"""
173        if not self._source.sync_groups:
174            self._task.info("Group syncing is disabled for this Source")
175            return -1
176        if not self._source.sync_group_hierarchy:
177            self._task.info("Group hierarchy syncing is disabled for this Source")
178            return -1
179        count = 0
180        for group_data in page_data:
181            if (attributes := self.get_attributes(group_data)) is None:
182                continue
183            group = self.get_group(group_data)
184            if not group:
185                continue
186
187            # Deliberately WET
188            if self._source.lookup_groups_from_user:
189                parents_from_source_raw = attributes.get(self._source.group_membership_field, [])
190                parents_from_source = Group.objects.filter(
191                    **{
192                        (
193                            "attributes__" f"{self._source.user_membership_attribute}__in"
194                        ): parents_from_source_raw
195                    }
196                )
197                parents_not_from_source = group.parents.exclude(
198                    groupsourceconnection__source=self._source
199                )
200
201                count = len(parents_from_source)
202                group.parents.set(parents_from_source.union(parents_not_from_source))
203            else:
204                children_from_source_raw = attributes.get(self._source.group_membership_field, [])
205                children_from_source = Group.objects.filter(
206                    **{
207                        (
208                            "attributes__" f"{self._source.user_membership_attribute}__in"
209                        ): children_from_source_raw
210                    }
211                )
212                children_not_from_source = group.children.exclude(
213                    groupsourceconnection__source=self._source
214                )
215
216                count = len(children_from_source)
217                group.children.set(children_from_source.union(children_not_from_source))
218
219        self._logger.debug("Successfully updated group hierarchy")
220        return count

Sync hierarchy of LDAP Groups into authentik

@staticmethod
def name() -> str:
144    @staticmethod
145    def name() -> str:
146        return "group hierarchy"

UI name for the type of object this class synchronizes

def get_objects(self, **kwargs) -> Generator:
148    def get_objects(self, **kwargs) -> Generator:
149        if not self._source.sync_groups:
150            self._task.info("Group syncing is disabled for this Source")
151            return iter(())
152        if not self._source.sync_group_hierarchy:
153            self._task.info("Group hierarchy syncing is disabled for this Source")
154            return iter(())
155
156        attributes = [
157            self._source.group_membership_field,
158            self._source.user_membership_attribute,
159            self._source.object_uniqueness_field,
160            LDAP_DISTINGUISHED_NAME,
161        ]
162
163        return self.search_paginator(
164            search_base=self.base_dn_groups,
165            search_filter=self._source.group_object_filter,
166            search_scope=SUBTREE,
167            attributes=attributes,
168            **kwargs,
169        )

Get objects from LDAP, implemented in subclass

def sync(self, page_data: list) -> int:
171    def sync(self, page_data: list) -> int:
172        """Iterate over all Groups and assign their parents"""
173        if not self._source.sync_groups:
174            self._task.info("Group syncing is disabled for this Source")
175            return -1
176        if not self._source.sync_group_hierarchy:
177            self._task.info("Group hierarchy syncing is disabled for this Source")
178            return -1
179        count = 0
180        for group_data in page_data:
181            if (attributes := self.get_attributes(group_data)) is None:
182                continue
183            group = self.get_group(group_data)
184            if not group:
185                continue
186
187            # Deliberately WET
188            if self._source.lookup_groups_from_user:
189                parents_from_source_raw = attributes.get(self._source.group_membership_field, [])
190                parents_from_source = Group.objects.filter(
191                    **{
192                        (
193                            "attributes__" f"{self._source.user_membership_attribute}__in"
194                        ): parents_from_source_raw
195                    }
196                )
197                parents_not_from_source = group.parents.exclude(
198                    groupsourceconnection__source=self._source
199                )
200
201                count = len(parents_from_source)
202                group.parents.set(parents_from_source.union(parents_not_from_source))
203            else:
204                children_from_source_raw = attributes.get(self._source.group_membership_field, [])
205                children_from_source = Group.objects.filter(
206                    **{
207                        (
208                            "attributes__" f"{self._source.user_membership_attribute}__in"
209                        ): children_from_source_raw
210                    }
211                )
212                children_not_from_source = group.children.exclude(
213                    groupsourceconnection__source=self._source
214                )
215
216                count = len(children_from_source)
217                group.children.set(children_from_source.union(children_not_from_source))
218
219        self._logger.debug("Successfully updated group hierarchy")
220        return count

Iterate over all Groups and assign their parents