authentik.lib.sync.outgoing.models

  1import math
  2from typing import Any, Self
  3
  4import pglock
  5from django.core.paginator import Paginator
  6from django.core.validators import MinValueValidator
  7from django.db import connection, models
  8from django.db.models import Model, QuerySet, TextChoices
  9from django.utils.translation import gettext_lazy as _
 10from dramatiq.actor import Actor
 11
 12from authentik.core.models import Group, User, UserTypes
 13from authentik.lib.config import advisory_lock_db_alias
 14from authentik.lib.sync.outgoing.base import BaseOutgoingSyncClient
 15from authentik.lib.utils.time import fqdn_rand, timedelta_from_string, timedelta_string_validator
 16from authentik.tasks.schedules.common import ScheduleSpec
 17from authentik.tasks.schedules.models import ScheduledModel
 18
 19
 20class OutgoingSyncDeleteAction(TextChoices):
 21    """Action taken when a user/group is deleted in authentik. Suspend is not available for groups,
 22    and will be treated as `do_nothing`"""
 23
 24    DO_NOTHING = "do_nothing"
 25    DELETE = "delete"
 26    SUSPEND = "suspend"
 27
 28
 29class OutgoingSyncProvider(ScheduledModel, Model):
 30    """Base abstract models for providers implementing outgoing sync"""
 31
 32    sync_page_size = models.PositiveIntegerField(
 33        help_text=_("Controls the number of objects synced in a single task"),
 34        default=100,
 35        validators=[MinValueValidator(1)],
 36    )
 37    sync_page_timeout = models.TextField(
 38        help_text=_("Timeout for synchronization of a single page"),
 39        default="minutes=30",
 40        validators=[timedelta_string_validator],
 41    )
 42
 43    discovery_enabled = models.BooleanField(
 44        default=True,
 45        help_text=_(
 46            "When enabled, authentik will attempt to discover existing resources "
 47            "in the remote system."
 48        ),
 49    )
 50    dry_run = models.BooleanField(
 51        default=False,
 52        help_text=_(
 53            "When enabled, provider will not modify or create objects in the remote system."
 54        ),
 55    )
 56
 57    class Meta:
 58        abstract = True
 59
 60    def client_for_model[T: User | Group](
 61        self, model: type[T]
 62    ) -> BaseOutgoingSyncClient[T, Any, Any, Self]:
 63        raise NotImplementedError
 64
 65    def get_object_qs[T: User | Group](self, type: type[T], **kwargs) -> QuerySet[T]:
 66        raise NotImplementedError
 67
 68    @classmethod
 69    def get_object_mappings(cls, obj: User | Group) -> list[tuple[str, str]]:
 70        """
 71        Get a list of mapping between User/Group and ProviderUser/Group:
 72        [("provider_pk", "obj_pk")]
 73        """
 74        raise NotImplementedError
 75
 76    def get_paginator[T: User | Group](self, type: type[T]) -> Paginator:
 77        return Paginator(self.get_object_qs(type), self.sync_page_size)
 78
 79    def get_object_sync_time_limit_ms[T: User | Group](self, type: type[T]) -> int:
 80        # Use a simple COUNT(*) on the model instead of materializing get_object_qs(),
 81        # which for some providers (e.g. SCIM) runs PolicyEngine per-user and is
 82        # extremely expensive. The time limit is an upper-bound estimate, so using
 83        # the total count (without policy filtering) is a safe overestimate.
 84        total_count = type.objects.count()
 85        num_pages = math.ceil(total_count / self.sync_page_size) if total_count > 0 else 1
 86        page_timeout_ms = timedelta_from_string(self.sync_page_timeout).total_seconds() * 1000
 87        return int(num_pages * page_timeout_ms * 1.5)
 88
 89    def get_sync_time_limit_ms(self) -> int:
 90        return int(
 91            (self.get_object_sync_time_limit_ms(User) + self.get_object_sync_time_limit_ms(Group))
 92            * 1.5
 93        )
 94
 95    @property
 96    def sync_lock(self) -> pglock.advisory:
 97        """Postgres lock for syncing to prevent multiple parallel syncs happening"""
 98        return pglock.advisory(
 99            lock_id=f"goauthentik.io/{connection.schema_name}/providers/outgoing-sync/{str(self.pk)}",
100            timeout=0,
101            side_effect=pglock.Return,
102            using=advisory_lock_db_alias(),
103        )
104
105    @property
106    def sync_actor(self) -> Actor:
107        raise NotImplementedError
108
109    def sync_dispatch(self) -> None:
110        for schedule in self.schedules.all():
111            schedule.send()
112
113    @property
114    def schedule_specs(self) -> list[ScheduleSpec]:
115        return [
116            ScheduleSpec(
117                actor=self.sync_actor,
118                uid=self.name,
119                args=(self.pk,),
120                options={
121                    "time_limit": self.get_sync_time_limit_ms(),
122                },
123                send_on_save=True,
124                crontab=f"{fqdn_rand(self.pk)} */4 * * *",
125            ),
126        ]
127
128
129class OutgoingSyncObjectQueryMixin:
130    """Select the users and groups an outgoing provider synchronizes.
131
132    Users are whoever can access the provider's backchannel application.
133    Groups are every group, or only ``group_filters`` when that list is set.
134    """
135
136    exclude_users_service_account: bool
137    backchannel_application: Any
138    group_filters: Any
139
140    def get_object_qs[T: User | Group](self, type: type[T], **kwargs) -> QuerySet[T]:
141        if type == User:
142            # Get queryset of all users with consistent ordering
143            # according to the provider's settings
144            base = User.objects.all().exclude_anonymous().filter(**kwargs)
145            if self.exclude_users_service_account:
146                base = base.exclude(type=UserTypes.SERVICE_ACCOUNT).exclude(
147                    type=UserTypes.INTERNAL_SERVICE_ACCOUNT
148                )
149            # Filter users by their access to the backchannel application if an application is set
150            if self.backchannel_application:
151                from authentik.core.apps import AppAccessWithoutBindings
152                from authentik.policies.engine import FilterPolicyEngine
153
154                engine = FilterPolicyEngine(self.backchannel_application, base)
155                engine.empty_result = AppAccessWithoutBindings.get()
156                base = engine.build().result
157            return base.order_by("pk")
158        if type == Group:
159            # Get queryset of all groups with consistent ordering
160            base = Group.objects.all().filter(**kwargs)
161            if self.group_filters.exists():
162                base = base.filter(pk__in=self.group_filters.values_list("pk", flat=True))
163            return base.order_by("pk")
164        raise ValueError(f"Invalid type {type}")
class OutgoingSyncDeleteAction(django.db.models.enums.TextChoices):
21class OutgoingSyncDeleteAction(TextChoices):
22    """Action taken when a user/group is deleted in authentik. Suspend is not available for groups,
23    and will be treated as `do_nothing`"""
24
25    DO_NOTHING = "do_nothing"
26    DELETE = "delete"
27    SUSPEND = "suspend"

Action taken when a user/group is deleted in authentik. Suspend is not available for groups, and will be treated as do_nothing

class OutgoingSyncProvider(authentik.tasks.schedules.models.ScheduledModel, django.db.models.base.Model):
 30class OutgoingSyncProvider(ScheduledModel, Model):
 31    """Base abstract models for providers implementing outgoing sync"""
 32
 33    sync_page_size = models.PositiveIntegerField(
 34        help_text=_("Controls the number of objects synced in a single task"),
 35        default=100,
 36        validators=[MinValueValidator(1)],
 37    )
 38    sync_page_timeout = models.TextField(
 39        help_text=_("Timeout for synchronization of a single page"),
 40        default="minutes=30",
 41        validators=[timedelta_string_validator],
 42    )
 43
 44    discovery_enabled = models.BooleanField(
 45        default=True,
 46        help_text=_(
 47            "When enabled, authentik will attempt to discover existing resources "
 48            "in the remote system."
 49        ),
 50    )
 51    dry_run = models.BooleanField(
 52        default=False,
 53        help_text=_(
 54            "When enabled, provider will not modify or create objects in the remote system."
 55        ),
 56    )
 57
 58    class Meta:
 59        abstract = True
 60
 61    def client_for_model[T: User | Group](
 62        self, model: type[T]
 63    ) -> BaseOutgoingSyncClient[T, Any, Any, Self]:
 64        raise NotImplementedError
 65
 66    def get_object_qs[T: User | Group](self, type: type[T], **kwargs) -> QuerySet[T]:
 67        raise NotImplementedError
 68
 69    @classmethod
 70    def get_object_mappings(cls, obj: User | Group) -> list[tuple[str, str]]:
 71        """
 72        Get a list of mapping between User/Group and ProviderUser/Group:
 73        [("provider_pk", "obj_pk")]
 74        """
 75        raise NotImplementedError
 76
 77    def get_paginator[T: User | Group](self, type: type[T]) -> Paginator:
 78        return Paginator(self.get_object_qs(type), self.sync_page_size)
 79
 80    def get_object_sync_time_limit_ms[T: User | Group](self, type: type[T]) -> int:
 81        # Use a simple COUNT(*) on the model instead of materializing get_object_qs(),
 82        # which for some providers (e.g. SCIM) runs PolicyEngine per-user and is
 83        # extremely expensive. The time limit is an upper-bound estimate, so using
 84        # the total count (without policy filtering) is a safe overestimate.
 85        total_count = type.objects.count()
 86        num_pages = math.ceil(total_count / self.sync_page_size) if total_count > 0 else 1
 87        page_timeout_ms = timedelta_from_string(self.sync_page_timeout).total_seconds() * 1000
 88        return int(num_pages * page_timeout_ms * 1.5)
 89
 90    def get_sync_time_limit_ms(self) -> int:
 91        return int(
 92            (self.get_object_sync_time_limit_ms(User) + self.get_object_sync_time_limit_ms(Group))
 93            * 1.5
 94        )
 95
 96    @property
 97    def sync_lock(self) -> pglock.advisory:
 98        """Postgres lock for syncing to prevent multiple parallel syncs happening"""
 99        return pglock.advisory(
100            lock_id=f"goauthentik.io/{connection.schema_name}/providers/outgoing-sync/{str(self.pk)}",
101            timeout=0,
102            side_effect=pglock.Return,
103            using=advisory_lock_db_alias(),
104        )
105
106    @property
107    def sync_actor(self) -> Actor:
108        raise NotImplementedError
109
110    def sync_dispatch(self) -> None:
111        for schedule in self.schedules.all():
112            schedule.send()
113
114    @property
115    def schedule_specs(self) -> list[ScheduleSpec]:
116        return [
117            ScheduleSpec(
118                actor=self.sync_actor,
119                uid=self.name,
120                args=(self.pk,),
121                options={
122                    "time_limit": self.get_sync_time_limit_ms(),
123                },
124                send_on_save=True,
125                crontab=f"{fqdn_rand(self.pk)} */4 * * *",
126            ),
127        ]

Base abstract models for providers implementing outgoing sync

def sync_page_size(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def sync_page_timeout(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def discovery_enabled(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def dry_run(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def client_for_model( self, model: type[T]) -> authentik.lib.sync.outgoing.base.BaseOutgoingSyncClient[T, typing.Any, typing.Any, typing.Self]:
61    def client_for_model[T: User | Group](
62        self, model: type[T]
63    ) -> BaseOutgoingSyncClient[T, Any, Any, Self]:
64        raise NotImplementedError
def get_object_qs(self, type: type[T], **kwargs) -> django.db.models.query.QuerySet:
66    def get_object_qs[T: User | Group](self, type: type[T], **kwargs) -> QuerySet[T]:
67        raise NotImplementedError
@classmethod
def get_object_mappings( cls, obj: authentik.core.models.User | authentik.core.models.Group) -> list[tuple[str, str]]:
69    @classmethod
70    def get_object_mappings(cls, obj: User | Group) -> list[tuple[str, str]]:
71        """
72        Get a list of mapping between User/Group and ProviderUser/Group:
73        [("provider_pk", "obj_pk")]
74        """
75        raise NotImplementedError

Get a list of mapping between User/Group and ProviderUser/Group: [("provider_pk", "obj_pk")]

def get_paginator(self, type: type[T]) -> django.core.paginator.Paginator:
77    def get_paginator[T: User | Group](self, type: type[T]) -> Paginator:
78        return Paginator(self.get_object_qs(type), self.sync_page_size)
def get_object_sync_time_limit_ms(self, type: type[T]) -> int:
80    def get_object_sync_time_limit_ms[T: User | Group](self, type: type[T]) -> int:
81        # Use a simple COUNT(*) on the model instead of materializing get_object_qs(),
82        # which for some providers (e.g. SCIM) runs PolicyEngine per-user and is
83        # extremely expensive. The time limit is an upper-bound estimate, so using
84        # the total count (without policy filtering) is a safe overestimate.
85        total_count = type.objects.count()
86        num_pages = math.ceil(total_count / self.sync_page_size) if total_count > 0 else 1
87        page_timeout_ms = timedelta_from_string(self.sync_page_timeout).total_seconds() * 1000
88        return int(num_pages * page_timeout_ms * 1.5)
def get_sync_time_limit_ms(self) -> int:
90    def get_sync_time_limit_ms(self) -> int:
91        return int(
92            (self.get_object_sync_time_limit_ms(User) + self.get_object_sync_time_limit_ms(Group))
93            * 1.5
94        )
sync_lock: pglock.core.advisory
 96    @property
 97    def sync_lock(self) -> pglock.advisory:
 98        """Postgres lock for syncing to prevent multiple parallel syncs happening"""
 99        return pglock.advisory(
100            lock_id=f"goauthentik.io/{connection.schema_name}/providers/outgoing-sync/{str(self.pk)}",
101            timeout=0,
102            side_effect=pglock.Return,
103            using=advisory_lock_db_alias(),
104        )

Postgres lock for syncing to prevent multiple parallel syncs happening

sync_actor: dramatiq.actor.Actor
106    @property
107    def sync_actor(self) -> Actor:
108        raise NotImplementedError
def sync_dispatch(self) -> None:
110    def sync_dispatch(self) -> None:
111        for schedule in self.schedules.all():
112            schedule.send()
schedule_specs: list[authentik.tasks.schedules.common.ScheduleSpec]
114    @property
115    def schedule_specs(self) -> list[ScheduleSpec]:
116        return [
117            ScheduleSpec(
118                actor=self.sync_actor,
119                uid=self.name,
120                args=(self.pk,),
121                options={
122                    "time_limit": self.get_sync_time_limit_ms(),
123                },
124                send_on_save=True,
125                crontab=f"{fqdn_rand(self.pk)} */4 * * *",
126            ),
127        ]
schedules

Accessor to the related objects manager on the one-to-many relation created by GenericRelation.

In the example::

class Post(Model):
    comments = GenericRelation(Comment)

post.comments is a ReverseGenericManyToOneDescriptor instance.

tasks

Accessor to the related objects manager on the one-to-many relation created by GenericRelation.

In the example::

class Post(Model):
    comments = GenericRelation(Comment)

post.comments is a ReverseGenericManyToOneDescriptor instance.

class OutgoingSyncProvider.Meta:
58    class Meta:
59        abstract = True
abstract = False
class OutgoingSyncObjectQueryMixin:
130class OutgoingSyncObjectQueryMixin:
131    """Select the users and groups an outgoing provider synchronizes.
132
133    Users are whoever can access the provider's backchannel application.
134    Groups are every group, or only ``group_filters`` when that list is set.
135    """
136
137    exclude_users_service_account: bool
138    backchannel_application: Any
139    group_filters: Any
140
141    def get_object_qs[T: User | Group](self, type: type[T], **kwargs) -> QuerySet[T]:
142        if type == User:
143            # Get queryset of all users with consistent ordering
144            # according to the provider's settings
145            base = User.objects.all().exclude_anonymous().filter(**kwargs)
146            if self.exclude_users_service_account:
147                base = base.exclude(type=UserTypes.SERVICE_ACCOUNT).exclude(
148                    type=UserTypes.INTERNAL_SERVICE_ACCOUNT
149                )
150            # Filter users by their access to the backchannel application if an application is set
151            if self.backchannel_application:
152                from authentik.core.apps import AppAccessWithoutBindings
153                from authentik.policies.engine import FilterPolicyEngine
154
155                engine = FilterPolicyEngine(self.backchannel_application, base)
156                engine.empty_result = AppAccessWithoutBindings.get()
157                base = engine.build().result
158            return base.order_by("pk")
159        if type == Group:
160            # Get queryset of all groups with consistent ordering
161            base = Group.objects.all().filter(**kwargs)
162            if self.group_filters.exists():
163                base = base.filter(pk__in=self.group_filters.values_list("pk", flat=True))
164            return base.order_by("pk")
165        raise ValueError(f"Invalid type {type}")

Select the users and groups an outgoing provider synchronizes.

Users are whoever can access the provider's backchannel application. Groups are every group, or only group_filters when that list is set.

exclude_users_service_account: bool
backchannel_application: Any
group_filters: Any
def get_object_qs(self, type: type[T], **kwargs) -> django.db.models.query.QuerySet:
141    def get_object_qs[T: User | Group](self, type: type[T], **kwargs) -> QuerySet[T]:
142        if type == User:
143            # Get queryset of all users with consistent ordering
144            # according to the provider's settings
145            base = User.objects.all().exclude_anonymous().filter(**kwargs)
146            if self.exclude_users_service_account:
147                base = base.exclude(type=UserTypes.SERVICE_ACCOUNT).exclude(
148                    type=UserTypes.INTERNAL_SERVICE_ACCOUNT
149                )
150            # Filter users by their access to the backchannel application if an application is set
151            if self.backchannel_application:
152                from authentik.core.apps import AppAccessWithoutBindings
153                from authentik.policies.engine import FilterPolicyEngine
154
155                engine = FilterPolicyEngine(self.backchannel_application, base)
156                engine.empty_result = AppAccessWithoutBindings.get()
157                base = engine.build().result
158            return base.order_by("pk")
159        if type == Group:
160            # Get queryset of all groups with consistent ordering
161            base = Group.objects.all().filter(**kwargs)
162            if self.group_filters.exists():
163                base = base.filter(pk__in=self.group_filters.values_list("pk", flat=True))
164            return base.order_by("pk")
165        raise ValueError(f"Invalid type {type}")