authentik.stages.authenticator_email.tests

Test Email Authenticator API

  1"""Test Email Authenticator API"""
  2
  3from datetime import timedelta
  4from unittest.mock import PropertyMock, patch
  5
  6from django.core import mail
  7from django.core.mail.backends.locmem import EmailBackend
  8from django.core.mail.backends.smtp import EmailBackend as SMTPEmailBackend
  9from django.db.models.deletion import ProtectedError
 10from django.db.utils import IntegrityError
 11from django.template.exceptions import TemplateDoesNotExist
 12from django.test import TestCase
 13from django.urls import reverse
 14from django.utils.timezone import now
 15
 16from authentik.core.tests.utils import RequestFactory, create_test_flow, create_test_user
 17from authentik.flows.models import FlowStageBinding
 18from authentik.flows.tests import APIFlowTestCase
 19from authentik.lib.config import CONFIG
 20from authentik.lib.utils.email import mask_email
 21from authentik.stages.authenticator.tests import ThrottlingTestMixin
 22from authentik.stages.authenticator_email.api import (
 23    AuthenticatorEmailStageSerializer,
 24    EmailDeviceSerializer,
 25)
 26from authentik.stages.authenticator_email.models import AuthenticatorEmailStage, EmailDevice
 27from authentik.stages.authenticator_email.stage import PLAN_CONTEXT_EMAIL_DEVICE
 28from authentik.stages.email.utils import TemplateEmailMessage
 29
 30
 31class TestAuthenticatorEmailStage(APIFlowTestCase):
 32    """Test Email Authenticator stage"""
 33
 34    def setUp(self):
 35        super().setUp()
 36        self.flow = create_test_flow()
 37        self.user = create_test_user()
 38        self.user_noemail = create_test_user(email="")
 39        self.stage = AuthenticatorEmailStage.objects.create(
 40            name="email-authenticator",
 41            use_global_settings=True,
 42            from_address="test@authentik.local",
 43            configure_flow=self.flow,
 44            token_expiry="minutes=30",
 45        )  # nosec
 46        self.binding = FlowStageBinding.objects.create(target=self.flow, stage=self.stage, order=0)
 47        self.device = EmailDevice.objects.create(
 48            user=self.user,
 49            stage=self.stage,
 50            email="test@authentik.local",
 51        )
 52        self.client.force_login(self.user)
 53
 54    def test_device_str(self):
 55        """Test string representation of device"""
 56        self.assertEqual(str(self.device), f"Email Device for {self.user.pk}")
 57        # Test unsaved device
 58        unsaved_device = EmailDevice(
 59            user=self.user,
 60            stage=self.stage,
 61            email="test@authentik.local",
 62        )
 63        self.assertEqual(str(unsaved_device), "New Email Device")
 64
 65    def test_stage_str(self):
 66        """Test string representation of stage"""
 67        self.assertEqual(str(self.stage), f"Email Authenticator Stage {self.stage.name}")
 68
 69    def test_stage_deletion_is_protected(self):
 70        """A setup stage with enrolled devices cannot be deleted."""
 71        with self.assertRaises(ProtectedError):
 72            self.stage.delete()
 73
 74        self.assertTrue(AuthenticatorEmailStage.objects.filter(pk=self.stage.pk).exists())
 75        self.assertTrue(EmailDevice.objects.filter(pk=self.device.pk).exists())
 76
 77    def test_token_lifecycle(self):
 78        """Test token generation, validation and expiry"""
 79        # Initially no token
 80        self.assertIsNone(self.device.token)
 81
 82        # Generate token
 83        self.device.generate_token()
 84        token = self.device.token
 85        self.assertIsNotNone(token)
 86        self.assertIsNotNone(self.device.valid_until)
 87        self.assertTrue(self.device.valid_until > now())
 88
 89        # Verify invalid token
 90        self.assertFalse(self.device.verify_token("000000"))
 91
 92        # Verify correct token (should clear token after verification)
 93        self.device.throttle_reset(commit=False)
 94        self.assertTrue(self.device.verify_token(token))
 95        self.assertIsNone(self.device.token)
 96
 97    @patch(
 98        "authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class",
 99        PropertyMock(return_value=EmailBackend),
100    )
101    def test_stage_no_prefill(self):
102        """Test stage without prefilled email"""
103        self.client.force_login(self.user_noemail)
104        response = self.client.get(
105            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
106        )
107        self.assertStageResponse(
108            response,
109            self.flow,
110            self.user_noemail,
111            component="ak-stage-authenticator-email",
112            email_required=True,
113        )
114
115    @patch(
116        "authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class",
117        PropertyMock(return_value=EmailBackend),
118    )
119    def test_stage_submit(self):
120        """Test stage email submission"""
121        # test fail because of existing device
122        response = self.client.get(
123            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
124        )
125        self.assertStageResponse(
126            response,
127            self.flow,
128            self.user,
129            component="ak-stage-access-denied",
130        )
131        self.device.delete()
132        # Initialize the flow
133        response = self.client.get(
134            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
135        )
136        self.assertStageResponse(
137            response,
138            self.flow,
139            self.user,
140            component="ak-stage-authenticator-email",
141            email_required=False,
142        )
143
144        # The user already has an email on file, so the address is established by the flow
145        # (email_required=False); an "email" in the request is ignored and the code is
146        # (re)sent to the established address.
147        response = self.client.post(
148            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
149            data={"component": "ak-stage-authenticator-email", "email": "test@example.com"},
150        )
151        self.assertEqual(response.status_code, 200)
152        self.assertEqual(len(mail.outbox), 2)
153        sent_mail = mail.outbox[1]
154        self.assertEqual(sent_mail.subject, self.stage.subject)
155        self.assertEqual(sent_mail.to, [f"{self.user} <{self.user.email}>"])
156        self.assertNotIn("test@example.com", str(sent_mail.to))
157        # Get from_address from global email config to test if global settings are being used
158        from_address_global = CONFIG.get("email.from")
159        self.assertEqual(sent_mail.from_email, from_address_global)
160
161        self.assertStageResponse(
162            response,
163            self.flow,
164            self.user,
165            component="ak-stage-authenticator-email",
166            response_errors={},
167            email_required=False,
168        )
169
170    @patch(
171        "authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class",
172        PropertyMock(return_value=EmailBackend),
173    )
174    def test_email_uses_established_address(self):
175        """A request-supplied email does not replace an address already set by the flow."""
176        # The user has an email on file, so the flow establishes the address
177        # (email_required=False) and the code is sent there on GET.
178        self.device.delete()
179        response = self.client.get(
180            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
181        )
182        self.assertStageResponse(
183            response,
184            self.flow,
185            self.user,
186            component="ak-stage-authenticator-email",
187            email_required=False,
188        )
189        self.assertEqual(len(mail.outbox), 1)
190        self.assertEqual(mail.outbox[0].to, [f"{self.user} <{self.user.email}>"])
191
192        # A code-less submission that carries a different email must not change where the
193        # code is sent.
194        response = self.client.post(
195            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
196            data={"component": "ak-stage-authenticator-email", "email": "other@example.com"},
197        )
198        self.assertEqual(response.status_code, 200)
199        self.assertEqual(len(mail.outbox), 2)
200        self.assertEqual(mail.outbox[1].to, [f"{self.user} <{self.user.email}>"])
201
202        device = self.get_flow_plan().context[PLAN_CONTEXT_EMAIL_DEVICE]
203        self.assertEqual(device.email, self.user.email)
204
205    def test_email_template(self):
206        """Test email template rendering"""
207        self.device.generate_token()
208        message = self.device._compose_email(RequestFactory().get("/"))
209
210        self.assertIsInstance(message, TemplateEmailMessage)
211        self.assertEqual(message.subject, self.stage.subject)
212        self.assertEqual(message.to, [f"{self.user.name} <{self.device.email}>"])
213        self.assertTrue(self.device.token in message.body)
214
215    def test_duplicate_email(self):
216        """Test attempting to use same email twice"""
217        email = "test2@authentik.local"
218        # First device
219        EmailDevice.objects.create(
220            user=self.user,
221            stage=self.stage,
222            email=email,
223        )
224        # Attempt to create second device with same email
225        with self.assertRaises(IntegrityError):
226            EmailDevice.objects.create(
227                user=self.user,
228                stage=self.stage,
229                email=email,
230            )
231
232    def test_token_expiry(self):
233        """Test token expiration behavior"""
234        self.device.generate_token()
235        token = self.device.token
236        # Set token as expired
237        self.device.valid_until = now() - timedelta(minutes=1)
238        self.device.save()
239        # Verify expired token fails
240        self.assertFalse(self.device.verify_token(token))
241
242    def test_template_errors(self):
243        """Test handling of template errors"""
244        self.stage.template = "{% invalid template %}"
245        with self.assertRaises(TemplateDoesNotExist):
246            self.stage.send(RequestFactory().get("/"), self.device)
247
248    @patch(
249        "authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class",
250        PropertyMock(return_value=EmailBackend),
251    )
252    def test_challenge_response_validation(self):
253        """Test challenge response validation"""
254        # Initialize the flow
255        self.client.force_login(self.user_noemail)
256        response = self.client.get(
257            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
258        )
259
260        # Test missing code and email
261        response = self.client.post(
262            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
263            data={"component": "ak-stage-authenticator-email"},
264        )
265        self.assertStageResponse(
266            response,
267            self.flow,
268            response_errors={"non_field_errors": [{"code": "invalid", "string": "email required"}]},
269        )
270
271        # Test invalid code
272        response = self.client.post(
273            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
274            data={"component": "ak-stage-authenticator-email", "code": "000000"},
275        )
276        self.assertStageResponse(
277            response,
278            self.flow,
279            response_errors={
280                "non_field_errors": [{"code": "invalid", "string": "Code does not match"}]
281            },
282        )
283
284        # Test valid code
285        device = self.device
286        token = device.token
287        response = self.client.post(
288            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
289            data={"component": "ak-stage-authenticator-email", "code": token},
290        )
291        self.assertEqual(response.status_code, 200)
292        self.assertTrue(device.confirmed)
293
294    @patch(
295        "authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class",
296        PropertyMock(return_value=EmailBackend),
297    )
298    def test_challenge_generation(self):
299        """Test challenge generation"""
300        # Test with masked email
301        self.device.delete()
302        response = self.client.get(
303            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
304        )
305        self.assertStageResponse(
306            response,
307            self.flow,
308            self.user,
309            component="ak-stage-authenticator-email",
310            email_required=False,
311        )
312        masked_email = mask_email(self.user.email)
313        self.assertEqual(masked_email, response.json()["email"])
314        self.client.logout()
315
316        # Test without email
317        self.client.force_login(self.user_noemail)
318        response = self.client.get(
319            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
320        )
321        self.assertStageResponse(
322            response,
323            self.flow,
324            self.user_noemail,
325            component="ak-stage-authenticator-email",
326            email_required=True,
327        )
328        self.assertIsNone(response.json()["email"])
329
330    @patch(
331        "authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class",
332        PropertyMock(return_value=EmailBackend),
333    )
334    def test_session_management(self):
335        """Test session device management"""
336        # Test device creation in session
337        # Delete any existing devices for this test
338        EmailDevice.objects.filter(user=self.user).delete()
339
340        response = self.client.get(
341            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
342        )
343        device = self.get_flow_plan().context[PLAN_CONTEXT_EMAIL_DEVICE]
344        self.assertIsInstance(device, EmailDevice)
345        self.assertFalse(device.confirmed)
346        self.assertEqual(device.user, self.user)
347
348        # Test device confirmation and cleanup
349        device.confirmed = True
350        device.email = "new_test@authentik.local"  # Use a different email
351        response = self.client.post(
352            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
353            data={"component": "ak-stage-authenticator-email", "code": device.token},
354        )
355        self.assertEqual(response.status_code, 200)
356
357    def test_model_properties_and_methods(self):
358        """Test model properties"""
359        device = self.device
360        stage = self.stage
361
362        self.assertEqual(stage.serializer, AuthenticatorEmailStageSerializer)
363        self.assertIsInstance(stage.backend, SMTPEmailBackend)
364        self.assertEqual(device.serializer, EmailDeviceSerializer)
365
366        # Test AuthenticatorEmailStage send method
367        self.device.generate_token()
368        # Test EmailDevice _compose_email method
369        message = self.device._compose_email(RequestFactory().get("/"))
370        self.assertIsInstance(message, TemplateEmailMessage)
371        self.assertEqual(message.subject, self.stage.subject)
372        self.assertEqual(message.to, [f"{self.user.name} <{self.device.email}>"])
373        self.assertTrue(self.device.token in message.body)
374
375    @patch(
376        "authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class",
377        PropertyMock(return_value=EmailBackend),
378    )
379    def test_email_tasks(self):
380        # Test AuthenticatorEmailStage send method
381        self.stage.send(RequestFactory().get("/"), self.device)
382        self.assertEqual(len(mail.outbox), 1)
383
384
385class TestEmailDeviceThrottling(ThrottlingTestMixin, TestCase):
386    def setUp(self):
387        super().setUp()
388        flow = create_test_flow()
389        user = create_test_user()
390        stage = AuthenticatorEmailStage.objects.create(
391            name="email-authenticator-throttle",
392            use_global_settings=True,
393            from_address="test@authentik.local",
394            configure_flow=flow,
395            token_expiry="minutes=30",
396        )  # nosec
397        self.device = EmailDevice.objects.create(
398            user=user, stage=stage, email="throttle@authentik.local"
399        )
400        self.device.generate_token()
401
402    def valid_token(self):
403        return self.device.token
404
405    def invalid_token(self):
406        return "000000" if self.device.token != "000000" else "111111"
class TestAuthenticatorEmailStage(authentik.flows.tests.APIFlowTestCase):
 32class TestAuthenticatorEmailStage(APIFlowTestCase):
 33    """Test Email Authenticator stage"""
 34
 35    def setUp(self):
 36        super().setUp()
 37        self.flow = create_test_flow()
 38        self.user = create_test_user()
 39        self.user_noemail = create_test_user(email="")
 40        self.stage = AuthenticatorEmailStage.objects.create(
 41            name="email-authenticator",
 42            use_global_settings=True,
 43            from_address="test@authentik.local",
 44            configure_flow=self.flow,
 45            token_expiry="minutes=30",
 46        )  # nosec
 47        self.binding = FlowStageBinding.objects.create(target=self.flow, stage=self.stage, order=0)
 48        self.device = EmailDevice.objects.create(
 49            user=self.user,
 50            stage=self.stage,
 51            email="test@authentik.local",
 52        )
 53        self.client.force_login(self.user)
 54
 55    def test_device_str(self):
 56        """Test string representation of device"""
 57        self.assertEqual(str(self.device), f"Email Device for {self.user.pk}")
 58        # Test unsaved device
 59        unsaved_device = EmailDevice(
 60            user=self.user,
 61            stage=self.stage,
 62            email="test@authentik.local",
 63        )
 64        self.assertEqual(str(unsaved_device), "New Email Device")
 65
 66    def test_stage_str(self):
 67        """Test string representation of stage"""
 68        self.assertEqual(str(self.stage), f"Email Authenticator Stage {self.stage.name}")
 69
 70    def test_stage_deletion_is_protected(self):
 71        """A setup stage with enrolled devices cannot be deleted."""
 72        with self.assertRaises(ProtectedError):
 73            self.stage.delete()
 74
 75        self.assertTrue(AuthenticatorEmailStage.objects.filter(pk=self.stage.pk).exists())
 76        self.assertTrue(EmailDevice.objects.filter(pk=self.device.pk).exists())
 77
 78    def test_token_lifecycle(self):
 79        """Test token generation, validation and expiry"""
 80        # Initially no token
 81        self.assertIsNone(self.device.token)
 82
 83        # Generate token
 84        self.device.generate_token()
 85        token = self.device.token
 86        self.assertIsNotNone(token)
 87        self.assertIsNotNone(self.device.valid_until)
 88        self.assertTrue(self.device.valid_until > now())
 89
 90        # Verify invalid token
 91        self.assertFalse(self.device.verify_token("000000"))
 92
 93        # Verify correct token (should clear token after verification)
 94        self.device.throttle_reset(commit=False)
 95        self.assertTrue(self.device.verify_token(token))
 96        self.assertIsNone(self.device.token)
 97
 98    @patch(
 99        "authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class",
100        PropertyMock(return_value=EmailBackend),
101    )
102    def test_stage_no_prefill(self):
103        """Test stage without prefilled email"""
104        self.client.force_login(self.user_noemail)
105        response = self.client.get(
106            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
107        )
108        self.assertStageResponse(
109            response,
110            self.flow,
111            self.user_noemail,
112            component="ak-stage-authenticator-email",
113            email_required=True,
114        )
115
116    @patch(
117        "authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class",
118        PropertyMock(return_value=EmailBackend),
119    )
120    def test_stage_submit(self):
121        """Test stage email submission"""
122        # test fail because of existing device
123        response = self.client.get(
124            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
125        )
126        self.assertStageResponse(
127            response,
128            self.flow,
129            self.user,
130            component="ak-stage-access-denied",
131        )
132        self.device.delete()
133        # Initialize the flow
134        response = self.client.get(
135            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
136        )
137        self.assertStageResponse(
138            response,
139            self.flow,
140            self.user,
141            component="ak-stage-authenticator-email",
142            email_required=False,
143        )
144
145        # The user already has an email on file, so the address is established by the flow
146        # (email_required=False); an "email" in the request is ignored and the code is
147        # (re)sent to the established address.
148        response = self.client.post(
149            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
150            data={"component": "ak-stage-authenticator-email", "email": "test@example.com"},
151        )
152        self.assertEqual(response.status_code, 200)
153        self.assertEqual(len(mail.outbox), 2)
154        sent_mail = mail.outbox[1]
155        self.assertEqual(sent_mail.subject, self.stage.subject)
156        self.assertEqual(sent_mail.to, [f"{self.user} <{self.user.email}>"])
157        self.assertNotIn("test@example.com", str(sent_mail.to))
158        # Get from_address from global email config to test if global settings are being used
159        from_address_global = CONFIG.get("email.from")
160        self.assertEqual(sent_mail.from_email, from_address_global)
161
162        self.assertStageResponse(
163            response,
164            self.flow,
165            self.user,
166            component="ak-stage-authenticator-email",
167            response_errors={},
168            email_required=False,
169        )
170
171    @patch(
172        "authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class",
173        PropertyMock(return_value=EmailBackend),
174    )
175    def test_email_uses_established_address(self):
176        """A request-supplied email does not replace an address already set by the flow."""
177        # The user has an email on file, so the flow establishes the address
178        # (email_required=False) and the code is sent there on GET.
179        self.device.delete()
180        response = self.client.get(
181            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
182        )
183        self.assertStageResponse(
184            response,
185            self.flow,
186            self.user,
187            component="ak-stage-authenticator-email",
188            email_required=False,
189        )
190        self.assertEqual(len(mail.outbox), 1)
191        self.assertEqual(mail.outbox[0].to, [f"{self.user} <{self.user.email}>"])
192
193        # A code-less submission that carries a different email must not change where the
194        # code is sent.
195        response = self.client.post(
196            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
197            data={"component": "ak-stage-authenticator-email", "email": "other@example.com"},
198        )
199        self.assertEqual(response.status_code, 200)
200        self.assertEqual(len(mail.outbox), 2)
201        self.assertEqual(mail.outbox[1].to, [f"{self.user} <{self.user.email}>"])
202
203        device = self.get_flow_plan().context[PLAN_CONTEXT_EMAIL_DEVICE]
204        self.assertEqual(device.email, self.user.email)
205
206    def test_email_template(self):
207        """Test email template rendering"""
208        self.device.generate_token()
209        message = self.device._compose_email(RequestFactory().get("/"))
210
211        self.assertIsInstance(message, TemplateEmailMessage)
212        self.assertEqual(message.subject, self.stage.subject)
213        self.assertEqual(message.to, [f"{self.user.name} <{self.device.email}>"])
214        self.assertTrue(self.device.token in message.body)
215
216    def test_duplicate_email(self):
217        """Test attempting to use same email twice"""
218        email = "test2@authentik.local"
219        # First device
220        EmailDevice.objects.create(
221            user=self.user,
222            stage=self.stage,
223            email=email,
224        )
225        # Attempt to create second device with same email
226        with self.assertRaises(IntegrityError):
227            EmailDevice.objects.create(
228                user=self.user,
229                stage=self.stage,
230                email=email,
231            )
232
233    def test_token_expiry(self):
234        """Test token expiration behavior"""
235        self.device.generate_token()
236        token = self.device.token
237        # Set token as expired
238        self.device.valid_until = now() - timedelta(minutes=1)
239        self.device.save()
240        # Verify expired token fails
241        self.assertFalse(self.device.verify_token(token))
242
243    def test_template_errors(self):
244        """Test handling of template errors"""
245        self.stage.template = "{% invalid template %}"
246        with self.assertRaises(TemplateDoesNotExist):
247            self.stage.send(RequestFactory().get("/"), self.device)
248
249    @patch(
250        "authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class",
251        PropertyMock(return_value=EmailBackend),
252    )
253    def test_challenge_response_validation(self):
254        """Test challenge response validation"""
255        # Initialize the flow
256        self.client.force_login(self.user_noemail)
257        response = self.client.get(
258            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
259        )
260
261        # Test missing code and email
262        response = self.client.post(
263            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
264            data={"component": "ak-stage-authenticator-email"},
265        )
266        self.assertStageResponse(
267            response,
268            self.flow,
269            response_errors={"non_field_errors": [{"code": "invalid", "string": "email required"}]},
270        )
271
272        # Test invalid code
273        response = self.client.post(
274            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
275            data={"component": "ak-stage-authenticator-email", "code": "000000"},
276        )
277        self.assertStageResponse(
278            response,
279            self.flow,
280            response_errors={
281                "non_field_errors": [{"code": "invalid", "string": "Code does not match"}]
282            },
283        )
284
285        # Test valid code
286        device = self.device
287        token = device.token
288        response = self.client.post(
289            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
290            data={"component": "ak-stage-authenticator-email", "code": token},
291        )
292        self.assertEqual(response.status_code, 200)
293        self.assertTrue(device.confirmed)
294
295    @patch(
296        "authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class",
297        PropertyMock(return_value=EmailBackend),
298    )
299    def test_challenge_generation(self):
300        """Test challenge generation"""
301        # Test with masked email
302        self.device.delete()
303        response = self.client.get(
304            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
305        )
306        self.assertStageResponse(
307            response,
308            self.flow,
309            self.user,
310            component="ak-stage-authenticator-email",
311            email_required=False,
312        )
313        masked_email = mask_email(self.user.email)
314        self.assertEqual(masked_email, response.json()["email"])
315        self.client.logout()
316
317        # Test without email
318        self.client.force_login(self.user_noemail)
319        response = self.client.get(
320            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
321        )
322        self.assertStageResponse(
323            response,
324            self.flow,
325            self.user_noemail,
326            component="ak-stage-authenticator-email",
327            email_required=True,
328        )
329        self.assertIsNone(response.json()["email"])
330
331    @patch(
332        "authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class",
333        PropertyMock(return_value=EmailBackend),
334    )
335    def test_session_management(self):
336        """Test session device management"""
337        # Test device creation in session
338        # Delete any existing devices for this test
339        EmailDevice.objects.filter(user=self.user).delete()
340
341        response = self.client.get(
342            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
343        )
344        device = self.get_flow_plan().context[PLAN_CONTEXT_EMAIL_DEVICE]
345        self.assertIsInstance(device, EmailDevice)
346        self.assertFalse(device.confirmed)
347        self.assertEqual(device.user, self.user)
348
349        # Test device confirmation and cleanup
350        device.confirmed = True
351        device.email = "new_test@authentik.local"  # Use a different email
352        response = self.client.post(
353            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
354            data={"component": "ak-stage-authenticator-email", "code": device.token},
355        )
356        self.assertEqual(response.status_code, 200)
357
358    def test_model_properties_and_methods(self):
359        """Test model properties"""
360        device = self.device
361        stage = self.stage
362
363        self.assertEqual(stage.serializer, AuthenticatorEmailStageSerializer)
364        self.assertIsInstance(stage.backend, SMTPEmailBackend)
365        self.assertEqual(device.serializer, EmailDeviceSerializer)
366
367        # Test AuthenticatorEmailStage send method
368        self.device.generate_token()
369        # Test EmailDevice _compose_email method
370        message = self.device._compose_email(RequestFactory().get("/"))
371        self.assertIsInstance(message, TemplateEmailMessage)
372        self.assertEqual(message.subject, self.stage.subject)
373        self.assertEqual(message.to, [f"{self.user.name} <{self.device.email}>"])
374        self.assertTrue(self.device.token in message.body)
375
376    @patch(
377        "authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class",
378        PropertyMock(return_value=EmailBackend),
379    )
380    def test_email_tasks(self):
381        # Test AuthenticatorEmailStage send method
382        self.stage.send(RequestFactory().get("/"), self.device)
383        self.assertEqual(len(mail.outbox), 1)

Test Email Authenticator stage

def setUp(self):
35    def setUp(self):
36        super().setUp()
37        self.flow = create_test_flow()
38        self.user = create_test_user()
39        self.user_noemail = create_test_user(email="")
40        self.stage = AuthenticatorEmailStage.objects.create(
41            name="email-authenticator",
42            use_global_settings=True,
43            from_address="test@authentik.local",
44            configure_flow=self.flow,
45            token_expiry="minutes=30",
46        )  # nosec
47        self.binding = FlowStageBinding.objects.create(target=self.flow, stage=self.stage, order=0)
48        self.device = EmailDevice.objects.create(
49            user=self.user,
50            stage=self.stage,
51            email="test@authentik.local",
52        )
53        self.client.force_login(self.user)

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

def test_device_str(self):
55    def test_device_str(self):
56        """Test string representation of device"""
57        self.assertEqual(str(self.device), f"Email Device for {self.user.pk}")
58        # Test unsaved device
59        unsaved_device = EmailDevice(
60            user=self.user,
61            stage=self.stage,
62            email="test@authentik.local",
63        )
64        self.assertEqual(str(unsaved_device), "New Email Device")

Test string representation of device

def test_stage_str(self):
66    def test_stage_str(self):
67        """Test string representation of stage"""
68        self.assertEqual(str(self.stage), f"Email Authenticator Stage {self.stage.name}")

Test string representation of stage

def test_stage_deletion_is_protected(self):
70    def test_stage_deletion_is_protected(self):
71        """A setup stage with enrolled devices cannot be deleted."""
72        with self.assertRaises(ProtectedError):
73            self.stage.delete()
74
75        self.assertTrue(AuthenticatorEmailStage.objects.filter(pk=self.stage.pk).exists())
76        self.assertTrue(EmailDevice.objects.filter(pk=self.device.pk).exists())

A setup stage with enrolled devices cannot be deleted.

def test_token_lifecycle(self):
78    def test_token_lifecycle(self):
79        """Test token generation, validation and expiry"""
80        # Initially no token
81        self.assertIsNone(self.device.token)
82
83        # Generate token
84        self.device.generate_token()
85        token = self.device.token
86        self.assertIsNotNone(token)
87        self.assertIsNotNone(self.device.valid_until)
88        self.assertTrue(self.device.valid_until > now())
89
90        # Verify invalid token
91        self.assertFalse(self.device.verify_token("000000"))
92
93        # Verify correct token (should clear token after verification)
94        self.device.throttle_reset(commit=False)
95        self.assertTrue(self.device.verify_token(token))
96        self.assertIsNone(self.device.token)

Test token generation, validation and expiry

@patch('authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class', PropertyMock(return_value=EmailBackend))
def test_stage_no_prefill(self):
 98    @patch(
 99        "authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class",
100        PropertyMock(return_value=EmailBackend),
101    )
102    def test_stage_no_prefill(self):
103        """Test stage without prefilled email"""
104        self.client.force_login(self.user_noemail)
105        response = self.client.get(
106            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
107        )
108        self.assertStageResponse(
109            response,
110            self.flow,
111            self.user_noemail,
112            component="ak-stage-authenticator-email",
113            email_required=True,
114        )

Test stage without prefilled email

@patch('authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class', PropertyMock(return_value=EmailBackend))
def test_stage_submit(self):
116    @patch(
117        "authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class",
118        PropertyMock(return_value=EmailBackend),
119    )
120    def test_stage_submit(self):
121        """Test stage email submission"""
122        # test fail because of existing device
123        response = self.client.get(
124            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
125        )
126        self.assertStageResponse(
127            response,
128            self.flow,
129            self.user,
130            component="ak-stage-access-denied",
131        )
132        self.device.delete()
133        # Initialize the flow
134        response = self.client.get(
135            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
136        )
137        self.assertStageResponse(
138            response,
139            self.flow,
140            self.user,
141            component="ak-stage-authenticator-email",
142            email_required=False,
143        )
144
145        # The user already has an email on file, so the address is established by the flow
146        # (email_required=False); an "email" in the request is ignored and the code is
147        # (re)sent to the established address.
148        response = self.client.post(
149            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
150            data={"component": "ak-stage-authenticator-email", "email": "test@example.com"},
151        )
152        self.assertEqual(response.status_code, 200)
153        self.assertEqual(len(mail.outbox), 2)
154        sent_mail = mail.outbox[1]
155        self.assertEqual(sent_mail.subject, self.stage.subject)
156        self.assertEqual(sent_mail.to, [f"{self.user} <{self.user.email}>"])
157        self.assertNotIn("test@example.com", str(sent_mail.to))
158        # Get from_address from global email config to test if global settings are being used
159        from_address_global = CONFIG.get("email.from")
160        self.assertEqual(sent_mail.from_email, from_address_global)
161
162        self.assertStageResponse(
163            response,
164            self.flow,
165            self.user,
166            component="ak-stage-authenticator-email",
167            response_errors={},
168            email_required=False,
169        )

Test stage email submission

@patch('authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class', PropertyMock(return_value=EmailBackend))
def test_email_uses_established_address(self):
171    @patch(
172        "authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class",
173        PropertyMock(return_value=EmailBackend),
174    )
175    def test_email_uses_established_address(self):
176        """A request-supplied email does not replace an address already set by the flow."""
177        # The user has an email on file, so the flow establishes the address
178        # (email_required=False) and the code is sent there on GET.
179        self.device.delete()
180        response = self.client.get(
181            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
182        )
183        self.assertStageResponse(
184            response,
185            self.flow,
186            self.user,
187            component="ak-stage-authenticator-email",
188            email_required=False,
189        )
190        self.assertEqual(len(mail.outbox), 1)
191        self.assertEqual(mail.outbox[0].to, [f"{self.user} <{self.user.email}>"])
192
193        # A code-less submission that carries a different email must not change where the
194        # code is sent.
195        response = self.client.post(
196            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
197            data={"component": "ak-stage-authenticator-email", "email": "other@example.com"},
198        )
199        self.assertEqual(response.status_code, 200)
200        self.assertEqual(len(mail.outbox), 2)
201        self.assertEqual(mail.outbox[1].to, [f"{self.user} <{self.user.email}>"])
202
203        device = self.get_flow_plan().context[PLAN_CONTEXT_EMAIL_DEVICE]
204        self.assertEqual(device.email, self.user.email)

A request-supplied email does not replace an address already set by the flow.

def test_email_template(self):
206    def test_email_template(self):
207        """Test email template rendering"""
208        self.device.generate_token()
209        message = self.device._compose_email(RequestFactory().get("/"))
210
211        self.assertIsInstance(message, TemplateEmailMessage)
212        self.assertEqual(message.subject, self.stage.subject)
213        self.assertEqual(message.to, [f"{self.user.name} <{self.device.email}>"])
214        self.assertTrue(self.device.token in message.body)

Test email template rendering

def test_duplicate_email(self):
216    def test_duplicate_email(self):
217        """Test attempting to use same email twice"""
218        email = "test2@authentik.local"
219        # First device
220        EmailDevice.objects.create(
221            user=self.user,
222            stage=self.stage,
223            email=email,
224        )
225        # Attempt to create second device with same email
226        with self.assertRaises(IntegrityError):
227            EmailDevice.objects.create(
228                user=self.user,
229                stage=self.stage,
230                email=email,
231            )

Test attempting to use same email twice

def test_token_expiry(self):
233    def test_token_expiry(self):
234        """Test token expiration behavior"""
235        self.device.generate_token()
236        token = self.device.token
237        # Set token as expired
238        self.device.valid_until = now() - timedelta(minutes=1)
239        self.device.save()
240        # Verify expired token fails
241        self.assertFalse(self.device.verify_token(token))

Test token expiration behavior

def test_template_errors(self):
243    def test_template_errors(self):
244        """Test handling of template errors"""
245        self.stage.template = "{% invalid template %}"
246        with self.assertRaises(TemplateDoesNotExist):
247            self.stage.send(RequestFactory().get("/"), self.device)

Test handling of template errors

@patch('authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class', PropertyMock(return_value=EmailBackend))
def test_challenge_response_validation(self):
249    @patch(
250        "authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class",
251        PropertyMock(return_value=EmailBackend),
252    )
253    def test_challenge_response_validation(self):
254        """Test challenge response validation"""
255        # Initialize the flow
256        self.client.force_login(self.user_noemail)
257        response = self.client.get(
258            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
259        )
260
261        # Test missing code and email
262        response = self.client.post(
263            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
264            data={"component": "ak-stage-authenticator-email"},
265        )
266        self.assertStageResponse(
267            response,
268            self.flow,
269            response_errors={"non_field_errors": [{"code": "invalid", "string": "email required"}]},
270        )
271
272        # Test invalid code
273        response = self.client.post(
274            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
275            data={"component": "ak-stage-authenticator-email", "code": "000000"},
276        )
277        self.assertStageResponse(
278            response,
279            self.flow,
280            response_errors={
281                "non_field_errors": [{"code": "invalid", "string": "Code does not match"}]
282            },
283        )
284
285        # Test valid code
286        device = self.device
287        token = device.token
288        response = self.client.post(
289            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
290            data={"component": "ak-stage-authenticator-email", "code": token},
291        )
292        self.assertEqual(response.status_code, 200)
293        self.assertTrue(device.confirmed)

Test challenge response validation

@patch('authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class', PropertyMock(return_value=EmailBackend))
def test_challenge_generation(self):
295    @patch(
296        "authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class",
297        PropertyMock(return_value=EmailBackend),
298    )
299    def test_challenge_generation(self):
300        """Test challenge generation"""
301        # Test with masked email
302        self.device.delete()
303        response = self.client.get(
304            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
305        )
306        self.assertStageResponse(
307            response,
308            self.flow,
309            self.user,
310            component="ak-stage-authenticator-email",
311            email_required=False,
312        )
313        masked_email = mask_email(self.user.email)
314        self.assertEqual(masked_email, response.json()["email"])
315        self.client.logout()
316
317        # Test without email
318        self.client.force_login(self.user_noemail)
319        response = self.client.get(
320            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
321        )
322        self.assertStageResponse(
323            response,
324            self.flow,
325            self.user_noemail,
326            component="ak-stage-authenticator-email",
327            email_required=True,
328        )
329        self.assertIsNone(response.json()["email"])

Test challenge generation

@patch('authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class', PropertyMock(return_value=EmailBackend))
def test_session_management(self):
331    @patch(
332        "authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class",
333        PropertyMock(return_value=EmailBackend),
334    )
335    def test_session_management(self):
336        """Test session device management"""
337        # Test device creation in session
338        # Delete any existing devices for this test
339        EmailDevice.objects.filter(user=self.user).delete()
340
341        response = self.client.get(
342            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
343        )
344        device = self.get_flow_plan().context[PLAN_CONTEXT_EMAIL_DEVICE]
345        self.assertIsInstance(device, EmailDevice)
346        self.assertFalse(device.confirmed)
347        self.assertEqual(device.user, self.user)
348
349        # Test device confirmation and cleanup
350        device.confirmed = True
351        device.email = "new_test@authentik.local"  # Use a different email
352        response = self.client.post(
353            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
354            data={"component": "ak-stage-authenticator-email", "code": device.token},
355        )
356        self.assertEqual(response.status_code, 200)

Test session device management

def test_model_properties_and_methods(self):
358    def test_model_properties_and_methods(self):
359        """Test model properties"""
360        device = self.device
361        stage = self.stage
362
363        self.assertEqual(stage.serializer, AuthenticatorEmailStageSerializer)
364        self.assertIsInstance(stage.backend, SMTPEmailBackend)
365        self.assertEqual(device.serializer, EmailDeviceSerializer)
366
367        # Test AuthenticatorEmailStage send method
368        self.device.generate_token()
369        # Test EmailDevice _compose_email method
370        message = self.device._compose_email(RequestFactory().get("/"))
371        self.assertIsInstance(message, TemplateEmailMessage)
372        self.assertEqual(message.subject, self.stage.subject)
373        self.assertEqual(message.to, [f"{self.user.name} <{self.device.email}>"])
374        self.assertTrue(self.device.token in message.body)

Test model properties

@patch('authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class', PropertyMock(return_value=EmailBackend))
def test_email_tasks(self):
376    @patch(
377        "authentik.stages.authenticator_email.models.AuthenticatorEmailStage.backend_class",
378        PropertyMock(return_value=EmailBackend),
379    )
380    def test_email_tasks(self):
381        # Test AuthenticatorEmailStage send method
382        self.stage.send(RequestFactory().get("/"), self.device)
383        self.assertEqual(len(mail.outbox), 1)
class TestEmailDeviceThrottling(authentik.stages.authenticator.tests.ThrottlingTestMixin, django.test.testcases.TestCase):
386class TestEmailDeviceThrottling(ThrottlingTestMixin, TestCase):
387    def setUp(self):
388        super().setUp()
389        flow = create_test_flow()
390        user = create_test_user()
391        stage = AuthenticatorEmailStage.objects.create(
392            name="email-authenticator-throttle",
393            use_global_settings=True,
394            from_address="test@authentik.local",
395            configure_flow=flow,
396            token_expiry="minutes=30",
397        )  # nosec
398        self.device = EmailDevice.objects.create(
399            user=user, stage=stage, email="throttle@authentik.local"
400        )
401        self.device.generate_token()
402
403    def valid_token(self):
404        return self.device.token
405
406    def invalid_token(self):
407        return "000000" if self.device.token != "000000" else "111111"

Generic tests for throttled devices.

Any concrete device implementation that uses throttling should define a TestCase subclass that includes this as a base class. This will help verify a correct integration of ThrottlingMixin.

Subclasses are responsible for populating self.device with a device to test as well as implementing methods to generate tokens to test with.

def setUp(self):
387    def setUp(self):
388        super().setUp()
389        flow = create_test_flow()
390        user = create_test_user()
391        stage = AuthenticatorEmailStage.objects.create(
392            name="email-authenticator-throttle",
393            use_global_settings=True,
394            from_address="test@authentik.local",
395            configure_flow=flow,
396            token_expiry="minutes=30",
397        )  # nosec
398        self.device = EmailDevice.objects.create(
399            user=user, stage=stage, email="throttle@authentik.local"
400        )
401        self.device.generate_token()

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

def valid_token(self):
403    def valid_token(self):
404        return self.device.token

Returns a valid token to pass to our device under test.

def invalid_token(self):
406    def invalid_token(self):
407        return "000000" if self.device.token != "000000" else "111111"

Returns an invalid token to pass to our device under test.