authentik.sources.ldap.tests.test_api

LDAP Source API tests

  1"""LDAP Source API tests"""
  2
  3from json import loads
  4from unittest.mock import MagicMock, patch
  5
  6from django.db.models import Q
  7from django.urls import reverse
  8from rest_framework.exceptions import ErrorDetail
  9from rest_framework.test import APITestCase
 10
 11from authentik.blueprints.tests import apply_blueprint
 12from authentik.core.tests.utils import create_test_admin_user, create_test_cert, create_test_user
 13from authentik.lib.generators import generate_id
 14from authentik.sources.ldap.api.sources import LDAPSourceSerializer
 15from authentik.sources.ldap.models import (
 16    LDAPSource,
 17    LDAPSourceBindMethod,
 18    LDAPSourcePropertyMapping,
 19)
 20from authentik.sources.ldap.tests.mock_ad import mock_ad_connection
 21
 22
 23class LDAPAPITests(APITestCase):
 24    """LDAP API tests"""
 25
 26    def source_data(self, **kwargs):
 27        """Build serializer data for an LDAP source."""
 28        data = {
 29            "name": "foo",
 30            "slug": generate_id(),
 31            "server_uri": "ldaps://1.2.3.4",
 32            "base_dn": "dc=foo",
 33        }
 34        data.update(kwargs)
 35        return data
 36
 37    def external_source_data(self, **kwargs):
 38        """Build serializer data for a SASL EXTERNAL source."""
 39        data = self.source_data(
 40            name="external",
 41            server_uri="ldap://ldap.example.com",
 42            start_tls=True,
 43            client_certificate=create_test_cert().pk,
 44            service_bind_method=LDAPSourceBindMethod.SASL_EXTERNAL,
 45            base_dn="dc=example,dc=com",
 46            sync_users_password=False,
 47        )
 48        data.update(kwargs)
 49        return data
 50
 51    def test_sasl_external_valid(self):
 52        """SASL EXTERNAL accepts a client certificate over StartTLS."""
 53        serializer = LDAPSourceSerializer(data=self.external_source_data())
 54        self.assertTrue(serializer.is_valid())
 55        self.assertEqual(serializer.errors, {})
 56
 57    def test_sasl_external_valid_ldaps(self):
 58        """SASL EXTERNAL accepts a client certificate over LDAPS."""
 59        serializer = LDAPSourceSerializer(
 60            data=self.external_source_data(
 61                server_uri="ldaps://ldap.example.com",
 62                start_tls=False,
 63            )
 64        )
 65        self.assertTrue(serializer.is_valid())
 66        self.assertEqual(serializer.errors, {})
 67
 68    def test_sasl_external_requires_certificate(self):
 69        """SASL EXTERNAL requires a client certificate and private key."""
 70        serializer = LDAPSourceSerializer(data=self.external_source_data(client_certificate=None))
 71        self.assertFalse(serializer.is_valid())
 72        self.assertEqual(
 73            serializer.errors,
 74            {
 75                "client_certificate": [
 76                    ErrorDetail(
 77                        string=("SASL EXTERNAL requires a client certificate with a private key."),
 78                        code="invalid",
 79                    )
 80                ]
 81            },
 82        )
 83
 84    def test_sasl_external_rejects_plaintext(self):
 85        """SASL EXTERNAL rejects LDAP without StartTLS."""
 86        serializer = LDAPSourceSerializer(data=self.external_source_data(start_tls=False))
 87        self.assertFalse(serializer.is_valid())
 88        self.assertEqual(
 89            serializer.errors,
 90            {
 91                "server_uri": [
 92                    ErrorDetail(
 93                        string=(
 94                            "SASL EXTERNAL requires ldap:// with StartTLS or ldaps:// without "
 95                            "StartTLS."
 96                        ),
 97                        code="invalid",
 98                    )
 99                ]
100            },
101        )
102
103    def test_sasl_external_rejects_start_tls_over_ldaps(self):
104        """SASL EXTERNAL rejects StartTLS when the URI already uses LDAPS."""
105        serializer = LDAPSourceSerializer(
106            data=self.external_source_data(server_uri="ldaps://ldap.example.com")
107        )
108        self.assertFalse(serializer.is_valid())
109        self.assertEqual(
110            serializer.errors,
111            {
112                "server_uri": [
113                    ErrorDetail(
114                        string=(
115                            "SASL EXTERNAL requires ldap:// with StartTLS or ldaps:// without "
116                            "StartTLS."
117                        ),
118                        code="invalid",
119                    )
120                ]
121            },
122        )
123
124    def test_sasl_external_rejects_mixed_server_schemes(self):
125        """Every server in a SASL EXTERNAL pool must use the same secure transport."""
126        serializer = LDAPSourceSerializer(
127            data=self.external_source_data(
128                server_uri="ldap://ldap.example.com,ldaps://ldap.example.net"
129            )
130        )
131        self.assertFalse(serializer.is_valid())
132        self.assertEqual(
133            serializer.errors,
134            {
135                "server_uri": [
136                    ErrorDetail(
137                        string=(
138                            "SASL EXTERNAL requires ldap:// with StartTLS or ldaps:// without "
139                            "StartTLS."
140                        ),
141                        code="invalid",
142                    )
143                ]
144            },
145        )
146
147    def test_sasl_external_partial_update(self):
148        """Partial updates validate changed fields against existing source fields."""
149        source = LDAPSource.objects.create(
150            **self.source_data(
151                name="external",
152                server_uri="ldap://ldap.example.com",
153                start_tls=True,
154                client_certificate=create_test_cert(),
155                service_bind_method=LDAPSourceBindMethod.SASL_EXTERNAL,
156                base_dn="dc=example,dc=com",
157                sync_users_password=False,
158            )
159        )
160        serializer = LDAPSourceSerializer(
161            source,
162            data={"start_tls": False},
163            partial=True,
164        )
165        self.assertFalse(serializer.is_valid())
166        self.assertEqual(
167            serializer.errors,
168            {
169                "server_uri": [
170                    ErrorDetail(
171                        string=(
172                            "SASL EXTERNAL requires ldap:// with StartTLS or ldaps:// without "
173                            "StartTLS."
174                        ),
175                        code="invalid",
176                    )
177                ]
178            },
179        )
180
181    def test_sync_users_password_valid(self):
182        """Check that single source with sync_users_password is valid"""
183        serializer = LDAPSourceSerializer(
184            data=self.source_data(
185                slug=" foo",
186                bind_cn="",
187                bind_password=generate_id(),
188                sync_users_password=True,
189            )
190        )
191        self.assertTrue(serializer.is_valid())
192        self.assertEqual(serializer.errors, {})
193
194    def test_sync_users_password_invalid(self):
195        """Ensure only a single source with password sync can be created"""
196        LDAPSource.objects.create(
197            **self.source_data(
198                bind_cn="",
199                bind_password=generate_id(),
200                sync_users_password=True,
201            )
202        )
203        serializer = LDAPSourceSerializer(
204            data=self.source_data(
205                bind_cn="",
206                bind_password=generate_id(),
207                sync_users_password=True,
208            )
209        )
210        self.assertFalse(serializer.is_valid())
211        self.assertEqual(
212            serializer.errors,
213            {
214                "sync_users_password": [
215                    ErrorDetail(
216                        string="Only a single LDAP Source with password synchronization is allowed",
217                        code="invalid",
218                    )
219                ]
220            },
221        )
222
223    def test_sync_users_mapping_empty(self):
224        """Check that when sync_users is enabled, property mappings must be set"""
225        serializer = LDAPSourceSerializer(
226            data=self.source_data(
227                slug=" foo",
228                bind_cn="",
229                bind_password=generate_id(),
230                sync_users=True,
231                user_property_mappings=[],
232            )
233        )
234        self.assertFalse(serializer.is_valid())
235
236    def test_sync_groups_mapping_empty(self):
237        """Check that when sync_groups is enabled, property mappings must be set"""
238        serializer = LDAPSourceSerializer(
239            data=self.source_data(
240                slug=" foo",
241                bind_cn="",
242                bind_password=generate_id(),
243                sync_groups=True,
244                group_property_mappings=[],
245            )
246        )
247        self.assertFalse(serializer.is_valid())
248
249    @apply_blueprint("system/sources-ldap.yaml")
250    def test_sync_debug(self):
251        user = create_test_admin_user()
252        self.client.force_login(user)
253
254        source: LDAPSource = LDAPSource.objects.create(
255            name=generate_id(),
256            slug=generate_id(),
257            base_dn="dc=goauthentik,dc=io",
258            additional_user_dn="ou=users",
259            additional_group_dn="ou=groups",
260        )
261        source.user_property_mappings.set(
262            LDAPSourcePropertyMapping.objects.filter(
263                Q(managed__startswith="goauthentik.io/sources/ldap/default")
264                | Q(managed__startswith="goauthentik.io/sources/ldap/ms")
265            )
266        )
267        connection = MagicMock(return_value=mock_ad_connection())
268        with patch("authentik.sources.ldap.models.LDAPSource.connection", connection):
269            res = self.client.get(
270                reverse("authentik_api:ldapsource-debug", kwargs={"slug": source.slug})
271            )
272            self.assertEqual(res.status_code, 200)
273            body = loads(res.content.decode())
274            self.assertIn("users", body)
275            self.assertIn("groups", body)
276            self.assertIn("membership", body)
277
278    def _create_debug_source(self) -> LDAPSource:
279        return LDAPSource.objects.create(
280            name=generate_id(),
281            slug=generate_id(),
282            base_dn="dc=goauthentik,dc=io",
283            additional_user_dn="ou=users",
284            additional_group_dn="ou=groups",
285        )
286
287    @apply_blueprint("system/sources-ldap.yaml")
288    def test_debug_denied_for_anonymous(self):
289        """debug must enforce RBAC: an anonymous caller may not read LDAP data."""
290        source = self._create_debug_source()
291        # NOTE: no self.client.force_login() -> caller is AnonymousUser
292        connection = MagicMock(return_value=mock_ad_connection())
293        with patch("authentik.sources.ldap.models.LDAPSource.connection", connection):
294            res = self.client.get(
295                reverse("authentik_api:ldapsource-debug", kwargs={"slug": source.slug})
296            )
297        self.assertEqual(res.status_code, 403)
298
299    @apply_blueprint("system/sources-ldap.yaml")
300    def test_debug_denied_for_unauthorized_user(self):
301        """debug must enforce RBAC: a user without view_ldapsource may not read LDAP data."""
302        source = self._create_debug_source()
303        # Authenticated, but holds no permission on the source object
304        self.client.force_login(create_test_user())
305        connection = MagicMock(return_value=mock_ad_connection())
306        with patch("authentik.sources.ldap.models.LDAPSource.connection", connection):
307            res = self.client.get(
308                reverse("authentik_api:ldapsource-debug", kwargs={"slug": source.slug})
309            )
310        self.assertEqual(res.status_code, 403)
class LDAPAPITests(rest_framework.test.APITestCase):
 24class LDAPAPITests(APITestCase):
 25    """LDAP API tests"""
 26
 27    def source_data(self, **kwargs):
 28        """Build serializer data for an LDAP source."""
 29        data = {
 30            "name": "foo",
 31            "slug": generate_id(),
 32            "server_uri": "ldaps://1.2.3.4",
 33            "base_dn": "dc=foo",
 34        }
 35        data.update(kwargs)
 36        return data
 37
 38    def external_source_data(self, **kwargs):
 39        """Build serializer data for a SASL EXTERNAL source."""
 40        data = self.source_data(
 41            name="external",
 42            server_uri="ldap://ldap.example.com",
 43            start_tls=True,
 44            client_certificate=create_test_cert().pk,
 45            service_bind_method=LDAPSourceBindMethod.SASL_EXTERNAL,
 46            base_dn="dc=example,dc=com",
 47            sync_users_password=False,
 48        )
 49        data.update(kwargs)
 50        return data
 51
 52    def test_sasl_external_valid(self):
 53        """SASL EXTERNAL accepts a client certificate over StartTLS."""
 54        serializer = LDAPSourceSerializer(data=self.external_source_data())
 55        self.assertTrue(serializer.is_valid())
 56        self.assertEqual(serializer.errors, {})
 57
 58    def test_sasl_external_valid_ldaps(self):
 59        """SASL EXTERNAL accepts a client certificate over LDAPS."""
 60        serializer = LDAPSourceSerializer(
 61            data=self.external_source_data(
 62                server_uri="ldaps://ldap.example.com",
 63                start_tls=False,
 64            )
 65        )
 66        self.assertTrue(serializer.is_valid())
 67        self.assertEqual(serializer.errors, {})
 68
 69    def test_sasl_external_requires_certificate(self):
 70        """SASL EXTERNAL requires a client certificate and private key."""
 71        serializer = LDAPSourceSerializer(data=self.external_source_data(client_certificate=None))
 72        self.assertFalse(serializer.is_valid())
 73        self.assertEqual(
 74            serializer.errors,
 75            {
 76                "client_certificate": [
 77                    ErrorDetail(
 78                        string=("SASL EXTERNAL requires a client certificate with a private key."),
 79                        code="invalid",
 80                    )
 81                ]
 82            },
 83        )
 84
 85    def test_sasl_external_rejects_plaintext(self):
 86        """SASL EXTERNAL rejects LDAP without StartTLS."""
 87        serializer = LDAPSourceSerializer(data=self.external_source_data(start_tls=False))
 88        self.assertFalse(serializer.is_valid())
 89        self.assertEqual(
 90            serializer.errors,
 91            {
 92                "server_uri": [
 93                    ErrorDetail(
 94                        string=(
 95                            "SASL EXTERNAL requires ldap:// with StartTLS or ldaps:// without "
 96                            "StartTLS."
 97                        ),
 98                        code="invalid",
 99                    )
100                ]
101            },
102        )
103
104    def test_sasl_external_rejects_start_tls_over_ldaps(self):
105        """SASL EXTERNAL rejects StartTLS when the URI already uses LDAPS."""
106        serializer = LDAPSourceSerializer(
107            data=self.external_source_data(server_uri="ldaps://ldap.example.com")
108        )
109        self.assertFalse(serializer.is_valid())
110        self.assertEqual(
111            serializer.errors,
112            {
113                "server_uri": [
114                    ErrorDetail(
115                        string=(
116                            "SASL EXTERNAL requires ldap:// with StartTLS or ldaps:// without "
117                            "StartTLS."
118                        ),
119                        code="invalid",
120                    )
121                ]
122            },
123        )
124
125    def test_sasl_external_rejects_mixed_server_schemes(self):
126        """Every server in a SASL EXTERNAL pool must use the same secure transport."""
127        serializer = LDAPSourceSerializer(
128            data=self.external_source_data(
129                server_uri="ldap://ldap.example.com,ldaps://ldap.example.net"
130            )
131        )
132        self.assertFalse(serializer.is_valid())
133        self.assertEqual(
134            serializer.errors,
135            {
136                "server_uri": [
137                    ErrorDetail(
138                        string=(
139                            "SASL EXTERNAL requires ldap:// with StartTLS or ldaps:// without "
140                            "StartTLS."
141                        ),
142                        code="invalid",
143                    )
144                ]
145            },
146        )
147
148    def test_sasl_external_partial_update(self):
149        """Partial updates validate changed fields against existing source fields."""
150        source = LDAPSource.objects.create(
151            **self.source_data(
152                name="external",
153                server_uri="ldap://ldap.example.com",
154                start_tls=True,
155                client_certificate=create_test_cert(),
156                service_bind_method=LDAPSourceBindMethod.SASL_EXTERNAL,
157                base_dn="dc=example,dc=com",
158                sync_users_password=False,
159            )
160        )
161        serializer = LDAPSourceSerializer(
162            source,
163            data={"start_tls": False},
164            partial=True,
165        )
166        self.assertFalse(serializer.is_valid())
167        self.assertEqual(
168            serializer.errors,
169            {
170                "server_uri": [
171                    ErrorDetail(
172                        string=(
173                            "SASL EXTERNAL requires ldap:// with StartTLS or ldaps:// without "
174                            "StartTLS."
175                        ),
176                        code="invalid",
177                    )
178                ]
179            },
180        )
181
182    def test_sync_users_password_valid(self):
183        """Check that single source with sync_users_password is valid"""
184        serializer = LDAPSourceSerializer(
185            data=self.source_data(
186                slug=" foo",
187                bind_cn="",
188                bind_password=generate_id(),
189                sync_users_password=True,
190            )
191        )
192        self.assertTrue(serializer.is_valid())
193        self.assertEqual(serializer.errors, {})
194
195    def test_sync_users_password_invalid(self):
196        """Ensure only a single source with password sync can be created"""
197        LDAPSource.objects.create(
198            **self.source_data(
199                bind_cn="",
200                bind_password=generate_id(),
201                sync_users_password=True,
202            )
203        )
204        serializer = LDAPSourceSerializer(
205            data=self.source_data(
206                bind_cn="",
207                bind_password=generate_id(),
208                sync_users_password=True,
209            )
210        )
211        self.assertFalse(serializer.is_valid())
212        self.assertEqual(
213            serializer.errors,
214            {
215                "sync_users_password": [
216                    ErrorDetail(
217                        string="Only a single LDAP Source with password synchronization is allowed",
218                        code="invalid",
219                    )
220                ]
221            },
222        )
223
224    def test_sync_users_mapping_empty(self):
225        """Check that when sync_users is enabled, property mappings must be set"""
226        serializer = LDAPSourceSerializer(
227            data=self.source_data(
228                slug=" foo",
229                bind_cn="",
230                bind_password=generate_id(),
231                sync_users=True,
232                user_property_mappings=[],
233            )
234        )
235        self.assertFalse(serializer.is_valid())
236
237    def test_sync_groups_mapping_empty(self):
238        """Check that when sync_groups is enabled, property mappings must be set"""
239        serializer = LDAPSourceSerializer(
240            data=self.source_data(
241                slug=" foo",
242                bind_cn="",
243                bind_password=generate_id(),
244                sync_groups=True,
245                group_property_mappings=[],
246            )
247        )
248        self.assertFalse(serializer.is_valid())
249
250    @apply_blueprint("system/sources-ldap.yaml")
251    def test_sync_debug(self):
252        user = create_test_admin_user()
253        self.client.force_login(user)
254
255        source: LDAPSource = LDAPSource.objects.create(
256            name=generate_id(),
257            slug=generate_id(),
258            base_dn="dc=goauthentik,dc=io",
259            additional_user_dn="ou=users",
260            additional_group_dn="ou=groups",
261        )
262        source.user_property_mappings.set(
263            LDAPSourcePropertyMapping.objects.filter(
264                Q(managed__startswith="goauthentik.io/sources/ldap/default")
265                | Q(managed__startswith="goauthentik.io/sources/ldap/ms")
266            )
267        )
268        connection = MagicMock(return_value=mock_ad_connection())
269        with patch("authentik.sources.ldap.models.LDAPSource.connection", connection):
270            res = self.client.get(
271                reverse("authentik_api:ldapsource-debug", kwargs={"slug": source.slug})
272            )
273            self.assertEqual(res.status_code, 200)
274            body = loads(res.content.decode())
275            self.assertIn("users", body)
276            self.assertIn("groups", body)
277            self.assertIn("membership", body)
278
279    def _create_debug_source(self) -> LDAPSource:
280        return LDAPSource.objects.create(
281            name=generate_id(),
282            slug=generate_id(),
283            base_dn="dc=goauthentik,dc=io",
284            additional_user_dn="ou=users",
285            additional_group_dn="ou=groups",
286        )
287
288    @apply_blueprint("system/sources-ldap.yaml")
289    def test_debug_denied_for_anonymous(self):
290        """debug must enforce RBAC: an anonymous caller may not read LDAP data."""
291        source = self._create_debug_source()
292        # NOTE: no self.client.force_login() -> caller is AnonymousUser
293        connection = MagicMock(return_value=mock_ad_connection())
294        with patch("authentik.sources.ldap.models.LDAPSource.connection", connection):
295            res = self.client.get(
296                reverse("authentik_api:ldapsource-debug", kwargs={"slug": source.slug})
297            )
298        self.assertEqual(res.status_code, 403)
299
300    @apply_blueprint("system/sources-ldap.yaml")
301    def test_debug_denied_for_unauthorized_user(self):
302        """debug must enforce RBAC: a user without view_ldapsource may not read LDAP data."""
303        source = self._create_debug_source()
304        # Authenticated, but holds no permission on the source object
305        self.client.force_login(create_test_user())
306        connection = MagicMock(return_value=mock_ad_connection())
307        with patch("authentik.sources.ldap.models.LDAPSource.connection", connection):
308            res = self.client.get(
309                reverse("authentik_api:ldapsource-debug", kwargs={"slug": source.slug})
310            )
311        self.assertEqual(res.status_code, 403)

LDAP API tests

def source_data(self, **kwargs):
27    def source_data(self, **kwargs):
28        """Build serializer data for an LDAP source."""
29        data = {
30            "name": "foo",
31            "slug": generate_id(),
32            "server_uri": "ldaps://1.2.3.4",
33            "base_dn": "dc=foo",
34        }
35        data.update(kwargs)
36        return data

Build serializer data for an LDAP source.

def external_source_data(self, **kwargs):
38    def external_source_data(self, **kwargs):
39        """Build serializer data for a SASL EXTERNAL source."""
40        data = self.source_data(
41            name="external",
42            server_uri="ldap://ldap.example.com",
43            start_tls=True,
44            client_certificate=create_test_cert().pk,
45            service_bind_method=LDAPSourceBindMethod.SASL_EXTERNAL,
46            base_dn="dc=example,dc=com",
47            sync_users_password=False,
48        )
49        data.update(kwargs)
50        return data

Build serializer data for a SASL EXTERNAL source.

def test_sasl_external_valid(self):
52    def test_sasl_external_valid(self):
53        """SASL EXTERNAL accepts a client certificate over StartTLS."""
54        serializer = LDAPSourceSerializer(data=self.external_source_data())
55        self.assertTrue(serializer.is_valid())
56        self.assertEqual(serializer.errors, {})

SASL EXTERNAL accepts a client certificate over StartTLS.

def test_sasl_external_valid_ldaps(self):
58    def test_sasl_external_valid_ldaps(self):
59        """SASL EXTERNAL accepts a client certificate over LDAPS."""
60        serializer = LDAPSourceSerializer(
61            data=self.external_source_data(
62                server_uri="ldaps://ldap.example.com",
63                start_tls=False,
64            )
65        )
66        self.assertTrue(serializer.is_valid())
67        self.assertEqual(serializer.errors, {})

SASL EXTERNAL accepts a client certificate over LDAPS.

def test_sasl_external_requires_certificate(self):
69    def test_sasl_external_requires_certificate(self):
70        """SASL EXTERNAL requires a client certificate and private key."""
71        serializer = LDAPSourceSerializer(data=self.external_source_data(client_certificate=None))
72        self.assertFalse(serializer.is_valid())
73        self.assertEqual(
74            serializer.errors,
75            {
76                "client_certificate": [
77                    ErrorDetail(
78                        string=("SASL EXTERNAL requires a client certificate with a private key."),
79                        code="invalid",
80                    )
81                ]
82            },
83        )

SASL EXTERNAL requires a client certificate and private key.

def test_sasl_external_rejects_plaintext(self):
 85    def test_sasl_external_rejects_plaintext(self):
 86        """SASL EXTERNAL rejects LDAP without StartTLS."""
 87        serializer = LDAPSourceSerializer(data=self.external_source_data(start_tls=False))
 88        self.assertFalse(serializer.is_valid())
 89        self.assertEqual(
 90            serializer.errors,
 91            {
 92                "server_uri": [
 93                    ErrorDetail(
 94                        string=(
 95                            "SASL EXTERNAL requires ldap:// with StartTLS or ldaps:// without "
 96                            "StartTLS."
 97                        ),
 98                        code="invalid",
 99                    )
100                ]
101            },
102        )

SASL EXTERNAL rejects LDAP without StartTLS.

def test_sasl_external_rejects_start_tls_over_ldaps(self):
104    def test_sasl_external_rejects_start_tls_over_ldaps(self):
105        """SASL EXTERNAL rejects StartTLS when the URI already uses LDAPS."""
106        serializer = LDAPSourceSerializer(
107            data=self.external_source_data(server_uri="ldaps://ldap.example.com")
108        )
109        self.assertFalse(serializer.is_valid())
110        self.assertEqual(
111            serializer.errors,
112            {
113                "server_uri": [
114                    ErrorDetail(
115                        string=(
116                            "SASL EXTERNAL requires ldap:// with StartTLS or ldaps:// without "
117                            "StartTLS."
118                        ),
119                        code="invalid",
120                    )
121                ]
122            },
123        )

SASL EXTERNAL rejects StartTLS when the URI already uses LDAPS.

def test_sasl_external_rejects_mixed_server_schemes(self):
125    def test_sasl_external_rejects_mixed_server_schemes(self):
126        """Every server in a SASL EXTERNAL pool must use the same secure transport."""
127        serializer = LDAPSourceSerializer(
128            data=self.external_source_data(
129                server_uri="ldap://ldap.example.com,ldaps://ldap.example.net"
130            )
131        )
132        self.assertFalse(serializer.is_valid())
133        self.assertEqual(
134            serializer.errors,
135            {
136                "server_uri": [
137                    ErrorDetail(
138                        string=(
139                            "SASL EXTERNAL requires ldap:// with StartTLS or ldaps:// without "
140                            "StartTLS."
141                        ),
142                        code="invalid",
143                    )
144                ]
145            },
146        )

Every server in a SASL EXTERNAL pool must use the same secure transport.

def test_sasl_external_partial_update(self):
148    def test_sasl_external_partial_update(self):
149        """Partial updates validate changed fields against existing source fields."""
150        source = LDAPSource.objects.create(
151            **self.source_data(
152                name="external",
153                server_uri="ldap://ldap.example.com",
154                start_tls=True,
155                client_certificate=create_test_cert(),
156                service_bind_method=LDAPSourceBindMethod.SASL_EXTERNAL,
157                base_dn="dc=example,dc=com",
158                sync_users_password=False,
159            )
160        )
161        serializer = LDAPSourceSerializer(
162            source,
163            data={"start_tls": False},
164            partial=True,
165        )
166        self.assertFalse(serializer.is_valid())
167        self.assertEqual(
168            serializer.errors,
169            {
170                "server_uri": [
171                    ErrorDetail(
172                        string=(
173                            "SASL EXTERNAL requires ldap:// with StartTLS or ldaps:// without "
174                            "StartTLS."
175                        ),
176                        code="invalid",
177                    )
178                ]
179            },
180        )

Partial updates validate changed fields against existing source fields.

def test_sync_users_password_valid(self):
182    def test_sync_users_password_valid(self):
183        """Check that single source with sync_users_password is valid"""
184        serializer = LDAPSourceSerializer(
185            data=self.source_data(
186                slug=" foo",
187                bind_cn="",
188                bind_password=generate_id(),
189                sync_users_password=True,
190            )
191        )
192        self.assertTrue(serializer.is_valid())
193        self.assertEqual(serializer.errors, {})

Check that single source with sync_users_password is valid

def test_sync_users_password_invalid(self):
195    def test_sync_users_password_invalid(self):
196        """Ensure only a single source with password sync can be created"""
197        LDAPSource.objects.create(
198            **self.source_data(
199                bind_cn="",
200                bind_password=generate_id(),
201                sync_users_password=True,
202            )
203        )
204        serializer = LDAPSourceSerializer(
205            data=self.source_data(
206                bind_cn="",
207                bind_password=generate_id(),
208                sync_users_password=True,
209            )
210        )
211        self.assertFalse(serializer.is_valid())
212        self.assertEqual(
213            serializer.errors,
214            {
215                "sync_users_password": [
216                    ErrorDetail(
217                        string="Only a single LDAP Source with password synchronization is allowed",
218                        code="invalid",
219                    )
220                ]
221            },
222        )

Ensure only a single source with password sync can be created

def test_sync_users_mapping_empty(self):
224    def test_sync_users_mapping_empty(self):
225        """Check that when sync_users is enabled, property mappings must be set"""
226        serializer = LDAPSourceSerializer(
227            data=self.source_data(
228                slug=" foo",
229                bind_cn="",
230                bind_password=generate_id(),
231                sync_users=True,
232                user_property_mappings=[],
233            )
234        )
235        self.assertFalse(serializer.is_valid())

Check that when sync_users is enabled, property mappings must be set

def test_sync_groups_mapping_empty(self):
237    def test_sync_groups_mapping_empty(self):
238        """Check that when sync_groups is enabled, property mappings must be set"""
239        serializer = LDAPSourceSerializer(
240            data=self.source_data(
241                slug=" foo",
242                bind_cn="",
243                bind_password=generate_id(),
244                sync_groups=True,
245                group_property_mappings=[],
246            )
247        )
248        self.assertFalse(serializer.is_valid())

Check that when sync_groups is enabled, property mappings must be set

@apply_blueprint('system/sources-ldap.yaml')
def test_sync_debug(self):
250    @apply_blueprint("system/sources-ldap.yaml")
251    def test_sync_debug(self):
252        user = create_test_admin_user()
253        self.client.force_login(user)
254
255        source: LDAPSource = LDAPSource.objects.create(
256            name=generate_id(),
257            slug=generate_id(),
258            base_dn="dc=goauthentik,dc=io",
259            additional_user_dn="ou=users",
260            additional_group_dn="ou=groups",
261        )
262        source.user_property_mappings.set(
263            LDAPSourcePropertyMapping.objects.filter(
264                Q(managed__startswith="goauthentik.io/sources/ldap/default")
265                | Q(managed__startswith="goauthentik.io/sources/ldap/ms")
266            )
267        )
268        connection = MagicMock(return_value=mock_ad_connection())
269        with patch("authentik.sources.ldap.models.LDAPSource.connection", connection):
270            res = self.client.get(
271                reverse("authentik_api:ldapsource-debug", kwargs={"slug": source.slug})
272            )
273            self.assertEqual(res.status_code, 200)
274            body = loads(res.content.decode())
275            self.assertIn("users", body)
276            self.assertIn("groups", body)
277            self.assertIn("membership", body)
@apply_blueprint('system/sources-ldap.yaml')
def test_debug_denied_for_anonymous(self):
288    @apply_blueprint("system/sources-ldap.yaml")
289    def test_debug_denied_for_anonymous(self):
290        """debug must enforce RBAC: an anonymous caller may not read LDAP data."""
291        source = self._create_debug_source()
292        # NOTE: no self.client.force_login() -> caller is AnonymousUser
293        connection = MagicMock(return_value=mock_ad_connection())
294        with patch("authentik.sources.ldap.models.LDAPSource.connection", connection):
295            res = self.client.get(
296                reverse("authentik_api:ldapsource-debug", kwargs={"slug": source.slug})
297            )
298        self.assertEqual(res.status_code, 403)

debug must enforce RBAC: an anonymous caller may not read LDAP data.

@apply_blueprint('system/sources-ldap.yaml')
def test_debug_denied_for_unauthorized_user(self):
300    @apply_blueprint("system/sources-ldap.yaml")
301    def test_debug_denied_for_unauthorized_user(self):
302        """debug must enforce RBAC: a user without view_ldapsource may not read LDAP data."""
303        source = self._create_debug_source()
304        # Authenticated, but holds no permission on the source object
305        self.client.force_login(create_test_user())
306        connection = MagicMock(return_value=mock_ad_connection())
307        with patch("authentik.sources.ldap.models.LDAPSource.connection", connection):
308            res = self.client.get(
309                reverse("authentik_api:ldapsource-debug", kwargs={"slug": source.slug})
310            )
311        self.assertEqual(res.status_code, 403)

debug must enforce RBAC: a user without view_ldapsource may not read LDAP data.