authentik.stages.authenticator_validate.tests.test_throttling

  1from django.test import TestCase
  2from django.test.client import RequestFactory
  3from django.urls.base import reverse
  4from freezegun import freeze_time
  5from rest_framework.exceptions import ValidationError
  6
  7from authentik.core.tests.utils import create_test_admin_user, create_test_flow
  8from authentik.flows.models import FlowStageBinding
  9from authentik.flows.stage import StageView
 10from authentik.flows.tests import APIFlowTestCase
 11from authentik.flows.views.executor import FlowExecutorView
 12from authentik.lib.generators import generate_id
 13from authentik.stages.authenticator_email.models import AuthenticatorEmailStage, EmailDevice
 14from authentik.stages.authenticator_sms.models import (
 15    AuthenticatorSMSStage,
 16    SMSDevice,
 17    SMSProviders,
 18)
 19from authentik.stages.authenticator_validate.challenge import validate_challenge_code
 20from authentik.stages.authenticator_validate.models import (
 21    AuthenticatorValidateStage,
 22    DeviceClasses,
 23)
 24from authentik.stages.identification.models import IdentificationStage, UserFields
 25
 26
 27class DeviceClassesHelperTests(TestCase):
 28    """Tests for the DeviceClasses.from_model_label helper."""
 29
 30    def test_from_model_label_all_classes(self):
 31        cases = {
 32            "authentik_stages_authenticator_email.emaildevice": DeviceClasses.EMAIL,
 33            "authentik_stages_authenticator_sms.smsdevice": DeviceClasses.SMS,
 34            "authentik_stages_authenticator_totp.totpdevice": DeviceClasses.TOTP,
 35            "authentik_stages_authenticator_static.staticdevice": DeviceClasses.STATIC,
 36            "authentik_stages_authenticator_duo.duodevice": DeviceClasses.DUO,
 37            "authentik_stages_authenticator_webauthn.webauthndevice": DeviceClasses.WEBAUTHN,
 38        }
 39        for label, expected in cases.items():
 40            with self.subTest(label=label):
 41                self.assertEqual(DeviceClasses.from_model_label(label), expected)
 42
 43
 44class AuthenticatorValidateStageFactorTests(TestCase):
 45    """Tests for AuthenticatorValidateStage.get_throttling_factor."""
 46
 47    def test_per_class_factors_returned(self):
 48        stage = AuthenticatorValidateStage.objects.create(
 49            name=generate_id(),
 50            email_otp_throttling_factor=5,
 51            sms_otp_throttling_factor=6,
 52            totp_otp_throttling_factor=7,
 53            static_otp_throttling_factor=8,
 54        )
 55        self.assertEqual(stage.get_throttling_factor(DeviceClasses.EMAIL), 5)
 56        self.assertEqual(stage.get_throttling_factor(DeviceClasses.SMS), 6)
 57        self.assertEqual(stage.get_throttling_factor(DeviceClasses.TOTP), 7)
 58        self.assertEqual(stage.get_throttling_factor(DeviceClasses.STATIC), 8)
 59
 60    def test_no_factor_for_webauthn_or_duo(self):
 61        stage = AuthenticatorValidateStage.objects.create(name=generate_id())
 62        self.assertIsNone(stage.get_throttling_factor(DeviceClasses.WEBAUTHN))
 63        self.assertIsNone(stage.get_throttling_factor(DeviceClasses.DUO))
 64
 65
 66class ValidateChallengeCodeThrottlingTests(APIFlowTestCase):
 67    """Tests for validate_challenge_code throttling behavior."""
 68
 69    def setUp(self) -> None:
 70        super().setUp()
 71        self.user = create_test_admin_user()
 72        self.request_factory = RequestFactory()
 73        self.email_stage = AuthenticatorEmailStage.objects.create(
 74            name="email-stage-validate-throttle",
 75            use_global_settings=True,
 76            from_address="test@authentik.local",
 77            token_expiry="minutes=30",
 78        )  # nosec
 79        self.sms_stage = AuthenticatorSMSStage.objects.create(
 80            name="sms-stage-validate-throttle",
 81            provider=SMSProviders.GENERIC,
 82            from_number="1234",
 83        )
 84
 85    def _validate_stage(self, **factors) -> AuthenticatorValidateStage:
 86        return AuthenticatorValidateStage.objects.create(
 87            name=generate_id(),
 88            device_classes=[
 89                DeviceClasses.EMAIL,
 90                DeviceClasses.SMS,
 91                DeviceClasses.TOTP,
 92                DeviceClasses.STATIC,
 93            ],
 94            **factors,
 95        )
 96
 97    def _stage_view(self, validate_stage: AuthenticatorValidateStage) -> StageView:
 98        request = self.request_factory.get("/")
 99        return StageView(FlowExecutorView(current_stage=validate_stage), request=request)
100
101    def _email_device(self, email: str = "throttle@authentik.local") -> EmailDevice:
102        return EmailDevice.objects.create(
103            user=self.user,
104            stage=self.email_stage,
105            confirmed=True,
106            email=email,
107        )
108
109    def _sms_device(self, phone_number: str = "+15551230101") -> SMSDevice:
110        return SMSDevice.objects.create(
111            user=self.user,
112            stage=self.sms_stage,
113            confirmed=True,
114            phone_number=phone_number,
115        )
116
117    def test_stage_factor_applied_to_email_device(self):
118        """The stage's email_otp_throttling_factor is pushed onto the device before verify."""
119        stage = self._validate_stage(email_otp_throttling_factor=3)
120        device = self._email_device()
121        device.generate_token()
122        challenges = [{"device_class": DeviceClasses.EMAIL, "device_uid": str(device.pk)}]
123        with self.assertRaises(ValidationError):
124            validate_challenge_code("000000", self._stage_view(stage), self.user, challenges)
125        device.refresh_from_db()
126        self.assertEqual(device.throttling_failure_count, 1)
127        # verify_is_allowed must compute the delay using factor=3 (3 * 2^0 = 3s).
128        device.set_throttle_factor(3)
129        allowed, data = device.verify_is_allowed()
130        self.assertFalse(allowed)
131        required = data["locked_until"] - device.throttling_failure_timestamp
132        self.assertAlmostEqual(required.total_seconds(), 3, places=3)
133
134    def test_factor_zero_disables_throttling_end_to_end(self):
135        """With email_otp_throttling_factor=0, repeated failures do not lock the device."""
136        stage = self._validate_stage(email_otp_throttling_factor=0)
137        device = self._email_device()
138        device.generate_token()
139        token = device.token
140        challenges = [{"device_class": DeviceClasses.EMAIL, "device_uid": str(device.pk)}]
141        for _ in range(10):
142            with self.assertRaises(ValidationError):
143                validate_challenge_code("000000", self._stage_view(stage), self.user, challenges)
144        matched = validate_challenge_code(token, self._stage_view(stage), self.user, challenges)
145        self.assertEqual(matched.pk, device.pk)
146
147    def test_lockout_persists_across_calls(self):
148        """
149        A correct token on the second call is still blocked and does not increment the counter.
150        """
151        stage = self._validate_stage(email_otp_throttling_factor=1)
152        device = self._email_device()
153        device.generate_token()
154        token = device.token
155        invalid_token = "000000" if token != "000000" else "111111"  # nosec
156        challenges = [{"device_class": DeviceClasses.EMAIL, "device_uid": str(device.pk)}]
157        with self.assertRaises(ValidationError):
158            validate_challenge_code(invalid_token, self._stage_view(stage), self.user, challenges)
159        # Immediately try with the correct token: lockout still active, attempt must be rejected.
160        with self.assertRaises(ValidationError):
161            validate_challenge_code(token, self._stage_view(stage), self.user, challenges)
162        device.refresh_from_db()
163        # Token wasn't consumed (verification never ran), and counter didn't get incremented.
164        self.assertEqual(device.token, token)
165        self.assertEqual(device.throttling_failure_count, 1)
166
167
168class ValidateStageThrottlingFlowTests(APIFlowTestCase):
169    """End-to-end lockout behavior through the flow executor HTTP API."""
170
171    def setUp(self) -> None:
172        super().setUp()
173        self.user = create_test_admin_user()
174        self.email_stage = AuthenticatorEmailStage.objects.create(
175            name="email-stage-flow-throttle",
176            use_global_settings=True,
177            from_address="test@authentik.local",
178            token_expiry="minutes=30",
179        )  # nosec
180        self.ident_stage = IdentificationStage.objects.create(
181            name=generate_id(),
182            user_fields=[UserFields.USERNAME],
183        )
184        self.validate_stage = AuthenticatorValidateStage.objects.create(
185            name=generate_id(),
186            device_classes=[DeviceClasses.EMAIL],
187            email_otp_throttling_factor=1,
188        )
189        self.flow = create_test_flow()
190        FlowStageBinding.objects.create(target=self.flow, stage=self.ident_stage, order=0)
191        FlowStageBinding.objects.create(target=self.flow, stage=self.validate_stage, order=1)
192
193    def _identify(self):
194        response = self.client.post(
195            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
196            {"uid_field": self.user.username},
197            follow=True,
198        )
199        self.assertEqual(response.status_code, 200)
200
201    def _select_email(self, device: EmailDevice):
202        self.client.post(
203            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
204            {
205                "component": "ak-stage-authenticator-validate",
206                "selected_challenge": {
207                    "device_class": "email",
208                    "device_uid": str(device.pk),
209                    "challenge": {},
210                    "last_used": None,
211                },
212            },
213        )
214
215    def test_bad_code_then_correct_code_is_still_blocked(self):
216        """After a bad code over HTTP, a subsequent correct code is still rejected
217        because the lockout persists in the database."""
218        device = EmailDevice.objects.create(
219            user=self.user,
220            confirmed=True,
221            stage=self.email_stage,
222            email="throttle-flow@authentik.local",
223        )
224        self._identify()
225        self._select_email(device)
226        # Server generated and stored the token - grab it from DB.
227        device.refresh_from_db()
228        token = device.token
229        with freeze_time():
230            # First attempt: bad code - must increment the DB counter.
231            self.client.post(
232                reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
233                {"component": "ak-stage-authenticator-validate", "code": "000000"},
234            )
235            device.refresh_from_db()
236            self.assertEqual(device.throttling_failure_count, 1)
237            self.assertEqual(device.token, token)
238            # Second attempt with the correct token - still blocked.
239            response = self.client.post(
240                reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
241                {"component": "ak-stage-authenticator-validate", "code": token},
242            )
243        self.assertStageResponse(
244            response,
245            flow=self.flow,
246            component="ak-stage-authenticator-validate",
247        )
248        device.refresh_from_db()
249        # Counter wasn't incremented on a blocked attempt
250        self.assertEqual(device.throttling_failure_count, 1)
251        # Token wasn't consumed.
252        self.assertEqual(device.token, token)
class DeviceClassesHelperTests(django.test.testcases.TestCase):
28class DeviceClassesHelperTests(TestCase):
29    """Tests for the DeviceClasses.from_model_label helper."""
30
31    def test_from_model_label_all_classes(self):
32        cases = {
33            "authentik_stages_authenticator_email.emaildevice": DeviceClasses.EMAIL,
34            "authentik_stages_authenticator_sms.smsdevice": DeviceClasses.SMS,
35            "authentik_stages_authenticator_totp.totpdevice": DeviceClasses.TOTP,
36            "authentik_stages_authenticator_static.staticdevice": DeviceClasses.STATIC,
37            "authentik_stages_authenticator_duo.duodevice": DeviceClasses.DUO,
38            "authentik_stages_authenticator_webauthn.webauthndevice": DeviceClasses.WEBAUTHN,
39        }
40        for label, expected in cases.items():
41            with self.subTest(label=label):
42                self.assertEqual(DeviceClasses.from_model_label(label), expected)

Tests for the DeviceClasses.from_model_label helper.

def test_from_model_label_all_classes(self):
31    def test_from_model_label_all_classes(self):
32        cases = {
33            "authentik_stages_authenticator_email.emaildevice": DeviceClasses.EMAIL,
34            "authentik_stages_authenticator_sms.smsdevice": DeviceClasses.SMS,
35            "authentik_stages_authenticator_totp.totpdevice": DeviceClasses.TOTP,
36            "authentik_stages_authenticator_static.staticdevice": DeviceClasses.STATIC,
37            "authentik_stages_authenticator_duo.duodevice": DeviceClasses.DUO,
38            "authentik_stages_authenticator_webauthn.webauthndevice": DeviceClasses.WEBAUTHN,
39        }
40        for label, expected in cases.items():
41            with self.subTest(label=label):
42                self.assertEqual(DeviceClasses.from_model_label(label), expected)
class AuthenticatorValidateStageFactorTests(django.test.testcases.TestCase):
45class AuthenticatorValidateStageFactorTests(TestCase):
46    """Tests for AuthenticatorValidateStage.get_throttling_factor."""
47
48    def test_per_class_factors_returned(self):
49        stage = AuthenticatorValidateStage.objects.create(
50            name=generate_id(),
51            email_otp_throttling_factor=5,
52            sms_otp_throttling_factor=6,
53            totp_otp_throttling_factor=7,
54            static_otp_throttling_factor=8,
55        )
56        self.assertEqual(stage.get_throttling_factor(DeviceClasses.EMAIL), 5)
57        self.assertEqual(stage.get_throttling_factor(DeviceClasses.SMS), 6)
58        self.assertEqual(stage.get_throttling_factor(DeviceClasses.TOTP), 7)
59        self.assertEqual(stage.get_throttling_factor(DeviceClasses.STATIC), 8)
60
61    def test_no_factor_for_webauthn_or_duo(self):
62        stage = AuthenticatorValidateStage.objects.create(name=generate_id())
63        self.assertIsNone(stage.get_throttling_factor(DeviceClasses.WEBAUTHN))
64        self.assertIsNone(stage.get_throttling_factor(DeviceClasses.DUO))

Tests for AuthenticatorValidateStage.get_throttling_factor.

def test_per_class_factors_returned(self):
48    def test_per_class_factors_returned(self):
49        stage = AuthenticatorValidateStage.objects.create(
50            name=generate_id(),
51            email_otp_throttling_factor=5,
52            sms_otp_throttling_factor=6,
53            totp_otp_throttling_factor=7,
54            static_otp_throttling_factor=8,
55        )
56        self.assertEqual(stage.get_throttling_factor(DeviceClasses.EMAIL), 5)
57        self.assertEqual(stage.get_throttling_factor(DeviceClasses.SMS), 6)
58        self.assertEqual(stage.get_throttling_factor(DeviceClasses.TOTP), 7)
59        self.assertEqual(stage.get_throttling_factor(DeviceClasses.STATIC), 8)
def test_no_factor_for_webauthn_or_duo(self):
61    def test_no_factor_for_webauthn_or_duo(self):
62        stage = AuthenticatorValidateStage.objects.create(name=generate_id())
63        self.assertIsNone(stage.get_throttling_factor(DeviceClasses.WEBAUTHN))
64        self.assertIsNone(stage.get_throttling_factor(DeviceClasses.DUO))
class ValidateChallengeCodeThrottlingTests(authentik.flows.tests.APIFlowTestCase):
 67class ValidateChallengeCodeThrottlingTests(APIFlowTestCase):
 68    """Tests for validate_challenge_code throttling behavior."""
 69
 70    def setUp(self) -> None:
 71        super().setUp()
 72        self.user = create_test_admin_user()
 73        self.request_factory = RequestFactory()
 74        self.email_stage = AuthenticatorEmailStage.objects.create(
 75            name="email-stage-validate-throttle",
 76            use_global_settings=True,
 77            from_address="test@authentik.local",
 78            token_expiry="minutes=30",
 79        )  # nosec
 80        self.sms_stage = AuthenticatorSMSStage.objects.create(
 81            name="sms-stage-validate-throttle",
 82            provider=SMSProviders.GENERIC,
 83            from_number="1234",
 84        )
 85
 86    def _validate_stage(self, **factors) -> AuthenticatorValidateStage:
 87        return AuthenticatorValidateStage.objects.create(
 88            name=generate_id(),
 89            device_classes=[
 90                DeviceClasses.EMAIL,
 91                DeviceClasses.SMS,
 92                DeviceClasses.TOTP,
 93                DeviceClasses.STATIC,
 94            ],
 95            **factors,
 96        )
 97
 98    def _stage_view(self, validate_stage: AuthenticatorValidateStage) -> StageView:
 99        request = self.request_factory.get("/")
100        return StageView(FlowExecutorView(current_stage=validate_stage), request=request)
101
102    def _email_device(self, email: str = "throttle@authentik.local") -> EmailDevice:
103        return EmailDevice.objects.create(
104            user=self.user,
105            stage=self.email_stage,
106            confirmed=True,
107            email=email,
108        )
109
110    def _sms_device(self, phone_number: str = "+15551230101") -> SMSDevice:
111        return SMSDevice.objects.create(
112            user=self.user,
113            stage=self.sms_stage,
114            confirmed=True,
115            phone_number=phone_number,
116        )
117
118    def test_stage_factor_applied_to_email_device(self):
119        """The stage's email_otp_throttling_factor is pushed onto the device before verify."""
120        stage = self._validate_stage(email_otp_throttling_factor=3)
121        device = self._email_device()
122        device.generate_token()
123        challenges = [{"device_class": DeviceClasses.EMAIL, "device_uid": str(device.pk)}]
124        with self.assertRaises(ValidationError):
125            validate_challenge_code("000000", self._stage_view(stage), self.user, challenges)
126        device.refresh_from_db()
127        self.assertEqual(device.throttling_failure_count, 1)
128        # verify_is_allowed must compute the delay using factor=3 (3 * 2^0 = 3s).
129        device.set_throttle_factor(3)
130        allowed, data = device.verify_is_allowed()
131        self.assertFalse(allowed)
132        required = data["locked_until"] - device.throttling_failure_timestamp
133        self.assertAlmostEqual(required.total_seconds(), 3, places=3)
134
135    def test_factor_zero_disables_throttling_end_to_end(self):
136        """With email_otp_throttling_factor=0, repeated failures do not lock the device."""
137        stage = self._validate_stage(email_otp_throttling_factor=0)
138        device = self._email_device()
139        device.generate_token()
140        token = device.token
141        challenges = [{"device_class": DeviceClasses.EMAIL, "device_uid": str(device.pk)}]
142        for _ in range(10):
143            with self.assertRaises(ValidationError):
144                validate_challenge_code("000000", self._stage_view(stage), self.user, challenges)
145        matched = validate_challenge_code(token, self._stage_view(stage), self.user, challenges)
146        self.assertEqual(matched.pk, device.pk)
147
148    def test_lockout_persists_across_calls(self):
149        """
150        A correct token on the second call is still blocked and does not increment the counter.
151        """
152        stage = self._validate_stage(email_otp_throttling_factor=1)
153        device = self._email_device()
154        device.generate_token()
155        token = device.token
156        invalid_token = "000000" if token != "000000" else "111111"  # nosec
157        challenges = [{"device_class": DeviceClasses.EMAIL, "device_uid": str(device.pk)}]
158        with self.assertRaises(ValidationError):
159            validate_challenge_code(invalid_token, self._stage_view(stage), self.user, challenges)
160        # Immediately try with the correct token: lockout still active, attempt must be rejected.
161        with self.assertRaises(ValidationError):
162            validate_challenge_code(token, self._stage_view(stage), self.user, challenges)
163        device.refresh_from_db()
164        # Token wasn't consumed (verification never ran), and counter didn't get incremented.
165        self.assertEqual(device.token, token)
166        self.assertEqual(device.throttling_failure_count, 1)

Tests for validate_challenge_code throttling behavior.

def setUp(self) -> None:
70    def setUp(self) -> None:
71        super().setUp()
72        self.user = create_test_admin_user()
73        self.request_factory = RequestFactory()
74        self.email_stage = AuthenticatorEmailStage.objects.create(
75            name="email-stage-validate-throttle",
76            use_global_settings=True,
77            from_address="test@authentik.local",
78            token_expiry="minutes=30",
79        )  # nosec
80        self.sms_stage = AuthenticatorSMSStage.objects.create(
81            name="sms-stage-validate-throttle",
82            provider=SMSProviders.GENERIC,
83            from_number="1234",
84        )

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

def test_stage_factor_applied_to_email_device(self):
118    def test_stage_factor_applied_to_email_device(self):
119        """The stage's email_otp_throttling_factor is pushed onto the device before verify."""
120        stage = self._validate_stage(email_otp_throttling_factor=3)
121        device = self._email_device()
122        device.generate_token()
123        challenges = [{"device_class": DeviceClasses.EMAIL, "device_uid": str(device.pk)}]
124        with self.assertRaises(ValidationError):
125            validate_challenge_code("000000", self._stage_view(stage), self.user, challenges)
126        device.refresh_from_db()
127        self.assertEqual(device.throttling_failure_count, 1)
128        # verify_is_allowed must compute the delay using factor=3 (3 * 2^0 = 3s).
129        device.set_throttle_factor(3)
130        allowed, data = device.verify_is_allowed()
131        self.assertFalse(allowed)
132        required = data["locked_until"] - device.throttling_failure_timestamp
133        self.assertAlmostEqual(required.total_seconds(), 3, places=3)

The stage's email_otp_throttling_factor is pushed onto the device before verify.

def test_factor_zero_disables_throttling_end_to_end(self):
135    def test_factor_zero_disables_throttling_end_to_end(self):
136        """With email_otp_throttling_factor=0, repeated failures do not lock the device."""
137        stage = self._validate_stage(email_otp_throttling_factor=0)
138        device = self._email_device()
139        device.generate_token()
140        token = device.token
141        challenges = [{"device_class": DeviceClasses.EMAIL, "device_uid": str(device.pk)}]
142        for _ in range(10):
143            with self.assertRaises(ValidationError):
144                validate_challenge_code("000000", self._stage_view(stage), self.user, challenges)
145        matched = validate_challenge_code(token, self._stage_view(stage), self.user, challenges)
146        self.assertEqual(matched.pk, device.pk)

With email_otp_throttling_factor=0, repeated failures do not lock the device.

def test_lockout_persists_across_calls(self):
148    def test_lockout_persists_across_calls(self):
149        """
150        A correct token on the second call is still blocked and does not increment the counter.
151        """
152        stage = self._validate_stage(email_otp_throttling_factor=1)
153        device = self._email_device()
154        device.generate_token()
155        token = device.token
156        invalid_token = "000000" if token != "000000" else "111111"  # nosec
157        challenges = [{"device_class": DeviceClasses.EMAIL, "device_uid": str(device.pk)}]
158        with self.assertRaises(ValidationError):
159            validate_challenge_code(invalid_token, self._stage_view(stage), self.user, challenges)
160        # Immediately try with the correct token: lockout still active, attempt must be rejected.
161        with self.assertRaises(ValidationError):
162            validate_challenge_code(token, self._stage_view(stage), self.user, challenges)
163        device.refresh_from_db()
164        # Token wasn't consumed (verification never ran), and counter didn't get incremented.
165        self.assertEqual(device.token, token)
166        self.assertEqual(device.throttling_failure_count, 1)

A correct token on the second call is still blocked and does not increment the counter.

class ValidateStageThrottlingFlowTests(authentik.flows.tests.APIFlowTestCase):
169class ValidateStageThrottlingFlowTests(APIFlowTestCase):
170    """End-to-end lockout behavior through the flow executor HTTP API."""
171
172    def setUp(self) -> None:
173        super().setUp()
174        self.user = create_test_admin_user()
175        self.email_stage = AuthenticatorEmailStage.objects.create(
176            name="email-stage-flow-throttle",
177            use_global_settings=True,
178            from_address="test@authentik.local",
179            token_expiry="minutes=30",
180        )  # nosec
181        self.ident_stage = IdentificationStage.objects.create(
182            name=generate_id(),
183            user_fields=[UserFields.USERNAME],
184        )
185        self.validate_stage = AuthenticatorValidateStage.objects.create(
186            name=generate_id(),
187            device_classes=[DeviceClasses.EMAIL],
188            email_otp_throttling_factor=1,
189        )
190        self.flow = create_test_flow()
191        FlowStageBinding.objects.create(target=self.flow, stage=self.ident_stage, order=0)
192        FlowStageBinding.objects.create(target=self.flow, stage=self.validate_stage, order=1)
193
194    def _identify(self):
195        response = self.client.post(
196            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
197            {"uid_field": self.user.username},
198            follow=True,
199        )
200        self.assertEqual(response.status_code, 200)
201
202    def _select_email(self, device: EmailDevice):
203        self.client.post(
204            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
205            {
206                "component": "ak-stage-authenticator-validate",
207                "selected_challenge": {
208                    "device_class": "email",
209                    "device_uid": str(device.pk),
210                    "challenge": {},
211                    "last_used": None,
212                },
213            },
214        )
215
216    def test_bad_code_then_correct_code_is_still_blocked(self):
217        """After a bad code over HTTP, a subsequent correct code is still rejected
218        because the lockout persists in the database."""
219        device = EmailDevice.objects.create(
220            user=self.user,
221            confirmed=True,
222            stage=self.email_stage,
223            email="throttle-flow@authentik.local",
224        )
225        self._identify()
226        self._select_email(device)
227        # Server generated and stored the token - grab it from DB.
228        device.refresh_from_db()
229        token = device.token
230        with freeze_time():
231            # First attempt: bad code - must increment the DB counter.
232            self.client.post(
233                reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
234                {"component": "ak-stage-authenticator-validate", "code": "000000"},
235            )
236            device.refresh_from_db()
237            self.assertEqual(device.throttling_failure_count, 1)
238            self.assertEqual(device.token, token)
239            # Second attempt with the correct token - still blocked.
240            response = self.client.post(
241                reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
242                {"component": "ak-stage-authenticator-validate", "code": token},
243            )
244        self.assertStageResponse(
245            response,
246            flow=self.flow,
247            component="ak-stage-authenticator-validate",
248        )
249        device.refresh_from_db()
250        # Counter wasn't incremented on a blocked attempt
251        self.assertEqual(device.throttling_failure_count, 1)
252        # Token wasn't consumed.
253        self.assertEqual(device.token, token)

End-to-end lockout behavior through the flow executor HTTP API.

def setUp(self) -> None:
172    def setUp(self) -> None:
173        super().setUp()
174        self.user = create_test_admin_user()
175        self.email_stage = AuthenticatorEmailStage.objects.create(
176            name="email-stage-flow-throttle",
177            use_global_settings=True,
178            from_address="test@authentik.local",
179            token_expiry="minutes=30",
180        )  # nosec
181        self.ident_stage = IdentificationStage.objects.create(
182            name=generate_id(),
183            user_fields=[UserFields.USERNAME],
184        )
185        self.validate_stage = AuthenticatorValidateStage.objects.create(
186            name=generate_id(),
187            device_classes=[DeviceClasses.EMAIL],
188            email_otp_throttling_factor=1,
189        )
190        self.flow = create_test_flow()
191        FlowStageBinding.objects.create(target=self.flow, stage=self.ident_stage, order=0)
192        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_bad_code_then_correct_code_is_still_blocked(self):
216    def test_bad_code_then_correct_code_is_still_blocked(self):
217        """After a bad code over HTTP, a subsequent correct code is still rejected
218        because the lockout persists in the database."""
219        device = EmailDevice.objects.create(
220            user=self.user,
221            confirmed=True,
222            stage=self.email_stage,
223            email="throttle-flow@authentik.local",
224        )
225        self._identify()
226        self._select_email(device)
227        # Server generated and stored the token - grab it from DB.
228        device.refresh_from_db()
229        token = device.token
230        with freeze_time():
231            # First attempt: bad code - must increment the DB counter.
232            self.client.post(
233                reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
234                {"component": "ak-stage-authenticator-validate", "code": "000000"},
235            )
236            device.refresh_from_db()
237            self.assertEqual(device.throttling_failure_count, 1)
238            self.assertEqual(device.token, token)
239            # Second attempt with the correct token - still blocked.
240            response = self.client.post(
241                reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
242                {"component": "ak-stage-authenticator-validate", "code": token},
243            )
244        self.assertStageResponse(
245            response,
246            flow=self.flow,
247            component="ak-stage-authenticator-validate",
248        )
249        device.refresh_from_db()
250        # Counter wasn't incremented on a blocked attempt
251        self.assertEqual(device.throttling_failure_count, 1)
252        # Token wasn't consumed.
253        self.assertEqual(device.token, token)

After a bad code over HTTP, a subsequent correct code is still rejected because the lockout persists in the database.