authentik.sources.kerberos.sync

Sync Kerberos users into authentik

  1"""Sync Kerberos users into authentik"""
  2
  3from typing import Any
  4
  5from django.core.exceptions import FieldError
  6from django.db import IntegrityError, transaction
  7from kadmin import KAdmin
  8from structlog.stdlib import BoundLogger, get_logger
  9
 10from authentik.core.expression.exceptions import (
 11    PropertyMappingExpressionException,
 12    SkipObjectException,
 13)
 14from authentik.core.models import Group, User
 15from authentik.core.sources.mapper import SourceMapper
 16from authentik.core.sources.matcher import Action, SourceMatcher
 17from authentik.events.models import Event, EventAction
 18from authentik.lib.sync.mapper import PropertyMappingManager
 19from authentik.lib.sync.outgoing.exceptions import StopSync
 20from authentik.sources.kerberos.models import (
 21    GroupKerberosSourceConnection,
 22    KerberosSource,
 23    Krb5ConfContext,
 24    UserKerberosSourceConnection,
 25)
 26from authentik.tasks.models import Task
 27
 28
 29class KerberosSync:
 30    """Sync Kerberos users into authentik"""
 31
 32    _source: KerberosSource
 33    _task: Task
 34    _logger: BoundLogger
 35    _connection: KAdmin
 36    mapper: SourceMapper
 37    user_manager: PropertyMappingManager
 38    group_manager: PropertyMappingManager
 39    matcher: SourceMatcher
 40
 41    def __init__(self, source: KerberosSource, task: Task):
 42        self._source = source
 43        self._task = task
 44        with Krb5ConfContext(self._source):
 45            self._connection = self._source.connection()
 46        self._logger = get_logger().bind(source=self._source, syncer=self.__class__.__name__)
 47        self.mapper = SourceMapper(self._source)
 48        self.user_manager = self.mapper.get_manager(User, ["principal", "principal_obj"])
 49        self.group_manager = self.mapper.get_manager(
 50            Group, ["group_id", "principal", "principal_obj"]
 51        )
 52        self.matcher = SourceMatcher(
 53            self._source, UserKerberosSourceConnection, GroupKerberosSourceConnection
 54        )
 55
 56    @staticmethod
 57    def name() -> str:
 58        """UI name for the type of object this class synchronizes"""
 59        return "users"
 60
 61    def _handle_principal(self, principal: str) -> bool:
 62        try:
 63            # TODO: handle permission error
 64            principal_obj = self._connection.get_principal(principal)
 65
 66            defaults = self.mapper.build_object_properties(
 67                object_type=User,
 68                manager=self.user_manager,
 69                user=None,
 70                request=None,
 71                principal=principal,
 72                principal_obj=principal_obj,
 73            )
 74            self._logger.debug("Writing user with attributes", attributes=defaults)
 75            if "username" not in defaults:
 76                raise IntegrityError("Username was not set by propertymappings")
 77
 78            action, connection = self.matcher.get_user_action(principal, defaults)
 79            self._logger.debug("Action returned", action=action, connection=connection)
 80            if action == Action.DENY:
 81                return False
 82
 83            group_properties = {
 84                group_id: self.mapper.build_object_properties(
 85                    object_type=Group,
 86                    manager=self.group_manager,
 87                    user=None,
 88                    request=None,
 89                    group_id=group_id,
 90                    principal=principal,
 91                    principal_obj=principal_obj,
 92                )
 93                for group_id in defaults.pop("groups", [])
 94            }
 95
 96            if action == Action.ENROLL:
 97                user = User.objects.create(**defaults)
 98                connection.user = user
 99                connection.save()
100            elif action in (Action.AUTH, Action.LINK):
101                user = connection.user
102                user.update_attributes(defaults)
103                connection.save()
104            else:
105                return False
106
107            groups: list[Group] = []
108            for group_id, properties in group_properties.items():
109                group = self._handle_group(group_id, properties)
110                if group:
111                    groups.append(group)
112
113            with transaction.atomic():
114                user.groups.remove(*user.groups.filter(groupsourceconnection__source=self._source))
115                user.groups.add(*groups)
116
117        except PropertyMappingExpressionException as exc:
118            raise StopSync(exc, None, exc.mapping) from exc
119        except SkipObjectException:
120            return False
121        except (IntegrityError, FieldError, TypeError, AttributeError) as exc:
122            Event.new(
123                EventAction.CONFIGURATION_ERROR,
124                message=(f"Failed to create user: {str(exc)} "),
125                source=self._source,
126                principal=principal,
127            ).save()
128            return False
129        self._logger.debug("Synced User", user=user.username)
130        return True
131
132    def _handle_group(
133        self, group_id: str, defaults: dict[str, Any | dict[str, Any]]
134    ) -> Group | None:
135        action, connection = self.matcher.get_group_action(group_id, defaults)
136        if action == Action.DENY:
137            return None
138        if action == Action.ENROLL:
139            group = Group.objects.create(**defaults)
140            connection.group = group
141            connection.save()
142            return group
143        if action in (Action.AUTH, Action.LINK):
144            group = connection.group
145            group.update_attributes(defaults)
146            connection.save()
147            return group
148        return None
149
150    def sync(self) -> int:
151        """Iterate over all Kerberos users and create authentik_core.User instances"""
152        if not self._source.enabled or not self._source.sync_users:
153            self._task.info("Source is disabled or user syncing is disabled for this Source")
154            return -1
155
156        user_count = 0
157        with Krb5ConfContext(self._source):
158            for principal in self._connection.list_principals(None):
159                if self._handle_principal(principal):
160                    user_count += 1
161        return user_count
class KerberosSync:
 30class KerberosSync:
 31    """Sync Kerberos users into authentik"""
 32
 33    _source: KerberosSource
 34    _task: Task
 35    _logger: BoundLogger
 36    _connection: KAdmin
 37    mapper: SourceMapper
 38    user_manager: PropertyMappingManager
 39    group_manager: PropertyMappingManager
 40    matcher: SourceMatcher
 41
 42    def __init__(self, source: KerberosSource, task: Task):
 43        self._source = source
 44        self._task = task
 45        with Krb5ConfContext(self._source):
 46            self._connection = self._source.connection()
 47        self._logger = get_logger().bind(source=self._source, syncer=self.__class__.__name__)
 48        self.mapper = SourceMapper(self._source)
 49        self.user_manager = self.mapper.get_manager(User, ["principal", "principal_obj"])
 50        self.group_manager = self.mapper.get_manager(
 51            Group, ["group_id", "principal", "principal_obj"]
 52        )
 53        self.matcher = SourceMatcher(
 54            self._source, UserKerberosSourceConnection, GroupKerberosSourceConnection
 55        )
 56
 57    @staticmethod
 58    def name() -> str:
 59        """UI name for the type of object this class synchronizes"""
 60        return "users"
 61
 62    def _handle_principal(self, principal: str) -> bool:
 63        try:
 64            # TODO: handle permission error
 65            principal_obj = self._connection.get_principal(principal)
 66
 67            defaults = self.mapper.build_object_properties(
 68                object_type=User,
 69                manager=self.user_manager,
 70                user=None,
 71                request=None,
 72                principal=principal,
 73                principal_obj=principal_obj,
 74            )
 75            self._logger.debug("Writing user with attributes", attributes=defaults)
 76            if "username" not in defaults:
 77                raise IntegrityError("Username was not set by propertymappings")
 78
 79            action, connection = self.matcher.get_user_action(principal, defaults)
 80            self._logger.debug("Action returned", action=action, connection=connection)
 81            if action == Action.DENY:
 82                return False
 83
 84            group_properties = {
 85                group_id: self.mapper.build_object_properties(
 86                    object_type=Group,
 87                    manager=self.group_manager,
 88                    user=None,
 89                    request=None,
 90                    group_id=group_id,
 91                    principal=principal,
 92                    principal_obj=principal_obj,
 93                )
 94                for group_id in defaults.pop("groups", [])
 95            }
 96
 97            if action == Action.ENROLL:
 98                user = User.objects.create(**defaults)
 99                connection.user = user
100                connection.save()
101            elif action in (Action.AUTH, Action.LINK):
102                user = connection.user
103                user.update_attributes(defaults)
104                connection.save()
105            else:
106                return False
107
108            groups: list[Group] = []
109            for group_id, properties in group_properties.items():
110                group = self._handle_group(group_id, properties)
111                if group:
112                    groups.append(group)
113
114            with transaction.atomic():
115                user.groups.remove(*user.groups.filter(groupsourceconnection__source=self._source))
116                user.groups.add(*groups)
117
118        except PropertyMappingExpressionException as exc:
119            raise StopSync(exc, None, exc.mapping) from exc
120        except SkipObjectException:
121            return False
122        except (IntegrityError, FieldError, TypeError, AttributeError) as exc:
123            Event.new(
124                EventAction.CONFIGURATION_ERROR,
125                message=(f"Failed to create user: {str(exc)} "),
126                source=self._source,
127                principal=principal,
128            ).save()
129            return False
130        self._logger.debug("Synced User", user=user.username)
131        return True
132
133    def _handle_group(
134        self, group_id: str, defaults: dict[str, Any | dict[str, Any]]
135    ) -> Group | None:
136        action, connection = self.matcher.get_group_action(group_id, defaults)
137        if action == Action.DENY:
138            return None
139        if action == Action.ENROLL:
140            group = Group.objects.create(**defaults)
141            connection.group = group
142            connection.save()
143            return group
144        if action in (Action.AUTH, Action.LINK):
145            group = connection.group
146            group.update_attributes(defaults)
147            connection.save()
148            return group
149        return None
150
151    def sync(self) -> int:
152        """Iterate over all Kerberos users and create authentik_core.User instances"""
153        if not self._source.enabled or not self._source.sync_users:
154            self._task.info("Source is disabled or user syncing is disabled for this Source")
155            return -1
156
157        user_count = 0
158        with Krb5ConfContext(self._source):
159            for principal in self._connection.list_principals(None):
160                if self._handle_principal(principal):
161                    user_count += 1
162        return user_count

Sync Kerberos users into authentik

42    def __init__(self, source: KerberosSource, task: Task):
43        self._source = source
44        self._task = task
45        with Krb5ConfContext(self._source):
46            self._connection = self._source.connection()
47        self._logger = get_logger().bind(source=self._source, syncer=self.__class__.__name__)
48        self.mapper = SourceMapper(self._source)
49        self.user_manager = self.mapper.get_manager(User, ["principal", "principal_obj"])
50        self.group_manager = self.mapper.get_manager(
51            Group, ["group_id", "principal", "principal_obj"]
52        )
53        self.matcher = SourceMatcher(
54            self._source, UserKerberosSourceConnection, GroupKerberosSourceConnection
55        )
@staticmethod
def name() -> str:
57    @staticmethod
58    def name() -> str:
59        """UI name for the type of object this class synchronizes"""
60        return "users"

UI name for the type of object this class synchronizes

def sync(self) -> int:
151    def sync(self) -> int:
152        """Iterate over all Kerberos users and create authentik_core.User instances"""
153        if not self._source.enabled or not self._source.sync_users:
154            self._task.info("Source is disabled or user syncing is disabled for this Source")
155            return -1
156
157        user_count = 0
158        with Krb5ConfContext(self._source):
159            for principal in self._connection.list_principals(None):
160                if self._handle_principal(principal):
161                    user_count += 1
162        return user_count

Iterate over all Kerberos users and create authentik_core.User instances