authentik.enterprise.stages.source.tests

Source stage tests

  1"""Source stage tests"""
  2
  3from datetime import timedelta
  4
  5from django.conf import settings
  6from django.contrib.auth.models import AnonymousUser
  7from django.urls import reverse
  8from django.utils.timezone import now
  9from guardian.shortcuts import get_anonymous_user
 10
 11from authentik.core.models import SourceUserMatchingModes
 12from authentik.core.sources.flow_manager import (
 13    PLAN_CONTEXT_SOURCE_MATCH_FAILURE,
 14    PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG,
 15    SESSION_KEY_OVERRIDE_FLOW_TOKEN,
 16    SESSION_KEY_SOURCE_FLOW_CONTEXT,
 17    SESSION_KEY_SOURCE_FLOW_STAGES,
 18    MatchFailureConfig,
 19)
 20from authentik.core.sources.matcher import MatchFailure, MatchFailureReason
 21from authentik.core.tests.utils import RequestFactory, create_test_flow, create_test_user
 22from authentik.enterprise.stages.source.models import SourceStage
 23from authentik.enterprise.stages.source.stage import SourceStageFinal
 24from authentik.flows.models import (
 25    Flow,
 26    FlowDesignation,
 27    FlowStageBinding,
 28    FlowToken,
 29    in_memory_stage,
 30)
 31from authentik.flows.planner import (
 32    PLAN_CONTEXT_IS_REDIRECTED,
 33    PLAN_CONTEXT_IS_RESTORED,
 34    FlowPlan,
 35)
 36from authentik.flows.tests import APIFlowTestCase
 37from authentik.flows.views.executor import SESSION_KEY_PLAN
 38from authentik.lib.generators import generate_id
 39from authentik.policies.denied import AccessDeniedResponse
 40from authentik.sources.oauth.models import OAuthSource, UserOAuthSourceConnection
 41from authentik.sources.oauth.views.callback import OAuthSourceFlowManager
 42from authentik.sources.saml.models import SAMLSource
 43from authentik.sources.saml.processors.response import SAMLSourceFlowManager
 44from authentik.stages.identification.models import IdentificationStage, UserFields
 45from authentik.stages.password import BACKEND_INBUILT
 46from authentik.stages.password.models import PasswordStage
 47from authentik.stages.user_login.models import UserLoginStage
 48
 49
 50class TestSourceStage(APIFlowTestCase):
 51    """Source stage tests"""
 52
 53    def setUp(self):
 54        self.request_factory = RequestFactory()
 55        self.source = SAMLSource.objects.create(
 56            slug=generate_id(),
 57            issuer_override="authentik",
 58            allow_idp_initiated=True,
 59            pre_authentication_flow=create_test_flow(),
 60        )
 61
 62    def create_source_plan(self, source, resume_on_match_failures: list[str]):
 63        """Create a suspended Source Stage plan for a source."""
 64        flow = create_test_flow(FlowDesignation.AUTHENTICATION)
 65        stage = SourceStage.objects.create(
 66            name=generate_id(),
 67            source=source,
 68            resume_on_match_failures=resume_on_match_failures,
 69        )
 70        binding = FlowStageBinding.objects.create(target=flow, stage=stage, order=10)
 71        plan = FlowPlan(flow_pk=flow.pk.hex)
 72        plan.append(binding)
 73        if resume_on_match_failures:
 74            plan.context[PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG] = MatchFailureConfig(
 75                reasons=resume_on_match_failures,
 76                source_pk=str(source.pk),
 77                stage_pk=str(stage.pk),
 78            )
 79        token = FlowToken.objects.create(
 80            expires=now() + timedelta(minutes=30),
 81            user=get_anonymous_user(),
 82            identifier=generate_id(),
 83            flow=flow,
 84            _plan=FlowToken.pickle(plan),
 85        )
 86        request = self.request_factory.get("/", user=AnonymousUser())
 87        request.session[SESSION_KEY_OVERRIDE_FLOW_TOKEN] = token
 88        request.session[SESSION_KEY_SOURCE_FLOW_STAGES] = [in_memory_stage(SourceStageFinal)]
 89        request.session[SESSION_KEY_SOURCE_FLOW_CONTEXT] = {
 90            PLAN_CONTEXT_IS_REDIRECTED: flow,
 91        }
 92        request.session.save()
 93        return request, token
 94
 95    def create_oauth_source_plan(self, resume: bool):
 96        """Create a suspended Source Stage plan for an OAuth source."""
 97        source = OAuthSource.objects.create(
 98            name=generate_id(),
 99            slug=generate_id(),
100            provider_type="openidconnect",
101            authorization_url="",
102            profile_url="",
103            consumer_key="",
104            user_matching_mode=SourceUserMatchingModes.EMAIL_LINK,
105        )
106        reasons = [MatchFailureReason.MISSING_PROPERTY] if resume else []
107        request, token = self.create_source_plan(source, reasons)
108        return source, request, token
109
110    def test_missing_match_property_resume(self):
111        """Missing OIDC properties can resume an opted-in parent flow."""
112        source, request, token = self.create_oauth_source_plan(resume=True)
113        userinfo = {"sub": generate_id()}
114        manager = OAuthSourceFlowManager(
115            source,
116            request,
117            userinfo["sub"],
118            {"info": userinfo},
119            {"oauth_userinfo": userinfo},
120        )
121
122        response = manager.get_flow()
123
124        self.assertEqual(response.status_code, 302)
125        self.assertFalse(FlowToken.objects.filter(pk=token.pk).exists())
126        self.assertFalse(UserOAuthSourceConnection.objects.filter(source=source).exists())
127        restored_plan: FlowPlan = request.session[SESSION_KEY_PLAN]
128        self.assertEqual(restored_plan.context["oauth_userinfo"], userinfo)
129        self.assertEqual(
130            restored_plan.context[PLAN_CONTEXT_SOURCE_MATCH_FAILURE],
131            MatchFailure(
132                reason=MatchFailureReason.MISSING_PROPERTY,
133                property="email",
134                source_slug=source.slug,
135            ),
136        )
137        self.assertNotIn(
138            PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG,
139            restored_plan.context,
140        )
141        request.session.save()
142        self.client.cookies[settings.SESSION_COOKIE_NAME] = request.session.session_key
143        with self.assertFlowFinishes():
144            self.client.get(
145                reverse("authentik_api:flow-executor", kwargs={"flow_slug": token.flow.slug})
146            )
147        session = self.client.session
148        self.assertNotIn(SESSION_KEY_OVERRIDE_FLOW_TOKEN, session)
149        self.assertNotIn(SESSION_KEY_SOURCE_FLOW_STAGES, session)
150        self.assertNotIn(SESSION_KEY_SOURCE_FLOW_CONTEXT, session)
151
152    def test_missing_match_property_default_denies(self):
153        """Missing OIDC properties retain the existing behavior by default."""
154        source, request, token = self.create_oauth_source_plan(resume=False)
155        userinfo = {"sub": generate_id()}
156        manager = OAuthSourceFlowManager(
157            source,
158            request,
159            userinfo["sub"],
160            {"info": userinfo},
161            {"oauth_userinfo": userinfo},
162        )
163
164        response = manager.get_flow()
165
166        self.assertIsInstance(response, AccessDeniedResponse)
167        self.assertTrue(FlowToken.objects.filter(pk=token.pk).exists())
168        self.assertFalse(UserOAuthSourceConnection.objects.filter(source=source).exists())
169
170    def test_missing_match_property_expired_token_denies(self):
171        """Missing OIDC properties cannot resume an expired parent flow."""
172        source, request, token = self.create_oauth_source_plan(resume=True)
173        token.expires = now() - timedelta(seconds=1)
174        token.save(update_fields=("expires",))
175        userinfo = {"sub": generate_id()}
176        manager = OAuthSourceFlowManager(
177            source,
178            request,
179            userinfo["sub"],
180            {"info": userinfo},
181            {"oauth_userinfo": userinfo},
182        )
183
184        response = manager.get_flow()
185
186        self.assertIsInstance(response, AccessDeniedResponse)
187        self.assertFalse(FlowToken.objects.filter(pk=token.pk).exists())
188        self.assertFalse(UserOAuthSourceConnection.objects.filter(source=source).exists())
189        self.assertNotIn(SESSION_KEY_OVERRIDE_FLOW_TOKEN, request.session)
190        self.assertNotIn(SESSION_KEY_SOURCE_FLOW_STAGES, request.session)
191        self.assertNotIn(SESSION_KEY_SOURCE_FLOW_CONTEXT, request.session)
192
193    def test_saml_missing_match_property_resume(self):
194        """SAML sources use the generic matching failure resume behavior."""
195        request, token = self.create_source_plan(self.source, [MatchFailureReason.MISSING_PROPERTY])
196        manager = SAMLSourceFlowManager.__new__(SAMLSourceFlowManager)
197        manager.source = self.source
198        manager.request = request
199        manager.policy_context = {"saml_response": b"<Response />"}
200
201        failure = MatchFailure(
202            reason=MatchFailureReason.MISSING_PROPERTY,
203            property="email",
204            source_slug=self.source.slug,
205        )
206
207        response = manager.handle_match_failure(failure)
208
209        self.assertEqual(response.status_code, 302)
210        self.assertFalse(FlowToken.objects.filter(pk=token.pk).exists())
211        restored_plan: FlowPlan = request.session[SESSION_KEY_PLAN]
212        self.assertEqual(restored_plan.context["saml_response"], b"<Response />")
213        self.assertEqual(restored_plan.context[PLAN_CONTEXT_SOURCE_MATCH_FAILURE], failure)
214
215    def run_to_source_redirect(self) -> tuple[Flow, SourceStage, FlowToken]:
216        """Run a flow with a bound Source Stage up to the point where the user is sent
217        to the source, and return the token that can resume it."""
218        user = create_test_user()
219        flow = create_test_flow(FlowDesignation.AUTHENTICATION)
220        stage = SourceStage.objects.create(
221            name=generate_id(),
222            source=self.source,
223            resume_on_match_failures=[MatchFailureReason.MISSING_PROPERTY],
224        )
225        FlowStageBinding.objects.create(
226            target=flow,
227            stage=IdentificationStage.objects.create(
228                name=generate_id(),
229                user_fields=[UserFields.USERNAME],
230            ),
231            order=0,
232        )
233        FlowStageBinding.objects.create(
234            target=flow,
235            stage=PasswordStage.objects.create(name=generate_id(), backends=[BACKEND_INBUILT]),
236            order=5,
237        )
238        FlowStageBinding.objects.create(target=flow, stage=stage, order=10)
239        FlowStageBinding.objects.create(
240            target=flow,
241            stage=UserLoginStage.objects.create(
242                name=generate_id(),
243            ),
244            order=15,
245        )
246
247        # Get user identification stage
248        response = self.client.get(
249            reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}),
250        )
251        self.assertEqual(response.status_code, 200)
252        self.assertStageResponse(response, flow, component="ak-stage-identification")
253        # Send username
254        response = self.client.post(
255            reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}),
256            data={"uid_field": user.username},
257            follow=True,
258        )
259        self.assertEqual(response.status_code, 200)
260        self.assertStageResponse(response, flow, component="ak-stage-password")
261        # Send password
262        response = self.client.post(
263            reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}),
264            data={"password": user.username},
265            follow=True,
266        )
267        self.assertEqual(response.status_code, 200)
268        self.assertStageResponse(
269            response,
270            flow,
271            component="xak-flow-redirect",
272            to=reverse("authentik_sources_saml:login", kwargs={"source_slug": self.source.slug}),
273            final_redirect=False,
274        )
275
276        flow_token = FlowToken.objects.filter(
277            identifier__startswith=f"ak-source-stage-{stage.name.lower()}"
278        ).first()
279        self.assertIsNotNone(flow_token)
280        return flow, stage, flow_token
281
282    def test_source_success(self):
283        """Test"""
284        flow, stage, flow_token = self.run_to_source_redirect()
285        self.assertEqual(
286            flow_token.plan.context[PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG],
287            MatchFailureConfig(
288                reasons=[MatchFailureReason.MISSING_PROPERTY],
289                source_pk=str(self.source.pk),
290                stage_pk=str(stage.pk),
291            ),
292        )
293        # Hijack flow plan so we don't have to emulate the source
294        session = self.client.session
295        plan: FlowPlan = session[SESSION_KEY_PLAN]
296        plan.insert_stage(in_memory_stage(SourceStageFinal), index=0)
297        plan.context[PLAN_CONTEXT_IS_RESTORED] = flow_token
298        plan.context["foo"] = "bar"
299        session[SESSION_KEY_PLAN] = plan
300        session.save()
301
302        # Pretend we've just returned from the source
303        with self.assertFlowFinishes() as ff:
304            response = self.client.get(
305                reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), follow=True
306            )
307            self.assertEqual(response.status_code, 200)
308            self.assertStageRedirects(
309                response, reverse("authentik_core:if-flow", kwargs={"flow_slug": flow.slug})
310            )
311        self.assertEqual(ff().context["foo"], "bar")
312
313    def test_source_expired_token(self):
314        """Test returning from the source after the resume token expired"""
315        flow, _, flow_token = self.run_to_source_redirect()
316        flow_token.expires = now() - timedelta(seconds=1)
317        flow_token.save(update_fields=("expires",))
318        # Hijack flow plan so we don't have to emulate the source
319        session = self.client.session
320        plan: FlowPlan = session[SESSION_KEY_PLAN]
321        plan.insert_stage(in_memory_stage(SourceStageFinal), index=0)
322        session[SESSION_KEY_PLAN] = plan
323        session.save()
324
325        # Pretend we've just returned from the source
326        response = self.client.get(
327            reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug})
328        )
329        self.assertStageResponse(response, component="ak-stage-access-denied")
330        session = self.client.session
331        self.assertNotIn(SESSION_KEY_OVERRIDE_FLOW_TOKEN, session)
332        self.assertNotIn(SESSION_KEY_SOURCE_FLOW_STAGES, session)
333        self.assertNotIn(SESSION_KEY_SOURCE_FLOW_CONTEXT, session)
class TestSourceStage(authentik.flows.tests.APIFlowTestCase):
 51class TestSourceStage(APIFlowTestCase):
 52    """Source stage tests"""
 53
 54    def setUp(self):
 55        self.request_factory = RequestFactory()
 56        self.source = SAMLSource.objects.create(
 57            slug=generate_id(),
 58            issuer_override="authentik",
 59            allow_idp_initiated=True,
 60            pre_authentication_flow=create_test_flow(),
 61        )
 62
 63    def create_source_plan(self, source, resume_on_match_failures: list[str]):
 64        """Create a suspended Source Stage plan for a source."""
 65        flow = create_test_flow(FlowDesignation.AUTHENTICATION)
 66        stage = SourceStage.objects.create(
 67            name=generate_id(),
 68            source=source,
 69            resume_on_match_failures=resume_on_match_failures,
 70        )
 71        binding = FlowStageBinding.objects.create(target=flow, stage=stage, order=10)
 72        plan = FlowPlan(flow_pk=flow.pk.hex)
 73        plan.append(binding)
 74        if resume_on_match_failures:
 75            plan.context[PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG] = MatchFailureConfig(
 76                reasons=resume_on_match_failures,
 77                source_pk=str(source.pk),
 78                stage_pk=str(stage.pk),
 79            )
 80        token = FlowToken.objects.create(
 81            expires=now() + timedelta(minutes=30),
 82            user=get_anonymous_user(),
 83            identifier=generate_id(),
 84            flow=flow,
 85            _plan=FlowToken.pickle(plan),
 86        )
 87        request = self.request_factory.get("/", user=AnonymousUser())
 88        request.session[SESSION_KEY_OVERRIDE_FLOW_TOKEN] = token
 89        request.session[SESSION_KEY_SOURCE_FLOW_STAGES] = [in_memory_stage(SourceStageFinal)]
 90        request.session[SESSION_KEY_SOURCE_FLOW_CONTEXT] = {
 91            PLAN_CONTEXT_IS_REDIRECTED: flow,
 92        }
 93        request.session.save()
 94        return request, token
 95
 96    def create_oauth_source_plan(self, resume: bool):
 97        """Create a suspended Source Stage plan for an OAuth source."""
 98        source = OAuthSource.objects.create(
 99            name=generate_id(),
100            slug=generate_id(),
101            provider_type="openidconnect",
102            authorization_url="",
103            profile_url="",
104            consumer_key="",
105            user_matching_mode=SourceUserMatchingModes.EMAIL_LINK,
106        )
107        reasons = [MatchFailureReason.MISSING_PROPERTY] if resume else []
108        request, token = self.create_source_plan(source, reasons)
109        return source, request, token
110
111    def test_missing_match_property_resume(self):
112        """Missing OIDC properties can resume an opted-in parent flow."""
113        source, request, token = self.create_oauth_source_plan(resume=True)
114        userinfo = {"sub": generate_id()}
115        manager = OAuthSourceFlowManager(
116            source,
117            request,
118            userinfo["sub"],
119            {"info": userinfo},
120            {"oauth_userinfo": userinfo},
121        )
122
123        response = manager.get_flow()
124
125        self.assertEqual(response.status_code, 302)
126        self.assertFalse(FlowToken.objects.filter(pk=token.pk).exists())
127        self.assertFalse(UserOAuthSourceConnection.objects.filter(source=source).exists())
128        restored_plan: FlowPlan = request.session[SESSION_KEY_PLAN]
129        self.assertEqual(restored_plan.context["oauth_userinfo"], userinfo)
130        self.assertEqual(
131            restored_plan.context[PLAN_CONTEXT_SOURCE_MATCH_FAILURE],
132            MatchFailure(
133                reason=MatchFailureReason.MISSING_PROPERTY,
134                property="email",
135                source_slug=source.slug,
136            ),
137        )
138        self.assertNotIn(
139            PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG,
140            restored_plan.context,
141        )
142        request.session.save()
143        self.client.cookies[settings.SESSION_COOKIE_NAME] = request.session.session_key
144        with self.assertFlowFinishes():
145            self.client.get(
146                reverse("authentik_api:flow-executor", kwargs={"flow_slug": token.flow.slug})
147            )
148        session = self.client.session
149        self.assertNotIn(SESSION_KEY_OVERRIDE_FLOW_TOKEN, session)
150        self.assertNotIn(SESSION_KEY_SOURCE_FLOW_STAGES, session)
151        self.assertNotIn(SESSION_KEY_SOURCE_FLOW_CONTEXT, session)
152
153    def test_missing_match_property_default_denies(self):
154        """Missing OIDC properties retain the existing behavior by default."""
155        source, request, token = self.create_oauth_source_plan(resume=False)
156        userinfo = {"sub": generate_id()}
157        manager = OAuthSourceFlowManager(
158            source,
159            request,
160            userinfo["sub"],
161            {"info": userinfo},
162            {"oauth_userinfo": userinfo},
163        )
164
165        response = manager.get_flow()
166
167        self.assertIsInstance(response, AccessDeniedResponse)
168        self.assertTrue(FlowToken.objects.filter(pk=token.pk).exists())
169        self.assertFalse(UserOAuthSourceConnection.objects.filter(source=source).exists())
170
171    def test_missing_match_property_expired_token_denies(self):
172        """Missing OIDC properties cannot resume an expired parent flow."""
173        source, request, token = self.create_oauth_source_plan(resume=True)
174        token.expires = now() - timedelta(seconds=1)
175        token.save(update_fields=("expires",))
176        userinfo = {"sub": generate_id()}
177        manager = OAuthSourceFlowManager(
178            source,
179            request,
180            userinfo["sub"],
181            {"info": userinfo},
182            {"oauth_userinfo": userinfo},
183        )
184
185        response = manager.get_flow()
186
187        self.assertIsInstance(response, AccessDeniedResponse)
188        self.assertFalse(FlowToken.objects.filter(pk=token.pk).exists())
189        self.assertFalse(UserOAuthSourceConnection.objects.filter(source=source).exists())
190        self.assertNotIn(SESSION_KEY_OVERRIDE_FLOW_TOKEN, request.session)
191        self.assertNotIn(SESSION_KEY_SOURCE_FLOW_STAGES, request.session)
192        self.assertNotIn(SESSION_KEY_SOURCE_FLOW_CONTEXT, request.session)
193
194    def test_saml_missing_match_property_resume(self):
195        """SAML sources use the generic matching failure resume behavior."""
196        request, token = self.create_source_plan(self.source, [MatchFailureReason.MISSING_PROPERTY])
197        manager = SAMLSourceFlowManager.__new__(SAMLSourceFlowManager)
198        manager.source = self.source
199        manager.request = request
200        manager.policy_context = {"saml_response": b"<Response />"}
201
202        failure = MatchFailure(
203            reason=MatchFailureReason.MISSING_PROPERTY,
204            property="email",
205            source_slug=self.source.slug,
206        )
207
208        response = manager.handle_match_failure(failure)
209
210        self.assertEqual(response.status_code, 302)
211        self.assertFalse(FlowToken.objects.filter(pk=token.pk).exists())
212        restored_plan: FlowPlan = request.session[SESSION_KEY_PLAN]
213        self.assertEqual(restored_plan.context["saml_response"], b"<Response />")
214        self.assertEqual(restored_plan.context[PLAN_CONTEXT_SOURCE_MATCH_FAILURE], failure)
215
216    def run_to_source_redirect(self) -> tuple[Flow, SourceStage, FlowToken]:
217        """Run a flow with a bound Source Stage up to the point where the user is sent
218        to the source, and return the token that can resume it."""
219        user = create_test_user()
220        flow = create_test_flow(FlowDesignation.AUTHENTICATION)
221        stage = SourceStage.objects.create(
222            name=generate_id(),
223            source=self.source,
224            resume_on_match_failures=[MatchFailureReason.MISSING_PROPERTY],
225        )
226        FlowStageBinding.objects.create(
227            target=flow,
228            stage=IdentificationStage.objects.create(
229                name=generate_id(),
230                user_fields=[UserFields.USERNAME],
231            ),
232            order=0,
233        )
234        FlowStageBinding.objects.create(
235            target=flow,
236            stage=PasswordStage.objects.create(name=generate_id(), backends=[BACKEND_INBUILT]),
237            order=5,
238        )
239        FlowStageBinding.objects.create(target=flow, stage=stage, order=10)
240        FlowStageBinding.objects.create(
241            target=flow,
242            stage=UserLoginStage.objects.create(
243                name=generate_id(),
244            ),
245            order=15,
246        )
247
248        # Get user identification stage
249        response = self.client.get(
250            reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}),
251        )
252        self.assertEqual(response.status_code, 200)
253        self.assertStageResponse(response, flow, component="ak-stage-identification")
254        # Send username
255        response = self.client.post(
256            reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}),
257            data={"uid_field": user.username},
258            follow=True,
259        )
260        self.assertEqual(response.status_code, 200)
261        self.assertStageResponse(response, flow, component="ak-stage-password")
262        # Send password
263        response = self.client.post(
264            reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}),
265            data={"password": user.username},
266            follow=True,
267        )
268        self.assertEqual(response.status_code, 200)
269        self.assertStageResponse(
270            response,
271            flow,
272            component="xak-flow-redirect",
273            to=reverse("authentik_sources_saml:login", kwargs={"source_slug": self.source.slug}),
274            final_redirect=False,
275        )
276
277        flow_token = FlowToken.objects.filter(
278            identifier__startswith=f"ak-source-stage-{stage.name.lower()}"
279        ).first()
280        self.assertIsNotNone(flow_token)
281        return flow, stage, flow_token
282
283    def test_source_success(self):
284        """Test"""
285        flow, stage, flow_token = self.run_to_source_redirect()
286        self.assertEqual(
287            flow_token.plan.context[PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG],
288            MatchFailureConfig(
289                reasons=[MatchFailureReason.MISSING_PROPERTY],
290                source_pk=str(self.source.pk),
291                stage_pk=str(stage.pk),
292            ),
293        )
294        # Hijack flow plan so we don't have to emulate the source
295        session = self.client.session
296        plan: FlowPlan = session[SESSION_KEY_PLAN]
297        plan.insert_stage(in_memory_stage(SourceStageFinal), index=0)
298        plan.context[PLAN_CONTEXT_IS_RESTORED] = flow_token
299        plan.context["foo"] = "bar"
300        session[SESSION_KEY_PLAN] = plan
301        session.save()
302
303        # Pretend we've just returned from the source
304        with self.assertFlowFinishes() as ff:
305            response = self.client.get(
306                reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), follow=True
307            )
308            self.assertEqual(response.status_code, 200)
309            self.assertStageRedirects(
310                response, reverse("authentik_core:if-flow", kwargs={"flow_slug": flow.slug})
311            )
312        self.assertEqual(ff().context["foo"], "bar")
313
314    def test_source_expired_token(self):
315        """Test returning from the source after the resume token expired"""
316        flow, _, flow_token = self.run_to_source_redirect()
317        flow_token.expires = now() - timedelta(seconds=1)
318        flow_token.save(update_fields=("expires",))
319        # Hijack flow plan so we don't have to emulate the source
320        session = self.client.session
321        plan: FlowPlan = session[SESSION_KEY_PLAN]
322        plan.insert_stage(in_memory_stage(SourceStageFinal), index=0)
323        session[SESSION_KEY_PLAN] = plan
324        session.save()
325
326        # Pretend we've just returned from the source
327        response = self.client.get(
328            reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug})
329        )
330        self.assertStageResponse(response, component="ak-stage-access-denied")
331        session = self.client.session
332        self.assertNotIn(SESSION_KEY_OVERRIDE_FLOW_TOKEN, session)
333        self.assertNotIn(SESSION_KEY_SOURCE_FLOW_STAGES, session)
334        self.assertNotIn(SESSION_KEY_SOURCE_FLOW_CONTEXT, session)

Source stage tests

def setUp(self):
54    def setUp(self):
55        self.request_factory = RequestFactory()
56        self.source = SAMLSource.objects.create(
57            slug=generate_id(),
58            issuer_override="authentik",
59            allow_idp_initiated=True,
60            pre_authentication_flow=create_test_flow(),
61        )

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

def create_source_plan(self, source, resume_on_match_failures: list[str]):
63    def create_source_plan(self, source, resume_on_match_failures: list[str]):
64        """Create a suspended Source Stage plan for a source."""
65        flow = create_test_flow(FlowDesignation.AUTHENTICATION)
66        stage = SourceStage.objects.create(
67            name=generate_id(),
68            source=source,
69            resume_on_match_failures=resume_on_match_failures,
70        )
71        binding = FlowStageBinding.objects.create(target=flow, stage=stage, order=10)
72        plan = FlowPlan(flow_pk=flow.pk.hex)
73        plan.append(binding)
74        if resume_on_match_failures:
75            plan.context[PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG] = MatchFailureConfig(
76                reasons=resume_on_match_failures,
77                source_pk=str(source.pk),
78                stage_pk=str(stage.pk),
79            )
80        token = FlowToken.objects.create(
81            expires=now() + timedelta(minutes=30),
82            user=get_anonymous_user(),
83            identifier=generate_id(),
84            flow=flow,
85            _plan=FlowToken.pickle(plan),
86        )
87        request = self.request_factory.get("/", user=AnonymousUser())
88        request.session[SESSION_KEY_OVERRIDE_FLOW_TOKEN] = token
89        request.session[SESSION_KEY_SOURCE_FLOW_STAGES] = [in_memory_stage(SourceStageFinal)]
90        request.session[SESSION_KEY_SOURCE_FLOW_CONTEXT] = {
91            PLAN_CONTEXT_IS_REDIRECTED: flow,
92        }
93        request.session.save()
94        return request, token

Create a suspended Source Stage plan for a source.

def create_oauth_source_plan(self, resume: bool):
 96    def create_oauth_source_plan(self, resume: bool):
 97        """Create a suspended Source Stage plan for an OAuth source."""
 98        source = OAuthSource.objects.create(
 99            name=generate_id(),
100            slug=generate_id(),
101            provider_type="openidconnect",
102            authorization_url="",
103            profile_url="",
104            consumer_key="",
105            user_matching_mode=SourceUserMatchingModes.EMAIL_LINK,
106        )
107        reasons = [MatchFailureReason.MISSING_PROPERTY] if resume else []
108        request, token = self.create_source_plan(source, reasons)
109        return source, request, token

Create a suspended Source Stage plan for an OAuth source.

def test_missing_match_property_resume(self):
111    def test_missing_match_property_resume(self):
112        """Missing OIDC properties can resume an opted-in parent flow."""
113        source, request, token = self.create_oauth_source_plan(resume=True)
114        userinfo = {"sub": generate_id()}
115        manager = OAuthSourceFlowManager(
116            source,
117            request,
118            userinfo["sub"],
119            {"info": userinfo},
120            {"oauth_userinfo": userinfo},
121        )
122
123        response = manager.get_flow()
124
125        self.assertEqual(response.status_code, 302)
126        self.assertFalse(FlowToken.objects.filter(pk=token.pk).exists())
127        self.assertFalse(UserOAuthSourceConnection.objects.filter(source=source).exists())
128        restored_plan: FlowPlan = request.session[SESSION_KEY_PLAN]
129        self.assertEqual(restored_plan.context["oauth_userinfo"], userinfo)
130        self.assertEqual(
131            restored_plan.context[PLAN_CONTEXT_SOURCE_MATCH_FAILURE],
132            MatchFailure(
133                reason=MatchFailureReason.MISSING_PROPERTY,
134                property="email",
135                source_slug=source.slug,
136            ),
137        )
138        self.assertNotIn(
139            PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG,
140            restored_plan.context,
141        )
142        request.session.save()
143        self.client.cookies[settings.SESSION_COOKIE_NAME] = request.session.session_key
144        with self.assertFlowFinishes():
145            self.client.get(
146                reverse("authentik_api:flow-executor", kwargs={"flow_slug": token.flow.slug})
147            )
148        session = self.client.session
149        self.assertNotIn(SESSION_KEY_OVERRIDE_FLOW_TOKEN, session)
150        self.assertNotIn(SESSION_KEY_SOURCE_FLOW_STAGES, session)
151        self.assertNotIn(SESSION_KEY_SOURCE_FLOW_CONTEXT, session)

Missing OIDC properties can resume an opted-in parent flow.

def test_missing_match_property_default_denies(self):
153    def test_missing_match_property_default_denies(self):
154        """Missing OIDC properties retain the existing behavior by default."""
155        source, request, token = self.create_oauth_source_plan(resume=False)
156        userinfo = {"sub": generate_id()}
157        manager = OAuthSourceFlowManager(
158            source,
159            request,
160            userinfo["sub"],
161            {"info": userinfo},
162            {"oauth_userinfo": userinfo},
163        )
164
165        response = manager.get_flow()
166
167        self.assertIsInstance(response, AccessDeniedResponse)
168        self.assertTrue(FlowToken.objects.filter(pk=token.pk).exists())
169        self.assertFalse(UserOAuthSourceConnection.objects.filter(source=source).exists())

Missing OIDC properties retain the existing behavior by default.

def test_missing_match_property_expired_token_denies(self):
171    def test_missing_match_property_expired_token_denies(self):
172        """Missing OIDC properties cannot resume an expired parent flow."""
173        source, request, token = self.create_oauth_source_plan(resume=True)
174        token.expires = now() - timedelta(seconds=1)
175        token.save(update_fields=("expires",))
176        userinfo = {"sub": generate_id()}
177        manager = OAuthSourceFlowManager(
178            source,
179            request,
180            userinfo["sub"],
181            {"info": userinfo},
182            {"oauth_userinfo": userinfo},
183        )
184
185        response = manager.get_flow()
186
187        self.assertIsInstance(response, AccessDeniedResponse)
188        self.assertFalse(FlowToken.objects.filter(pk=token.pk).exists())
189        self.assertFalse(UserOAuthSourceConnection.objects.filter(source=source).exists())
190        self.assertNotIn(SESSION_KEY_OVERRIDE_FLOW_TOKEN, request.session)
191        self.assertNotIn(SESSION_KEY_SOURCE_FLOW_STAGES, request.session)
192        self.assertNotIn(SESSION_KEY_SOURCE_FLOW_CONTEXT, request.session)

Missing OIDC properties cannot resume an expired parent flow.

def test_saml_missing_match_property_resume(self):
194    def test_saml_missing_match_property_resume(self):
195        """SAML sources use the generic matching failure resume behavior."""
196        request, token = self.create_source_plan(self.source, [MatchFailureReason.MISSING_PROPERTY])
197        manager = SAMLSourceFlowManager.__new__(SAMLSourceFlowManager)
198        manager.source = self.source
199        manager.request = request
200        manager.policy_context = {"saml_response": b"<Response />"}
201
202        failure = MatchFailure(
203            reason=MatchFailureReason.MISSING_PROPERTY,
204            property="email",
205            source_slug=self.source.slug,
206        )
207
208        response = manager.handle_match_failure(failure)
209
210        self.assertEqual(response.status_code, 302)
211        self.assertFalse(FlowToken.objects.filter(pk=token.pk).exists())
212        restored_plan: FlowPlan = request.session[SESSION_KEY_PLAN]
213        self.assertEqual(restored_plan.context["saml_response"], b"<Response />")
214        self.assertEqual(restored_plan.context[PLAN_CONTEXT_SOURCE_MATCH_FAILURE], failure)

SAML sources use the generic matching failure resume behavior.

216    def run_to_source_redirect(self) -> tuple[Flow, SourceStage, FlowToken]:
217        """Run a flow with a bound Source Stage up to the point where the user is sent
218        to the source, and return the token that can resume it."""
219        user = create_test_user()
220        flow = create_test_flow(FlowDesignation.AUTHENTICATION)
221        stage = SourceStage.objects.create(
222            name=generate_id(),
223            source=self.source,
224            resume_on_match_failures=[MatchFailureReason.MISSING_PROPERTY],
225        )
226        FlowStageBinding.objects.create(
227            target=flow,
228            stage=IdentificationStage.objects.create(
229                name=generate_id(),
230                user_fields=[UserFields.USERNAME],
231            ),
232            order=0,
233        )
234        FlowStageBinding.objects.create(
235            target=flow,
236            stage=PasswordStage.objects.create(name=generate_id(), backends=[BACKEND_INBUILT]),
237            order=5,
238        )
239        FlowStageBinding.objects.create(target=flow, stage=stage, order=10)
240        FlowStageBinding.objects.create(
241            target=flow,
242            stage=UserLoginStage.objects.create(
243                name=generate_id(),
244            ),
245            order=15,
246        )
247
248        # Get user identification stage
249        response = self.client.get(
250            reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}),
251        )
252        self.assertEqual(response.status_code, 200)
253        self.assertStageResponse(response, flow, component="ak-stage-identification")
254        # Send username
255        response = self.client.post(
256            reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}),
257            data={"uid_field": user.username},
258            follow=True,
259        )
260        self.assertEqual(response.status_code, 200)
261        self.assertStageResponse(response, flow, component="ak-stage-password")
262        # Send password
263        response = self.client.post(
264            reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}),
265            data={"password": user.username},
266            follow=True,
267        )
268        self.assertEqual(response.status_code, 200)
269        self.assertStageResponse(
270            response,
271            flow,
272            component="xak-flow-redirect",
273            to=reverse("authentik_sources_saml:login", kwargs={"source_slug": self.source.slug}),
274            final_redirect=False,
275        )
276
277        flow_token = FlowToken.objects.filter(
278            identifier__startswith=f"ak-source-stage-{stage.name.lower()}"
279        ).first()
280        self.assertIsNotNone(flow_token)
281        return flow, stage, flow_token

Run a flow with a bound Source Stage up to the point where the user is sent to the source, and return the token that can resume it.

def test_source_success(self):
283    def test_source_success(self):
284        """Test"""
285        flow, stage, flow_token = self.run_to_source_redirect()
286        self.assertEqual(
287            flow_token.plan.context[PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG],
288            MatchFailureConfig(
289                reasons=[MatchFailureReason.MISSING_PROPERTY],
290                source_pk=str(self.source.pk),
291                stage_pk=str(stage.pk),
292            ),
293        )
294        # Hijack flow plan so we don't have to emulate the source
295        session = self.client.session
296        plan: FlowPlan = session[SESSION_KEY_PLAN]
297        plan.insert_stage(in_memory_stage(SourceStageFinal), index=0)
298        plan.context[PLAN_CONTEXT_IS_RESTORED] = flow_token
299        plan.context["foo"] = "bar"
300        session[SESSION_KEY_PLAN] = plan
301        session.save()
302
303        # Pretend we've just returned from the source
304        with self.assertFlowFinishes() as ff:
305            response = self.client.get(
306                reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), follow=True
307            )
308            self.assertEqual(response.status_code, 200)
309            self.assertStageRedirects(
310                response, reverse("authentik_core:if-flow", kwargs={"flow_slug": flow.slug})
311            )
312        self.assertEqual(ff().context["foo"], "bar")

Test

def test_source_expired_token(self):
314    def test_source_expired_token(self):
315        """Test returning from the source after the resume token expired"""
316        flow, _, flow_token = self.run_to_source_redirect()
317        flow_token.expires = now() - timedelta(seconds=1)
318        flow_token.save(update_fields=("expires",))
319        # Hijack flow plan so we don't have to emulate the source
320        session = self.client.session
321        plan: FlowPlan = session[SESSION_KEY_PLAN]
322        plan.insert_stage(in_memory_stage(SourceStageFinal), index=0)
323        session[SESSION_KEY_PLAN] = plan
324        session.save()
325
326        # Pretend we've just returned from the source
327        response = self.client.get(
328            reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug})
329        )
330        self.assertStageResponse(response, component="ak-stage-access-denied")
331        session = self.client.session
332        self.assertNotIn(SESSION_KEY_OVERRIDE_FLOW_TOKEN, session)
333        self.assertNotIn(SESSION_KEY_SOURCE_FLOW_STAGES, session)
334        self.assertNotIn(SESSION_KEY_SOURCE_FLOW_CONTEXT, session)

Test returning from the source after the resume token expired