authentik.stages.authenticator_validate.tests.test_email
Test validator stage for Email devices
1"""Test validator stage for Email devices""" 2 3from unittest.mock import MagicMock, patch 4 5from django.template.exceptions import TemplateSyntaxError 6from django.test.client import RequestFactory 7from django.urls.base import reverse 8from freezegun import freeze_time 9 10from authentik.core.tests.utils import create_test_admin_user, create_test_flow 11from authentik.events.models import Event, EventAction 12from authentik.flows.models import FlowStageBinding, NotConfiguredAction 13from authentik.flows.tests import APIFlowTestCase 14from authentik.lib.generators import generate_id 15from authentik.lib.utils.email import mask_email 16from authentik.stages.authenticator.oath import TOTP 17from authentik.stages.authenticator_email.models import AuthenticatorEmailStage, EmailDevice 18from authentik.stages.authenticator_totp.models import TOTPDevice 19from authentik.stages.authenticator_validate.models import AuthenticatorValidateStage, DeviceClasses 20from authentik.stages.identification.models import IdentificationStage, UserFields 21 22 23class AuthenticatorValidateStageEmailTests(APIFlowTestCase): 24 """Test validator stage for Email devices""" 25 26 def setUp(self) -> None: 27 self.user = create_test_admin_user() 28 self.request_factory = RequestFactory() 29 # Create email authenticator stage 30 self.stage = AuthenticatorEmailStage.objects.create( 31 name="email-authenticator", 32 use_global_settings=True, 33 from_address="test@authentik.local", 34 ) 35 # Create identification stage 36 self.ident_stage = IdentificationStage.objects.create( 37 name=generate_id(), 38 user_fields=[UserFields.USERNAME], 39 ) 40 # Create validation stage 41 self.validate_stage = AuthenticatorValidateStage.objects.create( 42 name=generate_id(), 43 device_classes=[DeviceClasses.EMAIL], 44 ) 45 # Create flow with both stages 46 self.flow = create_test_flow() 47 FlowStageBinding.objects.create(target=self.flow, stage=self.ident_stage, order=0) 48 FlowStageBinding.objects.create(target=self.flow, stage=self.validate_stage, order=1) 49 50 def _identify_user(self): 51 """Helper to identify user in flow""" 52 response = self.client.post( 53 reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}), 54 {"uid_field": self.user.username}, 55 follow=True, 56 ) 57 self.assertEqual(response.status_code, 200) 58 return response 59 60 def _send_challenge(self, device): 61 """Helper to send challenge for device""" 62 response = self.client.post( 63 reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}), 64 { 65 "component": "ak-stage-authenticator-validate", 66 "selected_challenge": { 67 "device_class": "email", 68 "device_uid": str(device.pk), 69 "challenge": {}, 70 "last_used": device.last_used.isoformat() if device.last_used else None, 71 }, 72 }, 73 ) 74 self.assertEqual(response.status_code, 200) 75 return response 76 77 def test_happy_path(self): 78 """Test validator stage with valid code""" 79 # Create a device for our user 80 device = EmailDevice.objects.create( 81 user=self.user, 82 confirmed=True, 83 stage=self.stage, 84 email="xx@0.co", 85 ) # Short email for testing purposes 86 87 # First identify the user 88 self._identify_user() 89 90 # Send the challenge 91 response = self._send_challenge(device) 92 response_data = self.assertStageResponse( 93 response, 94 flow=self.flow, 95 component="ak-stage-authenticator-validate", 96 ) 97 98 # Get the device challenge from the response and verify it matches 99 device_challenge = response_data["device_challenges"][0] 100 self.assertEqual(device_challenge["device_class"], "email") 101 self.assertEqual(device_challenge["device_uid"], str(device.pk)) 102 self.assertEqual(device_challenge["challenge"], {"email": mask_email(device.email)}) 103 104 # Generate a token for the device 105 device.generate_token() 106 107 # Submit the valid code 108 response = self.client.post( 109 reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}), 110 {"component": "ak-stage-authenticator-validate", "code": device.token}, 111 ) 112 # Should redirect to root since this is the last stage 113 self.assertStageRedirects(response, "/") 114 115 @patch( 116 "authentik.stages.email.utils.render_to_string", 117 MagicMock(side_effect=TemplateSyntaxError("invalid")), 118 ) 119 def test_template_syntax_error(self): 120 """Test that a broken email template denies the flow and logs a configuration error""" 121 device = EmailDevice.objects.create( 122 user=self.user, 123 confirmed=True, 124 stage=self.stage, 125 email="xx@0.co", 126 ) 127 self._identify_user() 128 response = self._send_challenge(device) 129 self.assertStageResponse( 130 response, 131 flow=self.flow, 132 component="ak-stage-access-denied", 133 ) 134 self.assertTrue( 135 Event.objects.filter( 136 action=EventAction.CONFIGURATION_ERROR, 137 context__message="Exception occurred while rendering E-mail template", 138 ).exists() 139 ) 140 141 def test_no_device(self): 142 """Test validator stage without configured device""" 143 configuration_stage = AuthenticatorEmailStage.objects.create( 144 name=generate_id(), 145 use_global_settings=True, 146 from_address="test@authentik.local", 147 ) 148 stage = AuthenticatorValidateStage.objects.create( 149 name=generate_id(), 150 not_configured_action=NotConfiguredAction.CONFIGURE, 151 device_classes=[DeviceClasses.EMAIL], 152 ) 153 stage.configuration_stages.set([configuration_stage]) 154 flow = create_test_flow() 155 FlowStageBinding.objects.create(target=flow, stage=stage, order=2) 156 157 response = self.client.post( 158 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 159 {"component": "ak-stage-authenticator-validate"}, 160 ) 161 self.assertEqual(response.status_code, 200) 162 response_data = self.assertStageResponse( 163 response, 164 flow=flow, 165 component="ak-stage-authenticator-validate", 166 ) 167 self.assertEqual(response_data["configuration_stages"], []) 168 self.assertEqual(response_data["device_challenges"], []) 169 self.assertEqual( 170 response_data["response_errors"], 171 {"non_field_errors": [{"code": "invalid", "string": "Empty response"}]}, 172 ) 173 174 @freeze_time("2026-10-08 12:00:00") 175 def test_email_only_rejects_totp(self): 176 """An enrolled TOTP device cannot satisfy an email-only stage.""" 177 device = EmailDevice.objects.create( 178 user=self.user, stage=self.stage, email="test@authentik.local" 179 ) 180 totp_device = TOTPDevice.objects.create(user=self.user) 181 totp_code = str(TOTP(totp_device.bin_key).token()).zfill(totp_device.digits) 182 self.validate_stage.email_otp_throttling_factor = 0 183 self.validate_stage.save() 184 185 self._identify_user() 186 self._send_challenge(device) 187 device.refresh_from_db() 188 # Ensure the email and TOTP codes cannot coincidentally match. 189 device.token = "111111" if totp_code != "111111" else "222222" 190 device.save() 191 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}) 192 response = self.client.post(url, {"code": totp_code}) 193 data = self.assertStageResponse( 194 response, flow=self.flow, component="ak-stage-authenticator-validate" 195 ) 196 self.assertIn("code", data["response_errors"]) 197 totp_device.refresh_from_db() 198 self.assertEqual(totp_device.last_t, -1) 199 self.assertEqual(totp_device.throttling_failure_count, 0) 200 self.assertIsNone(totp_device.last_used) 201 202 response = self.client.post(url, {"code": device.token}) 203 self.assertStageRedirects(response, "/") 204 205 def test_invalid_code(self): 206 """Test validator stage with invalid code""" 207 # Create a device for our user 208 device = EmailDevice.objects.create( 209 user=self.user, 210 confirmed=True, 211 stage=self.stage, 212 email="test@authentik.local", 213 ) 214 215 # First identify the user 216 self._identify_user() 217 218 # Send the challenge 219 self._send_challenge(device) 220 221 # Generate a token for the device 222 device.generate_token() 223 224 # Try invalid code and verify error message 225 response = self.client.post( 226 reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}), 227 {"component": "ak-stage-authenticator-validate", "code": "invalid"}, 228 ) 229 response_data = self.assertStageResponse( 230 response, 231 flow=self.flow, 232 component="ak-stage-authenticator-validate", 233 ) 234 self.assertEqual( 235 response_data["response_errors"], 236 { 237 "code": [ 238 { 239 "code": "invalid", 240 "string": ( 241 "Invalid Token. Please ensure the time on your device " 242 "is accurate and try again." 243 ), 244 } 245 ], 246 }, 247 )
24class AuthenticatorValidateStageEmailTests(APIFlowTestCase): 25 """Test validator stage for Email devices""" 26 27 def setUp(self) -> None: 28 self.user = create_test_admin_user() 29 self.request_factory = RequestFactory() 30 # Create email authenticator stage 31 self.stage = AuthenticatorEmailStage.objects.create( 32 name="email-authenticator", 33 use_global_settings=True, 34 from_address="test@authentik.local", 35 ) 36 # Create identification stage 37 self.ident_stage = IdentificationStage.objects.create( 38 name=generate_id(), 39 user_fields=[UserFields.USERNAME], 40 ) 41 # Create validation stage 42 self.validate_stage = AuthenticatorValidateStage.objects.create( 43 name=generate_id(), 44 device_classes=[DeviceClasses.EMAIL], 45 ) 46 # Create flow with both stages 47 self.flow = create_test_flow() 48 FlowStageBinding.objects.create(target=self.flow, stage=self.ident_stage, order=0) 49 FlowStageBinding.objects.create(target=self.flow, stage=self.validate_stage, order=1) 50 51 def _identify_user(self): 52 """Helper to identify user in flow""" 53 response = self.client.post( 54 reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}), 55 {"uid_field": self.user.username}, 56 follow=True, 57 ) 58 self.assertEqual(response.status_code, 200) 59 return response 60 61 def _send_challenge(self, device): 62 """Helper to send challenge for device""" 63 response = self.client.post( 64 reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}), 65 { 66 "component": "ak-stage-authenticator-validate", 67 "selected_challenge": { 68 "device_class": "email", 69 "device_uid": str(device.pk), 70 "challenge": {}, 71 "last_used": device.last_used.isoformat() if device.last_used else None, 72 }, 73 }, 74 ) 75 self.assertEqual(response.status_code, 200) 76 return response 77 78 def test_happy_path(self): 79 """Test validator stage with valid code""" 80 # Create a device for our user 81 device = EmailDevice.objects.create( 82 user=self.user, 83 confirmed=True, 84 stage=self.stage, 85 email="xx@0.co", 86 ) # Short email for testing purposes 87 88 # First identify the user 89 self._identify_user() 90 91 # Send the challenge 92 response = self._send_challenge(device) 93 response_data = self.assertStageResponse( 94 response, 95 flow=self.flow, 96 component="ak-stage-authenticator-validate", 97 ) 98 99 # Get the device challenge from the response and verify it matches 100 device_challenge = response_data["device_challenges"][0] 101 self.assertEqual(device_challenge["device_class"], "email") 102 self.assertEqual(device_challenge["device_uid"], str(device.pk)) 103 self.assertEqual(device_challenge["challenge"], {"email": mask_email(device.email)}) 104 105 # Generate a token for the device 106 device.generate_token() 107 108 # Submit the valid code 109 response = self.client.post( 110 reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}), 111 {"component": "ak-stage-authenticator-validate", "code": device.token}, 112 ) 113 # Should redirect to root since this is the last stage 114 self.assertStageRedirects(response, "/") 115 116 @patch( 117 "authentik.stages.email.utils.render_to_string", 118 MagicMock(side_effect=TemplateSyntaxError("invalid")), 119 ) 120 def test_template_syntax_error(self): 121 """Test that a broken email template denies the flow and logs a configuration error""" 122 device = EmailDevice.objects.create( 123 user=self.user, 124 confirmed=True, 125 stage=self.stage, 126 email="xx@0.co", 127 ) 128 self._identify_user() 129 response = self._send_challenge(device) 130 self.assertStageResponse( 131 response, 132 flow=self.flow, 133 component="ak-stage-access-denied", 134 ) 135 self.assertTrue( 136 Event.objects.filter( 137 action=EventAction.CONFIGURATION_ERROR, 138 context__message="Exception occurred while rendering E-mail template", 139 ).exists() 140 ) 141 142 def test_no_device(self): 143 """Test validator stage without configured device""" 144 configuration_stage = AuthenticatorEmailStage.objects.create( 145 name=generate_id(), 146 use_global_settings=True, 147 from_address="test@authentik.local", 148 ) 149 stage = AuthenticatorValidateStage.objects.create( 150 name=generate_id(), 151 not_configured_action=NotConfiguredAction.CONFIGURE, 152 device_classes=[DeviceClasses.EMAIL], 153 ) 154 stage.configuration_stages.set([configuration_stage]) 155 flow = create_test_flow() 156 FlowStageBinding.objects.create(target=flow, stage=stage, order=2) 157 158 response = self.client.post( 159 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 160 {"component": "ak-stage-authenticator-validate"}, 161 ) 162 self.assertEqual(response.status_code, 200) 163 response_data = self.assertStageResponse( 164 response, 165 flow=flow, 166 component="ak-stage-authenticator-validate", 167 ) 168 self.assertEqual(response_data["configuration_stages"], []) 169 self.assertEqual(response_data["device_challenges"], []) 170 self.assertEqual( 171 response_data["response_errors"], 172 {"non_field_errors": [{"code": "invalid", "string": "Empty response"}]}, 173 ) 174 175 @freeze_time("2026-10-08 12:00:00") 176 def test_email_only_rejects_totp(self): 177 """An enrolled TOTP device cannot satisfy an email-only stage.""" 178 device = EmailDevice.objects.create( 179 user=self.user, stage=self.stage, email="test@authentik.local" 180 ) 181 totp_device = TOTPDevice.objects.create(user=self.user) 182 totp_code = str(TOTP(totp_device.bin_key).token()).zfill(totp_device.digits) 183 self.validate_stage.email_otp_throttling_factor = 0 184 self.validate_stage.save() 185 186 self._identify_user() 187 self._send_challenge(device) 188 device.refresh_from_db() 189 # Ensure the email and TOTP codes cannot coincidentally match. 190 device.token = "111111" if totp_code != "111111" else "222222" 191 device.save() 192 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}) 193 response = self.client.post(url, {"code": totp_code}) 194 data = self.assertStageResponse( 195 response, flow=self.flow, component="ak-stage-authenticator-validate" 196 ) 197 self.assertIn("code", data["response_errors"]) 198 totp_device.refresh_from_db() 199 self.assertEqual(totp_device.last_t, -1) 200 self.assertEqual(totp_device.throttling_failure_count, 0) 201 self.assertIsNone(totp_device.last_used) 202 203 response = self.client.post(url, {"code": device.token}) 204 self.assertStageRedirects(response, "/") 205 206 def test_invalid_code(self): 207 """Test validator stage with invalid code""" 208 # Create a device for our user 209 device = EmailDevice.objects.create( 210 user=self.user, 211 confirmed=True, 212 stage=self.stage, 213 email="test@authentik.local", 214 ) 215 216 # First identify the user 217 self._identify_user() 218 219 # Send the challenge 220 self._send_challenge(device) 221 222 # Generate a token for the device 223 device.generate_token() 224 225 # Try invalid code and verify error message 226 response = self.client.post( 227 reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}), 228 {"component": "ak-stage-authenticator-validate", "code": "invalid"}, 229 ) 230 response_data = self.assertStageResponse( 231 response, 232 flow=self.flow, 233 component="ak-stage-authenticator-validate", 234 ) 235 self.assertEqual( 236 response_data["response_errors"], 237 { 238 "code": [ 239 { 240 "code": "invalid", 241 "string": ( 242 "Invalid Token. Please ensure the time on your device " 243 "is accurate and try again." 244 ), 245 } 246 ], 247 }, 248 )
Test validator stage for Email devices
def
setUp(self) -> None:
27 def setUp(self) -> None: 28 self.user = create_test_admin_user() 29 self.request_factory = RequestFactory() 30 # Create email authenticator stage 31 self.stage = AuthenticatorEmailStage.objects.create( 32 name="email-authenticator", 33 use_global_settings=True, 34 from_address="test@authentik.local", 35 ) 36 # Create identification stage 37 self.ident_stage = IdentificationStage.objects.create( 38 name=generate_id(), 39 user_fields=[UserFields.USERNAME], 40 ) 41 # Create validation stage 42 self.validate_stage = AuthenticatorValidateStage.objects.create( 43 name=generate_id(), 44 device_classes=[DeviceClasses.EMAIL], 45 ) 46 # Create flow with both stages 47 self.flow = create_test_flow() 48 FlowStageBinding.objects.create(target=self.flow, stage=self.ident_stage, order=0) 49 FlowStageBinding.objects.create(target=self.flow, stage=self.validate_stage, order=1)
Hook method for setting up the test fixture before exercising it.
def
test_happy_path(self):
78 def test_happy_path(self): 79 """Test validator stage with valid code""" 80 # Create a device for our user 81 device = EmailDevice.objects.create( 82 user=self.user, 83 confirmed=True, 84 stage=self.stage, 85 email="xx@0.co", 86 ) # Short email for testing purposes 87 88 # First identify the user 89 self._identify_user() 90 91 # Send the challenge 92 response = self._send_challenge(device) 93 response_data = self.assertStageResponse( 94 response, 95 flow=self.flow, 96 component="ak-stage-authenticator-validate", 97 ) 98 99 # Get the device challenge from the response and verify it matches 100 device_challenge = response_data["device_challenges"][0] 101 self.assertEqual(device_challenge["device_class"], "email") 102 self.assertEqual(device_challenge["device_uid"], str(device.pk)) 103 self.assertEqual(device_challenge["challenge"], {"email": mask_email(device.email)}) 104 105 # Generate a token for the device 106 device.generate_token() 107 108 # Submit the valid code 109 response = self.client.post( 110 reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}), 111 {"component": "ak-stage-authenticator-validate", "code": device.token}, 112 ) 113 # Should redirect to root since this is the last stage 114 self.assertStageRedirects(response, "/")
Test validator stage with valid code
@patch('authentik.stages.email.utils.render_to_string', MagicMock(side_effect=TemplateSyntaxError('invalid')))
def
test_template_syntax_error(self):
116 @patch( 117 "authentik.stages.email.utils.render_to_string", 118 MagicMock(side_effect=TemplateSyntaxError("invalid")), 119 ) 120 def test_template_syntax_error(self): 121 """Test that a broken email template denies the flow and logs a configuration error""" 122 device = EmailDevice.objects.create( 123 user=self.user, 124 confirmed=True, 125 stage=self.stage, 126 email="xx@0.co", 127 ) 128 self._identify_user() 129 response = self._send_challenge(device) 130 self.assertStageResponse( 131 response, 132 flow=self.flow, 133 component="ak-stage-access-denied", 134 ) 135 self.assertTrue( 136 Event.objects.filter( 137 action=EventAction.CONFIGURATION_ERROR, 138 context__message="Exception occurred while rendering E-mail template", 139 ).exists() 140 )
Test that a broken email template denies the flow and logs a configuration error
def
test_no_device(self):
142 def test_no_device(self): 143 """Test validator stage without configured device""" 144 configuration_stage = AuthenticatorEmailStage.objects.create( 145 name=generate_id(), 146 use_global_settings=True, 147 from_address="test@authentik.local", 148 ) 149 stage = AuthenticatorValidateStage.objects.create( 150 name=generate_id(), 151 not_configured_action=NotConfiguredAction.CONFIGURE, 152 device_classes=[DeviceClasses.EMAIL], 153 ) 154 stage.configuration_stages.set([configuration_stage]) 155 flow = create_test_flow() 156 FlowStageBinding.objects.create(target=flow, stage=stage, order=2) 157 158 response = self.client.post( 159 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 160 {"component": "ak-stage-authenticator-validate"}, 161 ) 162 self.assertEqual(response.status_code, 200) 163 response_data = self.assertStageResponse( 164 response, 165 flow=flow, 166 component="ak-stage-authenticator-validate", 167 ) 168 self.assertEqual(response_data["configuration_stages"], []) 169 self.assertEqual(response_data["device_challenges"], []) 170 self.assertEqual( 171 response_data["response_errors"], 172 {"non_field_errors": [{"code": "invalid", "string": "Empty response"}]}, 173 )
Test validator stage without configured device
@freeze_time('2026-10-08 12:00:00')
def
test_email_only_rejects_totp(self):
175 @freeze_time("2026-10-08 12:00:00") 176 def test_email_only_rejects_totp(self): 177 """An enrolled TOTP device cannot satisfy an email-only stage.""" 178 device = EmailDevice.objects.create( 179 user=self.user, stage=self.stage, email="test@authentik.local" 180 ) 181 totp_device = TOTPDevice.objects.create(user=self.user) 182 totp_code = str(TOTP(totp_device.bin_key).token()).zfill(totp_device.digits) 183 self.validate_stage.email_otp_throttling_factor = 0 184 self.validate_stage.save() 185 186 self._identify_user() 187 self._send_challenge(device) 188 device.refresh_from_db() 189 # Ensure the email and TOTP codes cannot coincidentally match. 190 device.token = "111111" if totp_code != "111111" else "222222" 191 device.save() 192 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}) 193 response = self.client.post(url, {"code": totp_code}) 194 data = self.assertStageResponse( 195 response, flow=self.flow, component="ak-stage-authenticator-validate" 196 ) 197 self.assertIn("code", data["response_errors"]) 198 totp_device.refresh_from_db() 199 self.assertEqual(totp_device.last_t, -1) 200 self.assertEqual(totp_device.throttling_failure_count, 0) 201 self.assertIsNone(totp_device.last_used) 202 203 response = self.client.post(url, {"code": device.token}) 204 self.assertStageRedirects(response, "/")
An enrolled TOTP device cannot satisfy an email-only stage.
def
test_invalid_code(self):
206 def test_invalid_code(self): 207 """Test validator stage with invalid code""" 208 # Create a device for our user 209 device = EmailDevice.objects.create( 210 user=self.user, 211 confirmed=True, 212 stage=self.stage, 213 email="test@authentik.local", 214 ) 215 216 # First identify the user 217 self._identify_user() 218 219 # Send the challenge 220 self._send_challenge(device) 221 222 # Generate a token for the device 223 device.generate_token() 224 225 # Try invalid code and verify error message 226 response = self.client.post( 227 reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}), 228 {"component": "ak-stage-authenticator-validate", "code": "invalid"}, 229 ) 230 response_data = self.assertStageResponse( 231 response, 232 flow=self.flow, 233 component="ak-stage-authenticator-validate", 234 ) 235 self.assertEqual( 236 response_data["response_errors"], 237 { 238 "code": [ 239 { 240 "code": "invalid", 241 "string": ( 242 "Invalid Token. Please ensure the time on your device " 243 "is accurate and try again." 244 ), 245 } 246 ], 247 }, 248 )
Test validator stage with invalid code