authentik.core.tests.test_source_flow_manager

Test Source flow_manager

  1"""Test Source flow_manager"""
  2
  3from django.contrib.auth.models import AnonymousUser
  4from django.db import connection
  5from django.test import TestCase
  6from django.test.utils import CaptureQueriesContext
  7from django.urls import reverse
  8from guardian.shortcuts import get_anonymous_user
  9
 10from authentik.core import user_switching
 11from authentik.core.models import SourceUserMatchingModes, User
 12from authentik.core.sources.flow_manager import Action
 13from authentik.core.sources.matcher import MatchFailureReason
 14from authentik.core.sources.stage import PostSourceStage
 15from authentik.core.tests.utils import RequestFactory, create_test_flow, create_test_user
 16from authentik.events.models import Event, EventAction
 17from authentik.flows.models import FlowAuthenticationRequirement
 18from authentik.flows.planner import (
 19    PLAN_CONTEXT_PENDING_USER,
 20    PLAN_CONTEXT_USER_SWITCH_ADD_USER,
 21    FlowPlan,
 22)
 23from authentik.flows.views.executor import SESSION_KEY_PLAN
 24from authentik.lib.generators import generate_id
 25from authentik.policies.denied import AccessDeniedResponse
 26from authentik.policies.expression.models import ExpressionPolicy
 27from authentik.policies.models import PolicyBinding
 28from authentik.sources.oauth.models import (
 29    OAuthSource,
 30    OAuthSourcePropertyMapping,
 31    UserOAuthSourceConnection,
 32)
 33from authentik.sources.oauth.views.callback import OAuthSourceFlowManager
 34
 35
 36class TestSourceFlowManager(TestCase):
 37    """Test Source flow_manager"""
 38
 39    def setUp(self) -> None:
 40        super().setUp()
 41        self.authentication_flow = create_test_flow()
 42        self.enrollment_flow = create_test_flow()
 43        self.source: OAuthSource = OAuthSource.objects.create(
 44            name=generate_id(),
 45            slug=generate_id(),
 46            authentication_flow=self.authentication_flow,
 47            enrollment_flow=self.enrollment_flow,
 48        )
 49        self.identifier = generate_id()
 50        self.request_factory = RequestFactory()
 51
 52    def test_unauthenticated_enroll(self):
 53        """Test un-authenticated user enrolling"""
 54        request = self.request_factory.get("/", user=AnonymousUser())
 55        flow_manager = OAuthSourceFlowManager(
 56            self.source, request, self.identifier, {"info": {}}, {}
 57        )
 58        action, _ = flow_manager.get_action()
 59        self.assertEqual(action, Action.ENROLL)
 60        response = flow_manager.get_flow()
 61        self.assertEqual(response.status_code, 302)
 62        flow_plan: FlowPlan = request.session[SESSION_KEY_PLAN]
 63        self.assertEqual(flow_plan.bindings[0].stage.view, PostSourceStage)
 64
 65    def test_unauthenticated_auth(self):
 66        """Test un-authenticated user authenticating"""
 67        UserOAuthSourceConnection.objects.create(
 68            user=get_anonymous_user(), source=self.source, identifier=self.identifier
 69        )
 70        request = self.request_factory.get("/", user=AnonymousUser())
 71        flow_manager = OAuthSourceFlowManager(
 72            self.source, request, self.identifier, {"info": {}}, {}
 73        )
 74        action, _ = flow_manager.get_action()
 75        self.assertEqual(action, Action.AUTH)
 76        response = flow_manager.get_flow()
 77        self.assertEqual(response.status_code, 302)
 78        flow_plan: FlowPlan = request.session[SESSION_KEY_PLAN]
 79        self.assertEqual(flow_plan.bindings[0].stage.view, PostSourceStage)
 80
 81    def test_authenticated_link(self):
 82        """Test authenticated user linking"""
 83        user = User.objects.create(username="foo", email="foo@bar.baz")
 84        request = self.request_factory.get("/", user=user)
 85        flow_manager = OAuthSourceFlowManager(
 86            self.source, request, self.identifier, {"info": {}}, {}
 87        )
 88        action, connection = flow_manager.get_action()
 89        self.assertEqual(action, Action.LINK)
 90        self.assertIsNone(connection.pk)
 91        response = flow_manager.get_flow()
 92        self.assertEqual(response.status_code, 302)
 93        self.assertEqual(
 94            response.url,
 95            reverse("authentik_core:if-user") + "settings/sources",
 96        )
 97
 98    def test_authenticated_auth_forwards_kwargs(self):
 99        """kwargs must reach update_user_connection() for the *existing* connection.
100
101        Sources carry their credential in kwargs — Plex's `plex_token`, for
102        example. The AUTH branch dropped them, so `update_user_connection()`
103        read `kwargs.get(...)` as None and overwrote a valid stored credential
104        with NULL on every subsequent login through the source.
105
106        `get_action()` calls `update_user_connection()` twice on this path: once
107        for a fresh unsaved connection (which always forwarded kwargs) and once
108        for the existing row (which did not). Recording per call and keying on
109        whether the connection is saved is what separates them — an accumulated
110        dict is satisfied by the first call and proves nothing.
111        """
112        user = User.objects.create(username="foo", email="foo@bar.baz")
113        existing_connection = UserOAuthSourceConnection.objects.create(
114            user=user, source=self.source, identifier=self.identifier
115        )
116        request = self.request_factory.get("/", user=user)
117
118        calls: list[tuple] = []
119
120        class RecordingFlowManager(OAuthSourceFlowManager):
121            def update_user_connection(self, connection, **kwargs):
122                calls.append((connection.pk, kwargs))
123                return connection
124
125        flow_manager = RecordingFlowManager(self.source, request, self.identifier, {"info": {}}, {})
126        action, connection = flow_manager.get_action(some_token="a-credential")
127
128        self.assertEqual(action, Action.AUTH)
129        self.assertEqual(connection.pk, existing_connection.pk)
130
131        for_existing = [kw for pk, kw in calls if pk == existing_connection.pk]
132        self.assertEqual(
133            len(for_existing), 1, "expected exactly one update for the existing connection"
134        )
135        self.assertEqual(
136            for_existing[0].get("some_token"),
137            "a-credential",
138            "get_action() dropped kwargs when updating the existing connection",
139        )
140
141    def test_authenticated_auth(self):
142        """Test authenticated user linking"""
143        user = User.objects.create(username="foo", email="foo@bar.baz")
144        UserOAuthSourceConnection.objects.create(
145            user=user, source=self.source, identifier=self.identifier
146        )
147        request = self.request_factory.get("/", user=user)
148        flow_manager = OAuthSourceFlowManager(
149            self.source, request, self.identifier, {"info": {}}, {}
150        )
151        action, connection = flow_manager.get_action()
152        self.assertEqual(action, Action.AUTH)
153        self.assertIsNotNone(connection.pk)
154        response = flow_manager.get_flow()
155        self.assertEqual(response.status_code, 302)
156
157    def test_authenticated_auth_require_unauthenticated(self):
158        """Test authenticated user re-authenticating with a require_unauthenticated flow"""
159        self.authentication_flow.authentication = (
160            FlowAuthenticationRequirement.REQUIRE_UNAUTHENTICATED
161        )
162        self.authentication_flow.save()
163        user = create_test_user()
164        UserOAuthSourceConnection.objects.create(
165            user=user, source=self.source, identifier=self.identifier
166        )
167        request = self.request_factory.get("/", user=user)
168        flow_manager = OAuthSourceFlowManager(
169            self.source, request, self.identifier, {"info": {}}, {}
170        )
171        response = flow_manager.get_flow()
172        self.assertEqual(response.status_code, 302)
173
174        # A different logged-in user is still refused
175        request = self.request_factory.get("/", user=create_test_user())
176        flow_manager = OAuthSourceFlowManager(
177            self.source, request, self.identifier, {"info": {}}, {}
178        )
179        response = flow_manager.get_flow()
180        self.assertIsInstance(response, AccessDeniedResponse)
181
182    def test_unauthenticated_link(self):
183        """Test un-authenticated user linking"""
184        flow_manager = OAuthSourceFlowManager(
185            self.source,
186            self.request_factory.get("/", user=get_anonymous_user()),
187            self.identifier,
188            {"info": {}},
189            {},
190        )
191        action, connection = flow_manager.get_action()
192        self.assertEqual(action, Action.LINK)
193        self.assertIsNone(connection.pk)
194        flow_manager.get_flow()
195
196    def _add_user_request(self, user: User):
197        """Request from a signed-in browser that started a source login from "Add user"."""
198        request = self.request_factory.get("/", user=user)
199        request.session[user_switching.SESSION_KEY_ADD_USER] = True
200        return request
201
202    def test_add_user_auth_logs_in_connected_user(self):
203        """Test "Add user" logs in the source's user instead of linking the current user"""
204        current_user = create_test_user()
205        other_user = create_test_user()
206        UserOAuthSourceConnection.objects.create(
207            user=other_user, source=self.source, identifier=self.identifier
208        )
209        request = self._add_user_request(current_user)
210        flow_manager = OAuthSourceFlowManager(
211            self.source, request, self.identifier, {"info": {}}, {}
212        )
213
214        response = flow_manager.get_flow()
215
216        self.assertEqual(response.status_code, 302)
217        flow_plan: FlowPlan = request.session[SESSION_KEY_PLAN]
218        self.assertEqual(flow_plan.flow_pk, self.authentication_flow.pk.hex)
219        self.assertEqual(flow_plan.context[PLAN_CONTEXT_PENDING_USER], other_user)
220        self.assertTrue(flow_plan.context[PLAN_CONTEXT_USER_SWITCH_ADD_USER])
221        self.assertNotIn(user_switching.SESSION_KEY_ADD_USER, request.session)
222
223    def test_add_user_refuses_enrollment(self):
224        """Test "Add user" with a new source identity neither links nor enrolls"""
225        current_user = create_test_user()
226        users = User.objects.count()
227        request = self._add_user_request(current_user)
228        flow_manager = OAuthSourceFlowManager(
229            self.source, request, self.identifier, {"info": {}}, {}
230        )
231
232        action, _ = flow_manager.get_action()
233        response = flow_manager.get_flow()
234
235        self.assertEqual(action, Action.ENROLL)
236        self.assertIsInstance(response, AccessDeniedResponse)
237        self.assertEqual(response.error_message, "New users can't enroll while adding a user.")
238        self.assertNotIn(SESSION_KEY_PLAN, request.session)
239        self.assertEqual(User.objects.count(), users)
240        self.assertFalse(UserOAuthSourceConnection.objects.filter(user=current_user).exists())
241
242    def test_unusable_group_identifier_does_not_abort(self):
243        """Test a group identifier that cannot be used as a key being skipped (#25191)"""
244        request = self.request_factory.get("/", user=AnonymousUser())
245        flow_manager = OAuthSourceFlowManager(
246            self.source,
247            request,
248            self.identifier,
249            {"info": {"groups": ["usable", {"id": "unusable"}, ["also-unusable"]]}},
250            {},
251        )
252        # Enrolling has to remain possible: raising here surfaced as HTTP 500 and
253        # locked out every member of such a group.
254        self.assertEqual(list(flow_manager.groups_properties.keys()), ["usable"])
255        self.assertEqual(flow_manager.get_action()[0], Action.ENROLL)
256        self.assertEqual(flow_manager.get_flow().status_code, 302)
257
258        event = Event.objects.filter(action=EventAction.CONFIGURATION_ERROR).first()
259        self.assertIsNotNone(event)
260        self.assertIn("2 group(s)", event.context["message"])
261        self.assertEqual(event.context["groups"], [{"id": "unusable"}, ["also-unusable"]])
262
263    def test_unauthenticated_enroll_email(self):
264        """Test un-authenticated user enrolling (link on email)"""
265        User.objects.create(username="foo", email="foo@bar.baz")
266        self.source.user_matching_mode = SourceUserMatchingModes.EMAIL_LINK
267
268        # Without email, deny
269        flow_manager = OAuthSourceFlowManager(
270            self.source,
271            self.request_factory.get("/", user=AnonymousUser()),
272            self.identifier,
273            {"info": {}},
274            {},
275        )
276        action, _ = flow_manager.get_action()
277        self.assertEqual(action, Action.DENY)
278        failure = flow_manager.matcher.failure
279        self.assertIsNotNone(failure)
280        self.assertEqual(failure.reason, MatchFailureReason.MISSING_PROPERTY)
281        self.assertEqual(failure.property, "email")
282        self.assertEqual(failure.source_slug, self.source.slug)
283        self.assertFalse(UserOAuthSourceConnection.objects.exists())
284        flow_manager.get_flow()
285        # With email
286        flow_manager = OAuthSourceFlowManager(
287            self.source,
288            self.request_factory.get("/", user=AnonymousUser()),
289            self.identifier,
290            {
291                "info": {
292                    "email": "foo@bar.baz",
293                },
294            },
295            {},
296        )
297        action, _ = flow_manager.get_action()
298        self.assertEqual(action, Action.LINK)
299        self.assertIsNone(flow_manager.matcher.failure)
300        flow_manager.get_flow()
301
302    def test_unauthenticated_enroll_username(self):
303        """Test un-authenticated user enrolling (link on username)"""
304        User.objects.create(username="foo", email="foo@bar.baz")
305        self.source.user_matching_mode = SourceUserMatchingModes.USERNAME_LINK
306
307        # Without username, deny
308        flow_manager = OAuthSourceFlowManager(
309            self.source,
310            self.request_factory.get("/", user=AnonymousUser()),
311            self.identifier,
312            {"info": {}},
313            {},
314        )
315        action, _ = flow_manager.get_action()
316        self.assertEqual(action, Action.DENY)
317        failure = flow_manager.matcher.failure
318        self.assertIsNotNone(failure)
319        self.assertEqual(failure.reason, MatchFailureReason.MISSING_PROPERTY)
320        self.assertEqual(failure.property, "username")
321        flow_manager.get_flow()
322        # With username
323        flow_manager = OAuthSourceFlowManager(
324            self.source,
325            self.request_factory.get("/", user=AnonymousUser()),
326            self.identifier,
327            {
328                "info": {"username": "foo"},
329            },
330            {},
331        )
332        action, _ = flow_manager.get_action()
333        self.assertEqual(action, Action.LINK)
334        flow_manager.get_flow()
335
336    def test_unauthenticated_enroll_username_deny(self):
337        """Test un-authenticated user enrolling (deny on username)"""
338        User.objects.create(username="foo", email="foo@bar.baz")
339        self.source.user_matching_mode = SourceUserMatchingModes.USERNAME_DENY
340
341        # With non-existent username, enroll
342        flow_manager = OAuthSourceFlowManager(
343            self.source,
344            self.request_factory.get("/", user=AnonymousUser()),
345            self.identifier,
346            {
347                "info": {
348                    "username": "bar",
349                },
350            },
351            {},
352        )
353        action, _ = flow_manager.get_action()
354        self.assertEqual(action, Action.ENROLL)
355        flow_manager.get_flow()
356        # With username
357        flow_manager = OAuthSourceFlowManager(
358            self.source,
359            self.request_factory.get("/", user=AnonymousUser()),
360            self.identifier,
361            {
362                "info": {"username": "foo"},
363            },
364            {},
365        )
366        action, _ = flow_manager.get_action()
367        self.assertEqual(action, Action.DENY)
368        self.assertIsNone(flow_manager.matcher.failure)
369        flow_manager.get_flow()
370
371    def test_unauthenticated_enroll_link_non_existent(self):
372        """Test un-authenticated user enrolling (link on username), username doesn't exist"""
373        self.source.user_matching_mode = SourceUserMatchingModes.USERNAME_LINK
374
375        flow_manager = OAuthSourceFlowManager(
376            self.source,
377            self.request_factory.get("/", user=AnonymousUser()),
378            self.identifier,
379            {
380                "info": {"username": "foo"},
381            },
382            {},
383        )
384        action, _ = flow_manager.get_action()
385        self.assertEqual(action, Action.ENROLL)
386        flow_manager.get_flow()
387
388    def test_error_non_applicable_flow(self):
389        """Test error handling when a source selected flow is non-applicable due to a policy"""
390        self.source.user_matching_mode = SourceUserMatchingModes.USERNAME_LINK
391
392        flow = create_test_flow()
393        policy = ExpressionPolicy.objects.create(
394            name="false", expression="""ak_message("foo");return False"""
395        )
396        PolicyBinding.objects.create(
397            policy=policy,
398            target=flow,
399            order=0,
400        )
401        self.source.enrollment_flow = flow
402        self.source.save()
403
404        flow_manager = OAuthSourceFlowManager(
405            self.source,
406            self.request_factory.get("/", user=AnonymousUser()),
407            self.identifier,
408            {
409                "info": {"username": "foo"},
410            },
411            {},
412        )
413        action, _ = flow_manager.get_action()
414        self.assertEqual(action, Action.ENROLL)
415        response = flow_manager.get_flow()
416        self.assertIsInstance(response, AccessDeniedResponse)
417
418        self.assertEqual(response.error_message, "foo")
419
420    def calculate_group_property_mapping_queries(self, group_count: int) -> int:
421        """Build group properties for `group_count` groups, check them, and return the
422        number of queries it took"""
423        group_ids = [f"group-{index}" for index in range(group_count)]
424        with CaptureQueriesContext(connection) as queries:
425            flow_manager = OAuthSourceFlowManager(
426                self.source,
427                self.request_factory.get("/", user=AnonymousUser()),
428                self.identifier,
429                {"info": {"groups": group_ids}},
430                {},
431            )
432        self.assertEqual(len(flow_manager.groups_properties), group_count)
433        for group_id in group_ids:
434            # Each group must get its own properties, from both the base properties and
435            # the property mapping
436            self.assertEqual(
437                flow_manager.groups_properties[group_id],
438                {"name": group_id, "attributes": {"group_id": group_id}},
439            )
440        return len(queries.captured_queries)
441
442    def test_group_properties_reuse_mapping_manager(self):
443        """Test that building group properties doesn't re-fetch and re-compile the
444        source's group property mappings for every single group"""
445        self.source.group_property_mappings.add(
446            OAuthSourcePropertyMapping.objects.create(
447                name=generate_id(),
448                expression="""return {"attributes": {"group_id": group_id}}""",
449            )
450        )
451        # Building N groups must take fewer than N queries
452        self.assertLess(self.calculate_group_property_mapping_queries(100), 100)
class TestSourceFlowManager(django.test.testcases.TestCase):
 37class TestSourceFlowManager(TestCase):
 38    """Test Source flow_manager"""
 39
 40    def setUp(self) -> None:
 41        super().setUp()
 42        self.authentication_flow = create_test_flow()
 43        self.enrollment_flow = create_test_flow()
 44        self.source: OAuthSource = OAuthSource.objects.create(
 45            name=generate_id(),
 46            slug=generate_id(),
 47            authentication_flow=self.authentication_flow,
 48            enrollment_flow=self.enrollment_flow,
 49        )
 50        self.identifier = generate_id()
 51        self.request_factory = RequestFactory()
 52
 53    def test_unauthenticated_enroll(self):
 54        """Test un-authenticated user enrolling"""
 55        request = self.request_factory.get("/", user=AnonymousUser())
 56        flow_manager = OAuthSourceFlowManager(
 57            self.source, request, self.identifier, {"info": {}}, {}
 58        )
 59        action, _ = flow_manager.get_action()
 60        self.assertEqual(action, Action.ENROLL)
 61        response = flow_manager.get_flow()
 62        self.assertEqual(response.status_code, 302)
 63        flow_plan: FlowPlan = request.session[SESSION_KEY_PLAN]
 64        self.assertEqual(flow_plan.bindings[0].stage.view, PostSourceStage)
 65
 66    def test_unauthenticated_auth(self):
 67        """Test un-authenticated user authenticating"""
 68        UserOAuthSourceConnection.objects.create(
 69            user=get_anonymous_user(), source=self.source, identifier=self.identifier
 70        )
 71        request = self.request_factory.get("/", user=AnonymousUser())
 72        flow_manager = OAuthSourceFlowManager(
 73            self.source, request, self.identifier, {"info": {}}, {}
 74        )
 75        action, _ = flow_manager.get_action()
 76        self.assertEqual(action, Action.AUTH)
 77        response = flow_manager.get_flow()
 78        self.assertEqual(response.status_code, 302)
 79        flow_plan: FlowPlan = request.session[SESSION_KEY_PLAN]
 80        self.assertEqual(flow_plan.bindings[0].stage.view, PostSourceStage)
 81
 82    def test_authenticated_link(self):
 83        """Test authenticated user linking"""
 84        user = User.objects.create(username="foo", email="foo@bar.baz")
 85        request = self.request_factory.get("/", user=user)
 86        flow_manager = OAuthSourceFlowManager(
 87            self.source, request, self.identifier, {"info": {}}, {}
 88        )
 89        action, connection = flow_manager.get_action()
 90        self.assertEqual(action, Action.LINK)
 91        self.assertIsNone(connection.pk)
 92        response = flow_manager.get_flow()
 93        self.assertEqual(response.status_code, 302)
 94        self.assertEqual(
 95            response.url,
 96            reverse("authentik_core:if-user") + "settings/sources",
 97        )
 98
 99    def test_authenticated_auth_forwards_kwargs(self):
100        """kwargs must reach update_user_connection() for the *existing* connection.
101
102        Sources carry their credential in kwargs — Plex's `plex_token`, for
103        example. The AUTH branch dropped them, so `update_user_connection()`
104        read `kwargs.get(...)` as None and overwrote a valid stored credential
105        with NULL on every subsequent login through the source.
106
107        `get_action()` calls `update_user_connection()` twice on this path: once
108        for a fresh unsaved connection (which always forwarded kwargs) and once
109        for the existing row (which did not). Recording per call and keying on
110        whether the connection is saved is what separates them — an accumulated
111        dict is satisfied by the first call and proves nothing.
112        """
113        user = User.objects.create(username="foo", email="foo@bar.baz")
114        existing_connection = UserOAuthSourceConnection.objects.create(
115            user=user, source=self.source, identifier=self.identifier
116        )
117        request = self.request_factory.get("/", user=user)
118
119        calls: list[tuple] = []
120
121        class RecordingFlowManager(OAuthSourceFlowManager):
122            def update_user_connection(self, connection, **kwargs):
123                calls.append((connection.pk, kwargs))
124                return connection
125
126        flow_manager = RecordingFlowManager(self.source, request, self.identifier, {"info": {}}, {})
127        action, connection = flow_manager.get_action(some_token="a-credential")
128
129        self.assertEqual(action, Action.AUTH)
130        self.assertEqual(connection.pk, existing_connection.pk)
131
132        for_existing = [kw for pk, kw in calls if pk == existing_connection.pk]
133        self.assertEqual(
134            len(for_existing), 1, "expected exactly one update for the existing connection"
135        )
136        self.assertEqual(
137            for_existing[0].get("some_token"),
138            "a-credential",
139            "get_action() dropped kwargs when updating the existing connection",
140        )
141
142    def test_authenticated_auth(self):
143        """Test authenticated user linking"""
144        user = User.objects.create(username="foo", email="foo@bar.baz")
145        UserOAuthSourceConnection.objects.create(
146            user=user, source=self.source, identifier=self.identifier
147        )
148        request = self.request_factory.get("/", user=user)
149        flow_manager = OAuthSourceFlowManager(
150            self.source, request, self.identifier, {"info": {}}, {}
151        )
152        action, connection = flow_manager.get_action()
153        self.assertEqual(action, Action.AUTH)
154        self.assertIsNotNone(connection.pk)
155        response = flow_manager.get_flow()
156        self.assertEqual(response.status_code, 302)
157
158    def test_authenticated_auth_require_unauthenticated(self):
159        """Test authenticated user re-authenticating with a require_unauthenticated flow"""
160        self.authentication_flow.authentication = (
161            FlowAuthenticationRequirement.REQUIRE_UNAUTHENTICATED
162        )
163        self.authentication_flow.save()
164        user = create_test_user()
165        UserOAuthSourceConnection.objects.create(
166            user=user, source=self.source, identifier=self.identifier
167        )
168        request = self.request_factory.get("/", user=user)
169        flow_manager = OAuthSourceFlowManager(
170            self.source, request, self.identifier, {"info": {}}, {}
171        )
172        response = flow_manager.get_flow()
173        self.assertEqual(response.status_code, 302)
174
175        # A different logged-in user is still refused
176        request = self.request_factory.get("/", user=create_test_user())
177        flow_manager = OAuthSourceFlowManager(
178            self.source, request, self.identifier, {"info": {}}, {}
179        )
180        response = flow_manager.get_flow()
181        self.assertIsInstance(response, AccessDeniedResponse)
182
183    def test_unauthenticated_link(self):
184        """Test un-authenticated user linking"""
185        flow_manager = OAuthSourceFlowManager(
186            self.source,
187            self.request_factory.get("/", user=get_anonymous_user()),
188            self.identifier,
189            {"info": {}},
190            {},
191        )
192        action, connection = flow_manager.get_action()
193        self.assertEqual(action, Action.LINK)
194        self.assertIsNone(connection.pk)
195        flow_manager.get_flow()
196
197    def _add_user_request(self, user: User):
198        """Request from a signed-in browser that started a source login from "Add user"."""
199        request = self.request_factory.get("/", user=user)
200        request.session[user_switching.SESSION_KEY_ADD_USER] = True
201        return request
202
203    def test_add_user_auth_logs_in_connected_user(self):
204        """Test "Add user" logs in the source's user instead of linking the current user"""
205        current_user = create_test_user()
206        other_user = create_test_user()
207        UserOAuthSourceConnection.objects.create(
208            user=other_user, source=self.source, identifier=self.identifier
209        )
210        request = self._add_user_request(current_user)
211        flow_manager = OAuthSourceFlowManager(
212            self.source, request, self.identifier, {"info": {}}, {}
213        )
214
215        response = flow_manager.get_flow()
216
217        self.assertEqual(response.status_code, 302)
218        flow_plan: FlowPlan = request.session[SESSION_KEY_PLAN]
219        self.assertEqual(flow_plan.flow_pk, self.authentication_flow.pk.hex)
220        self.assertEqual(flow_plan.context[PLAN_CONTEXT_PENDING_USER], other_user)
221        self.assertTrue(flow_plan.context[PLAN_CONTEXT_USER_SWITCH_ADD_USER])
222        self.assertNotIn(user_switching.SESSION_KEY_ADD_USER, request.session)
223
224    def test_add_user_refuses_enrollment(self):
225        """Test "Add user" with a new source identity neither links nor enrolls"""
226        current_user = create_test_user()
227        users = User.objects.count()
228        request = self._add_user_request(current_user)
229        flow_manager = OAuthSourceFlowManager(
230            self.source, request, self.identifier, {"info": {}}, {}
231        )
232
233        action, _ = flow_manager.get_action()
234        response = flow_manager.get_flow()
235
236        self.assertEqual(action, Action.ENROLL)
237        self.assertIsInstance(response, AccessDeniedResponse)
238        self.assertEqual(response.error_message, "New users can't enroll while adding a user.")
239        self.assertNotIn(SESSION_KEY_PLAN, request.session)
240        self.assertEqual(User.objects.count(), users)
241        self.assertFalse(UserOAuthSourceConnection.objects.filter(user=current_user).exists())
242
243    def test_unusable_group_identifier_does_not_abort(self):
244        """Test a group identifier that cannot be used as a key being skipped (#25191)"""
245        request = self.request_factory.get("/", user=AnonymousUser())
246        flow_manager = OAuthSourceFlowManager(
247            self.source,
248            request,
249            self.identifier,
250            {"info": {"groups": ["usable", {"id": "unusable"}, ["also-unusable"]]}},
251            {},
252        )
253        # Enrolling has to remain possible: raising here surfaced as HTTP 500 and
254        # locked out every member of such a group.
255        self.assertEqual(list(flow_manager.groups_properties.keys()), ["usable"])
256        self.assertEqual(flow_manager.get_action()[0], Action.ENROLL)
257        self.assertEqual(flow_manager.get_flow().status_code, 302)
258
259        event = Event.objects.filter(action=EventAction.CONFIGURATION_ERROR).first()
260        self.assertIsNotNone(event)
261        self.assertIn("2 group(s)", event.context["message"])
262        self.assertEqual(event.context["groups"], [{"id": "unusable"}, ["also-unusable"]])
263
264    def test_unauthenticated_enroll_email(self):
265        """Test un-authenticated user enrolling (link on email)"""
266        User.objects.create(username="foo", email="foo@bar.baz")
267        self.source.user_matching_mode = SourceUserMatchingModes.EMAIL_LINK
268
269        # Without email, deny
270        flow_manager = OAuthSourceFlowManager(
271            self.source,
272            self.request_factory.get("/", user=AnonymousUser()),
273            self.identifier,
274            {"info": {}},
275            {},
276        )
277        action, _ = flow_manager.get_action()
278        self.assertEqual(action, Action.DENY)
279        failure = flow_manager.matcher.failure
280        self.assertIsNotNone(failure)
281        self.assertEqual(failure.reason, MatchFailureReason.MISSING_PROPERTY)
282        self.assertEqual(failure.property, "email")
283        self.assertEqual(failure.source_slug, self.source.slug)
284        self.assertFalse(UserOAuthSourceConnection.objects.exists())
285        flow_manager.get_flow()
286        # With email
287        flow_manager = OAuthSourceFlowManager(
288            self.source,
289            self.request_factory.get("/", user=AnonymousUser()),
290            self.identifier,
291            {
292                "info": {
293                    "email": "foo@bar.baz",
294                },
295            },
296            {},
297        )
298        action, _ = flow_manager.get_action()
299        self.assertEqual(action, Action.LINK)
300        self.assertIsNone(flow_manager.matcher.failure)
301        flow_manager.get_flow()
302
303    def test_unauthenticated_enroll_username(self):
304        """Test un-authenticated user enrolling (link on username)"""
305        User.objects.create(username="foo", email="foo@bar.baz")
306        self.source.user_matching_mode = SourceUserMatchingModes.USERNAME_LINK
307
308        # Without username, deny
309        flow_manager = OAuthSourceFlowManager(
310            self.source,
311            self.request_factory.get("/", user=AnonymousUser()),
312            self.identifier,
313            {"info": {}},
314            {},
315        )
316        action, _ = flow_manager.get_action()
317        self.assertEqual(action, Action.DENY)
318        failure = flow_manager.matcher.failure
319        self.assertIsNotNone(failure)
320        self.assertEqual(failure.reason, MatchFailureReason.MISSING_PROPERTY)
321        self.assertEqual(failure.property, "username")
322        flow_manager.get_flow()
323        # With username
324        flow_manager = OAuthSourceFlowManager(
325            self.source,
326            self.request_factory.get("/", user=AnonymousUser()),
327            self.identifier,
328            {
329                "info": {"username": "foo"},
330            },
331            {},
332        )
333        action, _ = flow_manager.get_action()
334        self.assertEqual(action, Action.LINK)
335        flow_manager.get_flow()
336
337    def test_unauthenticated_enroll_username_deny(self):
338        """Test un-authenticated user enrolling (deny on username)"""
339        User.objects.create(username="foo", email="foo@bar.baz")
340        self.source.user_matching_mode = SourceUserMatchingModes.USERNAME_DENY
341
342        # With non-existent username, enroll
343        flow_manager = OAuthSourceFlowManager(
344            self.source,
345            self.request_factory.get("/", user=AnonymousUser()),
346            self.identifier,
347            {
348                "info": {
349                    "username": "bar",
350                },
351            },
352            {},
353        )
354        action, _ = flow_manager.get_action()
355        self.assertEqual(action, Action.ENROLL)
356        flow_manager.get_flow()
357        # With username
358        flow_manager = OAuthSourceFlowManager(
359            self.source,
360            self.request_factory.get("/", user=AnonymousUser()),
361            self.identifier,
362            {
363                "info": {"username": "foo"},
364            },
365            {},
366        )
367        action, _ = flow_manager.get_action()
368        self.assertEqual(action, Action.DENY)
369        self.assertIsNone(flow_manager.matcher.failure)
370        flow_manager.get_flow()
371
372    def test_unauthenticated_enroll_link_non_existent(self):
373        """Test un-authenticated user enrolling (link on username), username doesn't exist"""
374        self.source.user_matching_mode = SourceUserMatchingModes.USERNAME_LINK
375
376        flow_manager = OAuthSourceFlowManager(
377            self.source,
378            self.request_factory.get("/", user=AnonymousUser()),
379            self.identifier,
380            {
381                "info": {"username": "foo"},
382            },
383            {},
384        )
385        action, _ = flow_manager.get_action()
386        self.assertEqual(action, Action.ENROLL)
387        flow_manager.get_flow()
388
389    def test_error_non_applicable_flow(self):
390        """Test error handling when a source selected flow is non-applicable due to a policy"""
391        self.source.user_matching_mode = SourceUserMatchingModes.USERNAME_LINK
392
393        flow = create_test_flow()
394        policy = ExpressionPolicy.objects.create(
395            name="false", expression="""ak_message("foo");return False"""
396        )
397        PolicyBinding.objects.create(
398            policy=policy,
399            target=flow,
400            order=0,
401        )
402        self.source.enrollment_flow = flow
403        self.source.save()
404
405        flow_manager = OAuthSourceFlowManager(
406            self.source,
407            self.request_factory.get("/", user=AnonymousUser()),
408            self.identifier,
409            {
410                "info": {"username": "foo"},
411            },
412            {},
413        )
414        action, _ = flow_manager.get_action()
415        self.assertEqual(action, Action.ENROLL)
416        response = flow_manager.get_flow()
417        self.assertIsInstance(response, AccessDeniedResponse)
418
419        self.assertEqual(response.error_message, "foo")
420
421    def calculate_group_property_mapping_queries(self, group_count: int) -> int:
422        """Build group properties for `group_count` groups, check them, and return the
423        number of queries it took"""
424        group_ids = [f"group-{index}" for index in range(group_count)]
425        with CaptureQueriesContext(connection) as queries:
426            flow_manager = OAuthSourceFlowManager(
427                self.source,
428                self.request_factory.get("/", user=AnonymousUser()),
429                self.identifier,
430                {"info": {"groups": group_ids}},
431                {},
432            )
433        self.assertEqual(len(flow_manager.groups_properties), group_count)
434        for group_id in group_ids:
435            # Each group must get its own properties, from both the base properties and
436            # the property mapping
437            self.assertEqual(
438                flow_manager.groups_properties[group_id],
439                {"name": group_id, "attributes": {"group_id": group_id}},
440            )
441        return len(queries.captured_queries)
442
443    def test_group_properties_reuse_mapping_manager(self):
444        """Test that building group properties doesn't re-fetch and re-compile the
445        source's group property mappings for every single group"""
446        self.source.group_property_mappings.add(
447            OAuthSourcePropertyMapping.objects.create(
448                name=generate_id(),
449                expression="""return {"attributes": {"group_id": group_id}}""",
450            )
451        )
452        # Building N groups must take fewer than N queries
453        self.assertLess(self.calculate_group_property_mapping_queries(100), 100)

Test Source flow_manager

def setUp(self) -> None:
40    def setUp(self) -> None:
41        super().setUp()
42        self.authentication_flow = create_test_flow()
43        self.enrollment_flow = create_test_flow()
44        self.source: OAuthSource = OAuthSource.objects.create(
45            name=generate_id(),
46            slug=generate_id(),
47            authentication_flow=self.authentication_flow,
48            enrollment_flow=self.enrollment_flow,
49        )
50        self.identifier = generate_id()
51        self.request_factory = RequestFactory()

Hook method for setting up the test fixture before exercising it.

def test_unauthenticated_enroll(self):
53    def test_unauthenticated_enroll(self):
54        """Test un-authenticated user enrolling"""
55        request = self.request_factory.get("/", user=AnonymousUser())
56        flow_manager = OAuthSourceFlowManager(
57            self.source, request, self.identifier, {"info": {}}, {}
58        )
59        action, _ = flow_manager.get_action()
60        self.assertEqual(action, Action.ENROLL)
61        response = flow_manager.get_flow()
62        self.assertEqual(response.status_code, 302)
63        flow_plan: FlowPlan = request.session[SESSION_KEY_PLAN]
64        self.assertEqual(flow_plan.bindings[0].stage.view, PostSourceStage)

Test un-authenticated user enrolling

def test_unauthenticated_auth(self):
66    def test_unauthenticated_auth(self):
67        """Test un-authenticated user authenticating"""
68        UserOAuthSourceConnection.objects.create(
69            user=get_anonymous_user(), source=self.source, identifier=self.identifier
70        )
71        request = self.request_factory.get("/", user=AnonymousUser())
72        flow_manager = OAuthSourceFlowManager(
73            self.source, request, self.identifier, {"info": {}}, {}
74        )
75        action, _ = flow_manager.get_action()
76        self.assertEqual(action, Action.AUTH)
77        response = flow_manager.get_flow()
78        self.assertEqual(response.status_code, 302)
79        flow_plan: FlowPlan = request.session[SESSION_KEY_PLAN]
80        self.assertEqual(flow_plan.bindings[0].stage.view, PostSourceStage)

Test un-authenticated user authenticating

def test_authenticated_auth_forwards_kwargs(self):
 99    def test_authenticated_auth_forwards_kwargs(self):
100        """kwargs must reach update_user_connection() for the *existing* connection.
101
102        Sources carry their credential in kwargs — Plex's `plex_token`, for
103        example. The AUTH branch dropped them, so `update_user_connection()`
104        read `kwargs.get(...)` as None and overwrote a valid stored credential
105        with NULL on every subsequent login through the source.
106
107        `get_action()` calls `update_user_connection()` twice on this path: once
108        for a fresh unsaved connection (which always forwarded kwargs) and once
109        for the existing row (which did not). Recording per call and keying on
110        whether the connection is saved is what separates them — an accumulated
111        dict is satisfied by the first call and proves nothing.
112        """
113        user = User.objects.create(username="foo", email="foo@bar.baz")
114        existing_connection = UserOAuthSourceConnection.objects.create(
115            user=user, source=self.source, identifier=self.identifier
116        )
117        request = self.request_factory.get("/", user=user)
118
119        calls: list[tuple] = []
120
121        class RecordingFlowManager(OAuthSourceFlowManager):
122            def update_user_connection(self, connection, **kwargs):
123                calls.append((connection.pk, kwargs))
124                return connection
125
126        flow_manager = RecordingFlowManager(self.source, request, self.identifier, {"info": {}}, {})
127        action, connection = flow_manager.get_action(some_token="a-credential")
128
129        self.assertEqual(action, Action.AUTH)
130        self.assertEqual(connection.pk, existing_connection.pk)
131
132        for_existing = [kw for pk, kw in calls if pk == existing_connection.pk]
133        self.assertEqual(
134            len(for_existing), 1, "expected exactly one update for the existing connection"
135        )
136        self.assertEqual(
137            for_existing[0].get("some_token"),
138            "a-credential",
139            "get_action() dropped kwargs when updating the existing connection",
140        )

kwargs must reach update_user_connection() for the existing connection.

Sources carry their credential in kwargs — Plex's plex_token, for example. The AUTH branch dropped them, so update_user_connection() read kwargs.get(...) as None and overwrote a valid stored credential with NULL on every subsequent login through the source.

get_action() calls update_user_connection() twice on this path: once for a fresh unsaved connection (which always forwarded kwargs) and once for the existing row (which did not). Recording per call and keying on whether the connection is saved is what separates them — an accumulated dict is satisfied by the first call and proves nothing.

def test_authenticated_auth(self):
142    def test_authenticated_auth(self):
143        """Test authenticated user linking"""
144        user = User.objects.create(username="foo", email="foo@bar.baz")
145        UserOAuthSourceConnection.objects.create(
146            user=user, source=self.source, identifier=self.identifier
147        )
148        request = self.request_factory.get("/", user=user)
149        flow_manager = OAuthSourceFlowManager(
150            self.source, request, self.identifier, {"info": {}}, {}
151        )
152        action, connection = flow_manager.get_action()
153        self.assertEqual(action, Action.AUTH)
154        self.assertIsNotNone(connection.pk)
155        response = flow_manager.get_flow()
156        self.assertEqual(response.status_code, 302)

Test authenticated user linking

def test_authenticated_auth_require_unauthenticated(self):
158    def test_authenticated_auth_require_unauthenticated(self):
159        """Test authenticated user re-authenticating with a require_unauthenticated flow"""
160        self.authentication_flow.authentication = (
161            FlowAuthenticationRequirement.REQUIRE_UNAUTHENTICATED
162        )
163        self.authentication_flow.save()
164        user = create_test_user()
165        UserOAuthSourceConnection.objects.create(
166            user=user, source=self.source, identifier=self.identifier
167        )
168        request = self.request_factory.get("/", user=user)
169        flow_manager = OAuthSourceFlowManager(
170            self.source, request, self.identifier, {"info": {}}, {}
171        )
172        response = flow_manager.get_flow()
173        self.assertEqual(response.status_code, 302)
174
175        # A different logged-in user is still refused
176        request = self.request_factory.get("/", user=create_test_user())
177        flow_manager = OAuthSourceFlowManager(
178            self.source, request, self.identifier, {"info": {}}, {}
179        )
180        response = flow_manager.get_flow()
181        self.assertIsInstance(response, AccessDeniedResponse)

Test authenticated user re-authenticating with a require_unauthenticated flow

def test_add_user_auth_logs_in_connected_user(self):
203    def test_add_user_auth_logs_in_connected_user(self):
204        """Test "Add user" logs in the source's user instead of linking the current user"""
205        current_user = create_test_user()
206        other_user = create_test_user()
207        UserOAuthSourceConnection.objects.create(
208            user=other_user, source=self.source, identifier=self.identifier
209        )
210        request = self._add_user_request(current_user)
211        flow_manager = OAuthSourceFlowManager(
212            self.source, request, self.identifier, {"info": {}}, {}
213        )
214
215        response = flow_manager.get_flow()
216
217        self.assertEqual(response.status_code, 302)
218        flow_plan: FlowPlan = request.session[SESSION_KEY_PLAN]
219        self.assertEqual(flow_plan.flow_pk, self.authentication_flow.pk.hex)
220        self.assertEqual(flow_plan.context[PLAN_CONTEXT_PENDING_USER], other_user)
221        self.assertTrue(flow_plan.context[PLAN_CONTEXT_USER_SWITCH_ADD_USER])
222        self.assertNotIn(user_switching.SESSION_KEY_ADD_USER, request.session)

Test "Add user" logs in the source's user instead of linking the current user

def test_add_user_refuses_enrollment(self):
224    def test_add_user_refuses_enrollment(self):
225        """Test "Add user" with a new source identity neither links nor enrolls"""
226        current_user = create_test_user()
227        users = User.objects.count()
228        request = self._add_user_request(current_user)
229        flow_manager = OAuthSourceFlowManager(
230            self.source, request, self.identifier, {"info": {}}, {}
231        )
232
233        action, _ = flow_manager.get_action()
234        response = flow_manager.get_flow()
235
236        self.assertEqual(action, Action.ENROLL)
237        self.assertIsInstance(response, AccessDeniedResponse)
238        self.assertEqual(response.error_message, "New users can't enroll while adding a user.")
239        self.assertNotIn(SESSION_KEY_PLAN, request.session)
240        self.assertEqual(User.objects.count(), users)
241        self.assertFalse(UserOAuthSourceConnection.objects.filter(user=current_user).exists())

Test "Add user" with a new source identity neither links nor enrolls

def test_unusable_group_identifier_does_not_abort(self):
243    def test_unusable_group_identifier_does_not_abort(self):
244        """Test a group identifier that cannot be used as a key being skipped (#25191)"""
245        request = self.request_factory.get("/", user=AnonymousUser())
246        flow_manager = OAuthSourceFlowManager(
247            self.source,
248            request,
249            self.identifier,
250            {"info": {"groups": ["usable", {"id": "unusable"}, ["also-unusable"]]}},
251            {},
252        )
253        # Enrolling has to remain possible: raising here surfaced as HTTP 500 and
254        # locked out every member of such a group.
255        self.assertEqual(list(flow_manager.groups_properties.keys()), ["usable"])
256        self.assertEqual(flow_manager.get_action()[0], Action.ENROLL)
257        self.assertEqual(flow_manager.get_flow().status_code, 302)
258
259        event = Event.objects.filter(action=EventAction.CONFIGURATION_ERROR).first()
260        self.assertIsNotNone(event)
261        self.assertIn("2 group(s)", event.context["message"])
262        self.assertEqual(event.context["groups"], [{"id": "unusable"}, ["also-unusable"]])

Test a group identifier that cannot be used as a key being skipped (#25191)

def test_unauthenticated_enroll_email(self):
264    def test_unauthenticated_enroll_email(self):
265        """Test un-authenticated user enrolling (link on email)"""
266        User.objects.create(username="foo", email="foo@bar.baz")
267        self.source.user_matching_mode = SourceUserMatchingModes.EMAIL_LINK
268
269        # Without email, deny
270        flow_manager = OAuthSourceFlowManager(
271            self.source,
272            self.request_factory.get("/", user=AnonymousUser()),
273            self.identifier,
274            {"info": {}},
275            {},
276        )
277        action, _ = flow_manager.get_action()
278        self.assertEqual(action, Action.DENY)
279        failure = flow_manager.matcher.failure
280        self.assertIsNotNone(failure)
281        self.assertEqual(failure.reason, MatchFailureReason.MISSING_PROPERTY)
282        self.assertEqual(failure.property, "email")
283        self.assertEqual(failure.source_slug, self.source.slug)
284        self.assertFalse(UserOAuthSourceConnection.objects.exists())
285        flow_manager.get_flow()
286        # With email
287        flow_manager = OAuthSourceFlowManager(
288            self.source,
289            self.request_factory.get("/", user=AnonymousUser()),
290            self.identifier,
291            {
292                "info": {
293                    "email": "foo@bar.baz",
294                },
295            },
296            {},
297        )
298        action, _ = flow_manager.get_action()
299        self.assertEqual(action, Action.LINK)
300        self.assertIsNone(flow_manager.matcher.failure)
301        flow_manager.get_flow()

Test un-authenticated user enrolling (link on email)

def test_unauthenticated_enroll_username(self):
303    def test_unauthenticated_enroll_username(self):
304        """Test un-authenticated user enrolling (link on username)"""
305        User.objects.create(username="foo", email="foo@bar.baz")
306        self.source.user_matching_mode = SourceUserMatchingModes.USERNAME_LINK
307
308        # Without username, deny
309        flow_manager = OAuthSourceFlowManager(
310            self.source,
311            self.request_factory.get("/", user=AnonymousUser()),
312            self.identifier,
313            {"info": {}},
314            {},
315        )
316        action, _ = flow_manager.get_action()
317        self.assertEqual(action, Action.DENY)
318        failure = flow_manager.matcher.failure
319        self.assertIsNotNone(failure)
320        self.assertEqual(failure.reason, MatchFailureReason.MISSING_PROPERTY)
321        self.assertEqual(failure.property, "username")
322        flow_manager.get_flow()
323        # With username
324        flow_manager = OAuthSourceFlowManager(
325            self.source,
326            self.request_factory.get("/", user=AnonymousUser()),
327            self.identifier,
328            {
329                "info": {"username": "foo"},
330            },
331            {},
332        )
333        action, _ = flow_manager.get_action()
334        self.assertEqual(action, Action.LINK)
335        flow_manager.get_flow()

Test un-authenticated user enrolling (link on username)

def test_unauthenticated_enroll_username_deny(self):
337    def test_unauthenticated_enroll_username_deny(self):
338        """Test un-authenticated user enrolling (deny on username)"""
339        User.objects.create(username="foo", email="foo@bar.baz")
340        self.source.user_matching_mode = SourceUserMatchingModes.USERNAME_DENY
341
342        # With non-existent username, enroll
343        flow_manager = OAuthSourceFlowManager(
344            self.source,
345            self.request_factory.get("/", user=AnonymousUser()),
346            self.identifier,
347            {
348                "info": {
349                    "username": "bar",
350                },
351            },
352            {},
353        )
354        action, _ = flow_manager.get_action()
355        self.assertEqual(action, Action.ENROLL)
356        flow_manager.get_flow()
357        # With username
358        flow_manager = OAuthSourceFlowManager(
359            self.source,
360            self.request_factory.get("/", user=AnonymousUser()),
361            self.identifier,
362            {
363                "info": {"username": "foo"},
364            },
365            {},
366        )
367        action, _ = flow_manager.get_action()
368        self.assertEqual(action, Action.DENY)
369        self.assertIsNone(flow_manager.matcher.failure)
370        flow_manager.get_flow()

Test un-authenticated user enrolling (deny on username)

def test_error_non_applicable_flow(self):
389    def test_error_non_applicable_flow(self):
390        """Test error handling when a source selected flow is non-applicable due to a policy"""
391        self.source.user_matching_mode = SourceUserMatchingModes.USERNAME_LINK
392
393        flow = create_test_flow()
394        policy = ExpressionPolicy.objects.create(
395            name="false", expression="""ak_message("foo");return False"""
396        )
397        PolicyBinding.objects.create(
398            policy=policy,
399            target=flow,
400            order=0,
401        )
402        self.source.enrollment_flow = flow
403        self.source.save()
404
405        flow_manager = OAuthSourceFlowManager(
406            self.source,
407            self.request_factory.get("/", user=AnonymousUser()),
408            self.identifier,
409            {
410                "info": {"username": "foo"},
411            },
412            {},
413        )
414        action, _ = flow_manager.get_action()
415        self.assertEqual(action, Action.ENROLL)
416        response = flow_manager.get_flow()
417        self.assertIsInstance(response, AccessDeniedResponse)
418
419        self.assertEqual(response.error_message, "foo")

Test error handling when a source selected flow is non-applicable due to a policy

def calculate_group_property_mapping_queries(self, group_count: int) -> int:
421    def calculate_group_property_mapping_queries(self, group_count: int) -> int:
422        """Build group properties for `group_count` groups, check them, and return the
423        number of queries it took"""
424        group_ids = [f"group-{index}" for index in range(group_count)]
425        with CaptureQueriesContext(connection) as queries:
426            flow_manager = OAuthSourceFlowManager(
427                self.source,
428                self.request_factory.get("/", user=AnonymousUser()),
429                self.identifier,
430                {"info": {"groups": group_ids}},
431                {},
432            )
433        self.assertEqual(len(flow_manager.groups_properties), group_count)
434        for group_id in group_ids:
435            # Each group must get its own properties, from both the base properties and
436            # the property mapping
437            self.assertEqual(
438                flow_manager.groups_properties[group_id],
439                {"name": group_id, "attributes": {"group_id": group_id}},
440            )
441        return len(queries.captured_queries)

Build group properties for group_count groups, check them, and return the number of queries it took

def test_group_properties_reuse_mapping_manager(self):
443    def test_group_properties_reuse_mapping_manager(self):
444        """Test that building group properties doesn't re-fetch and re-compile the
445        source's group property mappings for every single group"""
446        self.source.group_property_mappings.add(
447            OAuthSourcePropertyMapping.objects.create(
448                name=generate_id(),
449                expression="""return {"attributes": {"group_id": group_id}}""",
450            )
451        )
452        # Building N groups must take fewer than N queries
453        self.assertLess(self.calculate_group_property_mapping_queries(100), 100)

Test that building group properties doesn't re-fetch and re-compile the source's group property mappings for every single group