authentik.core.sources.matcher

Source user and group matching

  1"""Source user and group matching"""
  2
  3from dataclasses import dataclass
  4from enum import Enum
  5from typing import Any
  6
  7from django.db import models
  8from django.db.models import Q
  9from django.utils.translation import gettext_lazy as _
 10from structlog import get_logger
 11
 12from authentik.core.models import (
 13    Group,
 14    GroupSourceConnection,
 15    Source,
 16    SourceGroupMatchingModes,
 17    SourceUserMatchingModes,
 18    User,
 19    UserSourceConnection,
 20)
 21
 22
 23class Action(Enum):
 24    """Actions that can be decided based on the request and source settings"""
 25
 26    LINK = "link"
 27    AUTH = "auth"
 28    ENROLL = "enroll"
 29    DENY = "deny"
 30
 31
 32class MatchFailureReason(models.TextChoices):
 33    """Reason source matching could not determine an action."""
 34
 35    MISSING_PROPERTY = "missing_property", _("Missing property")
 36
 37
 38@dataclass(frozen=True)
 39class MatchFailure:
 40    """Details about a source matching failure."""
 41
 42    reason: MatchFailureReason
 43    property: str
 44    source_slug: str
 45
 46
 47@dataclass
 48class MatchableProperty:
 49    property: str
 50    link_mode: SourceUserMatchingModes | SourceGroupMatchingModes
 51    deny_mode: SourceUserMatchingModes | SourceGroupMatchingModes
 52
 53
 54class SourceMatcher:
 55    def __init__(
 56        self,
 57        source: Source,
 58        user_connection_type: type[UserSourceConnection],
 59        group_connection_type: type[GroupSourceConnection],
 60    ):
 61        self.source = source
 62        self.user_connection_type = user_connection_type
 63        self.group_connection_type = group_connection_type
 64        self.failure: MatchFailure | None = None
 65        self._logger = get_logger().bind(source=self.source)
 66
 67    def get_action(
 68        self,
 69        object_type: type[User | Group],
 70        matchable_properties: list[MatchableProperty],
 71        identifier: str,
 72        properties: dict[str, Any | dict[str, Any]],
 73    ) -> tuple[Action, UserSourceConnection | GroupSourceConnection | None]:
 74        self.failure = None
 75        connection_type = None
 76        matching_mode = None
 77        identifier_matching_mode = None
 78        if object_type == User:
 79            connection_type = self.user_connection_type
 80            matching_mode = self.source.user_matching_mode
 81            identifier_matching_mode = SourceUserMatchingModes.IDENTIFIER
 82        if object_type == Group:
 83            connection_type = self.group_connection_type
 84            matching_mode = self.source.group_matching_mode
 85            identifier_matching_mode = SourceGroupMatchingModes.IDENTIFIER
 86        if not connection_type or not matching_mode or not identifier_matching_mode:
 87            return Action.DENY, None
 88
 89        existing_connections = connection_type.objects.filter(
 90            source=self.source, identifier=identifier
 91        )
 92        if existing_connections.exists():
 93            return Action.AUTH, existing_connections.first()
 94        new_connection = connection_type(source=self.source, identifier=identifier)
 95        # No connection exists, but we match on identifier, so enroll
 96        if matching_mode == identifier_matching_mode:
 97            # We don't save the connection here cause it doesn't have a user/group assigned yet
 98            return Action.ENROLL, new_connection
 99
100        # Check for existing users with matching attributes
101        query = Q()
102        for matchable_property in matchable_properties:
103            property = matchable_property.property
104            if matching_mode in [matchable_property.link_mode, matchable_property.deny_mode]:
105                if not properties.get(property, None):
106                    self.failure = MatchFailure(
107                        reason=MatchFailureReason.MISSING_PROPERTY,
108                        property=property,
109                        source_slug=self.source.slug,
110                    )
111                    self._logger.warning(
112                        "Refusing to use none property", identifier=identifier, property=property
113                    )
114                    return Action.DENY, None
115                query_args = {
116                    f"{property}__exact": properties[property],
117                }
118                query = Q(**query_args)
119        self._logger.debug(
120            "Trying to link with existing object", query=query, identifier=identifier
121        )
122        matching_objects = object_type.objects.filter(query)
123        # Not matching objects, always enroll
124        if not matching_objects.exists():
125            self._logger.debug("No matching objects found, enrolling")
126            return Action.ENROLL, new_connection
127
128        obj = matching_objects.first()
129        if matching_mode in [mp.link_mode for mp in matchable_properties]:
130            attr = None
131            if object_type == User:
132                attr = "user"
133            if object_type == Group:
134                attr = "group"
135            setattr(new_connection, attr, obj)
136            return Action.LINK, new_connection
137        if matching_mode in [mp.deny_mode for mp in matchable_properties]:
138            self._logger.info("Denying source because object exists", obj=obj)
139            return Action.DENY, None
140
141        # Should never get here as default enroll case is returned above.
142        return Action.DENY, None  # pragma: no cover
143
144    def get_user_action(
145        self, identifier: str, properties: dict[str, Any | dict[str, Any]]
146    ) -> tuple[Action, UserSourceConnection | None]:
147        return self.get_action(
148            User,
149            [
150                MatchableProperty(
151                    "username",
152                    SourceUserMatchingModes.USERNAME_LINK,
153                    SourceUserMatchingModes.USERNAME_DENY,
154                ),
155                MatchableProperty(
156                    "email", SourceUserMatchingModes.EMAIL_LINK, SourceUserMatchingModes.EMAIL_DENY
157                ),
158            ],
159            identifier,
160            properties,
161        )
162
163    def get_group_action(
164        self, identifier: str, properties: dict[str, Any | dict[str, Any]]
165    ) -> tuple[Action, GroupSourceConnection | None]:
166        return self.get_action(
167            Group,
168            [
169                MatchableProperty(
170                    "name", SourceGroupMatchingModes.NAME_LINK, SourceGroupMatchingModes.NAME_DENY
171                ),
172            ],
173            identifier,
174            properties,
175        )
class Action(enum.Enum):
24class Action(Enum):
25    """Actions that can be decided based on the request and source settings"""
26
27    LINK = "link"
28    AUTH = "auth"
29    ENROLL = "enroll"
30    DENY = "deny"

Actions that can be decided based on the request and source settings

AUTH = <Action.AUTH: 'auth'>
ENROLL = <Action.ENROLL: 'enroll'>
DENY = <Action.DENY: 'deny'>
class MatchFailureReason(django.db.models.enums.TextChoices):
33class MatchFailureReason(models.TextChoices):
34    """Reason source matching could not determine an action."""
35
36    MISSING_PROPERTY = "missing_property", _("Missing property")

Reason source matching could not determine an action.

@dataclass(frozen=True)
class MatchFailure:
39@dataclass(frozen=True)
40class MatchFailure:
41    """Details about a source matching failure."""
42
43    reason: MatchFailureReason
44    property: str
45    source_slug: str

Details about a source matching failure.

MatchFailure( reason: MatchFailureReason, property: str, source_slug: str)
property: str
source_slug: str
@dataclass
class MatchableProperty:
48@dataclass
49class MatchableProperty:
50    property: str
51    link_mode: SourceUserMatchingModes | SourceGroupMatchingModes
52    deny_mode: SourceUserMatchingModes | SourceGroupMatchingModes
property: str
class SourceMatcher:
 55class SourceMatcher:
 56    def __init__(
 57        self,
 58        source: Source,
 59        user_connection_type: type[UserSourceConnection],
 60        group_connection_type: type[GroupSourceConnection],
 61    ):
 62        self.source = source
 63        self.user_connection_type = user_connection_type
 64        self.group_connection_type = group_connection_type
 65        self.failure: MatchFailure | None = None
 66        self._logger = get_logger().bind(source=self.source)
 67
 68    def get_action(
 69        self,
 70        object_type: type[User | Group],
 71        matchable_properties: list[MatchableProperty],
 72        identifier: str,
 73        properties: dict[str, Any | dict[str, Any]],
 74    ) -> tuple[Action, UserSourceConnection | GroupSourceConnection | None]:
 75        self.failure = None
 76        connection_type = None
 77        matching_mode = None
 78        identifier_matching_mode = None
 79        if object_type == User:
 80            connection_type = self.user_connection_type
 81            matching_mode = self.source.user_matching_mode
 82            identifier_matching_mode = SourceUserMatchingModes.IDENTIFIER
 83        if object_type == Group:
 84            connection_type = self.group_connection_type
 85            matching_mode = self.source.group_matching_mode
 86            identifier_matching_mode = SourceGroupMatchingModes.IDENTIFIER
 87        if not connection_type or not matching_mode or not identifier_matching_mode:
 88            return Action.DENY, None
 89
 90        existing_connections = connection_type.objects.filter(
 91            source=self.source, identifier=identifier
 92        )
 93        if existing_connections.exists():
 94            return Action.AUTH, existing_connections.first()
 95        new_connection = connection_type(source=self.source, identifier=identifier)
 96        # No connection exists, but we match on identifier, so enroll
 97        if matching_mode == identifier_matching_mode:
 98            # We don't save the connection here cause it doesn't have a user/group assigned yet
 99            return Action.ENROLL, new_connection
100
101        # Check for existing users with matching attributes
102        query = Q()
103        for matchable_property in matchable_properties:
104            property = matchable_property.property
105            if matching_mode in [matchable_property.link_mode, matchable_property.deny_mode]:
106                if not properties.get(property, None):
107                    self.failure = MatchFailure(
108                        reason=MatchFailureReason.MISSING_PROPERTY,
109                        property=property,
110                        source_slug=self.source.slug,
111                    )
112                    self._logger.warning(
113                        "Refusing to use none property", identifier=identifier, property=property
114                    )
115                    return Action.DENY, None
116                query_args = {
117                    f"{property}__exact": properties[property],
118                }
119                query = Q(**query_args)
120        self._logger.debug(
121            "Trying to link with existing object", query=query, identifier=identifier
122        )
123        matching_objects = object_type.objects.filter(query)
124        # Not matching objects, always enroll
125        if not matching_objects.exists():
126            self._logger.debug("No matching objects found, enrolling")
127            return Action.ENROLL, new_connection
128
129        obj = matching_objects.first()
130        if matching_mode in [mp.link_mode for mp in matchable_properties]:
131            attr = None
132            if object_type == User:
133                attr = "user"
134            if object_type == Group:
135                attr = "group"
136            setattr(new_connection, attr, obj)
137            return Action.LINK, new_connection
138        if matching_mode in [mp.deny_mode for mp in matchable_properties]:
139            self._logger.info("Denying source because object exists", obj=obj)
140            return Action.DENY, None
141
142        # Should never get here as default enroll case is returned above.
143        return Action.DENY, None  # pragma: no cover
144
145    def get_user_action(
146        self, identifier: str, properties: dict[str, Any | dict[str, Any]]
147    ) -> tuple[Action, UserSourceConnection | None]:
148        return self.get_action(
149            User,
150            [
151                MatchableProperty(
152                    "username",
153                    SourceUserMatchingModes.USERNAME_LINK,
154                    SourceUserMatchingModes.USERNAME_DENY,
155                ),
156                MatchableProperty(
157                    "email", SourceUserMatchingModes.EMAIL_LINK, SourceUserMatchingModes.EMAIL_DENY
158                ),
159            ],
160            identifier,
161            properties,
162        )
163
164    def get_group_action(
165        self, identifier: str, properties: dict[str, Any | dict[str, Any]]
166    ) -> tuple[Action, GroupSourceConnection | None]:
167        return self.get_action(
168            Group,
169            [
170                MatchableProperty(
171                    "name", SourceGroupMatchingModes.NAME_LINK, SourceGroupMatchingModes.NAME_DENY
172                ),
173            ],
174            identifier,
175            properties,
176        )
SourceMatcher( source: authentik.core.models.Source, user_connection_type: type[authentik.core.models.UserSourceConnection], group_connection_type: type[authentik.core.models.GroupSourceConnection])
56    def __init__(
57        self,
58        source: Source,
59        user_connection_type: type[UserSourceConnection],
60        group_connection_type: type[GroupSourceConnection],
61    ):
62        self.source = source
63        self.user_connection_type = user_connection_type
64        self.group_connection_type = group_connection_type
65        self.failure: MatchFailure | None = None
66        self._logger = get_logger().bind(source=self.source)
source
user_connection_type
group_connection_type
failure: MatchFailure | None
def get_action( self, object_type: type[authentik.core.models.User | authentik.core.models.Group], matchable_properties: list[MatchableProperty], identifier: str, properties: dict[str, typing.Any | dict[str, typing.Any]]) -> tuple[Action, authentik.core.models.UserSourceConnection | authentik.core.models.GroupSourceConnection | None]:
 68    def get_action(
 69        self,
 70        object_type: type[User | Group],
 71        matchable_properties: list[MatchableProperty],
 72        identifier: str,
 73        properties: dict[str, Any | dict[str, Any]],
 74    ) -> tuple[Action, UserSourceConnection | GroupSourceConnection | None]:
 75        self.failure = None
 76        connection_type = None
 77        matching_mode = None
 78        identifier_matching_mode = None
 79        if object_type == User:
 80            connection_type = self.user_connection_type
 81            matching_mode = self.source.user_matching_mode
 82            identifier_matching_mode = SourceUserMatchingModes.IDENTIFIER
 83        if object_type == Group:
 84            connection_type = self.group_connection_type
 85            matching_mode = self.source.group_matching_mode
 86            identifier_matching_mode = SourceGroupMatchingModes.IDENTIFIER
 87        if not connection_type or not matching_mode or not identifier_matching_mode:
 88            return Action.DENY, None
 89
 90        existing_connections = connection_type.objects.filter(
 91            source=self.source, identifier=identifier
 92        )
 93        if existing_connections.exists():
 94            return Action.AUTH, existing_connections.first()
 95        new_connection = connection_type(source=self.source, identifier=identifier)
 96        # No connection exists, but we match on identifier, so enroll
 97        if matching_mode == identifier_matching_mode:
 98            # We don't save the connection here cause it doesn't have a user/group assigned yet
 99            return Action.ENROLL, new_connection
100
101        # Check for existing users with matching attributes
102        query = Q()
103        for matchable_property in matchable_properties:
104            property = matchable_property.property
105            if matching_mode in [matchable_property.link_mode, matchable_property.deny_mode]:
106                if not properties.get(property, None):
107                    self.failure = MatchFailure(
108                        reason=MatchFailureReason.MISSING_PROPERTY,
109                        property=property,
110                        source_slug=self.source.slug,
111                    )
112                    self._logger.warning(
113                        "Refusing to use none property", identifier=identifier, property=property
114                    )
115                    return Action.DENY, None
116                query_args = {
117                    f"{property}__exact": properties[property],
118                }
119                query = Q(**query_args)
120        self._logger.debug(
121            "Trying to link with existing object", query=query, identifier=identifier
122        )
123        matching_objects = object_type.objects.filter(query)
124        # Not matching objects, always enroll
125        if not matching_objects.exists():
126            self._logger.debug("No matching objects found, enrolling")
127            return Action.ENROLL, new_connection
128
129        obj = matching_objects.first()
130        if matching_mode in [mp.link_mode for mp in matchable_properties]:
131            attr = None
132            if object_type == User:
133                attr = "user"
134            if object_type == Group:
135                attr = "group"
136            setattr(new_connection, attr, obj)
137            return Action.LINK, new_connection
138        if matching_mode in [mp.deny_mode for mp in matchable_properties]:
139            self._logger.info("Denying source because object exists", obj=obj)
140            return Action.DENY, None
141
142        # Should never get here as default enroll case is returned above.
143        return Action.DENY, None  # pragma: no cover
def get_user_action( self, identifier: str, properties: dict[str, typing.Any | dict[str, typing.Any]]) -> tuple[Action, authentik.core.models.UserSourceConnection | None]:
145    def get_user_action(
146        self, identifier: str, properties: dict[str, Any | dict[str, Any]]
147    ) -> tuple[Action, UserSourceConnection | None]:
148        return self.get_action(
149            User,
150            [
151                MatchableProperty(
152                    "username",
153                    SourceUserMatchingModes.USERNAME_LINK,
154                    SourceUserMatchingModes.USERNAME_DENY,
155                ),
156                MatchableProperty(
157                    "email", SourceUserMatchingModes.EMAIL_LINK, SourceUserMatchingModes.EMAIL_DENY
158                ),
159            ],
160            identifier,
161            properties,
162        )
def get_group_action( self, identifier: str, properties: dict[str, typing.Any | dict[str, typing.Any]]) -> tuple[Action, authentik.core.models.GroupSourceConnection | None]:
164    def get_group_action(
165        self, identifier: str, properties: dict[str, Any | dict[str, Any]]
166    ) -> tuple[Action, GroupSourceConnection | None]:
167        return self.get_action(
168            Group,
169            [
170                MatchableProperty(
171                    "name", SourceGroupMatchingModes.NAME_LINK, SourceGroupMatchingModes.NAME_DENY
172                ),
173            ],
174            identifier,
175            properties,
176        )