authentik.stages.identification.tests

identification tests

  1"""identification tests"""
  2
  3from json import loads
  4
  5from django.urls import reverse
  6from requests_mock import Mocker
  7from rest_framework.exceptions import ValidationError
  8
  9from authentik.core.tests.utils import create_test_admin_user, create_test_flow
 10from authentik.enterprise.tests import enterprise_test
 11from authentik.flows.models import FlowDesignation, FlowStageBinding
 12from authentik.flows.stage import PLAN_CONTEXT_PENDING_USER_IDENTIFIER
 13from authentik.flows.tests import APIFlowTestCase
 14from authentik.lib.generators import generate_id
 15from authentik.sources.oauth.models import OAuthSource
 16from authentik.stages.authenticator_validate.models import AuthenticatorValidateStage, DeviceClasses
 17from authentik.stages.authenticator_webauthn.models import WebAuthnDevice
 18from authentik.stages.captcha.models import CaptchaStage
 19from authentik.stages.captcha.stage import (
 20    PLAN_CONTEXT_CAPTCHA_PRIVATE_KEY,
 21    PLAN_CONTEXT_CAPTCHA_SITE_KEY,
 22)
 23from authentik.stages.captcha.tests import RECAPTCHA_PRIVATE_KEY, RECAPTCHA_PUBLIC_KEY
 24from authentik.stages.identification.api import IdentificationStageSerializer
 25from authentik.stages.identification.models import IdentificationStage, UserFields
 26from authentik.stages.password import BACKEND_INBUILT
 27from authentik.stages.password.models import PasswordDevice, PasswordStage
 28
 29
 30class TestIdentificationStagePasskey(APIFlowTestCase):
 31    """Passkey authentication tests"""
 32
 33    def setUp(self):
 34        super().setUp()
 35        self.user = create_test_admin_user()
 36        self.flow = create_test_flow(FlowDesignation.AUTHENTICATION)
 37        self.webauthn_stage = AuthenticatorValidateStage.objects.create(
 38            name="webauthn-validate",
 39            device_classes=[DeviceClasses.WEBAUTHN],
 40        )
 41        self.stage = IdentificationStage.objects.create(
 42            name="identification",
 43            user_fields=[UserFields.E_MAIL],
 44            webauthn_stage=self.webauthn_stage,
 45        )
 46        FlowStageBinding.objects.create(target=self.flow, stage=self.stage, order=0)
 47        self.device = WebAuthnDevice.objects.create(
 48            user=self.user,
 49            name="Test Passkey",
 50            credential_id="test-credential-id",
 51            public_key="test-public-key",
 52            sign_count=0,
 53            rp_id="testserver",
 54        )
 55
 56    def test_passkey_auth_success(self):
 57        """Test passkey sets device, user, backend and updates last_used"""
 58        from unittest.mock import patch
 59
 60        # Get challenge to initialize session
 61        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
 62        self.client.get(url)
 63
 64        with patch(
 65            "authentik.stages.identification.stage.validate_challenge_webauthn",
 66            return_value=self.device,
 67        ):
 68            response = self.client.post(
 69                url, {"passkey": {"id": "test"}}, content_type="application/json"
 70            )
 71
 72        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
 73        # Verify device last_used was updated
 74        self.device.refresh_from_db()
 75        self.assertIsNotNone(self.device.last_used)
 76
 77    def test_passkey_challenge_disabled(self):
 78        """Test that passkey challenge is not included when webauthn_stage is not set"""
 79        self.stage.webauthn_stage = None
 80        self.stage.save()
 81        response = self.client.get(
 82            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
 83        )
 84        self.assertEqual(response.status_code, 200)
 85        data = response.json()
 86        self.assertIsNone(data.get("passkey_challenge"))
 87
 88    def test_passkey_challenge_enabled(self):
 89        """Test that passkey challenge is included when webauthn_stage is set"""
 90        response = self.client.get(
 91            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
 92        )
 93        self.assertEqual(response.status_code, 200)
 94        data = response.json()
 95        self.assertIsNotNone(data.get("passkey_challenge"))
 96        passkey_challenge = data["passkey_challenge"]
 97        self.assertIn("challenge", passkey_challenge)
 98        self.assertIn("rpId", passkey_challenge)
 99        self.assertEqual(passkey_challenge["allowCredentials"], [])
100
101    def test_passkey_challenge_generation(self):
102        """Test passkey challenge is generated correctly"""
103        response = self.client.get(
104            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
105        )
106        self.assertEqual(response.status_code, 200)
107        data = response.json()
108        self.assertIsNotNone(data.get("passkey_challenge"))
109
110    def test_passkey_no_uid_field_required(self):
111        """Test that uid_field is not required when passkey is provided"""
112        # Get the challenge first to set up the session
113        response = self.client.get(
114            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
115        )
116        self.assertEqual(response.status_code, 200)
117
118        # Submit without uid_field but with passkey (invalid passkey will fail validation)
119        form_data = {
120            "passkey": {
121                "id": "invalid",
122                "rawId": "invalid",
123                "type": "public-key",
124                "response": {
125                    "clientDataJSON": "invalid",
126                    "authenticatorData": "invalid",
127                    "signature": "invalid",
128                },
129            }
130        }
131        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
132        response = self.client.post(url, form_data, content_type="application/json")
133        self.assertEqual(response.status_code, 200)
134        data = response.json()
135        self.assertIn("response_errors", data)
136        errors = data.get("response_errors", {})
137        self.assertNotIn("uid_field", errors)
138
139
140class TestIdentificationStage(APIFlowTestCase):
141    """Identification tests"""
142
143    def setUp(self):
144        super().setUp()
145        self.user = create_test_admin_user()
146
147        # OAuthSource for the login view
148        self.source = OAuthSource.objects.create(name=generate_id(), slug=generate_id())
149
150        self.flow = create_test_flow(FlowDesignation.AUTHENTICATION)
151        self.stage = IdentificationStage.objects.create(
152            name="identification",
153            user_fields=[UserFields.E_MAIL],
154            pretend_user_exists=False,
155        )
156        self.stage.sources.set([self.source])
157        self.stage.save()
158        FlowStageBinding.objects.create(
159            target=self.flow,
160            stage=self.stage,
161            order=0,
162        )
163
164    def test_valid_render(self):
165        """Test that View renders correctly"""
166        response = self.client.get(
167            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
168        )
169        self.assertEqual(response.status_code, 200)
170
171    def test_source_icon_themed_urls(self):
172        """Test themed icon URLs of login sources"""
173        sources = [
174            # Built-in default icon
175            OAuthSource(provider_type="github"),
176            # Built-in icon picked in the file picker
177            OAuthSource(icon="/static/authentik/sources/github/%(theme)s.svg"),
178            OAuthSource(icon="https://example.com/logo-%(theme)s.svg"),
179            OAuthSource(icon="https://example.com/logo.png"),
180        ]
181        for idx, source in enumerate(sources):
182            source.name = f"{idx}-{generate_id()}"
183            source.slug = generate_id()
184            source.save()
185        self.stage.sources.set(sources)
186
187        response = self.client.get(
188            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
189        )
190
191        self.assertEqual(
192            [source["icon_themed_urls"] for source in loads(response.content)["sources"]],
193            [
194                # Default icons are relative, like their icon_url
195                {
196                    "light": "/static/authentik/sources/github/light.svg",
197                    "dark": "/static/authentik/sources/github/dark.svg",
198                },
199                {
200                    "light": "http://testserver/static/authentik/sources/github/light.svg",
201                    "dark": "http://testserver/static/authentik/sources/github/dark.svg",
202                },
203                {
204                    "light": "https://example.com/logo-light.svg",
205                    "dark": "https://example.com/logo-dark.svg",
206                },
207                None,
208            ],
209        )
210
211    def test_valid_with_email(self):
212        """Test with valid email, check that URL redirects back to itself"""
213        form_data = {"uid_field": self.user.email}
214        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
215        response = self.client.post(url, form_data)
216        self.assertEqual(response.status_code, 200)
217        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
218
219    def test_valid_with_password(self):
220        """Test with valid email and password in single step"""
221        pw_stage = PasswordStage.objects.create(name="password", backends=[BACKEND_INBUILT])
222        self.stage.password_stage = pw_stage
223        self.stage.save()
224        form_data = {"uid_field": self.user.email, "password": self.user.username}
225        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
226        response = self.client.post(url, form_data)
227        self.assertEqual(response.status_code, 200)
228        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
229
230    def test_invalid_with_password(self):
231        """Test with valid email and invalid password in single step"""
232        pw_stage = PasswordStage.objects.create(name="password", backends=[BACKEND_INBUILT])
233        self.stage.password_stage = pw_stage
234        self.stage.save()
235        form_data = {
236            "uid_field": self.user.email,
237            "password": self.user.username + "test",
238        }
239        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
240        response = self.client.post(url, form_data)
241        self.assertStageResponse(
242            response,
243            self.flow,
244            component="ak-stage-identification",
245            password_fields=True,
246            primary_action="Log in",
247            response_errors={
248                "non_field_errors": [{"code": "invalid", "string": "Failed to authenticate."}]
249            },
250            sources=[
251                {
252                    "challenge": {
253                        "component": "xak-flow-redirect",
254                        "to": f"/source/oauth/login/{self.source.slug}/",
255                        "final_redirect": False,
256                    },
257                    "icon_url": "/static/authentik/sources/default/light.svg",
258                    "icon_themed_urls": {
259                        "light": "/static/authentik/sources/default/light.svg",
260                        "dark": "/static/authentik/sources/default/dark.svg",
261                    },
262                    "name": self.source.name,
263                    "promoted": False,
264                }
265            ],
266            show_source_labels=False,
267            user_fields=["email"],
268        )
269
270    @enterprise_test()
271    def test_invalid_with_password_lockout(self):
272        """Test lockout applies to a password embedded in identification"""
273        pw_stage = PasswordStage.objects.create(
274            name="password-lockout",
275            backends=[BACKEND_INBUILT],
276            failed_attempts_before_lockout=2,
277            last_attempt_warning_message="One attempt remains.",
278            lockout_message="Password locked.",
279        )
280        self.stage.password_stage = pw_stage
281        self.stage.save(update_fields=("password_stage",))
282        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
283        form_data = {
284            "uid_field": self.user.email,
285            "password": self.user.username + "test",
286        }
287
288        response = self.client.post(url, form_data)
289        self.assertEqual(
290            response.json()["response_errors"]["non_field_errors"][0]["string"],
291            "One attempt remains.",
292        )
293
294        response = self.client.post(url, form_data)
295        self.assertStageResponse(
296            response,
297            self.flow,
298            component="ak-stage-access-denied",
299            error_message="Password locked.",
300        )
301        self.assertTrue(PasswordDevice.objects.get(user=self.user).locked)
302
303    def test_invalid_with_password_pretend(self):
304        """Test with invalid email and invalid password in single step (with pretend_user_exists)"""
305        self.stage.pretend_user_exists = True
306        pw_stage = PasswordStage.objects.create(name="password", backends=[BACKEND_INBUILT])
307        self.stage.password_stage = pw_stage
308        self.stage.save()
309        form_data = {
310            "uid_field": self.user.email + "test",
311            "password": self.user.username + "test",
312        }
313        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
314        response = self.client.post(url, form_data)
315        self.assertStageResponse(
316            response,
317            self.flow,
318            component="ak-stage-identification",
319            password_fields=True,
320            primary_action="Log in",
321            response_errors={
322                "non_field_errors": [{"code": "invalid", "string": "Failed to authenticate."}]
323            },
324            sources=[
325                {
326                    "challenge": {
327                        "component": "xak-flow-redirect",
328                        "to": f"/source/oauth/login/{self.source.slug}/",
329                        "final_redirect": False,
330                    },
331                    "icon_url": "/static/authentik/sources/default/light.svg",
332                    "icon_themed_urls": {
333                        "light": "/static/authentik/sources/default/light.svg",
334                        "dark": "/static/authentik/sources/default/dark.svg",
335                    },
336                    "name": self.source.name,
337                    "promoted": False,
338                }
339            ],
340            show_source_labels=False,
341            user_fields=["email"],
342        )
343
344    @Mocker()
345    def test_valid_with_captcha(self, mock: Mocker):
346        """Test with valid email and captcha token in single step"""
347        mock.post(
348            "https://www.recaptcha.net/recaptcha/api/siteverify",
349            json={
350                "success": True,
351                "score": 0.5,
352            },
353        )
354
355        captcha_stage = CaptchaStage.objects.create(
356            name="captcha",
357            public_key=RECAPTCHA_PUBLIC_KEY,
358            private_key=RECAPTCHA_PRIVATE_KEY,
359        )
360        self.stage.captcha_stage = captcha_stage
361        self.stage.save()
362
363        form_data = {"uid_field": self.user.email, "captcha_token": "PASSED"}
364        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
365        response = self.client.post(url, form_data)
366        self.assertEqual(response.status_code, 200)
367        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
368
369    @Mocker()
370    def test_valid_with_captcha_override(self, mock: Mocker):
371        """Test embedded captcha with overridden site and private keys"""
372        mock.post(
373            "https://www.recaptcha.net/recaptcha/api/siteverify",
374            json={
375                "success": True,
376                "score": 0.5,
377            },
378        )
379        configured_site_key = generate_id()
380        captcha_stage = CaptchaStage.objects.create(
381            name="captcha",
382            public_key=configured_site_key,
383            private_key=generate_id(),
384        )
385        self.stage.captcha_stage = captcha_stage
386        self.stage.save()
387        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
388
389        response = self.client.get(url)
390        challenge = self.assertStageResponse(response, self.flow)
391        self.assertEqual(challenge["captcha_stage"]["site_key"], configured_site_key)
392
393        site_key = generate_id()
394        private_key = generate_id()
395        plan = self.get_flow_plan()
396        plan.context.update(
397            {
398                PLAN_CONTEXT_CAPTCHA_SITE_KEY: site_key,
399                PLAN_CONTEXT_CAPTCHA_PRIVATE_KEY: private_key,
400            }
401        )
402        self.set_flow_plan(plan)
403
404        response = self.client.get(url)
405        challenge = self.assertStageResponse(response, self.flow)
406        self.assertEqual(challenge["captcha_stage"]["site_key"], site_key)
407
408        response = self.client.post(
409            url,
410            {"uid_field": self.user.email, "captcha_token": "PASSED"},
411        )
412        self.assertEqual(response.status_code, 200)
413        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
414        self.assertIn(private_key, mock.request_history[0].text)
415
416    @Mocker()
417    def test_invalid_with_captcha(self, mock: Mocker):
418        """Test with valid email and invalid captcha token in single step"""
419        mock.post(
420            "https://www.recaptcha.net/recaptcha/api/siteverify",
421            json={
422                "success": False,
423                "score": 0.5,
424            },
425        )
426
427        captcha_stage = CaptchaStage.objects.create(
428            name="captcha",
429            public_key=RECAPTCHA_PUBLIC_KEY,
430            private_key=RECAPTCHA_PRIVATE_KEY,
431        )
432
433        self.stage.captcha_stage = captcha_stage
434        self.stage.save()
435
436        form_data = {
437            "uid_field": self.user.email,
438            "captcha_token": "FAILED",
439        }
440        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
441        response = self.client.post(url, form_data)
442        self.assertStageResponse(
443            response,
444            self.flow,
445            component="ak-stage-identification",
446            password_fields=False,
447            primary_action="Log in",
448            response_errors={
449                "non_field_errors": [{"code": "invalid", "string": "Failed to authenticate."}]
450            },
451            sources=[
452                {
453                    "challenge": {
454                        "component": "xak-flow-redirect",
455                        "to": f"/source/oauth/login/{self.source.slug}/",
456                        "final_redirect": False,
457                    },
458                    "icon_url": "/static/authentik/sources/default/light.svg",
459                    "icon_themed_urls": {
460                        "light": "/static/authentik/sources/default/light.svg",
461                        "dark": "/static/authentik/sources/default/dark.svg",
462                    },
463                    "name": self.source.name,
464                    "promoted": False,
465                }
466            ],
467            show_source_labels=False,
468            user_fields=["email"],
469        )
470
471    @Mocker()
472    def test_invalid_with_captcha_retriable(self, mock: Mocker):
473        """Test with valid email and invalid captcha token in single step"""
474        mock.post(
475            "https://www.recaptcha.net/recaptcha/api/siteverify",
476            json={
477                "success": False,
478                "score": 0.5,
479                "error-codes": ["timeout-or-duplicate"],
480            },
481        )
482
483        captcha_stage = CaptchaStage.objects.create(
484            name="captcha",
485            public_key=RECAPTCHA_PUBLIC_KEY,
486            private_key=RECAPTCHA_PRIVATE_KEY,
487        )
488
489        self.stage.captcha_stage = captcha_stage
490        self.stage.save()
491
492        form_data = {
493            "uid_field": self.user.email,
494            "captcha_token": "FAILED",
495        }
496        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
497        response = self.client.post(url, form_data)
498        self.assertStageResponse(
499            response,
500            self.flow,
501            component="ak-stage-identification",
502            password_fields=False,
503            primary_action="Log in",
504            response_errors={
505                "non_field_errors": [
506                    {
507                        "code": "invalid",
508                        "string": "Failed to authenticate.",
509                    }
510                ]
511            },
512            sources=[
513                {
514                    "challenge": {
515                        "component": "xak-flow-redirect",
516                        "to": f"/source/oauth/login/{self.source.slug}/",
517                        "final_redirect": False,
518                    },
519                    "icon_url": "/static/authentik/sources/default/light.svg",
520                    "icon_themed_urls": {
521                        "light": "/static/authentik/sources/default/light.svg",
522                        "dark": "/static/authentik/sources/default/dark.svg",
523                    },
524                    "name": self.source.name,
525                    "promoted": False,
526                }
527            ],
528            show_source_labels=False,
529            user_fields=["email"],
530        )
531
532    def test_invalid_with_username(self):
533        """Test invalid with username (user exists but stage only allows email)"""
534        form_data = {"uid_field": self.user.username}
535        response = self.client.post(
536            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
537            form_data,
538        )
539        self.assertEqual(response.status_code, 200)
540        self.assertStageResponse(
541            response,
542            self.flow,
543            component="ak-stage-identification",
544            response_errors={
545                "non_field_errors": [{"string": "Failed to authenticate.", "code": "invalid"}]
546            },
547        )
548
549    def test_invalid_with_username_pretend(self):
550        """Test invalid with username (user exists but stage only allows email)"""
551        self.stage.pretend_user_exists = True
552        self.stage.save()
553        form_data = {"uid_field": self.user.username}
554        response = self.client.post(
555            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
556            form_data,
557        )
558        self.assertEqual(response.status_code, 200)
559        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
560
561    def test_invalid_no_fields(self):
562        """Test invalid with username (no user fields are enabled)"""
563        self.stage.user_fields = []
564        self.stage.save()
565        form_data = {"uid_field": self.user.username}
566        response = self.client.post(
567            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
568            form_data,
569        )
570        self.assertStageResponse(
571            response,
572            self.flow,
573            component="ak-stage-identification",
574            password_fields=False,
575            primary_action="Log in",
576            response_errors={
577                "non_field_errors": [{"code": "invalid", "string": "Failed to authenticate."}]
578            },
579            show_source_labels=False,
580            sources=[
581                {
582                    "challenge": {
583                        "component": "xak-flow-redirect",
584                        "to": f"/source/oauth/login/{self.source.slug}/",
585                        "final_redirect": False,
586                    },
587                    "icon_url": "/static/authentik/sources/default/light.svg",
588                    "icon_themed_urls": {
589                        "light": "/static/authentik/sources/default/light.svg",
590                        "dark": "/static/authentik/sources/default/dark.svg",
591                    },
592                    "name": self.source.name,
593                    "promoted": False,
594                }
595            ],
596            user_fields=[],
597        )
598
599    def test_invalid_with_invalid_email(self):
600        """Test with invalid email (user doesn't exist) -> Will return to login form"""
601        form_data = {"uid_field": self.user.email + "test"}
602        response = self.client.post(
603            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
604            form_data,
605        )
606        self.assertEqual(response.status_code, 200)
607
608    def test_enrollment_flow(self):
609        """Test that enrollment flow is linked correctly"""
610        flow = create_test_flow()
611        self.stage.enrollment_flow = flow
612        self.stage.save()
613        FlowStageBinding.objects.create(
614            target=flow,
615            stage=self.stage,
616            order=0,
617        )
618
619        response = self.client.get(
620            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
621        )
622        self.assertStageResponse(
623            response,
624            self.flow,
625            component="ak-stage-identification",
626            user_fields=["email"],
627            password_fields=False,
628            enroll_url=reverse(
629                "authentik_core:if-flow",
630                kwargs={"flow_slug": flow.slug},
631            ),
632            show_source_labels=False,
633            primary_action="Log in",
634            sources=[
635                {
636                    "icon_url": "/static/authentik/sources/default/light.svg",
637                    "icon_themed_urls": {
638                        "light": "/static/authentik/sources/default/light.svg",
639                        "dark": "/static/authentik/sources/default/dark.svg",
640                    },
641                    "name": self.source.name,
642                    "challenge": {
643                        "component": "xak-flow-redirect",
644                        "to": f"/source/oauth/login/{self.source.slug}/",
645                        "final_redirect": False,
646                    },
647                    "promoted": False,
648                }
649            ],
650        )
651
652    def test_link_recovery_flow(self):
653        """Test that recovery flow is linked correctly"""
654        flow = create_test_flow()
655        self.stage.recovery_flow = flow
656        self.stage.save()
657        FlowStageBinding.objects.create(
658            target=flow,
659            stage=self.stage,
660            order=0,
661        )
662        response = self.client.get(
663            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
664        )
665        self.assertStageResponse(
666            response,
667            self.flow,
668            component="ak-stage-identification",
669            user_fields=["email"],
670            password_fields=False,
671            recovery_url=reverse(
672                "authentik_core:if-flow",
673                kwargs={"flow_slug": flow.slug},
674            ),
675            show_source_labels=False,
676            primary_action="Log in",
677            sources=[
678                {
679                    "challenge": {
680                        "component": "xak-flow-redirect",
681                        "to": f"/source/oauth/login/{self.source.slug}/",
682                        "final_redirect": False,
683                    },
684                    "icon_url": "/static/authentik/sources/default/light.svg",
685                    "icon_themed_urls": {
686                        "light": "/static/authentik/sources/default/light.svg",
687                        "dark": "/static/authentik/sources/default/dark.svg",
688                    },
689                    "name": self.source.name,
690                    "promoted": False,
691                }
692            ],
693        )
694
695    def test_recovery_flow_invalid_user(self):
696        """Test that an invalid user can proceed in a recovery flow"""
697        self.flow.designation = FlowDesignation.RECOVERY
698        self.flow.save()
699        response = self.client.get(
700            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
701        )
702        self.assertStageResponse(
703            response,
704            self.flow,
705            component="ak-stage-identification",
706            user_fields=["email"],
707            password_fields=False,
708            show_source_labels=False,
709            primary_action="Continue",
710            sources=[
711                {
712                    "challenge": {
713                        "component": "xak-flow-redirect",
714                        "to": f"/source/oauth/login/{self.source.slug}/",
715                        "final_redirect": False,
716                    },
717                    "icon_url": "/static/authentik/sources/default/light.svg",
718                    "icon_themed_urls": {
719                        "light": "/static/authentik/sources/default/light.svg",
720                        "dark": "/static/authentik/sources/default/dark.svg",
721                    },
722                    "name": self.source.name,
723                    "promoted": False,
724                }
725            ],
726        )
727        form_data = {"uid_field": generate_id()}
728        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
729        response = self.client.post(url, form_data)
730        self.assertEqual(response.status_code, 200)
731
732    def test_api_validate(self):
733        """Test API validation"""
734        self.assertTrue(
735            IdentificationStageSerializer(
736                data={
737                    "name": generate_id(),
738                    "user_fields": [UserFields.E_MAIL, UserFields.USERNAME],
739                }
740            ).is_valid(raise_exception=True)
741        )
742        with self.assertRaises(ValidationError):
743            IdentificationStageSerializer(
744                data={
745                    "name": generate_id(),
746                    "user_fields": [],
747                    "sources": [],
748                }
749            ).is_valid(raise_exception=True)
750
751    def test_prefill(self):
752        """Username prefill from existing flow context"""
753        pw_stage = PasswordStage.objects.create(name=generate_id(), backends=[BACKEND_INBUILT])
754        self.stage.password_stage = pw_stage
755        self.stage.save()
756
757        self.client.get(
758            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
759        )
760
761        plan = self.get_flow_plan()
762        plan.context[PLAN_CONTEXT_PENDING_USER_IDENTIFIER] = "foo"
763        self.set_flow_plan(plan)
764        with self.assertFlowFinishes() as plan:
765            response = self.client.get(
766                reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
767            )
768            self.assertEqual(response.status_code, 200)
769            self.assertStageResponse(
770                response,
771                self.flow,
772                component="ak-stage-identification",
773                pending_user_identifier="foo",
774            )
775
776    def test_prefill_simple(self):
777        """Username prefill from existing flow context"""
778        self.stage.pretend_user_exists = True
779        self.stage.save()
780
781        self.client.get(
782            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
783        )
784        plan = self.get_flow_plan()
785        plan.context[PLAN_CONTEXT_PENDING_USER_IDENTIFIER] = "foo"
786        self.set_flow_plan(plan)
787        response = self.client.get(
788            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
789        )
790        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
class TestIdentificationStagePasskey(authentik.flows.tests.APIFlowTestCase):
 31class TestIdentificationStagePasskey(APIFlowTestCase):
 32    """Passkey authentication tests"""
 33
 34    def setUp(self):
 35        super().setUp()
 36        self.user = create_test_admin_user()
 37        self.flow = create_test_flow(FlowDesignation.AUTHENTICATION)
 38        self.webauthn_stage = AuthenticatorValidateStage.objects.create(
 39            name="webauthn-validate",
 40            device_classes=[DeviceClasses.WEBAUTHN],
 41        )
 42        self.stage = IdentificationStage.objects.create(
 43            name="identification",
 44            user_fields=[UserFields.E_MAIL],
 45            webauthn_stage=self.webauthn_stage,
 46        )
 47        FlowStageBinding.objects.create(target=self.flow, stage=self.stage, order=0)
 48        self.device = WebAuthnDevice.objects.create(
 49            user=self.user,
 50            name="Test Passkey",
 51            credential_id="test-credential-id",
 52            public_key="test-public-key",
 53            sign_count=0,
 54            rp_id="testserver",
 55        )
 56
 57    def test_passkey_auth_success(self):
 58        """Test passkey sets device, user, backend and updates last_used"""
 59        from unittest.mock import patch
 60
 61        # Get challenge to initialize session
 62        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
 63        self.client.get(url)
 64
 65        with patch(
 66            "authentik.stages.identification.stage.validate_challenge_webauthn",
 67            return_value=self.device,
 68        ):
 69            response = self.client.post(
 70                url, {"passkey": {"id": "test"}}, content_type="application/json"
 71            )
 72
 73        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
 74        # Verify device last_used was updated
 75        self.device.refresh_from_db()
 76        self.assertIsNotNone(self.device.last_used)
 77
 78    def test_passkey_challenge_disabled(self):
 79        """Test that passkey challenge is not included when webauthn_stage is not set"""
 80        self.stage.webauthn_stage = None
 81        self.stage.save()
 82        response = self.client.get(
 83            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
 84        )
 85        self.assertEqual(response.status_code, 200)
 86        data = response.json()
 87        self.assertIsNone(data.get("passkey_challenge"))
 88
 89    def test_passkey_challenge_enabled(self):
 90        """Test that passkey challenge is included when webauthn_stage is set"""
 91        response = self.client.get(
 92            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
 93        )
 94        self.assertEqual(response.status_code, 200)
 95        data = response.json()
 96        self.assertIsNotNone(data.get("passkey_challenge"))
 97        passkey_challenge = data["passkey_challenge"]
 98        self.assertIn("challenge", passkey_challenge)
 99        self.assertIn("rpId", passkey_challenge)
100        self.assertEqual(passkey_challenge["allowCredentials"], [])
101
102    def test_passkey_challenge_generation(self):
103        """Test passkey challenge is generated correctly"""
104        response = self.client.get(
105            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
106        )
107        self.assertEqual(response.status_code, 200)
108        data = response.json()
109        self.assertIsNotNone(data.get("passkey_challenge"))
110
111    def test_passkey_no_uid_field_required(self):
112        """Test that uid_field is not required when passkey is provided"""
113        # Get the challenge first to set up the session
114        response = self.client.get(
115            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
116        )
117        self.assertEqual(response.status_code, 200)
118
119        # Submit without uid_field but with passkey (invalid passkey will fail validation)
120        form_data = {
121            "passkey": {
122                "id": "invalid",
123                "rawId": "invalid",
124                "type": "public-key",
125                "response": {
126                    "clientDataJSON": "invalid",
127                    "authenticatorData": "invalid",
128                    "signature": "invalid",
129                },
130            }
131        }
132        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
133        response = self.client.post(url, form_data, content_type="application/json")
134        self.assertEqual(response.status_code, 200)
135        data = response.json()
136        self.assertIn("response_errors", data)
137        errors = data.get("response_errors", {})
138        self.assertNotIn("uid_field", errors)

Passkey authentication tests

def setUp(self):
34    def setUp(self):
35        super().setUp()
36        self.user = create_test_admin_user()
37        self.flow = create_test_flow(FlowDesignation.AUTHENTICATION)
38        self.webauthn_stage = AuthenticatorValidateStage.objects.create(
39            name="webauthn-validate",
40            device_classes=[DeviceClasses.WEBAUTHN],
41        )
42        self.stage = IdentificationStage.objects.create(
43            name="identification",
44            user_fields=[UserFields.E_MAIL],
45            webauthn_stage=self.webauthn_stage,
46        )
47        FlowStageBinding.objects.create(target=self.flow, stage=self.stage, order=0)
48        self.device = WebAuthnDevice.objects.create(
49            user=self.user,
50            name="Test Passkey",
51            credential_id="test-credential-id",
52            public_key="test-public-key",
53            sign_count=0,
54            rp_id="testserver",
55        )

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

def test_passkey_auth_success(self):
57    def test_passkey_auth_success(self):
58        """Test passkey sets device, user, backend and updates last_used"""
59        from unittest.mock import patch
60
61        # Get challenge to initialize session
62        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
63        self.client.get(url)
64
65        with patch(
66            "authentik.stages.identification.stage.validate_challenge_webauthn",
67            return_value=self.device,
68        ):
69            response = self.client.post(
70                url, {"passkey": {"id": "test"}}, content_type="application/json"
71            )
72
73        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
74        # Verify device last_used was updated
75        self.device.refresh_from_db()
76        self.assertIsNotNone(self.device.last_used)

Test passkey sets device, user, backend and updates last_used

def test_passkey_challenge_disabled(self):
78    def test_passkey_challenge_disabled(self):
79        """Test that passkey challenge is not included when webauthn_stage is not set"""
80        self.stage.webauthn_stage = None
81        self.stage.save()
82        response = self.client.get(
83            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
84        )
85        self.assertEqual(response.status_code, 200)
86        data = response.json()
87        self.assertIsNone(data.get("passkey_challenge"))

Test that passkey challenge is not included when webauthn_stage is not set

def test_passkey_challenge_enabled(self):
 89    def test_passkey_challenge_enabled(self):
 90        """Test that passkey challenge is included when webauthn_stage is set"""
 91        response = self.client.get(
 92            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
 93        )
 94        self.assertEqual(response.status_code, 200)
 95        data = response.json()
 96        self.assertIsNotNone(data.get("passkey_challenge"))
 97        passkey_challenge = data["passkey_challenge"]
 98        self.assertIn("challenge", passkey_challenge)
 99        self.assertIn("rpId", passkey_challenge)
100        self.assertEqual(passkey_challenge["allowCredentials"], [])

Test that passkey challenge is included when webauthn_stage is set

def test_passkey_challenge_generation(self):
102    def test_passkey_challenge_generation(self):
103        """Test passkey challenge is generated correctly"""
104        response = self.client.get(
105            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
106        )
107        self.assertEqual(response.status_code, 200)
108        data = response.json()
109        self.assertIsNotNone(data.get("passkey_challenge"))

Test passkey challenge is generated correctly

def test_passkey_no_uid_field_required(self):
111    def test_passkey_no_uid_field_required(self):
112        """Test that uid_field is not required when passkey is provided"""
113        # Get the challenge first to set up the session
114        response = self.client.get(
115            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
116        )
117        self.assertEqual(response.status_code, 200)
118
119        # Submit without uid_field but with passkey (invalid passkey will fail validation)
120        form_data = {
121            "passkey": {
122                "id": "invalid",
123                "rawId": "invalid",
124                "type": "public-key",
125                "response": {
126                    "clientDataJSON": "invalid",
127                    "authenticatorData": "invalid",
128                    "signature": "invalid",
129                },
130            }
131        }
132        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
133        response = self.client.post(url, form_data, content_type="application/json")
134        self.assertEqual(response.status_code, 200)
135        data = response.json()
136        self.assertIn("response_errors", data)
137        errors = data.get("response_errors", {})
138        self.assertNotIn("uid_field", errors)

Test that uid_field is not required when passkey is provided

class TestIdentificationStage(authentik.flows.tests.APIFlowTestCase):
141class TestIdentificationStage(APIFlowTestCase):
142    """Identification tests"""
143
144    def setUp(self):
145        super().setUp()
146        self.user = create_test_admin_user()
147
148        # OAuthSource for the login view
149        self.source = OAuthSource.objects.create(name=generate_id(), slug=generate_id())
150
151        self.flow = create_test_flow(FlowDesignation.AUTHENTICATION)
152        self.stage = IdentificationStage.objects.create(
153            name="identification",
154            user_fields=[UserFields.E_MAIL],
155            pretend_user_exists=False,
156        )
157        self.stage.sources.set([self.source])
158        self.stage.save()
159        FlowStageBinding.objects.create(
160            target=self.flow,
161            stage=self.stage,
162            order=0,
163        )
164
165    def test_valid_render(self):
166        """Test that View renders correctly"""
167        response = self.client.get(
168            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
169        )
170        self.assertEqual(response.status_code, 200)
171
172    def test_source_icon_themed_urls(self):
173        """Test themed icon URLs of login sources"""
174        sources = [
175            # Built-in default icon
176            OAuthSource(provider_type="github"),
177            # Built-in icon picked in the file picker
178            OAuthSource(icon="/static/authentik/sources/github/%(theme)s.svg"),
179            OAuthSource(icon="https://example.com/logo-%(theme)s.svg"),
180            OAuthSource(icon="https://example.com/logo.png"),
181        ]
182        for idx, source in enumerate(sources):
183            source.name = f"{idx}-{generate_id()}"
184            source.slug = generate_id()
185            source.save()
186        self.stage.sources.set(sources)
187
188        response = self.client.get(
189            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
190        )
191
192        self.assertEqual(
193            [source["icon_themed_urls"] for source in loads(response.content)["sources"]],
194            [
195                # Default icons are relative, like their icon_url
196                {
197                    "light": "/static/authentik/sources/github/light.svg",
198                    "dark": "/static/authentik/sources/github/dark.svg",
199                },
200                {
201                    "light": "http://testserver/static/authentik/sources/github/light.svg",
202                    "dark": "http://testserver/static/authentik/sources/github/dark.svg",
203                },
204                {
205                    "light": "https://example.com/logo-light.svg",
206                    "dark": "https://example.com/logo-dark.svg",
207                },
208                None,
209            ],
210        )
211
212    def test_valid_with_email(self):
213        """Test with valid email, check that URL redirects back to itself"""
214        form_data = {"uid_field": self.user.email}
215        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
216        response = self.client.post(url, form_data)
217        self.assertEqual(response.status_code, 200)
218        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
219
220    def test_valid_with_password(self):
221        """Test with valid email and password in single step"""
222        pw_stage = PasswordStage.objects.create(name="password", backends=[BACKEND_INBUILT])
223        self.stage.password_stage = pw_stage
224        self.stage.save()
225        form_data = {"uid_field": self.user.email, "password": self.user.username}
226        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
227        response = self.client.post(url, form_data)
228        self.assertEqual(response.status_code, 200)
229        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
230
231    def test_invalid_with_password(self):
232        """Test with valid email and invalid password in single step"""
233        pw_stage = PasswordStage.objects.create(name="password", backends=[BACKEND_INBUILT])
234        self.stage.password_stage = pw_stage
235        self.stage.save()
236        form_data = {
237            "uid_field": self.user.email,
238            "password": self.user.username + "test",
239        }
240        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
241        response = self.client.post(url, form_data)
242        self.assertStageResponse(
243            response,
244            self.flow,
245            component="ak-stage-identification",
246            password_fields=True,
247            primary_action="Log in",
248            response_errors={
249                "non_field_errors": [{"code": "invalid", "string": "Failed to authenticate."}]
250            },
251            sources=[
252                {
253                    "challenge": {
254                        "component": "xak-flow-redirect",
255                        "to": f"/source/oauth/login/{self.source.slug}/",
256                        "final_redirect": False,
257                    },
258                    "icon_url": "/static/authentik/sources/default/light.svg",
259                    "icon_themed_urls": {
260                        "light": "/static/authentik/sources/default/light.svg",
261                        "dark": "/static/authentik/sources/default/dark.svg",
262                    },
263                    "name": self.source.name,
264                    "promoted": False,
265                }
266            ],
267            show_source_labels=False,
268            user_fields=["email"],
269        )
270
271    @enterprise_test()
272    def test_invalid_with_password_lockout(self):
273        """Test lockout applies to a password embedded in identification"""
274        pw_stage = PasswordStage.objects.create(
275            name="password-lockout",
276            backends=[BACKEND_INBUILT],
277            failed_attempts_before_lockout=2,
278            last_attempt_warning_message="One attempt remains.",
279            lockout_message="Password locked.",
280        )
281        self.stage.password_stage = pw_stage
282        self.stage.save(update_fields=("password_stage",))
283        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
284        form_data = {
285            "uid_field": self.user.email,
286            "password": self.user.username + "test",
287        }
288
289        response = self.client.post(url, form_data)
290        self.assertEqual(
291            response.json()["response_errors"]["non_field_errors"][0]["string"],
292            "One attempt remains.",
293        )
294
295        response = self.client.post(url, form_data)
296        self.assertStageResponse(
297            response,
298            self.flow,
299            component="ak-stage-access-denied",
300            error_message="Password locked.",
301        )
302        self.assertTrue(PasswordDevice.objects.get(user=self.user).locked)
303
304    def test_invalid_with_password_pretend(self):
305        """Test with invalid email and invalid password in single step (with pretend_user_exists)"""
306        self.stage.pretend_user_exists = True
307        pw_stage = PasswordStage.objects.create(name="password", backends=[BACKEND_INBUILT])
308        self.stage.password_stage = pw_stage
309        self.stage.save()
310        form_data = {
311            "uid_field": self.user.email + "test",
312            "password": self.user.username + "test",
313        }
314        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
315        response = self.client.post(url, form_data)
316        self.assertStageResponse(
317            response,
318            self.flow,
319            component="ak-stage-identification",
320            password_fields=True,
321            primary_action="Log in",
322            response_errors={
323                "non_field_errors": [{"code": "invalid", "string": "Failed to authenticate."}]
324            },
325            sources=[
326                {
327                    "challenge": {
328                        "component": "xak-flow-redirect",
329                        "to": f"/source/oauth/login/{self.source.slug}/",
330                        "final_redirect": False,
331                    },
332                    "icon_url": "/static/authentik/sources/default/light.svg",
333                    "icon_themed_urls": {
334                        "light": "/static/authentik/sources/default/light.svg",
335                        "dark": "/static/authentik/sources/default/dark.svg",
336                    },
337                    "name": self.source.name,
338                    "promoted": False,
339                }
340            ],
341            show_source_labels=False,
342            user_fields=["email"],
343        )
344
345    @Mocker()
346    def test_valid_with_captcha(self, mock: Mocker):
347        """Test with valid email and captcha token in single step"""
348        mock.post(
349            "https://www.recaptcha.net/recaptcha/api/siteverify",
350            json={
351                "success": True,
352                "score": 0.5,
353            },
354        )
355
356        captcha_stage = CaptchaStage.objects.create(
357            name="captcha",
358            public_key=RECAPTCHA_PUBLIC_KEY,
359            private_key=RECAPTCHA_PRIVATE_KEY,
360        )
361        self.stage.captcha_stage = captcha_stage
362        self.stage.save()
363
364        form_data = {"uid_field": self.user.email, "captcha_token": "PASSED"}
365        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
366        response = self.client.post(url, form_data)
367        self.assertEqual(response.status_code, 200)
368        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
369
370    @Mocker()
371    def test_valid_with_captcha_override(self, mock: Mocker):
372        """Test embedded captcha with overridden site and private keys"""
373        mock.post(
374            "https://www.recaptcha.net/recaptcha/api/siteverify",
375            json={
376                "success": True,
377                "score": 0.5,
378            },
379        )
380        configured_site_key = generate_id()
381        captcha_stage = CaptchaStage.objects.create(
382            name="captcha",
383            public_key=configured_site_key,
384            private_key=generate_id(),
385        )
386        self.stage.captcha_stage = captcha_stage
387        self.stage.save()
388        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
389
390        response = self.client.get(url)
391        challenge = self.assertStageResponse(response, self.flow)
392        self.assertEqual(challenge["captcha_stage"]["site_key"], configured_site_key)
393
394        site_key = generate_id()
395        private_key = generate_id()
396        plan = self.get_flow_plan()
397        plan.context.update(
398            {
399                PLAN_CONTEXT_CAPTCHA_SITE_KEY: site_key,
400                PLAN_CONTEXT_CAPTCHA_PRIVATE_KEY: private_key,
401            }
402        )
403        self.set_flow_plan(plan)
404
405        response = self.client.get(url)
406        challenge = self.assertStageResponse(response, self.flow)
407        self.assertEqual(challenge["captcha_stage"]["site_key"], site_key)
408
409        response = self.client.post(
410            url,
411            {"uid_field": self.user.email, "captcha_token": "PASSED"},
412        )
413        self.assertEqual(response.status_code, 200)
414        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
415        self.assertIn(private_key, mock.request_history[0].text)
416
417    @Mocker()
418    def test_invalid_with_captcha(self, mock: Mocker):
419        """Test with valid email and invalid captcha token in single step"""
420        mock.post(
421            "https://www.recaptcha.net/recaptcha/api/siteverify",
422            json={
423                "success": False,
424                "score": 0.5,
425            },
426        )
427
428        captcha_stage = CaptchaStage.objects.create(
429            name="captcha",
430            public_key=RECAPTCHA_PUBLIC_KEY,
431            private_key=RECAPTCHA_PRIVATE_KEY,
432        )
433
434        self.stage.captcha_stage = captcha_stage
435        self.stage.save()
436
437        form_data = {
438            "uid_field": self.user.email,
439            "captcha_token": "FAILED",
440        }
441        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
442        response = self.client.post(url, form_data)
443        self.assertStageResponse(
444            response,
445            self.flow,
446            component="ak-stage-identification",
447            password_fields=False,
448            primary_action="Log in",
449            response_errors={
450                "non_field_errors": [{"code": "invalid", "string": "Failed to authenticate."}]
451            },
452            sources=[
453                {
454                    "challenge": {
455                        "component": "xak-flow-redirect",
456                        "to": f"/source/oauth/login/{self.source.slug}/",
457                        "final_redirect": False,
458                    },
459                    "icon_url": "/static/authentik/sources/default/light.svg",
460                    "icon_themed_urls": {
461                        "light": "/static/authentik/sources/default/light.svg",
462                        "dark": "/static/authentik/sources/default/dark.svg",
463                    },
464                    "name": self.source.name,
465                    "promoted": False,
466                }
467            ],
468            show_source_labels=False,
469            user_fields=["email"],
470        )
471
472    @Mocker()
473    def test_invalid_with_captcha_retriable(self, mock: Mocker):
474        """Test with valid email and invalid captcha token in single step"""
475        mock.post(
476            "https://www.recaptcha.net/recaptcha/api/siteverify",
477            json={
478                "success": False,
479                "score": 0.5,
480                "error-codes": ["timeout-or-duplicate"],
481            },
482        )
483
484        captcha_stage = CaptchaStage.objects.create(
485            name="captcha",
486            public_key=RECAPTCHA_PUBLIC_KEY,
487            private_key=RECAPTCHA_PRIVATE_KEY,
488        )
489
490        self.stage.captcha_stage = captcha_stage
491        self.stage.save()
492
493        form_data = {
494            "uid_field": self.user.email,
495            "captcha_token": "FAILED",
496        }
497        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
498        response = self.client.post(url, form_data)
499        self.assertStageResponse(
500            response,
501            self.flow,
502            component="ak-stage-identification",
503            password_fields=False,
504            primary_action="Log in",
505            response_errors={
506                "non_field_errors": [
507                    {
508                        "code": "invalid",
509                        "string": "Failed to authenticate.",
510                    }
511                ]
512            },
513            sources=[
514                {
515                    "challenge": {
516                        "component": "xak-flow-redirect",
517                        "to": f"/source/oauth/login/{self.source.slug}/",
518                        "final_redirect": False,
519                    },
520                    "icon_url": "/static/authentik/sources/default/light.svg",
521                    "icon_themed_urls": {
522                        "light": "/static/authentik/sources/default/light.svg",
523                        "dark": "/static/authentik/sources/default/dark.svg",
524                    },
525                    "name": self.source.name,
526                    "promoted": False,
527                }
528            ],
529            show_source_labels=False,
530            user_fields=["email"],
531        )
532
533    def test_invalid_with_username(self):
534        """Test invalid with username (user exists but stage only allows email)"""
535        form_data = {"uid_field": self.user.username}
536        response = self.client.post(
537            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
538            form_data,
539        )
540        self.assertEqual(response.status_code, 200)
541        self.assertStageResponse(
542            response,
543            self.flow,
544            component="ak-stage-identification",
545            response_errors={
546                "non_field_errors": [{"string": "Failed to authenticate.", "code": "invalid"}]
547            },
548        )
549
550    def test_invalid_with_username_pretend(self):
551        """Test invalid with username (user exists but stage only allows email)"""
552        self.stage.pretend_user_exists = True
553        self.stage.save()
554        form_data = {"uid_field": self.user.username}
555        response = self.client.post(
556            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
557            form_data,
558        )
559        self.assertEqual(response.status_code, 200)
560        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
561
562    def test_invalid_no_fields(self):
563        """Test invalid with username (no user fields are enabled)"""
564        self.stage.user_fields = []
565        self.stage.save()
566        form_data = {"uid_field": self.user.username}
567        response = self.client.post(
568            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
569            form_data,
570        )
571        self.assertStageResponse(
572            response,
573            self.flow,
574            component="ak-stage-identification",
575            password_fields=False,
576            primary_action="Log in",
577            response_errors={
578                "non_field_errors": [{"code": "invalid", "string": "Failed to authenticate."}]
579            },
580            show_source_labels=False,
581            sources=[
582                {
583                    "challenge": {
584                        "component": "xak-flow-redirect",
585                        "to": f"/source/oauth/login/{self.source.slug}/",
586                        "final_redirect": False,
587                    },
588                    "icon_url": "/static/authentik/sources/default/light.svg",
589                    "icon_themed_urls": {
590                        "light": "/static/authentik/sources/default/light.svg",
591                        "dark": "/static/authentik/sources/default/dark.svg",
592                    },
593                    "name": self.source.name,
594                    "promoted": False,
595                }
596            ],
597            user_fields=[],
598        )
599
600    def test_invalid_with_invalid_email(self):
601        """Test with invalid email (user doesn't exist) -> Will return to login form"""
602        form_data = {"uid_field": self.user.email + "test"}
603        response = self.client.post(
604            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
605            form_data,
606        )
607        self.assertEqual(response.status_code, 200)
608
609    def test_enrollment_flow(self):
610        """Test that enrollment flow is linked correctly"""
611        flow = create_test_flow()
612        self.stage.enrollment_flow = flow
613        self.stage.save()
614        FlowStageBinding.objects.create(
615            target=flow,
616            stage=self.stage,
617            order=0,
618        )
619
620        response = self.client.get(
621            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
622        )
623        self.assertStageResponse(
624            response,
625            self.flow,
626            component="ak-stage-identification",
627            user_fields=["email"],
628            password_fields=False,
629            enroll_url=reverse(
630                "authentik_core:if-flow",
631                kwargs={"flow_slug": flow.slug},
632            ),
633            show_source_labels=False,
634            primary_action="Log in",
635            sources=[
636                {
637                    "icon_url": "/static/authentik/sources/default/light.svg",
638                    "icon_themed_urls": {
639                        "light": "/static/authentik/sources/default/light.svg",
640                        "dark": "/static/authentik/sources/default/dark.svg",
641                    },
642                    "name": self.source.name,
643                    "challenge": {
644                        "component": "xak-flow-redirect",
645                        "to": f"/source/oauth/login/{self.source.slug}/",
646                        "final_redirect": False,
647                    },
648                    "promoted": False,
649                }
650            ],
651        )
652
653    def test_link_recovery_flow(self):
654        """Test that recovery flow is linked correctly"""
655        flow = create_test_flow()
656        self.stage.recovery_flow = flow
657        self.stage.save()
658        FlowStageBinding.objects.create(
659            target=flow,
660            stage=self.stage,
661            order=0,
662        )
663        response = self.client.get(
664            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
665        )
666        self.assertStageResponse(
667            response,
668            self.flow,
669            component="ak-stage-identification",
670            user_fields=["email"],
671            password_fields=False,
672            recovery_url=reverse(
673                "authentik_core:if-flow",
674                kwargs={"flow_slug": flow.slug},
675            ),
676            show_source_labels=False,
677            primary_action="Log in",
678            sources=[
679                {
680                    "challenge": {
681                        "component": "xak-flow-redirect",
682                        "to": f"/source/oauth/login/{self.source.slug}/",
683                        "final_redirect": False,
684                    },
685                    "icon_url": "/static/authentik/sources/default/light.svg",
686                    "icon_themed_urls": {
687                        "light": "/static/authentik/sources/default/light.svg",
688                        "dark": "/static/authentik/sources/default/dark.svg",
689                    },
690                    "name": self.source.name,
691                    "promoted": False,
692                }
693            ],
694        )
695
696    def test_recovery_flow_invalid_user(self):
697        """Test that an invalid user can proceed in a recovery flow"""
698        self.flow.designation = FlowDesignation.RECOVERY
699        self.flow.save()
700        response = self.client.get(
701            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
702        )
703        self.assertStageResponse(
704            response,
705            self.flow,
706            component="ak-stage-identification",
707            user_fields=["email"],
708            password_fields=False,
709            show_source_labels=False,
710            primary_action="Continue",
711            sources=[
712                {
713                    "challenge": {
714                        "component": "xak-flow-redirect",
715                        "to": f"/source/oauth/login/{self.source.slug}/",
716                        "final_redirect": False,
717                    },
718                    "icon_url": "/static/authentik/sources/default/light.svg",
719                    "icon_themed_urls": {
720                        "light": "/static/authentik/sources/default/light.svg",
721                        "dark": "/static/authentik/sources/default/dark.svg",
722                    },
723                    "name": self.source.name,
724                    "promoted": False,
725                }
726            ],
727        )
728        form_data = {"uid_field": generate_id()}
729        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
730        response = self.client.post(url, form_data)
731        self.assertEqual(response.status_code, 200)
732
733    def test_api_validate(self):
734        """Test API validation"""
735        self.assertTrue(
736            IdentificationStageSerializer(
737                data={
738                    "name": generate_id(),
739                    "user_fields": [UserFields.E_MAIL, UserFields.USERNAME],
740                }
741            ).is_valid(raise_exception=True)
742        )
743        with self.assertRaises(ValidationError):
744            IdentificationStageSerializer(
745                data={
746                    "name": generate_id(),
747                    "user_fields": [],
748                    "sources": [],
749                }
750            ).is_valid(raise_exception=True)
751
752    def test_prefill(self):
753        """Username prefill from existing flow context"""
754        pw_stage = PasswordStage.objects.create(name=generate_id(), backends=[BACKEND_INBUILT])
755        self.stage.password_stage = pw_stage
756        self.stage.save()
757
758        self.client.get(
759            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
760        )
761
762        plan = self.get_flow_plan()
763        plan.context[PLAN_CONTEXT_PENDING_USER_IDENTIFIER] = "foo"
764        self.set_flow_plan(plan)
765        with self.assertFlowFinishes() as plan:
766            response = self.client.get(
767                reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
768            )
769            self.assertEqual(response.status_code, 200)
770            self.assertStageResponse(
771                response,
772                self.flow,
773                component="ak-stage-identification",
774                pending_user_identifier="foo",
775            )
776
777    def test_prefill_simple(self):
778        """Username prefill from existing flow context"""
779        self.stage.pretend_user_exists = True
780        self.stage.save()
781
782        self.client.get(
783            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
784        )
785        plan = self.get_flow_plan()
786        plan.context[PLAN_CONTEXT_PENDING_USER_IDENTIFIER] = "foo"
787        self.set_flow_plan(plan)
788        response = self.client.get(
789            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
790        )
791        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))

Identification tests

def setUp(self):
144    def setUp(self):
145        super().setUp()
146        self.user = create_test_admin_user()
147
148        # OAuthSource for the login view
149        self.source = OAuthSource.objects.create(name=generate_id(), slug=generate_id())
150
151        self.flow = create_test_flow(FlowDesignation.AUTHENTICATION)
152        self.stage = IdentificationStage.objects.create(
153            name="identification",
154            user_fields=[UserFields.E_MAIL],
155            pretend_user_exists=False,
156        )
157        self.stage.sources.set([self.source])
158        self.stage.save()
159        FlowStageBinding.objects.create(
160            target=self.flow,
161            stage=self.stage,
162            order=0,
163        )

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

def test_valid_render(self):
165    def test_valid_render(self):
166        """Test that View renders correctly"""
167        response = self.client.get(
168            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
169        )
170        self.assertEqual(response.status_code, 200)

Test that View renders correctly

def test_source_icon_themed_urls(self):
172    def test_source_icon_themed_urls(self):
173        """Test themed icon URLs of login sources"""
174        sources = [
175            # Built-in default icon
176            OAuthSource(provider_type="github"),
177            # Built-in icon picked in the file picker
178            OAuthSource(icon="/static/authentik/sources/github/%(theme)s.svg"),
179            OAuthSource(icon="https://example.com/logo-%(theme)s.svg"),
180            OAuthSource(icon="https://example.com/logo.png"),
181        ]
182        for idx, source in enumerate(sources):
183            source.name = f"{idx}-{generate_id()}"
184            source.slug = generate_id()
185            source.save()
186        self.stage.sources.set(sources)
187
188        response = self.client.get(
189            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
190        )
191
192        self.assertEqual(
193            [source["icon_themed_urls"] for source in loads(response.content)["sources"]],
194            [
195                # Default icons are relative, like their icon_url
196                {
197                    "light": "/static/authentik/sources/github/light.svg",
198                    "dark": "/static/authentik/sources/github/dark.svg",
199                },
200                {
201                    "light": "http://testserver/static/authentik/sources/github/light.svg",
202                    "dark": "http://testserver/static/authentik/sources/github/dark.svg",
203                },
204                {
205                    "light": "https://example.com/logo-light.svg",
206                    "dark": "https://example.com/logo-dark.svg",
207                },
208                None,
209            ],
210        )

Test themed icon URLs of login sources

def test_valid_with_email(self):
212    def test_valid_with_email(self):
213        """Test with valid email, check that URL redirects back to itself"""
214        form_data = {"uid_field": self.user.email}
215        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
216        response = self.client.post(url, form_data)
217        self.assertEqual(response.status_code, 200)
218        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))

Test with valid email, check that URL redirects back to itself

def test_valid_with_password(self):
220    def test_valid_with_password(self):
221        """Test with valid email and password in single step"""
222        pw_stage = PasswordStage.objects.create(name="password", backends=[BACKEND_INBUILT])
223        self.stage.password_stage = pw_stage
224        self.stage.save()
225        form_data = {"uid_field": self.user.email, "password": self.user.username}
226        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
227        response = self.client.post(url, form_data)
228        self.assertEqual(response.status_code, 200)
229        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))

Test with valid email and password in single step

def test_invalid_with_password(self):
231    def test_invalid_with_password(self):
232        """Test with valid email and invalid password in single step"""
233        pw_stage = PasswordStage.objects.create(name="password", backends=[BACKEND_INBUILT])
234        self.stage.password_stage = pw_stage
235        self.stage.save()
236        form_data = {
237            "uid_field": self.user.email,
238            "password": self.user.username + "test",
239        }
240        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
241        response = self.client.post(url, form_data)
242        self.assertStageResponse(
243            response,
244            self.flow,
245            component="ak-stage-identification",
246            password_fields=True,
247            primary_action="Log in",
248            response_errors={
249                "non_field_errors": [{"code": "invalid", "string": "Failed to authenticate."}]
250            },
251            sources=[
252                {
253                    "challenge": {
254                        "component": "xak-flow-redirect",
255                        "to": f"/source/oauth/login/{self.source.slug}/",
256                        "final_redirect": False,
257                    },
258                    "icon_url": "/static/authentik/sources/default/light.svg",
259                    "icon_themed_urls": {
260                        "light": "/static/authentik/sources/default/light.svg",
261                        "dark": "/static/authentik/sources/default/dark.svg",
262                    },
263                    "name": self.source.name,
264                    "promoted": False,
265                }
266            ],
267            show_source_labels=False,
268            user_fields=["email"],
269        )

Test with valid email and invalid password in single step

@enterprise_test()
def test_invalid_with_password_lockout(self):
271    @enterprise_test()
272    def test_invalid_with_password_lockout(self):
273        """Test lockout applies to a password embedded in identification"""
274        pw_stage = PasswordStage.objects.create(
275            name="password-lockout",
276            backends=[BACKEND_INBUILT],
277            failed_attempts_before_lockout=2,
278            last_attempt_warning_message="One attempt remains.",
279            lockout_message="Password locked.",
280        )
281        self.stage.password_stage = pw_stage
282        self.stage.save(update_fields=("password_stage",))
283        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
284        form_data = {
285            "uid_field": self.user.email,
286            "password": self.user.username + "test",
287        }
288
289        response = self.client.post(url, form_data)
290        self.assertEqual(
291            response.json()["response_errors"]["non_field_errors"][0]["string"],
292            "One attempt remains.",
293        )
294
295        response = self.client.post(url, form_data)
296        self.assertStageResponse(
297            response,
298            self.flow,
299            component="ak-stage-access-denied",
300            error_message="Password locked.",
301        )
302        self.assertTrue(PasswordDevice.objects.get(user=self.user).locked)

Test lockout applies to a password embedded in identification

def test_invalid_with_password_pretend(self):
304    def test_invalid_with_password_pretend(self):
305        """Test with invalid email and invalid password in single step (with pretend_user_exists)"""
306        self.stage.pretend_user_exists = True
307        pw_stage = PasswordStage.objects.create(name="password", backends=[BACKEND_INBUILT])
308        self.stage.password_stage = pw_stage
309        self.stage.save()
310        form_data = {
311            "uid_field": self.user.email + "test",
312            "password": self.user.username + "test",
313        }
314        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
315        response = self.client.post(url, form_data)
316        self.assertStageResponse(
317            response,
318            self.flow,
319            component="ak-stage-identification",
320            password_fields=True,
321            primary_action="Log in",
322            response_errors={
323                "non_field_errors": [{"code": "invalid", "string": "Failed to authenticate."}]
324            },
325            sources=[
326                {
327                    "challenge": {
328                        "component": "xak-flow-redirect",
329                        "to": f"/source/oauth/login/{self.source.slug}/",
330                        "final_redirect": False,
331                    },
332                    "icon_url": "/static/authentik/sources/default/light.svg",
333                    "icon_themed_urls": {
334                        "light": "/static/authentik/sources/default/light.svg",
335                        "dark": "/static/authentik/sources/default/dark.svg",
336                    },
337                    "name": self.source.name,
338                    "promoted": False,
339                }
340            ],
341            show_source_labels=False,
342            user_fields=["email"],
343        )

Test with invalid email and invalid password in single step (with pretend_user_exists)

@Mocker()
def test_valid_with_captcha(self, mock: requests_mock.mocker.Mocker):
345    @Mocker()
346    def test_valid_with_captcha(self, mock: Mocker):
347        """Test with valid email and captcha token in single step"""
348        mock.post(
349            "https://www.recaptcha.net/recaptcha/api/siteverify",
350            json={
351                "success": True,
352                "score": 0.5,
353            },
354        )
355
356        captcha_stage = CaptchaStage.objects.create(
357            name="captcha",
358            public_key=RECAPTCHA_PUBLIC_KEY,
359            private_key=RECAPTCHA_PRIVATE_KEY,
360        )
361        self.stage.captcha_stage = captcha_stage
362        self.stage.save()
363
364        form_data = {"uid_field": self.user.email, "captcha_token": "PASSED"}
365        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
366        response = self.client.post(url, form_data)
367        self.assertEqual(response.status_code, 200)
368        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))

Test with valid email and captcha token in single step

@Mocker()
def test_valid_with_captcha_override(self, mock: requests_mock.mocker.Mocker):
370    @Mocker()
371    def test_valid_with_captcha_override(self, mock: Mocker):
372        """Test embedded captcha with overridden site and private keys"""
373        mock.post(
374            "https://www.recaptcha.net/recaptcha/api/siteverify",
375            json={
376                "success": True,
377                "score": 0.5,
378            },
379        )
380        configured_site_key = generate_id()
381        captcha_stage = CaptchaStage.objects.create(
382            name="captcha",
383            public_key=configured_site_key,
384            private_key=generate_id(),
385        )
386        self.stage.captcha_stage = captcha_stage
387        self.stage.save()
388        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
389
390        response = self.client.get(url)
391        challenge = self.assertStageResponse(response, self.flow)
392        self.assertEqual(challenge["captcha_stage"]["site_key"], configured_site_key)
393
394        site_key = generate_id()
395        private_key = generate_id()
396        plan = self.get_flow_plan()
397        plan.context.update(
398            {
399                PLAN_CONTEXT_CAPTCHA_SITE_KEY: site_key,
400                PLAN_CONTEXT_CAPTCHA_PRIVATE_KEY: private_key,
401            }
402        )
403        self.set_flow_plan(plan)
404
405        response = self.client.get(url)
406        challenge = self.assertStageResponse(response, self.flow)
407        self.assertEqual(challenge["captcha_stage"]["site_key"], site_key)
408
409        response = self.client.post(
410            url,
411            {"uid_field": self.user.email, "captcha_token": "PASSED"},
412        )
413        self.assertEqual(response.status_code, 200)
414        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
415        self.assertIn(private_key, mock.request_history[0].text)

Test embedded captcha with overridden site and private keys

@Mocker()
def test_invalid_with_captcha(self, mock: requests_mock.mocker.Mocker):
417    @Mocker()
418    def test_invalid_with_captcha(self, mock: Mocker):
419        """Test with valid email and invalid captcha token in single step"""
420        mock.post(
421            "https://www.recaptcha.net/recaptcha/api/siteverify",
422            json={
423                "success": False,
424                "score": 0.5,
425            },
426        )
427
428        captcha_stage = CaptchaStage.objects.create(
429            name="captcha",
430            public_key=RECAPTCHA_PUBLIC_KEY,
431            private_key=RECAPTCHA_PRIVATE_KEY,
432        )
433
434        self.stage.captcha_stage = captcha_stage
435        self.stage.save()
436
437        form_data = {
438            "uid_field": self.user.email,
439            "captcha_token": "FAILED",
440        }
441        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
442        response = self.client.post(url, form_data)
443        self.assertStageResponse(
444            response,
445            self.flow,
446            component="ak-stage-identification",
447            password_fields=False,
448            primary_action="Log in",
449            response_errors={
450                "non_field_errors": [{"code": "invalid", "string": "Failed to authenticate."}]
451            },
452            sources=[
453                {
454                    "challenge": {
455                        "component": "xak-flow-redirect",
456                        "to": f"/source/oauth/login/{self.source.slug}/",
457                        "final_redirect": False,
458                    },
459                    "icon_url": "/static/authentik/sources/default/light.svg",
460                    "icon_themed_urls": {
461                        "light": "/static/authentik/sources/default/light.svg",
462                        "dark": "/static/authentik/sources/default/dark.svg",
463                    },
464                    "name": self.source.name,
465                    "promoted": False,
466                }
467            ],
468            show_source_labels=False,
469            user_fields=["email"],
470        )

Test with valid email and invalid captcha token in single step

@Mocker()
def test_invalid_with_captcha_retriable(self, mock: requests_mock.mocker.Mocker):
472    @Mocker()
473    def test_invalid_with_captcha_retriable(self, mock: Mocker):
474        """Test with valid email and invalid captcha token in single step"""
475        mock.post(
476            "https://www.recaptcha.net/recaptcha/api/siteverify",
477            json={
478                "success": False,
479                "score": 0.5,
480                "error-codes": ["timeout-or-duplicate"],
481            },
482        )
483
484        captcha_stage = CaptchaStage.objects.create(
485            name="captcha",
486            public_key=RECAPTCHA_PUBLIC_KEY,
487            private_key=RECAPTCHA_PRIVATE_KEY,
488        )
489
490        self.stage.captcha_stage = captcha_stage
491        self.stage.save()
492
493        form_data = {
494            "uid_field": self.user.email,
495            "captcha_token": "FAILED",
496        }
497        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
498        response = self.client.post(url, form_data)
499        self.assertStageResponse(
500            response,
501            self.flow,
502            component="ak-stage-identification",
503            password_fields=False,
504            primary_action="Log in",
505            response_errors={
506                "non_field_errors": [
507                    {
508                        "code": "invalid",
509                        "string": "Failed to authenticate.",
510                    }
511                ]
512            },
513            sources=[
514                {
515                    "challenge": {
516                        "component": "xak-flow-redirect",
517                        "to": f"/source/oauth/login/{self.source.slug}/",
518                        "final_redirect": False,
519                    },
520                    "icon_url": "/static/authentik/sources/default/light.svg",
521                    "icon_themed_urls": {
522                        "light": "/static/authentik/sources/default/light.svg",
523                        "dark": "/static/authentik/sources/default/dark.svg",
524                    },
525                    "name": self.source.name,
526                    "promoted": False,
527                }
528            ],
529            show_source_labels=False,
530            user_fields=["email"],
531        )

Test with valid email and invalid captcha token in single step

def test_invalid_with_username(self):
533    def test_invalid_with_username(self):
534        """Test invalid with username (user exists but stage only allows email)"""
535        form_data = {"uid_field": self.user.username}
536        response = self.client.post(
537            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
538            form_data,
539        )
540        self.assertEqual(response.status_code, 200)
541        self.assertStageResponse(
542            response,
543            self.flow,
544            component="ak-stage-identification",
545            response_errors={
546                "non_field_errors": [{"string": "Failed to authenticate.", "code": "invalid"}]
547            },
548        )

Test invalid with username (user exists but stage only allows email)

def test_invalid_with_username_pretend(self):
550    def test_invalid_with_username_pretend(self):
551        """Test invalid with username (user exists but stage only allows email)"""
552        self.stage.pretend_user_exists = True
553        self.stage.save()
554        form_data = {"uid_field": self.user.username}
555        response = self.client.post(
556            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
557            form_data,
558        )
559        self.assertEqual(response.status_code, 200)
560        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))

Test invalid with username (user exists but stage only allows email)

def test_invalid_no_fields(self):
562    def test_invalid_no_fields(self):
563        """Test invalid with username (no user fields are enabled)"""
564        self.stage.user_fields = []
565        self.stage.save()
566        form_data = {"uid_field": self.user.username}
567        response = self.client.post(
568            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
569            form_data,
570        )
571        self.assertStageResponse(
572            response,
573            self.flow,
574            component="ak-stage-identification",
575            password_fields=False,
576            primary_action="Log in",
577            response_errors={
578                "non_field_errors": [{"code": "invalid", "string": "Failed to authenticate."}]
579            },
580            show_source_labels=False,
581            sources=[
582                {
583                    "challenge": {
584                        "component": "xak-flow-redirect",
585                        "to": f"/source/oauth/login/{self.source.slug}/",
586                        "final_redirect": False,
587                    },
588                    "icon_url": "/static/authentik/sources/default/light.svg",
589                    "icon_themed_urls": {
590                        "light": "/static/authentik/sources/default/light.svg",
591                        "dark": "/static/authentik/sources/default/dark.svg",
592                    },
593                    "name": self.source.name,
594                    "promoted": False,
595                }
596            ],
597            user_fields=[],
598        )

Test invalid with username (no user fields are enabled)

def test_invalid_with_invalid_email(self):
600    def test_invalid_with_invalid_email(self):
601        """Test with invalid email (user doesn't exist) -> Will return to login form"""
602        form_data = {"uid_field": self.user.email + "test"}
603        response = self.client.post(
604            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
605            form_data,
606        )
607        self.assertEqual(response.status_code, 200)

Test with invalid email (user doesn't exist) -> Will return to login form

def test_enrollment_flow(self):
609    def test_enrollment_flow(self):
610        """Test that enrollment flow is linked correctly"""
611        flow = create_test_flow()
612        self.stage.enrollment_flow = flow
613        self.stage.save()
614        FlowStageBinding.objects.create(
615            target=flow,
616            stage=self.stage,
617            order=0,
618        )
619
620        response = self.client.get(
621            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
622        )
623        self.assertStageResponse(
624            response,
625            self.flow,
626            component="ak-stage-identification",
627            user_fields=["email"],
628            password_fields=False,
629            enroll_url=reverse(
630                "authentik_core:if-flow",
631                kwargs={"flow_slug": flow.slug},
632            ),
633            show_source_labels=False,
634            primary_action="Log in",
635            sources=[
636                {
637                    "icon_url": "/static/authentik/sources/default/light.svg",
638                    "icon_themed_urls": {
639                        "light": "/static/authentik/sources/default/light.svg",
640                        "dark": "/static/authentik/sources/default/dark.svg",
641                    },
642                    "name": self.source.name,
643                    "challenge": {
644                        "component": "xak-flow-redirect",
645                        "to": f"/source/oauth/login/{self.source.slug}/",
646                        "final_redirect": False,
647                    },
648                    "promoted": False,
649                }
650            ],
651        )

Test that enrollment flow is linked correctly

def test_recovery_flow_invalid_user(self):
696    def test_recovery_flow_invalid_user(self):
697        """Test that an invalid user can proceed in a recovery flow"""
698        self.flow.designation = FlowDesignation.RECOVERY
699        self.flow.save()
700        response = self.client.get(
701            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
702        )
703        self.assertStageResponse(
704            response,
705            self.flow,
706            component="ak-stage-identification",
707            user_fields=["email"],
708            password_fields=False,
709            show_source_labels=False,
710            primary_action="Continue",
711            sources=[
712                {
713                    "challenge": {
714                        "component": "xak-flow-redirect",
715                        "to": f"/source/oauth/login/{self.source.slug}/",
716                        "final_redirect": False,
717                    },
718                    "icon_url": "/static/authentik/sources/default/light.svg",
719                    "icon_themed_urls": {
720                        "light": "/static/authentik/sources/default/light.svg",
721                        "dark": "/static/authentik/sources/default/dark.svg",
722                    },
723                    "name": self.source.name,
724                    "promoted": False,
725                }
726            ],
727        )
728        form_data = {"uid_field": generate_id()}
729        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
730        response = self.client.post(url, form_data)
731        self.assertEqual(response.status_code, 200)

Test that an invalid user can proceed in a recovery flow

def test_api_validate(self):
733    def test_api_validate(self):
734        """Test API validation"""
735        self.assertTrue(
736            IdentificationStageSerializer(
737                data={
738                    "name": generate_id(),
739                    "user_fields": [UserFields.E_MAIL, UserFields.USERNAME],
740                }
741            ).is_valid(raise_exception=True)
742        )
743        with self.assertRaises(ValidationError):
744            IdentificationStageSerializer(
745                data={
746                    "name": generate_id(),
747                    "user_fields": [],
748                    "sources": [],
749                }
750            ).is_valid(raise_exception=True)

Test API validation

def test_prefill(self):
752    def test_prefill(self):
753        """Username prefill from existing flow context"""
754        pw_stage = PasswordStage.objects.create(name=generate_id(), backends=[BACKEND_INBUILT])
755        self.stage.password_stage = pw_stage
756        self.stage.save()
757
758        self.client.get(
759            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
760        )
761
762        plan = self.get_flow_plan()
763        plan.context[PLAN_CONTEXT_PENDING_USER_IDENTIFIER] = "foo"
764        self.set_flow_plan(plan)
765        with self.assertFlowFinishes() as plan:
766            response = self.client.get(
767                reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
768            )
769            self.assertEqual(response.status_code, 200)
770            self.assertStageResponse(
771                response,
772                self.flow,
773                component="ak-stage-identification",
774                pending_user_identifier="foo",
775            )

Username prefill from existing flow context

def test_prefill_simple(self):
777    def test_prefill_simple(self):
778        """Username prefill from existing flow context"""
779        self.stage.pretend_user_exists = True
780        self.stage.save()
781
782        self.client.get(
783            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
784        )
785        plan = self.get_flow_plan()
786        plan.context[PLAN_CONTEXT_PENDING_USER_IDENTIFIER] = "foo"
787        self.set_flow_plan(plan)
788        response = self.client.get(
789            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
790        )
791        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))

Username prefill from existing flow context