authentik.stages.authenticator_validate.tests.test_code

Code validation must respect stage and challenge restrictions.

  1"""Code validation must respect stage and challenge restrictions."""
  2
  3from django.test import TestCase
  4from django.test.client import RequestFactory
  5from freezegun import freeze_time
  6from rest_framework.exceptions import ValidationError
  7
  8from authentik.core.tests.utils import create_test_admin_user
  9from authentik.flows.stage import StageView
 10from authentik.flows.views.executor import FlowExecutorView
 11from authentik.lib.generators import generate_id
 12from authentik.stages.authenticator.oath import TOTP
 13from authentik.stages.authenticator_email.models import AuthenticatorEmailStage, EmailDevice
 14from authentik.stages.authenticator_sms.models import AuthenticatorSMSStage, SMSDevice
 15from authentik.stages.authenticator_static.models import StaticDevice, StaticToken
 16from authentik.stages.authenticator_totp.models import TOTPDevice
 17from authentik.stages.authenticator_validate.challenge import validate_challenge_code
 18from authentik.stages.authenticator_validate.models import AuthenticatorValidateStage, DeviceClasses
 19
 20
 21@freeze_time("2026-10-08 12:00:00")
 22class ValidateChallengeCodeTests(TestCase):
 23    """Exercise real tokens for each code-based device class."""
 24
 25    def setUp(self):
 26        self.user = create_test_admin_user()
 27        email_stage = AuthenticatorEmailStage.objects.create(name=generate_id())
 28        sms_stage = AuthenticatorSMSStage.objects.create(name=generate_id())
 29        self.devices = [
 30            EmailDevice.objects.create(user=self.user, stage=email_stage, email="test@0.co"),
 31            SMSDevice.objects.create(user=self.user, stage=sms_stage, phone_number="+15551230101"),
 32            TOTPDevice.objects.create(user=self.user),
 33            StaticDevice.objects.create(user=self.user),
 34        ]
 35        self.devices[0].generate_token()
 36        self.devices[1].generate_token()
 37        static_token = StaticToken.objects.create(device=self.devices[3], token=generate_id())
 38        self.tokens = [
 39            self.devices[0].token,
 40            self.devices[1].token,
 41            str(TOTP(self.devices[2].bin_key).token()),
 42            static_token.token,
 43        ]
 44
 45    def _view(self, classes):
 46        stage = AuthenticatorValidateStage.objects.create(
 47            name=generate_id(), device_classes=classes
 48        )
 49        return StageView(
 50            FlowExecutorView(current_stage=stage),
 51            request=RequestFactory().get("/"),
 52        )
 53
 54    def test_disallowed_classes(self):
 55        """Even an existing challenge cannot authorize a class excluded by the stage."""
 56        for device, token in zip(self.devices, self.tokens, strict=True):
 57            device_class = DeviceClasses.from_model_label(device.model_label())
 58            with self.subTest(device_class=device_class):
 59                view = self._view([DeviceClasses.WEBAUTHN])
 60                challenges = [{"device_class": device_class, "device_uid": str(device.pk)}]
 61                with self.assertRaises(ValidationError):
 62                    validate_challenge_code(token, view, self.user, challenges)
 63                device.refresh_from_db()
 64                self.assertEqual(device.throttling_failure_count, 0)
 65                # Rejection must not consume or otherwise invalidate the token.
 66                self.assertTrue(device.verify_token(token))
 67
 68    def test_missing_challenge(self):
 69        """Allowed classes still require an issued challenge."""
 70        for device, token in zip(self.devices, self.tokens, strict=True):
 71            device_class = DeviceClasses.from_model_label(device.model_label())
 72            with self.subTest(device_class=device_class):
 73                with self.assertRaises(ValidationError):
 74                    validate_challenge_code(token, self._view([device_class]), self.user, [])
 75                device.refresh_from_db()
 76                self.assertEqual(device.throttling_failure_count, 0)
 77                self.assertTrue(device.verify_token(token))
 78
 79    def test_email_sms_require_matching_device(self):
 80        """A code from another device of the same class cannot satisfy the challenge."""
 81        for device, token in zip(self.devices[:2], self.tokens[:2], strict=True):
 82            device_class = DeviceClasses.from_model_label(device.model_label())
 83            with self.subTest(device_class=device_class):
 84                view = self._view([device_class])
 85                challenges = [{"device_class": device_class, "device_uid": str(device.pk + 1)}]
 86                with self.assertRaises(ValidationError):
 87                    validate_challenge_code(token, view, self.user, challenges)
 88                device.refresh_from_db()
 89                self.assertEqual(device.throttling_failure_count, 0)
 90                challenges[0]["device_uid"] = str(device.pk)
 91                self.assertEqual(
 92                    validate_challenge_code(token, view, self.user, challenges), device
 93                )
 94
 95    def test_totp_static_challenges_are_class_wide(self):
 96        """A single challenge permits all enrolled devices of an allowed TOTP/static class."""
 97        for device, token in zip(self.devices[2:], self.tokens[2:], strict=True):
 98            device_class = DeviceClasses.from_model_label(device.model_label())
 99            with self.subTest(device_class=device_class):
100                other = type(device).objects.create(user=self.user)
101                view = self._view([DeviceClasses.TOTP, DeviceClasses.STATIC])
102                challenges = [{"device_class": device_class, "device_uid": str(other.pk)}]
103                self.assertEqual(
104                    validate_challenge_code(token, view, self.user, challenges), device
105                )
@freeze_time('2026-10-08 12:00:00')
class ValidateChallengeCodeTests(django.test.testcases.TestCase):
 22@freeze_time("2026-10-08 12:00:00")
 23class ValidateChallengeCodeTests(TestCase):
 24    """Exercise real tokens for each code-based device class."""
 25
 26    def setUp(self):
 27        self.user = create_test_admin_user()
 28        email_stage = AuthenticatorEmailStage.objects.create(name=generate_id())
 29        sms_stage = AuthenticatorSMSStage.objects.create(name=generate_id())
 30        self.devices = [
 31            EmailDevice.objects.create(user=self.user, stage=email_stage, email="test@0.co"),
 32            SMSDevice.objects.create(user=self.user, stage=sms_stage, phone_number="+15551230101"),
 33            TOTPDevice.objects.create(user=self.user),
 34            StaticDevice.objects.create(user=self.user),
 35        ]
 36        self.devices[0].generate_token()
 37        self.devices[1].generate_token()
 38        static_token = StaticToken.objects.create(device=self.devices[3], token=generate_id())
 39        self.tokens = [
 40            self.devices[0].token,
 41            self.devices[1].token,
 42            str(TOTP(self.devices[2].bin_key).token()),
 43            static_token.token,
 44        ]
 45
 46    def _view(self, classes):
 47        stage = AuthenticatorValidateStage.objects.create(
 48            name=generate_id(), device_classes=classes
 49        )
 50        return StageView(
 51            FlowExecutorView(current_stage=stage),
 52            request=RequestFactory().get("/"),
 53        )
 54
 55    def test_disallowed_classes(self):
 56        """Even an existing challenge cannot authorize a class excluded by the stage."""
 57        for device, token in zip(self.devices, self.tokens, strict=True):
 58            device_class = DeviceClasses.from_model_label(device.model_label())
 59            with self.subTest(device_class=device_class):
 60                view = self._view([DeviceClasses.WEBAUTHN])
 61                challenges = [{"device_class": device_class, "device_uid": str(device.pk)}]
 62                with self.assertRaises(ValidationError):
 63                    validate_challenge_code(token, view, self.user, challenges)
 64                device.refresh_from_db()
 65                self.assertEqual(device.throttling_failure_count, 0)
 66                # Rejection must not consume or otherwise invalidate the token.
 67                self.assertTrue(device.verify_token(token))
 68
 69    def test_missing_challenge(self):
 70        """Allowed classes still require an issued challenge."""
 71        for device, token in zip(self.devices, self.tokens, strict=True):
 72            device_class = DeviceClasses.from_model_label(device.model_label())
 73            with self.subTest(device_class=device_class):
 74                with self.assertRaises(ValidationError):
 75                    validate_challenge_code(token, self._view([device_class]), self.user, [])
 76                device.refresh_from_db()
 77                self.assertEqual(device.throttling_failure_count, 0)
 78                self.assertTrue(device.verify_token(token))
 79
 80    def test_email_sms_require_matching_device(self):
 81        """A code from another device of the same class cannot satisfy the challenge."""
 82        for device, token in zip(self.devices[:2], self.tokens[:2], strict=True):
 83            device_class = DeviceClasses.from_model_label(device.model_label())
 84            with self.subTest(device_class=device_class):
 85                view = self._view([device_class])
 86                challenges = [{"device_class": device_class, "device_uid": str(device.pk + 1)}]
 87                with self.assertRaises(ValidationError):
 88                    validate_challenge_code(token, view, self.user, challenges)
 89                device.refresh_from_db()
 90                self.assertEqual(device.throttling_failure_count, 0)
 91                challenges[0]["device_uid"] = str(device.pk)
 92                self.assertEqual(
 93                    validate_challenge_code(token, view, self.user, challenges), device
 94                )
 95
 96    def test_totp_static_challenges_are_class_wide(self):
 97        """A single challenge permits all enrolled devices of an allowed TOTP/static class."""
 98        for device, token in zip(self.devices[2:], self.tokens[2:], strict=True):
 99            device_class = DeviceClasses.from_model_label(device.model_label())
100            with self.subTest(device_class=device_class):
101                other = type(device).objects.create(user=self.user)
102                view = self._view([DeviceClasses.TOTP, DeviceClasses.STATIC])
103                challenges = [{"device_class": device_class, "device_uid": str(other.pk)}]
104                self.assertEqual(
105                    validate_challenge_code(token, view, self.user, challenges), device
106                )

Exercise real tokens for each code-based device class.

def setUp(*args: Any, **kwargs: Any) -> None:
692            def setUp(*args: Any, **kwargs: Any) -> None:
693                self.start()
694                if orig_setUp is not None:
695                    orig_setUp(*args, **kwargs)

The type of the None singleton.

def test_disallowed_classes(self):
55    def test_disallowed_classes(self):
56        """Even an existing challenge cannot authorize a class excluded by the stage."""
57        for device, token in zip(self.devices, self.tokens, strict=True):
58            device_class = DeviceClasses.from_model_label(device.model_label())
59            with self.subTest(device_class=device_class):
60                view = self._view([DeviceClasses.WEBAUTHN])
61                challenges = [{"device_class": device_class, "device_uid": str(device.pk)}]
62                with self.assertRaises(ValidationError):
63                    validate_challenge_code(token, view, self.user, challenges)
64                device.refresh_from_db()
65                self.assertEqual(device.throttling_failure_count, 0)
66                # Rejection must not consume or otherwise invalidate the token.
67                self.assertTrue(device.verify_token(token))

Even an existing challenge cannot authorize a class excluded by the stage.

def test_missing_challenge(self):
69    def test_missing_challenge(self):
70        """Allowed classes still require an issued challenge."""
71        for device, token in zip(self.devices, self.tokens, strict=True):
72            device_class = DeviceClasses.from_model_label(device.model_label())
73            with self.subTest(device_class=device_class):
74                with self.assertRaises(ValidationError):
75                    validate_challenge_code(token, self._view([device_class]), self.user, [])
76                device.refresh_from_db()
77                self.assertEqual(device.throttling_failure_count, 0)
78                self.assertTrue(device.verify_token(token))

Allowed classes still require an issued challenge.

def test_email_sms_require_matching_device(self):
80    def test_email_sms_require_matching_device(self):
81        """A code from another device of the same class cannot satisfy the challenge."""
82        for device, token in zip(self.devices[:2], self.tokens[:2], strict=True):
83            device_class = DeviceClasses.from_model_label(device.model_label())
84            with self.subTest(device_class=device_class):
85                view = self._view([device_class])
86                challenges = [{"device_class": device_class, "device_uid": str(device.pk + 1)}]
87                with self.assertRaises(ValidationError):
88                    validate_challenge_code(token, view, self.user, challenges)
89                device.refresh_from_db()
90                self.assertEqual(device.throttling_failure_count, 0)
91                challenges[0]["device_uid"] = str(device.pk)
92                self.assertEqual(
93                    validate_challenge_code(token, view, self.user, challenges), device
94                )

A code from another device of the same class cannot satisfy the challenge.

def test_totp_static_challenges_are_class_wide(self):
 96    def test_totp_static_challenges_are_class_wide(self):
 97        """A single challenge permits all enrolled devices of an allowed TOTP/static class."""
 98        for device, token in zip(self.devices[2:], self.tokens[2:], strict=True):
 99            device_class = DeviceClasses.from_model_label(device.model_label())
100            with self.subTest(device_class=device_class):
101                other = type(device).objects.create(user=self.user)
102                view = self._view([DeviceClasses.TOTP, DeviceClasses.STATIC])
103                challenges = [{"device_class": device_class, "device_uid": str(other.pk)}]
104                self.assertEqual(
105                    validate_challenge_code(token, view, self.user, challenges), device
106                )

A single challenge permits all enrolled devices of an allowed TOTP/static class.

@classmethod
def setUpClass(cls: type) -> None:
671            @classmethod  # type: ignore
672            def setUpClass(cls: type) -> None:
673                self.start()
674                if orig_setUpClass is not None:
675                    orig_setUpClass()
676                self.stop()

The type of the None singleton.

@classmethod
def tearDownClass(cls: type) -> None:
679            @classmethod  # type: ignore
680            def tearDownClass(cls: type) -> None:
681                self.start()
682                if orig_tearDownClass is not None:
683                    orig_tearDownClass()
684                self.stop()

The type of the None singleton.

def tearDown(*args: Any, **kwargs: Any) -> None:
697            def tearDown(*args: Any, **kwargs: Any) -> None:
698                if orig_tearDown is not None:
699                    orig_tearDown(*args, **kwargs)
700                self.stop()

The type of the None singleton.