authentik.stages.email.tests.test_stage

email tests

  1"""email tests"""
  2
  3from hashlib import sha256
  4from unittest.mock import MagicMock, PropertyMock, patch
  5
  6from django.contrib import messages
  7from django.core import mail
  8from django.core.mail.backends.locmem import EmailBackend
  9from django.core.mail.backends.smtp import EmailBackend as SMTPEmailBackend
 10from django.urls import reverse
 11from django.utils.http import urlencode
 12
 13from authentik.brands.models import Brand
 14from authentik.core.models import User
 15from authentik.core.tests.utils import RequestFactory, create_test_admin_user, create_test_flow
 16from authentik.flows.markers import StageMarker
 17from authentik.flows.models import FlowDesignation, FlowStageBinding, FlowToken
 18from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER, FlowPlan
 19from authentik.flows.tests import APIFlowTestCase
 20from authentik.flows.views.executor import QS_KEY_TOKEN, SESSION_KEY_PLAN, FlowExecutorView
 21from authentik.lib.config import CONFIG
 22from authentik.lib.generators import generate_id
 23from authentik.stages.consent.stage import PLAN_CONTEXT_CONSENT_TOKEN
 24from authentik.stages.email.models import EmailStage
 25from authentik.stages.email.stage import PLAN_CONTEXT_EMAIL_OVERRIDE, EmailStageView
 26
 27
 28class TestEmailStage(APIFlowTestCase):
 29    """Email tests"""
 30
 31    def setUp(self):
 32        super().setUp()
 33        self.factory = RequestFactory()
 34        self.user = create_test_admin_user()
 35        self.flow = create_test_flow(FlowDesignation.AUTHENTICATION)
 36        self.stage = EmailStage.objects.create(
 37            name="email",
 38            activate_user_on_success=True,
 39        )
 40        self.binding = FlowStageBinding.objects.create(target=self.flow, stage=self.stage, order=2)
 41
 42    @patch(
 43        "authentik.stages.email.models.EmailStage.backend_class",
 44        PropertyMock(return_value=EmailBackend),
 45    )
 46    def test_rendering(self):
 47        """Test with pending user"""
 48        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
 49        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
 50        session = self.client.session
 51        session[SESSION_KEY_PLAN] = plan
 52        session.save()
 53
 54        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
 55        response = self.client.get(url)
 56        self.assertEqual(response.status_code, 200)
 57
 58    @patch(
 59        "authentik.stages.email.models.EmailStage.backend_class",
 60        PropertyMock(return_value=EmailBackend),
 61    )
 62    def test_rendering_locale(self):
 63        """Test with pending user"""
 64        self.user.attributes = {"settings": {"locale": "de"}}
 65        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
 66        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
 67        session = self.client.session
 68        session[SESSION_KEY_PLAN] = plan
 69        session.save()
 70
 71        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
 72        response = self.client.get(url)
 73        self.assertEqual(response.status_code, 200)
 74        self.assertEqual(len(mail.outbox), 1)
 75        self.assertEqual(mail.outbox[0].subject, "authentik")
 76        self.assertNotIn("Password Reset", mail.outbox[0].alternatives[0][0])
 77
 78    def test_without_user(self):
 79        """Test without pending user"""
 80        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
 81        session = self.client.session
 82        session[SESSION_KEY_PLAN] = plan
 83        session.save()
 84
 85        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
 86        response = self.client.get(url)
 87        self.assertEqual(response.status_code, 200)
 88
 89    @patch(
 90        "authentik.stages.email.models.EmailStage.backend_class",
 91        PropertyMock(return_value=EmailBackend),
 92    )
 93    def test_pending_user(self):
 94        """Test with pending user"""
 95        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
 96        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
 97        session = self.client.session
 98        session[SESSION_KEY_PLAN] = plan
 99        session.save()
100
101        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
102        response = self.client.post(url)
103        self.assertEqual(response.status_code, 200)
104        self.assertEqual(len(mail.outbox), 1)
105        self.assertEqual(mail.outbox[0].subject, "authentik")
106        self.assertEqual(mail.outbox[0].to, [f"{self.user.name} <{self.user.email}>"])
107        self.assertEqual(FlowToken.objects.filter(user=self.user).count(), 1)
108
109    def test_synthetic_pending_user(self):
110        """Test that synthetic users get the sent-email challenge without a token or email."""
111        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
112
113        for designation in (FlowDesignation.AUTHENTICATION, FlowDesignation.RECOVERY):
114            with self.subTest(designation=designation):
115                self.flow.designation = designation
116                self.flow.save(update_fields=["designation"])
117                pending_user = User(
118                    username="unknown",
119                    email="unknown@example.com",
120                )
121                self.assertIsNone(pending_user.pk)
122
123                plan = FlowPlan(
124                    flow_pk=self.flow.pk.hex,
125                    bindings=[self.binding],
126                    markers=[StageMarker()],
127                )
128                plan.context[PLAN_CONTEXT_PENDING_USER] = pending_user
129
130                session = self.client.session
131                session[SESSION_KEY_PLAN] = plan
132                session.save()
133
134                response = self.client.get(url)
135
136                self.assertEqual(response.status_code, 200)
137                self.assertStageResponse(response, self.flow, component="ak-stage-email")
138                self.assertEqual(FlowToken.objects.filter(flow=self.flow).count(), 0)
139                self.assertEqual(len(mail.outbox), 0)
140
141    @patch(
142        "authentik.stages.email.models.EmailStage.backend_class",
143        PropertyMock(return_value=EmailBackend),
144    )
145    def test_pending_user_without_email(self):
146        """Test that a user without an email address gets the sent-email challenge
147        without a token or email, the same as a synthetic user."""
148        self.user.email = ""
149        self.user.save()
150        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
151        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
152        session = self.client.session
153        session[SESSION_KEY_PLAN] = plan
154        session.save()
155
156        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
157        response = self.client.get(url)
158        self.assertEqual(response.status_code, 200)
159        self.assertStageResponse(response, self.flow, component="ak-stage-email")
160        self.assertEqual(FlowToken.objects.filter(user=self.user).count(), 0)
161        self.assertEqual(len(mail.outbox), 0)
162
163    @patch(
164        "authentik.stages.email.models.EmailStage.backend_class",
165        PropertyMock(return_value=EmailBackend),
166    )
167    def test_pending_user_override(self):
168        """Test with pending user (override to)"""
169        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
170        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
171        plan.context[PLAN_CONTEXT_EMAIL_OVERRIDE] = "foo@bar.baz"
172        session = self.client.session
173        session[SESSION_KEY_PLAN] = plan
174        session.save()
175
176        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
177        response = self.client.post(url)
178        self.assertEqual(response.status_code, 200)
179        self.assertEqual(len(mail.outbox), 1)
180        self.assertEqual(mail.outbox[0].subject, "authentik")
181        self.assertEqual(mail.outbox[0].to, [f"{self.user.name} <foo@bar.baz>"])
182
183    @patch(
184        "authentik.stages.email.models.EmailStage.backend_class",
185        PropertyMock(return_value=SMTPEmailBackend),
186    )
187    def test_use_global_settings(self):
188        """Test use_global_settings"""
189        host = "some-unique-string"
190        with CONFIG.patch("email.host", host):
191            self.assertEqual(EmailStage(use_global_settings=True).backend.host, host)
192
193    def test_token(self):
194        """Test with token"""
195        # Make sure token exists
196        self.test_pending_user()
197        self.user.is_active = False
198        self.user.save()
199        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
200        session = self.client.session
201        session[SESSION_KEY_PLAN] = plan
202        session.save()
203        token: FlowToken = FlowToken.objects.get(user=self.user)
204
205        with patch("authentik.flows.views.executor.FlowExecutorView.cancel", MagicMock()):
206            # Call the executor shell to preseed the session
207            url = reverse(
208                "authentik_api:flow-executor",
209                kwargs={"flow_slug": self.flow.slug},
210            )
211            url_query = urlencode(
212                {
213                    QS_KEY_TOKEN: token.key,
214                }
215            )
216            url += f"?query={url_query}"
217            self.client.get(url)
218
219            # Call the actual executor to get the JSON Response
220            response = self.client.get(
221                reverse(
222                    "authentik_api:flow-executor",
223                    kwargs={"flow_slug": self.flow.slug},
224                )
225            )
226            self.assertStageResponse(response, self.flow, component="ak-stage-consent")
227            response = self.client.post(
228                reverse(
229                    "authentik_api:flow-executor",
230                    kwargs={"flow_slug": self.flow.slug},
231                ),
232                data={
233                    "token": self.get_flow_plan().context[PLAN_CONTEXT_CONSENT_TOKEN],
234                },
235                follow=True,
236            )
237
238            self.assertEqual(response.status_code, 200)
239            self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
240
241            session = self.client.session
242            plan: FlowPlan = session[SESSION_KEY_PLAN]
243            self.assertEqual(plan.context[PLAN_CONTEXT_PENDING_USER], self.user)
244            self.assertTrue(plan.context[PLAN_CONTEXT_PENDING_USER].is_active)
245
246    def test_token_invalid_user(self):
247        """Test with token with invalid user"""
248        # Make sure token exists
249        self.test_pending_user()
250        self.user.is_active = False
251        self.user.save()
252        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
253        session = self.client.session
254        session[SESSION_KEY_PLAN] = plan
255        session.save()
256        # Set flow token user to a different user
257        token: FlowToken = FlowToken.objects.get(user=self.user)
258        token.user = create_test_admin_user()
259        token.revoke_on_execution = True
260        token.save()
261
262        with patch("authentik.flows.views.executor.FlowExecutorView.cancel", MagicMock()):
263            # Call the executor shell to preseed the session
264            url = reverse(
265                "authentik_api:flow-executor",
266                kwargs={"flow_slug": self.flow.slug},
267            )
268            url_query = urlencode(
269                {
270                    QS_KEY_TOKEN: token.key,
271                }
272            )
273            url += f"?query={url_query}"
274            self.client.get(url)
275
276            # Call the actual executor to get the JSON Response
277            response = self.client.get(
278                reverse(
279                    "authentik_api:flow-executor",
280                    kwargs={"flow_slug": self.flow.slug},
281                )
282            )
283
284            self.assertEqual(response.status_code, 200)
285            self.assertStageResponse(response, component="ak-stage-access-denied")
286
287    def test_url_no_params(self):
288        """Test generation of the URL in the EMail"""
289        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
290        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
291        session = self.client.session
292        session[SESSION_KEY_PLAN] = plan
293        session.save()
294
295        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
296        request = self.factory.get(url)
297        stage_view = EmailStageView(
298            FlowExecutorView(
299                request=request,
300                flow=self.flow,
301            ),
302            request=request,
303        )
304        self.assertEqual(stage_view.get_full_url(), f"http://testserver/if/flow/{self.flow.slug}/")
305
306    def test_url_our_params(self):
307        """Test that all of our parameters are passed to the URL correctly"""
308        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
309        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
310        session = self.client.session
311        session[SESSION_KEY_PLAN] = plan
312        session.save()
313
314        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
315        request = self.factory.get(url)
316        stage_view = EmailStageView(
317            FlowExecutorView(
318                request=request,
319                flow=self.flow,
320            ),
321            request=request,
322        )
323        token = generate_id()
324        self.assertEqual(
325            stage_view.get_full_url(**{QS_KEY_TOKEN: token}),
326            f"http://testserver/if/flow/{self.flow.slug}/?flow_token={token}",
327        )
328
329    def test_url_existing_params(self):
330        """Test to ensure that URL params are preserved in the URL being sent"""
331        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
332        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
333        session = self.client.session
334        session[SESSION_KEY_PLAN] = plan
335        session.save()
336
337        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
338        url += "?query=" + urlencode({"foo": "bar"})
339        request = self.factory.get(url)
340        stage_view = EmailStageView(
341            FlowExecutorView(
342                request=request,
343                flow=self.flow,
344            ),
345            request=request,
346        )
347        token = generate_id()
348        self.assertEqual(
349            stage_view.get_full_url(**{QS_KEY_TOKEN: token}),
350            f"http://testserver/if/flow/{self.flow.slug}/?foo=bar&flow_token={token}",
351        )
352
353    def test_get_cache_key(self):
354        """Test to ensure that the correct cache key is returned."""
355        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
356        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
357        session = self.client.session
358        session[SESSION_KEY_PLAN] = plan
359        session.save()
360
361        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
362        request = self.factory.post(url)
363        request.user = self.user
364        request.session = session
365
366        executor = FlowExecutorView(request=request, flow=self.flow)
367        executor.plan = plan
368
369        stage_view = EmailStageView(executor, request=request)
370
371        cache_key = stage_view._get_cache_key()
372
373        expected_hash = sha256(self.user.email.lower().encode("utf-8")).hexdigest()
374        expected_cache_key = "goauthentik.io/stages/email/stage/" + expected_hash
375
376        self.assertEqual(cache_key, expected_cache_key)
377
378    def test_is_rate_limited_returns_none(self):
379        """Test to ensure None is returned if the request shouldn't be rate limited."""
380        self.stage.recovery_max_attempts = 2
381        self.stage.recovery_cache_timeout = "minutes=10"
382        self.stage.save()
383
384        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
385        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
386        session = self.client.session
387        session[SESSION_KEY_PLAN] = plan
388        session.save()
389
390        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
391        request = self.factory.post(url)
392        request.user = self.user
393        request.session = session
394
395        executor = FlowExecutorView(request=request, flow=self.flow)
396        executor.current_stage = self.stage
397        executor.plan = plan
398
399        stage_view = EmailStageView(executor, request=request)
400
401        result = stage_view._is_rate_limited()
402        self.assertIsNone(result)
403
404    def test_is_rate_limited_returns_remaining_time(self):
405        """Test to ensure the remaining time is returned if the request
406        should be rate limited."""
407        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
408        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
409        session = self.client.session
410        session[SESSION_KEY_PLAN] = plan
411        session.save()
412
413        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
414        request = self.factory.post(url)
415        request.user = self.user
416        request.session = session
417
418        executor = FlowExecutorView(request=request, flow=self.flow)
419        executor.current_stage = self.stage
420        executor.plan = plan
421
422        stage_view = EmailStageView(executor, request=request)
423
424        test_cases = [
425            # 2 attempts within 2 minutes
426            (2, "seconds=120", 2),
427            # 4 attempts within 5 minutes
428            (4, "minutes=5", 5),
429            # 6 attempts within 5 minutes. Although 299 seconds is less than
430            # 5 minutes, the user is intentionally shown "5 minutes". This is
431            # because an initial rate limiting message like "Try again after 4 minutes"
432            # can be confusing.
433            (6, "seconds=299", 5),
434        ]
435        for test_case in test_cases:
436            max_attempts, cache_timeout, minutes_remaining = test_case
437            with self.subTest(
438                f"Test recovery with {max_attempts} max attempts and "
439                f"{cache_timeout} cache timeout seconds"
440            ):
441                self.stage.recovery_max_attempts = max_attempts
442                self.stage.recovery_cache_timeout = cache_timeout
443                self.stage.save()
444
445                # Simulate multiple requests
446                for _ in range(max_attempts):
447                    stage_view._is_rate_limited()
448
449                # The following request should be rate-limited
450                result = stage_view._is_rate_limited()
451
452                self.assertEqual(result, minutes_remaining)
453
454    def _challenge_invalid_helper(self):
455        """Helper to test the challenge_invalid() method."""
456        self.stage.recovery_max_attempts = 1
457        self.stage.recovery_cache_timeout = "seconds=300"
458        self.stage.save()
459
460        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
461        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
462        session = self.client.session
463        session[SESSION_KEY_PLAN] = plan
464        session.save()
465
466        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
467        request = self.factory.get(url, user=self.user)
468        request.session = session
469
470        request.brand = Brand.objects.create(domain="foo-domain.com", default=True)
471
472        executor = FlowExecutorView(request=request, flow=self.flow)
473        executor.current_stage = self.stage
474        executor.plan = plan
475
476        stage_view = EmailStageView(executor, request=request)
477        challenge_response = stage_view.get_response_instance(data={})
478        challenge_response.is_valid()
479
480        return challenge_response, stage_view, request
481
482    def test_challenge_invalid_not_rate_limited(self):
483        """Tests that the request is not rate limited and email is sent."""
484        challenge_response, stage_view, request = self._challenge_invalid_helper()
485
486        with patch.object(stage_view, "send_email") as mock_send_email:
487            result = stage_view.challenge_invalid(challenge_response)
488
489            self.assertEqual(result.status_code, 200)
490
491            mock_send_email.assert_called_once()
492
493            message_list = list(messages.get_messages(request))
494            self.assertEqual(len(message_list), 1)
495            self.assertEqual(
496                "Email Successfully sent.",
497                message_list[-1].message,
498            )
499
500    def test_challenge_invalid_returns_error_if_rate_limited(self):
501        """Tests that an error is returned if the request is rate limited. Ensure
502        that an email is not sent."""
503        challenge_response, stage_view, request = self._challenge_invalid_helper()
504
505        # Initial request that shouldn't be rate limited
506        stage_view.challenge_invalid(challenge_response)
507
508        with patch.object(stage_view, "send_email") as mock_send_email:
509            # This next request should be rate limited
510            result = stage_view.challenge_invalid(challenge_response)
511
512            self.assertEqual(result.status_code, 200)
513
514            mock_send_email.assert_not_called()
515
516            message_list = list(messages.get_messages(request))
517            self.assertEqual(len(message_list), 2)
518            self.assertEqual(
519                "Too many account verification attempts. Please try again after 5 minutes.",
520                message_list[-1].message,
521            )
522
523    @patch(
524        "authentik.stages.email.models.EmailStage.backend_class",
525        PropertyMock(return_value=EmailBackend),
526    )
527    def test_initial_send_rate_limited_on_flow_restart(self):
528        """Tests that restarting the flow does not bypass the rate limit
529        applied to resending the email."""
530        self.stage.recovery_max_attempts = 2
531        self.stage.recovery_cache_timeout = "minutes=10"
532        self.stage.save()
533
534        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
535        # Each iteration simulates a full flow restart by seeding a fresh plan,
536        # so the initial email is attempted every time
537        for expected_mails in (1, 2, 2):
538            plan = FlowPlan(
539                flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()]
540            )
541            plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
542            session = self.client.session
543            session[SESSION_KEY_PLAN] = plan
544            session.save()
545
546            response = self.client.get(url)
547            self.assertStageResponse(response, self.flow, component="ak-stage-email")
548            self.assertEqual(len(mail.outbox), expected_mails)
class TestEmailStage(authentik.flows.tests.APIFlowTestCase):
 29class TestEmailStage(APIFlowTestCase):
 30    """Email tests"""
 31
 32    def setUp(self):
 33        super().setUp()
 34        self.factory = RequestFactory()
 35        self.user = create_test_admin_user()
 36        self.flow = create_test_flow(FlowDesignation.AUTHENTICATION)
 37        self.stage = EmailStage.objects.create(
 38            name="email",
 39            activate_user_on_success=True,
 40        )
 41        self.binding = FlowStageBinding.objects.create(target=self.flow, stage=self.stage, order=2)
 42
 43    @patch(
 44        "authentik.stages.email.models.EmailStage.backend_class",
 45        PropertyMock(return_value=EmailBackend),
 46    )
 47    def test_rendering(self):
 48        """Test with pending user"""
 49        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
 50        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
 51        session = self.client.session
 52        session[SESSION_KEY_PLAN] = plan
 53        session.save()
 54
 55        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
 56        response = self.client.get(url)
 57        self.assertEqual(response.status_code, 200)
 58
 59    @patch(
 60        "authentik.stages.email.models.EmailStage.backend_class",
 61        PropertyMock(return_value=EmailBackend),
 62    )
 63    def test_rendering_locale(self):
 64        """Test with pending user"""
 65        self.user.attributes = {"settings": {"locale": "de"}}
 66        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
 67        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
 68        session = self.client.session
 69        session[SESSION_KEY_PLAN] = plan
 70        session.save()
 71
 72        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
 73        response = self.client.get(url)
 74        self.assertEqual(response.status_code, 200)
 75        self.assertEqual(len(mail.outbox), 1)
 76        self.assertEqual(mail.outbox[0].subject, "authentik")
 77        self.assertNotIn("Password Reset", mail.outbox[0].alternatives[0][0])
 78
 79    def test_without_user(self):
 80        """Test without pending user"""
 81        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
 82        session = self.client.session
 83        session[SESSION_KEY_PLAN] = plan
 84        session.save()
 85
 86        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
 87        response = self.client.get(url)
 88        self.assertEqual(response.status_code, 200)
 89
 90    @patch(
 91        "authentik.stages.email.models.EmailStage.backend_class",
 92        PropertyMock(return_value=EmailBackend),
 93    )
 94    def test_pending_user(self):
 95        """Test with pending user"""
 96        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
 97        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
 98        session = self.client.session
 99        session[SESSION_KEY_PLAN] = plan
100        session.save()
101
102        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
103        response = self.client.post(url)
104        self.assertEqual(response.status_code, 200)
105        self.assertEqual(len(mail.outbox), 1)
106        self.assertEqual(mail.outbox[0].subject, "authentik")
107        self.assertEqual(mail.outbox[0].to, [f"{self.user.name} <{self.user.email}>"])
108        self.assertEqual(FlowToken.objects.filter(user=self.user).count(), 1)
109
110    def test_synthetic_pending_user(self):
111        """Test that synthetic users get the sent-email challenge without a token or email."""
112        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
113
114        for designation in (FlowDesignation.AUTHENTICATION, FlowDesignation.RECOVERY):
115            with self.subTest(designation=designation):
116                self.flow.designation = designation
117                self.flow.save(update_fields=["designation"])
118                pending_user = User(
119                    username="unknown",
120                    email="unknown@example.com",
121                )
122                self.assertIsNone(pending_user.pk)
123
124                plan = FlowPlan(
125                    flow_pk=self.flow.pk.hex,
126                    bindings=[self.binding],
127                    markers=[StageMarker()],
128                )
129                plan.context[PLAN_CONTEXT_PENDING_USER] = pending_user
130
131                session = self.client.session
132                session[SESSION_KEY_PLAN] = plan
133                session.save()
134
135                response = self.client.get(url)
136
137                self.assertEqual(response.status_code, 200)
138                self.assertStageResponse(response, self.flow, component="ak-stage-email")
139                self.assertEqual(FlowToken.objects.filter(flow=self.flow).count(), 0)
140                self.assertEqual(len(mail.outbox), 0)
141
142    @patch(
143        "authentik.stages.email.models.EmailStage.backend_class",
144        PropertyMock(return_value=EmailBackend),
145    )
146    def test_pending_user_without_email(self):
147        """Test that a user without an email address gets the sent-email challenge
148        without a token or email, the same as a synthetic user."""
149        self.user.email = ""
150        self.user.save()
151        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
152        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
153        session = self.client.session
154        session[SESSION_KEY_PLAN] = plan
155        session.save()
156
157        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
158        response = self.client.get(url)
159        self.assertEqual(response.status_code, 200)
160        self.assertStageResponse(response, self.flow, component="ak-stage-email")
161        self.assertEqual(FlowToken.objects.filter(user=self.user).count(), 0)
162        self.assertEqual(len(mail.outbox), 0)
163
164    @patch(
165        "authentik.stages.email.models.EmailStage.backend_class",
166        PropertyMock(return_value=EmailBackend),
167    )
168    def test_pending_user_override(self):
169        """Test with pending user (override to)"""
170        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
171        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
172        plan.context[PLAN_CONTEXT_EMAIL_OVERRIDE] = "foo@bar.baz"
173        session = self.client.session
174        session[SESSION_KEY_PLAN] = plan
175        session.save()
176
177        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
178        response = self.client.post(url)
179        self.assertEqual(response.status_code, 200)
180        self.assertEqual(len(mail.outbox), 1)
181        self.assertEqual(mail.outbox[0].subject, "authentik")
182        self.assertEqual(mail.outbox[0].to, [f"{self.user.name} <foo@bar.baz>"])
183
184    @patch(
185        "authentik.stages.email.models.EmailStage.backend_class",
186        PropertyMock(return_value=SMTPEmailBackend),
187    )
188    def test_use_global_settings(self):
189        """Test use_global_settings"""
190        host = "some-unique-string"
191        with CONFIG.patch("email.host", host):
192            self.assertEqual(EmailStage(use_global_settings=True).backend.host, host)
193
194    def test_token(self):
195        """Test with token"""
196        # Make sure token exists
197        self.test_pending_user()
198        self.user.is_active = False
199        self.user.save()
200        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
201        session = self.client.session
202        session[SESSION_KEY_PLAN] = plan
203        session.save()
204        token: FlowToken = FlowToken.objects.get(user=self.user)
205
206        with patch("authentik.flows.views.executor.FlowExecutorView.cancel", MagicMock()):
207            # Call the executor shell to preseed the session
208            url = reverse(
209                "authentik_api:flow-executor",
210                kwargs={"flow_slug": self.flow.slug},
211            )
212            url_query = urlencode(
213                {
214                    QS_KEY_TOKEN: token.key,
215                }
216            )
217            url += f"?query={url_query}"
218            self.client.get(url)
219
220            # Call the actual executor to get the JSON Response
221            response = self.client.get(
222                reverse(
223                    "authentik_api:flow-executor",
224                    kwargs={"flow_slug": self.flow.slug},
225                )
226            )
227            self.assertStageResponse(response, self.flow, component="ak-stage-consent")
228            response = self.client.post(
229                reverse(
230                    "authentik_api:flow-executor",
231                    kwargs={"flow_slug": self.flow.slug},
232                ),
233                data={
234                    "token": self.get_flow_plan().context[PLAN_CONTEXT_CONSENT_TOKEN],
235                },
236                follow=True,
237            )
238
239            self.assertEqual(response.status_code, 200)
240            self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
241
242            session = self.client.session
243            plan: FlowPlan = session[SESSION_KEY_PLAN]
244            self.assertEqual(plan.context[PLAN_CONTEXT_PENDING_USER], self.user)
245            self.assertTrue(plan.context[PLAN_CONTEXT_PENDING_USER].is_active)
246
247    def test_token_invalid_user(self):
248        """Test with token with invalid user"""
249        # Make sure token exists
250        self.test_pending_user()
251        self.user.is_active = False
252        self.user.save()
253        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
254        session = self.client.session
255        session[SESSION_KEY_PLAN] = plan
256        session.save()
257        # Set flow token user to a different user
258        token: FlowToken = FlowToken.objects.get(user=self.user)
259        token.user = create_test_admin_user()
260        token.revoke_on_execution = True
261        token.save()
262
263        with patch("authentik.flows.views.executor.FlowExecutorView.cancel", MagicMock()):
264            # Call the executor shell to preseed the session
265            url = reverse(
266                "authentik_api:flow-executor",
267                kwargs={"flow_slug": self.flow.slug},
268            )
269            url_query = urlencode(
270                {
271                    QS_KEY_TOKEN: token.key,
272                }
273            )
274            url += f"?query={url_query}"
275            self.client.get(url)
276
277            # Call the actual executor to get the JSON Response
278            response = self.client.get(
279                reverse(
280                    "authentik_api:flow-executor",
281                    kwargs={"flow_slug": self.flow.slug},
282                )
283            )
284
285            self.assertEqual(response.status_code, 200)
286            self.assertStageResponse(response, component="ak-stage-access-denied")
287
288    def test_url_no_params(self):
289        """Test generation of the URL in the EMail"""
290        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
291        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
292        session = self.client.session
293        session[SESSION_KEY_PLAN] = plan
294        session.save()
295
296        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
297        request = self.factory.get(url)
298        stage_view = EmailStageView(
299            FlowExecutorView(
300                request=request,
301                flow=self.flow,
302            ),
303            request=request,
304        )
305        self.assertEqual(stage_view.get_full_url(), f"http://testserver/if/flow/{self.flow.slug}/")
306
307    def test_url_our_params(self):
308        """Test that all of our parameters are passed to the URL correctly"""
309        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
310        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
311        session = self.client.session
312        session[SESSION_KEY_PLAN] = plan
313        session.save()
314
315        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
316        request = self.factory.get(url)
317        stage_view = EmailStageView(
318            FlowExecutorView(
319                request=request,
320                flow=self.flow,
321            ),
322            request=request,
323        )
324        token = generate_id()
325        self.assertEqual(
326            stage_view.get_full_url(**{QS_KEY_TOKEN: token}),
327            f"http://testserver/if/flow/{self.flow.slug}/?flow_token={token}",
328        )
329
330    def test_url_existing_params(self):
331        """Test to ensure that URL params are preserved in the URL being sent"""
332        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
333        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
334        session = self.client.session
335        session[SESSION_KEY_PLAN] = plan
336        session.save()
337
338        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
339        url += "?query=" + urlencode({"foo": "bar"})
340        request = self.factory.get(url)
341        stage_view = EmailStageView(
342            FlowExecutorView(
343                request=request,
344                flow=self.flow,
345            ),
346            request=request,
347        )
348        token = generate_id()
349        self.assertEqual(
350            stage_view.get_full_url(**{QS_KEY_TOKEN: token}),
351            f"http://testserver/if/flow/{self.flow.slug}/?foo=bar&flow_token={token}",
352        )
353
354    def test_get_cache_key(self):
355        """Test to ensure that the correct cache key is returned."""
356        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
357        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
358        session = self.client.session
359        session[SESSION_KEY_PLAN] = plan
360        session.save()
361
362        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
363        request = self.factory.post(url)
364        request.user = self.user
365        request.session = session
366
367        executor = FlowExecutorView(request=request, flow=self.flow)
368        executor.plan = plan
369
370        stage_view = EmailStageView(executor, request=request)
371
372        cache_key = stage_view._get_cache_key()
373
374        expected_hash = sha256(self.user.email.lower().encode("utf-8")).hexdigest()
375        expected_cache_key = "goauthentik.io/stages/email/stage/" + expected_hash
376
377        self.assertEqual(cache_key, expected_cache_key)
378
379    def test_is_rate_limited_returns_none(self):
380        """Test to ensure None is returned if the request shouldn't be rate limited."""
381        self.stage.recovery_max_attempts = 2
382        self.stage.recovery_cache_timeout = "minutes=10"
383        self.stage.save()
384
385        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
386        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
387        session = self.client.session
388        session[SESSION_KEY_PLAN] = plan
389        session.save()
390
391        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
392        request = self.factory.post(url)
393        request.user = self.user
394        request.session = session
395
396        executor = FlowExecutorView(request=request, flow=self.flow)
397        executor.current_stage = self.stage
398        executor.plan = plan
399
400        stage_view = EmailStageView(executor, request=request)
401
402        result = stage_view._is_rate_limited()
403        self.assertIsNone(result)
404
405    def test_is_rate_limited_returns_remaining_time(self):
406        """Test to ensure the remaining time is returned if the request
407        should be rate limited."""
408        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
409        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
410        session = self.client.session
411        session[SESSION_KEY_PLAN] = plan
412        session.save()
413
414        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
415        request = self.factory.post(url)
416        request.user = self.user
417        request.session = session
418
419        executor = FlowExecutorView(request=request, flow=self.flow)
420        executor.current_stage = self.stage
421        executor.plan = plan
422
423        stage_view = EmailStageView(executor, request=request)
424
425        test_cases = [
426            # 2 attempts within 2 minutes
427            (2, "seconds=120", 2),
428            # 4 attempts within 5 minutes
429            (4, "minutes=5", 5),
430            # 6 attempts within 5 minutes. Although 299 seconds is less than
431            # 5 minutes, the user is intentionally shown "5 minutes". This is
432            # because an initial rate limiting message like "Try again after 4 minutes"
433            # can be confusing.
434            (6, "seconds=299", 5),
435        ]
436        for test_case in test_cases:
437            max_attempts, cache_timeout, minutes_remaining = test_case
438            with self.subTest(
439                f"Test recovery with {max_attempts} max attempts and "
440                f"{cache_timeout} cache timeout seconds"
441            ):
442                self.stage.recovery_max_attempts = max_attempts
443                self.stage.recovery_cache_timeout = cache_timeout
444                self.stage.save()
445
446                # Simulate multiple requests
447                for _ in range(max_attempts):
448                    stage_view._is_rate_limited()
449
450                # The following request should be rate-limited
451                result = stage_view._is_rate_limited()
452
453                self.assertEqual(result, minutes_remaining)
454
455    def _challenge_invalid_helper(self):
456        """Helper to test the challenge_invalid() method."""
457        self.stage.recovery_max_attempts = 1
458        self.stage.recovery_cache_timeout = "seconds=300"
459        self.stage.save()
460
461        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
462        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
463        session = self.client.session
464        session[SESSION_KEY_PLAN] = plan
465        session.save()
466
467        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
468        request = self.factory.get(url, user=self.user)
469        request.session = session
470
471        request.brand = Brand.objects.create(domain="foo-domain.com", default=True)
472
473        executor = FlowExecutorView(request=request, flow=self.flow)
474        executor.current_stage = self.stage
475        executor.plan = plan
476
477        stage_view = EmailStageView(executor, request=request)
478        challenge_response = stage_view.get_response_instance(data={})
479        challenge_response.is_valid()
480
481        return challenge_response, stage_view, request
482
483    def test_challenge_invalid_not_rate_limited(self):
484        """Tests that the request is not rate limited and email is sent."""
485        challenge_response, stage_view, request = self._challenge_invalid_helper()
486
487        with patch.object(stage_view, "send_email") as mock_send_email:
488            result = stage_view.challenge_invalid(challenge_response)
489
490            self.assertEqual(result.status_code, 200)
491
492            mock_send_email.assert_called_once()
493
494            message_list = list(messages.get_messages(request))
495            self.assertEqual(len(message_list), 1)
496            self.assertEqual(
497                "Email Successfully sent.",
498                message_list[-1].message,
499            )
500
501    def test_challenge_invalid_returns_error_if_rate_limited(self):
502        """Tests that an error is returned if the request is rate limited. Ensure
503        that an email is not sent."""
504        challenge_response, stage_view, request = self._challenge_invalid_helper()
505
506        # Initial request that shouldn't be rate limited
507        stage_view.challenge_invalid(challenge_response)
508
509        with patch.object(stage_view, "send_email") as mock_send_email:
510            # This next request should be rate limited
511            result = stage_view.challenge_invalid(challenge_response)
512
513            self.assertEqual(result.status_code, 200)
514
515            mock_send_email.assert_not_called()
516
517            message_list = list(messages.get_messages(request))
518            self.assertEqual(len(message_list), 2)
519            self.assertEqual(
520                "Too many account verification attempts. Please try again after 5 minutes.",
521                message_list[-1].message,
522            )
523
524    @patch(
525        "authentik.stages.email.models.EmailStage.backend_class",
526        PropertyMock(return_value=EmailBackend),
527    )
528    def test_initial_send_rate_limited_on_flow_restart(self):
529        """Tests that restarting the flow does not bypass the rate limit
530        applied to resending the email."""
531        self.stage.recovery_max_attempts = 2
532        self.stage.recovery_cache_timeout = "minutes=10"
533        self.stage.save()
534
535        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
536        # Each iteration simulates a full flow restart by seeding a fresh plan,
537        # so the initial email is attempted every time
538        for expected_mails in (1, 2, 2):
539            plan = FlowPlan(
540                flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()]
541            )
542            plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
543            session = self.client.session
544            session[SESSION_KEY_PLAN] = plan
545            session.save()
546
547            response = self.client.get(url)
548            self.assertStageResponse(response, self.flow, component="ak-stage-email")
549            self.assertEqual(len(mail.outbox), expected_mails)

Email tests

def setUp(self):
32    def setUp(self):
33        super().setUp()
34        self.factory = RequestFactory()
35        self.user = create_test_admin_user()
36        self.flow = create_test_flow(FlowDesignation.AUTHENTICATION)
37        self.stage = EmailStage.objects.create(
38            name="email",
39            activate_user_on_success=True,
40        )
41        self.binding = FlowStageBinding.objects.create(target=self.flow, stage=self.stage, order=2)

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

@patch('authentik.stages.email.models.EmailStage.backend_class', PropertyMock(return_value=EmailBackend))
def test_rendering(self):
43    @patch(
44        "authentik.stages.email.models.EmailStage.backend_class",
45        PropertyMock(return_value=EmailBackend),
46    )
47    def test_rendering(self):
48        """Test with pending user"""
49        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
50        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
51        session = self.client.session
52        session[SESSION_KEY_PLAN] = plan
53        session.save()
54
55        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
56        response = self.client.get(url)
57        self.assertEqual(response.status_code, 200)

Test with pending user

@patch('authentik.stages.email.models.EmailStage.backend_class', PropertyMock(return_value=EmailBackend))
def test_rendering_locale(self):
59    @patch(
60        "authentik.stages.email.models.EmailStage.backend_class",
61        PropertyMock(return_value=EmailBackend),
62    )
63    def test_rendering_locale(self):
64        """Test with pending user"""
65        self.user.attributes = {"settings": {"locale": "de"}}
66        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
67        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
68        session = self.client.session
69        session[SESSION_KEY_PLAN] = plan
70        session.save()
71
72        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
73        response = self.client.get(url)
74        self.assertEqual(response.status_code, 200)
75        self.assertEqual(len(mail.outbox), 1)
76        self.assertEqual(mail.outbox[0].subject, "authentik")
77        self.assertNotIn("Password Reset", mail.outbox[0].alternatives[0][0])

Test with pending user

def test_without_user(self):
79    def test_without_user(self):
80        """Test without pending user"""
81        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
82        session = self.client.session
83        session[SESSION_KEY_PLAN] = plan
84        session.save()
85
86        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
87        response = self.client.get(url)
88        self.assertEqual(response.status_code, 200)

Test without pending user

@patch('authentik.stages.email.models.EmailStage.backend_class', PropertyMock(return_value=EmailBackend))
def test_pending_user(self):
 90    @patch(
 91        "authentik.stages.email.models.EmailStage.backend_class",
 92        PropertyMock(return_value=EmailBackend),
 93    )
 94    def test_pending_user(self):
 95        """Test with pending user"""
 96        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
 97        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
 98        session = self.client.session
 99        session[SESSION_KEY_PLAN] = plan
100        session.save()
101
102        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
103        response = self.client.post(url)
104        self.assertEqual(response.status_code, 200)
105        self.assertEqual(len(mail.outbox), 1)
106        self.assertEqual(mail.outbox[0].subject, "authentik")
107        self.assertEqual(mail.outbox[0].to, [f"{self.user.name} <{self.user.email}>"])
108        self.assertEqual(FlowToken.objects.filter(user=self.user).count(), 1)

Test with pending user

def test_synthetic_pending_user(self):
110    def test_synthetic_pending_user(self):
111        """Test that synthetic users get the sent-email challenge without a token or email."""
112        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
113
114        for designation in (FlowDesignation.AUTHENTICATION, FlowDesignation.RECOVERY):
115            with self.subTest(designation=designation):
116                self.flow.designation = designation
117                self.flow.save(update_fields=["designation"])
118                pending_user = User(
119                    username="unknown",
120                    email="unknown@example.com",
121                )
122                self.assertIsNone(pending_user.pk)
123
124                plan = FlowPlan(
125                    flow_pk=self.flow.pk.hex,
126                    bindings=[self.binding],
127                    markers=[StageMarker()],
128                )
129                plan.context[PLAN_CONTEXT_PENDING_USER] = pending_user
130
131                session = self.client.session
132                session[SESSION_KEY_PLAN] = plan
133                session.save()
134
135                response = self.client.get(url)
136
137                self.assertEqual(response.status_code, 200)
138                self.assertStageResponse(response, self.flow, component="ak-stage-email")
139                self.assertEqual(FlowToken.objects.filter(flow=self.flow).count(), 0)
140                self.assertEqual(len(mail.outbox), 0)

Test that synthetic users get the sent-email challenge without a token or email.

@patch('authentik.stages.email.models.EmailStage.backend_class', PropertyMock(return_value=EmailBackend))
def test_pending_user_without_email(self):
142    @patch(
143        "authentik.stages.email.models.EmailStage.backend_class",
144        PropertyMock(return_value=EmailBackend),
145    )
146    def test_pending_user_without_email(self):
147        """Test that a user without an email address gets the sent-email challenge
148        without a token or email, the same as a synthetic user."""
149        self.user.email = ""
150        self.user.save()
151        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
152        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
153        session = self.client.session
154        session[SESSION_KEY_PLAN] = plan
155        session.save()
156
157        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
158        response = self.client.get(url)
159        self.assertEqual(response.status_code, 200)
160        self.assertStageResponse(response, self.flow, component="ak-stage-email")
161        self.assertEqual(FlowToken.objects.filter(user=self.user).count(), 0)
162        self.assertEqual(len(mail.outbox), 0)

Test that a user without an email address gets the sent-email challenge without a token or email, the same as a synthetic user.

@patch('authentik.stages.email.models.EmailStage.backend_class', PropertyMock(return_value=EmailBackend))
def test_pending_user_override(self):
164    @patch(
165        "authentik.stages.email.models.EmailStage.backend_class",
166        PropertyMock(return_value=EmailBackend),
167    )
168    def test_pending_user_override(self):
169        """Test with pending user (override to)"""
170        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
171        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
172        plan.context[PLAN_CONTEXT_EMAIL_OVERRIDE] = "foo@bar.baz"
173        session = self.client.session
174        session[SESSION_KEY_PLAN] = plan
175        session.save()
176
177        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
178        response = self.client.post(url)
179        self.assertEqual(response.status_code, 200)
180        self.assertEqual(len(mail.outbox), 1)
181        self.assertEqual(mail.outbox[0].subject, "authentik")
182        self.assertEqual(mail.outbox[0].to, [f"{self.user.name} <foo@bar.baz>"])

Test with pending user (override to)

@patch('authentik.stages.email.models.EmailStage.backend_class', PropertyMock(return_value=SMTPEmailBackend))
def test_use_global_settings(self):
184    @patch(
185        "authentik.stages.email.models.EmailStage.backend_class",
186        PropertyMock(return_value=SMTPEmailBackend),
187    )
188    def test_use_global_settings(self):
189        """Test use_global_settings"""
190        host = "some-unique-string"
191        with CONFIG.patch("email.host", host):
192            self.assertEqual(EmailStage(use_global_settings=True).backend.host, host)

Test use_global_settings

def test_token(self):
194    def test_token(self):
195        """Test with token"""
196        # Make sure token exists
197        self.test_pending_user()
198        self.user.is_active = False
199        self.user.save()
200        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
201        session = self.client.session
202        session[SESSION_KEY_PLAN] = plan
203        session.save()
204        token: FlowToken = FlowToken.objects.get(user=self.user)
205
206        with patch("authentik.flows.views.executor.FlowExecutorView.cancel", MagicMock()):
207            # Call the executor shell to preseed the session
208            url = reverse(
209                "authentik_api:flow-executor",
210                kwargs={"flow_slug": self.flow.slug},
211            )
212            url_query = urlencode(
213                {
214                    QS_KEY_TOKEN: token.key,
215                }
216            )
217            url += f"?query={url_query}"
218            self.client.get(url)
219
220            # Call the actual executor to get the JSON Response
221            response = self.client.get(
222                reverse(
223                    "authentik_api:flow-executor",
224                    kwargs={"flow_slug": self.flow.slug},
225                )
226            )
227            self.assertStageResponse(response, self.flow, component="ak-stage-consent")
228            response = self.client.post(
229                reverse(
230                    "authentik_api:flow-executor",
231                    kwargs={"flow_slug": self.flow.slug},
232                ),
233                data={
234                    "token": self.get_flow_plan().context[PLAN_CONTEXT_CONSENT_TOKEN],
235                },
236                follow=True,
237            )
238
239            self.assertEqual(response.status_code, 200)
240            self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
241
242            session = self.client.session
243            plan: FlowPlan = session[SESSION_KEY_PLAN]
244            self.assertEqual(plan.context[PLAN_CONTEXT_PENDING_USER], self.user)
245            self.assertTrue(plan.context[PLAN_CONTEXT_PENDING_USER].is_active)

Test with token

def test_token_invalid_user(self):
247    def test_token_invalid_user(self):
248        """Test with token with invalid user"""
249        # Make sure token exists
250        self.test_pending_user()
251        self.user.is_active = False
252        self.user.save()
253        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
254        session = self.client.session
255        session[SESSION_KEY_PLAN] = plan
256        session.save()
257        # Set flow token user to a different user
258        token: FlowToken = FlowToken.objects.get(user=self.user)
259        token.user = create_test_admin_user()
260        token.revoke_on_execution = True
261        token.save()
262
263        with patch("authentik.flows.views.executor.FlowExecutorView.cancel", MagicMock()):
264            # Call the executor shell to preseed the session
265            url = reverse(
266                "authentik_api:flow-executor",
267                kwargs={"flow_slug": self.flow.slug},
268            )
269            url_query = urlencode(
270                {
271                    QS_KEY_TOKEN: token.key,
272                }
273            )
274            url += f"?query={url_query}"
275            self.client.get(url)
276
277            # Call the actual executor to get the JSON Response
278            response = self.client.get(
279                reverse(
280                    "authentik_api:flow-executor",
281                    kwargs={"flow_slug": self.flow.slug},
282                )
283            )
284
285            self.assertEqual(response.status_code, 200)
286            self.assertStageResponse(response, component="ak-stage-access-denied")

Test with token with invalid user

def test_url_no_params(self):
288    def test_url_no_params(self):
289        """Test generation of the URL in the EMail"""
290        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
291        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
292        session = self.client.session
293        session[SESSION_KEY_PLAN] = plan
294        session.save()
295
296        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
297        request = self.factory.get(url)
298        stage_view = EmailStageView(
299            FlowExecutorView(
300                request=request,
301                flow=self.flow,
302            ),
303            request=request,
304        )
305        self.assertEqual(stage_view.get_full_url(), f"http://testserver/if/flow/{self.flow.slug}/")

Test generation of the URL in the EMail

def test_url_our_params(self):
307    def test_url_our_params(self):
308        """Test that all of our parameters are passed to the URL correctly"""
309        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
310        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
311        session = self.client.session
312        session[SESSION_KEY_PLAN] = plan
313        session.save()
314
315        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
316        request = self.factory.get(url)
317        stage_view = EmailStageView(
318            FlowExecutorView(
319                request=request,
320                flow=self.flow,
321            ),
322            request=request,
323        )
324        token = generate_id()
325        self.assertEqual(
326            stage_view.get_full_url(**{QS_KEY_TOKEN: token}),
327            f"http://testserver/if/flow/{self.flow.slug}/?flow_token={token}",
328        )

Test that all of our parameters are passed to the URL correctly

def test_url_existing_params(self):
330    def test_url_existing_params(self):
331        """Test to ensure that URL params are preserved in the URL being sent"""
332        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
333        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
334        session = self.client.session
335        session[SESSION_KEY_PLAN] = plan
336        session.save()
337
338        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
339        url += "?query=" + urlencode({"foo": "bar"})
340        request = self.factory.get(url)
341        stage_view = EmailStageView(
342            FlowExecutorView(
343                request=request,
344                flow=self.flow,
345            ),
346            request=request,
347        )
348        token = generate_id()
349        self.assertEqual(
350            stage_view.get_full_url(**{QS_KEY_TOKEN: token}),
351            f"http://testserver/if/flow/{self.flow.slug}/?foo=bar&flow_token={token}",
352        )

Test to ensure that URL params are preserved in the URL being sent

def test_get_cache_key(self):
354    def test_get_cache_key(self):
355        """Test to ensure that the correct cache key is returned."""
356        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
357        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
358        session = self.client.session
359        session[SESSION_KEY_PLAN] = plan
360        session.save()
361
362        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
363        request = self.factory.post(url)
364        request.user = self.user
365        request.session = session
366
367        executor = FlowExecutorView(request=request, flow=self.flow)
368        executor.plan = plan
369
370        stage_view = EmailStageView(executor, request=request)
371
372        cache_key = stage_view._get_cache_key()
373
374        expected_hash = sha256(self.user.email.lower().encode("utf-8")).hexdigest()
375        expected_cache_key = "goauthentik.io/stages/email/stage/" + expected_hash
376
377        self.assertEqual(cache_key, expected_cache_key)

Test to ensure that the correct cache key is returned.

def test_is_rate_limited_returns_none(self):
379    def test_is_rate_limited_returns_none(self):
380        """Test to ensure None is returned if the request shouldn't be rate limited."""
381        self.stage.recovery_max_attempts = 2
382        self.stage.recovery_cache_timeout = "minutes=10"
383        self.stage.save()
384
385        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
386        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
387        session = self.client.session
388        session[SESSION_KEY_PLAN] = plan
389        session.save()
390
391        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
392        request = self.factory.post(url)
393        request.user = self.user
394        request.session = session
395
396        executor = FlowExecutorView(request=request, flow=self.flow)
397        executor.current_stage = self.stage
398        executor.plan = plan
399
400        stage_view = EmailStageView(executor, request=request)
401
402        result = stage_view._is_rate_limited()
403        self.assertIsNone(result)

Test to ensure None is returned if the request shouldn't be rate limited.

def test_is_rate_limited_returns_remaining_time(self):
405    def test_is_rate_limited_returns_remaining_time(self):
406        """Test to ensure the remaining time is returned if the request
407        should be rate limited."""
408        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
409        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
410        session = self.client.session
411        session[SESSION_KEY_PLAN] = plan
412        session.save()
413
414        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
415        request = self.factory.post(url)
416        request.user = self.user
417        request.session = session
418
419        executor = FlowExecutorView(request=request, flow=self.flow)
420        executor.current_stage = self.stage
421        executor.plan = plan
422
423        stage_view = EmailStageView(executor, request=request)
424
425        test_cases = [
426            # 2 attempts within 2 minutes
427            (2, "seconds=120", 2),
428            # 4 attempts within 5 minutes
429            (4, "minutes=5", 5),
430            # 6 attempts within 5 minutes. Although 299 seconds is less than
431            # 5 minutes, the user is intentionally shown "5 minutes". This is
432            # because an initial rate limiting message like "Try again after 4 minutes"
433            # can be confusing.
434            (6, "seconds=299", 5),
435        ]
436        for test_case in test_cases:
437            max_attempts, cache_timeout, minutes_remaining = test_case
438            with self.subTest(
439                f"Test recovery with {max_attempts} max attempts and "
440                f"{cache_timeout} cache timeout seconds"
441            ):
442                self.stage.recovery_max_attempts = max_attempts
443                self.stage.recovery_cache_timeout = cache_timeout
444                self.stage.save()
445
446                # Simulate multiple requests
447                for _ in range(max_attempts):
448                    stage_view._is_rate_limited()
449
450                # The following request should be rate-limited
451                result = stage_view._is_rate_limited()
452
453                self.assertEqual(result, minutes_remaining)

Test to ensure the remaining time is returned if the request should be rate limited.

def test_challenge_invalid_not_rate_limited(self):
483    def test_challenge_invalid_not_rate_limited(self):
484        """Tests that the request is not rate limited and email is sent."""
485        challenge_response, stage_view, request = self._challenge_invalid_helper()
486
487        with patch.object(stage_view, "send_email") as mock_send_email:
488            result = stage_view.challenge_invalid(challenge_response)
489
490            self.assertEqual(result.status_code, 200)
491
492            mock_send_email.assert_called_once()
493
494            message_list = list(messages.get_messages(request))
495            self.assertEqual(len(message_list), 1)
496            self.assertEqual(
497                "Email Successfully sent.",
498                message_list[-1].message,
499            )

Tests that the request is not rate limited and email is sent.

def test_challenge_invalid_returns_error_if_rate_limited(self):
501    def test_challenge_invalid_returns_error_if_rate_limited(self):
502        """Tests that an error is returned if the request is rate limited. Ensure
503        that an email is not sent."""
504        challenge_response, stage_view, request = self._challenge_invalid_helper()
505
506        # Initial request that shouldn't be rate limited
507        stage_view.challenge_invalid(challenge_response)
508
509        with patch.object(stage_view, "send_email") as mock_send_email:
510            # This next request should be rate limited
511            result = stage_view.challenge_invalid(challenge_response)
512
513            self.assertEqual(result.status_code, 200)
514
515            mock_send_email.assert_not_called()
516
517            message_list = list(messages.get_messages(request))
518            self.assertEqual(len(message_list), 2)
519            self.assertEqual(
520                "Too many account verification attempts. Please try again after 5 minutes.",
521                message_list[-1].message,
522            )

Tests that an error is returned if the request is rate limited. Ensure that an email is not sent.

@patch('authentik.stages.email.models.EmailStage.backend_class', PropertyMock(return_value=EmailBackend))
def test_initial_send_rate_limited_on_flow_restart(self):
524    @patch(
525        "authentik.stages.email.models.EmailStage.backend_class",
526        PropertyMock(return_value=EmailBackend),
527    )
528    def test_initial_send_rate_limited_on_flow_restart(self):
529        """Tests that restarting the flow does not bypass the rate limit
530        applied to resending the email."""
531        self.stage.recovery_max_attempts = 2
532        self.stage.recovery_cache_timeout = "minutes=10"
533        self.stage.save()
534
535        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
536        # Each iteration simulates a full flow restart by seeding a fresh plan,
537        # so the initial email is attempted every time
538        for expected_mails in (1, 2, 2):
539            plan = FlowPlan(
540                flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()]
541            )
542            plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
543            session = self.client.session
544            session[SESSION_KEY_PLAN] = plan
545            session.save()
546
547            response = self.client.get(url)
548            self.assertStageResponse(response, self.flow, component="ak-stage-email")
549            self.assertEqual(len(mail.outbox), expected_mails)

Tests that restarting the flow does not bypass the rate limit applied to resending the email.