authentik.stages.password.tests

password tests

  1"""password tests"""
  2
  3from concurrent.futures import ThreadPoolExecutor
  4from io import StringIO
  5from threading import Barrier
  6from unittest.mock import MagicMock, patch
  7
  8from asgiref.sync import async_to_sync
  9from django.contrib.auth.hashers import PBKDF2PasswordHasher, make_password
 10from django.core.exceptions import PermissionDenied
 11from django.core.management import call_command
 12from django.db import IntegrityError, connection, transaction
 13from django.db.models.signals import post_save
 14from django.test import RequestFactory, TestCase, TransactionTestCase
 15from django.urls import reverse
 16from django.utils.timezone import now
 17
 18from authentik.core.auth import InbuiltBackend, TokenBackend
 19from authentik.core.models import Token, TokenIntents, User, UserTypes
 20from authentik.core.signals import login_failed, password_changed
 21from authentik.core.tests.utils import (
 22    create_test_admin_user,
 23    create_test_brand,
 24    create_test_flow,
 25    create_test_user,
 26)
 27from authentik.enterprise.license import LicenseSummary
 28from authentik.enterprise.models import LicenseUsageStatus
 29from authentik.events.models import Event, EventAction
 30from authentik.flows.markers import StageMarker
 31from authentik.flows.models import FlowDesignation, FlowStageBinding
 32from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER, FlowPlan
 33from authentik.flows.tests import APIFlowTestCase
 34from authentik.flows.tests.test_executor import TO_STAGE_RESPONSE_MOCK
 35from authentik.flows.views.executor import SESSION_KEY_PLAN
 36from authentik.lib.generators import generate_id
 37from authentik.sources.kerberos.models import KerberosSource, UserKerberosSourceConnection
 38from authentik.sources.ldap.models import LDAP_DISTINGUISHED_NAME, LDAPSource
 39from authentik.stages.authenticator import device_classes, devices_for_user
 40from authentik.stages.authenticator.models import Device
 41from authentik.stages.password import (
 42    BACKEND_APP_PASSWORD,
 43    BACKEND_INBUILT,
 44    BACKEND_KERBEROS,
 45    BACKEND_LDAP,
 46)
 47from authentik.stages.password.lockout import (
 48    PasswordLockout,
 49    PasswordLockoutBase,
 50    PasswordLockoutResult,
 51)
 52from authentik.stages.password.models import PasswordDevice, PasswordStage
 53
 54MOCK_BACKEND_AUTHENTICATE = MagicMock(side_effect=PermissionDenied("test"))
 55
 56
 57class TestPasswordStage(APIFlowTestCase):
 58    """Password tests"""
 59
 60    def setUp(self):
 61        super().setUp()
 62        self.user = create_test_admin_user()
 63
 64        self.flow = create_test_flow(FlowDesignation.AUTHENTICATION)
 65        self.stage = PasswordStage.objects.create(name=generate_id(), backends=[BACKEND_INBUILT])
 66        self.binding = FlowStageBinding.objects.create(target=self.flow, stage=self.stage, order=2)
 67
 68    @patch(
 69        "authentik.flows.views.executor.to_stage_response",
 70        TO_STAGE_RESPONSE_MOCK,
 71    )
 72    def test_without_user(self):
 73        """Test without user"""
 74        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
 75        session = self.client.session
 76        session[SESSION_KEY_PLAN] = plan
 77        session.save()
 78
 79        response = self.client.post(
 80            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
 81            # Still have to send the password so the form is valid
 82            {"password": self.user.username},
 83        )
 84
 85        self.assertStageResponse(
 86            response,
 87            self.flow,
 88            component="ak-stage-access-denied",
 89            error_message="Unknown error",
 90        )
 91
 92    def test_recovery_flow_link(self):
 93        """Test link to the default recovery flow"""
 94        flow = create_test_flow(designation=FlowDesignation.RECOVERY)
 95        brand = create_test_brand()
 96        brand.flow_recovery = flow
 97        brand.save()
 98
 99        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
100        session = self.client.session
101        session[SESSION_KEY_PLAN] = plan
102        session.save()
103
104        response = self.client.get(
105            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
106        )
107        self.assertEqual(response.status_code, 200)
108        self.assertIn(flow.slug, response.content.decode())
109
110    def test_valid_password(self):
111        """Test with a valid pending user and valid password"""
112        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
113        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
114        session = self.client.session
115        session[SESSION_KEY_PLAN] = plan
116        session.save()
117
118        response = self.client.post(
119            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
120            # Form data
121            {"password": self.user.username},
122        )
123
124        self.assertEqual(response.status_code, 200)
125        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
126
127    def test_valid_password_inactive(self):
128        """Test with a valid pending user and valid password"""
129        self.user.is_active = False
130        self.user.save()
131        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
132        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
133        session = self.client.session
134        session[SESSION_KEY_PLAN] = plan
135        session.save()
136
137        response = self.client.post(
138            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
139            # Form data
140            {"password": self.user.username},
141        )
142
143        self.assertEqual(response.status_code, 200)
144        self.assertStageResponse(
145            response,
146            self.flow,
147            response_errors={"password": [{"string": "Invalid password", "code": "invalid"}]},
148        )
149
150    def test_invalid_password(self):
151        """Test with a valid pending user and invalid password"""
152        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
153        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
154        session = self.client.session
155        session[SESSION_KEY_PLAN] = plan
156        session.save()
157
158        response = self.client.post(
159            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
160            # Form data
161            {"password": self.user.username + "test"},
162        )
163        self.assertEqual(response.status_code, 200)
164
165    def test_invalid_password_lockout(self):
166        """Test with a valid pending user and invalid password (trigger logout counter)"""
167        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
168        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
169        session = self.client.session
170        session[SESSION_KEY_PLAN] = plan
171        session.save()
172
173        res = self.client.get(
174            reverse(
175                "authentik_api:flow-executor",
176                kwargs={"flow_slug": self.flow.slug},
177            ),
178        )
179        self.assertEqual(res.status_code, 200)
180        for _ in range(self.stage.failed_attempts_before_cancel - 1):
181            response = self.client.post(
182                reverse(
183                    "authentik_api:flow-executor",
184                    kwargs={"flow_slug": self.flow.slug},
185                ),
186                # Form data
187                {"password": self.user.username + "test"},
188            )
189            self.assertEqual(response.status_code, 200)
190            self.assertStageResponse(
191                response,
192                flow=self.flow,
193                response_errors={"password": [{"string": "Invalid password", "code": "invalid"}]},
194            )
195
196        response = self.client.post(
197            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
198            # Form data
199            {"password": self.user.username + "test"},
200        )
201        self.assertEqual(response.status_code, 200)
202        # To ensure the plan has been cancelled, check SESSION_KEY_PLAN
203        self.assertNotIn(SESSION_KEY_PLAN, self.client.session)
204        self.assertStageResponse(response, flow=self.flow, error_message="Invalid password")
205
206    @patch(
207        "authentik.flows.views.executor.to_stage_response",
208        TO_STAGE_RESPONSE_MOCK,
209    )
210    @patch(
211        "authentik.core.auth.InbuiltBackend.authenticate",
212        MOCK_BACKEND_AUTHENTICATE,
213    )
214    def test_permission_denied(self):
215        """Test with a valid pending user and valid password.
216        Backend is patched to return PermissionError"""
217        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
218        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
219        session = self.client.session
220        session[SESSION_KEY_PLAN] = plan
221        session.save()
222
223        response = self.client.post(
224            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
225            # Form data
226            {"password": self.user.username + "test"},
227        )
228
229        self.assertStageResponse(
230            response,
231            self.flow,
232            component="ak-stage-access-denied",
233            error_message="Unknown error",
234        )
235
236
237class TestPasswordDevice(TestCase):
238    """Password device tests"""
239
240    def test_not_offered_as_mfa(self):
241        """Test password devices are not usable as a second factor"""
242        user = create_test_admin_user()
243        device = PasswordDevice.objects.get(user=user)
244
245        self.assertNotIn(PasswordDevice, list(device_classes()))
246        self.assertEqual(list(devices_for_user(user)), [])
247        self.assertIsNone(Device.from_persistent_id(device.persistent_id))
248
249    def test_set_password(self):
250        """Test changing a password replaces it on the user's only device"""
251        user = create_test_user()
252        PasswordDevice.set_password(user, "changed")
253
254        device = PasswordDevice.objects.get(user=user)
255        self.assertTrue(device.check_password("changed"))
256        self.assertFalse(device.check_password(user.username))
257        self.assertEqual(user.password, device.password)
258
259    def test_one_device_per_user(self):
260        """Test the database refuses a second password device"""
261        user = create_test_user()
262        with self.assertRaises(IntegrityError), transaction.atomic():
263            PasswordDevice.objects.create(user=user, name="Password", password="second")
264
265    def test_password_write_saves_user(self):
266        """Test password writes save the user, so sync and policy caches see the change"""
267        user = create_test_user()
268        for write in (
269            lambda: PasswordDevice.set_password(user, generate_id()),
270            lambda: PasswordDevice.set_password_from_hash(user, make_password(generate_id())),
271            lambda: PasswordDevice.set_unusable_password(user),
272        ):
273            with self.subTest(write=write), patch.object(post_save, "send") as send:
274                write()
275                self.assertIn(User, [call.kwargs["sender"] for call in send.call_args_list])
276
277    def test_password_change_keeps_lock(self):
278        """Test a new password clears failed attempts without unlocking"""
279        user = create_test_user()
280        locked_at = now()
281        PasswordDevice.objects.filter(user=user).update(failed_attempts=2, locked_at=locked_at)
282
283        PasswordDevice.set_password(user, generate_id())
284
285        device = PasswordDevice.objects.get(user=user)
286        self.assertEqual(device.failed_attempts, 0)
287        self.assertEqual(device.locked_at, locked_at)
288
289    def test_set_unusable_password(self):
290        """Test revoking a password keeps its device state and creates no device"""
291        user = create_test_user()
292        changed_at = user.password_change_date
293        PasswordDevice.objects.filter(user=user).update(failed_attempts=2)
294        PasswordDevice.set_unusable_password(user)
295
296        device = PasswordDevice.objects.get(user=user)
297        self.assertFalse(user.has_usable_password())
298        self.assertEqual(device.failed_attempts, 2)
299        self.assertEqual(device.password_change_date, changed_at)
300
301        without_device = User.objects.create(username=generate_id())
302        PasswordDevice.set_unusable_password(without_device)
303        self.assertFalse(PasswordDevice.objects.filter(user=without_device).exists())
304
305    def test_user_without_device(self):
306        """Test a user without a password device has no usable password"""
307        user = User.objects.create(username=generate_id())
308
309        self.assertFalse(user.has_usable_password())
310        self.assertEqual(user.password_change_date, user.date_joined)
311        self.assertIsNone(
312            InbuiltBackend().authenticate(None, username=user.username, password=user.username)
313        )
314
315    def test_hash_upgrade(self):
316        """Test rehashing keeps the change date, sends no signal and loses to a concurrent reset"""
317        user = create_test_user()
318        old_hash = PBKDF2PasswordHasher().encode("initial", "salt", iterations=1)
319        PasswordDevice.objects.filter(user=user).update(password=old_hash)
320        device = PasswordDevice.objects.get(user=user)
321        changed_at = device.password_change_date
322
323        with patch.object(password_changed, "send") as signal:
324            self.assertTrue(device.check_password("initial"))
325        signal.assert_not_called()
326        upgraded = PasswordDevice.objects.get(user=user)
327        self.assertNotEqual(upgraded.password, old_hash)
328        self.assertEqual(upgraded.password_change_date, changed_at)
329
330        PasswordDevice.objects.filter(user=user).update(password=old_hash)
331        device = PasswordDevice.objects.get(user=user)
332        reset_hash = make_password("reset")
333        PasswordDevice.objects.filter(user=user).update(password=reset_hash)
334        self.assertTrue(device.check_password("initial"))
335        self.assertEqual(PasswordDevice.objects.get(user=user).password, reset_hash)
336
337    def test_async_authenticate(self):
338        """Test async authentication runs the backend's own check"""
339        user = create_test_user()
340        self.assertEqual(
341            async_to_sync(InbuiltBackend().aauthenticate)(
342                None, username=user.username, password=user.username
343            ),
344            user,
345        )
346        self.assertIsNone(
347            async_to_sync(TokenBackend().aauthenticate)(
348                None, username=user.username, password=user.username
349            )
350        )
351
352    def test_changepassword(self):
353        """Test `ak changepassword` stores the password on the device"""
354        user = create_test_user()
355        with patch(
356            "authentik.admin.management.commands.changepassword.getpass", return_value="changed"
357        ):
358            call_command("changepassword", user.username, stdout=StringIO())
359        self.assertTrue(PasswordDevice.objects.get(user=user).check_password("changed"))
360
361
362class TestPasswordLockout(APIFlowTestCase):
363    """Password lockout tests"""
364
365    def setUp(self):
366        super().setUp()
367        self.licensed(True).start()
368        self.addCleanup(patch.stopall)
369
370        self.user = create_test_admin_user()
371        self.flow = create_test_flow(FlowDesignation.AUTHENTICATION)
372        self.stage = PasswordStage.objects.create(
373            name=generate_id(),
374            backends=[BACKEND_INBUILT],
375            failed_attempts_before_lockout=2,
376        )
377        self.binding = FlowStageBinding.objects.create(target=self.flow, stage=self.stage, order=2)
378
379    def licensed(self, valid: bool):
380        """Patch the license summary this stage reads to decide whether it may lock"""
381        summary = LicenseSummary(
382            internal_users=100,
383            external_users=100,
384            status=LicenseUsageStatus.VALID if valid else LicenseUsageStatus.UNLICENSED,
385            latest_valid=now(),
386            license_flags=[],
387        )
388        return patch(
389            "authentik.enterprise.stages.password.lockout.LicenseKey.cached_summary",
390            return_value=summary,
391        )
392
393    def start_flow(self):
394        """Put a plan with the test user pending into the session"""
395        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
396        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
397        session = self.client.session
398        session[SESSION_KEY_PLAN] = plan
399        session.save()
400
401    def submit(self, password: str):
402        return self.client.post(
403            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
404            {"password": password},
405        )
406
407    @property
408    def device(self) -> PasswordDevice:
409        return PasswordDevice.objects.get(user=self.user)
410
411    def test_locks_after_limit(self):
412        """Test the password is locked once the stage's limit is reached"""
413        self.start_flow()
414        response = self.submit("wrong")
415        self.assertEqual(self.device.failed_attempts, 1)
416        self.assertFalse(self.device.locked)
417        self.assertStageResponse(
418            response,
419            self.flow,
420            response_errors={"password": [{"string": "Invalid password", "code": "invalid"}]},
421        )
422
423        response = self.submit("wrong")
424        self.assertEqual(self.device.failed_attempts, 0)
425        self.assertTrue(self.device.locked)
426        self.assertStageResponse(
427            response,
428            self.flow,
429            component="ak-stage-access-denied",
430            error_message="Invalid password",
431        )
432        self.assertTrue(
433            Event.objects.filter(
434                action=EventAction.AUTHENTICATOR_LOCKED,
435                context__affected_user__pk=self.user.pk,
436            ).exists()
437        )
438
439    def test_locked_refuses_correct_password(self):
440        """Test a locked password is refused even when the submitted password is correct"""
441        device = self.device
442        device.locked_at = now()
443        device.save()
444
445        self.start_flow()
446        response = self.submit(self.user.username)
447        self.assertStageResponse(
448            response,
449            self.flow,
450            response_errors={"password": [{"string": "Invalid password", "code": "invalid"}]},
451        )
452
453        response = self.submit(self.user.username)
454        self.assertStageResponse(
455            response,
456            self.flow,
457            component="ak-stage-access-denied",
458            error_message="Invalid password",
459        )
460
461    def test_locked_password_refuses_app_password_in_flow(self):
462        """App passwords submitted through a password stage obey the same lock."""
463        token = Token.objects.create(
464            identifier=generate_id(), user=self.user, intent=TokenIntents.INTENT_APP_PASSWORD
465        )
466        self.stage.backends = [BACKEND_APP_PASSWORD]
467        self.stage.save()
468        self.start_flow()
469        self.assertStageRedirects(self.submit(token.key), reverse("authentik_core:root-redirect"))
470
471        PasswordDevice.objects.filter(user=self.user).update(locked_at=now())
472        self.start_flow()
473        self.assertStageResponse(
474            self.submit(token.key),
475            self.flow,
476            response_errors={"password": [{"string": "Invalid password", "code": "invalid"}]},
477        )
478
479    def test_success_resets_failures(self):
480        """Test authenticating successfully forgets earlier failures"""
481        for licensed in (True, False):
482            with self.subTest(licensed=licensed), self.licensed(licensed):
483                PasswordDevice.objects.filter(user=self.user).update(failed_attempts=1)
484                self.start_flow()
485                self.submit(self.user.username)
486                self.assertEqual(self.device.failed_attempts, 0)
487
488    def test_password_hash_upgrade_preserves_lock(self):
489        """Test upgrading a password hash keeps a lock set by another request"""
490        old_hash = PBKDF2PasswordHasher().encode("initial", "salt", iterations=1)
491        PasswordDevice.objects.filter(user=self.user).update(password=old_hash)
492        device = self.device
493        PasswordDevice.objects.filter(pk=device.pk).update(locked_at=now())
494
495        self.assertTrue(device.check_password("initial"))
496
497        device.refresh_from_db()
498        self.assertTrue(device.locked)
499        self.assertNotEqual(device.password, old_hash)
500
501    def test_unlicensed_never_locks(self):
502        """Test passwords are not locked without an enterprise license"""
503        with self.licensed(False):
504            self.start_flow()
505            self.submit("wrong")
506            self.submit("wrong")
507        self.assertFalse(self.device.locked)
508
509    def test_existing_lock_survives_license_expiry(self):
510        """Losing a license cannot re-enable a password an administrator locked."""
511        PasswordDevice.objects.filter(user=self.user).update(locked_at=now())
512        with self.licensed(False):
513            self.start_flow()
514            response = self.submit(self.user.username)
515        self.assertStageResponse(
516            response,
517            self.flow,
518            response_errors={"password": [{"string": "Invalid password", "code": "invalid"}]},
519        )
520
521    def test_locked_password_skips_backends_and_records_failure(self):
522        """Correct and incorrect locked passwords cause the same failed-login signal."""
523        PasswordDevice.objects.filter(user=self.user).update(locked_at=now())
524        for password in (self.user.username, "wrong"):
525            with self.subTest(password=password):
526                self.start_flow()
527                with (
528                    patch("authentik.core.auth.InbuiltBackend.authenticate") as backend,
529                    patch.object(login_failed, "send", wraps=login_failed.send) as failed,
530                    patch(
531                        "authentik.stages.password.stage.make_password", wraps=make_password
532                    ) as hash_password,
533                ):
534                    self.submit(password)
535                backend.assert_not_called()
536                hash_password.assert_called_once_with(password)
537                failed.assert_called_once()
538
539    def test_lock_during_authentication_records_failure(self):
540        """A lock set while a backend runs still rejects and records the attempt."""
541        PasswordDevice.objects.filter(user=self.user).update(locked_at=now())
542        with patch.object(login_failed, "send") as failed:
543            result = PasswordLockout(self.stage, RequestFactory().post("/")).apply(
544                self.user, self.user, {}
545            )
546        self.assertIsNone(result.user)
547        failed.assert_called_once()
548
549    def test_lock_enforcement_without_enterprise(self):
550        """The OSS implementation enforces existing locks but creates none."""
551        policy = PasswordLockoutBase(self.stage, RequestFactory().post("/"))
552        self.assertEqual(policy.apply(self.user, self.user, {}), PasswordLockoutResult(self.user))
553        for _ in range(self.stage.failed_attempts_before_lockout):
554            self.assertEqual(policy.apply(self.user, None, {}), PasswordLockoutResult())
555        self.assertFalse(self.device.locked)
556        PasswordDevice.objects.filter(user=self.user).update(locked_at=now())
557        self.assertIsNone(policy.apply(self.user, self.user, {}).user)
558
559    def test_external_password_exemption_requires_enabled_source(self):
560        """Disabled sources must not exempt locally verified passwords from lockout."""
561        for backend, model in ((BACKEND_LDAP, LDAPSource), (BACKEND_KERBEROS, KerberosSource)):
562            with self.subTest(backend=backend):
563                source = model.objects.create(name=generate_id(), slug=generate_id())
564                if backend == BACKEND_LDAP:
565                    self.user.attributes[LDAP_DISTINGUISHED_NAME] = "cn=user,dc=example,dc=com"
566                    self.user.save()
567                else:
568                    UserKerberosSourceConnection.objects.create(
569                        source=source, user=self.user, identifier="user@EXAMPLE.COM"
570                    )
571                self.stage.backends = [BACKEND_INBUILT, backend]
572                policy = PasswordLockout(self.stage, RequestFactory().post("/"))
573                PasswordDevice.objects.filter(user=self.user).update(failed_attempts=0)
574                policy.apply(self.user, None, {})
575                self.assertEqual(self.device.failed_attempts, 0)
576                source.enabled = False
577                source.save()
578                policy.apply(self.user, None, {})
579                self.assertEqual(self.device.failed_attempts, 1)
580
581    def test_custom_messages(self):
582        """Test custom warning and lockout messages are returned"""
583        self.stage.last_attempt_warning_message = "One attempt remains."
584        self.stage.lockout_message = "Contact support."
585        self.stage.save()
586        self.start_flow()
587
588        response = self.submit("wrong")
589        self.assertStageResponse(
590            response,
591            self.flow,
592            response_errors={"password": [{"string": "One attempt remains.", "code": "invalid"}]},
593        )
594
595        response = self.submit("wrong")
596        self.assertStageResponse(
597            response,
598            self.flow,
599            component="ak-stage-access-denied",
600            error_message="Contact support.",
601        )
602
603    def test_flow_cancel_preserves_last_attempt_warning(self):
604        """Test flow cancellation keeps a warning returned on the same attempt"""
605        self.stage.failed_attempts_before_cancel = 1
606        self.stage.last_attempt_warning_message = "One attempt remains."
607        self.stage.save(
608            update_fields=("failed_attempts_before_cancel", "last_attempt_warning_message")
609        )
610        self.start_flow()
611        self.client.get(
612            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
613        )
614
615        response = self.submit("wrong")
616
617        self.assertNotIn(SESSION_KEY_PLAN, self.client.session)
618        self.assertStageResponse(
619            response,
620            self.flow,
621            error_message="One attempt remains.",
622        )
623
624    def test_service_accounts_are_exempt(self):
625        """Both service account types bypass automatic and explicit locking."""
626        self.client.force_login(self.user)
627        for user_type in (UserTypes.SERVICE_ACCOUNT, UserTypes.INTERNAL_SERVICE_ACCOUNT):
628            with self.subTest(user_type=user_type):
629                user = create_test_admin_user(type=user_type)
630                policy = PasswordLockout(self.stage, RequestFactory().post("/"))
631                for _ in range(self.stage.failed_attempts_before_lockout + 1):
632                    self.assertEqual(policy.apply(user, None, {}), PasswordLockoutResult())
633                response = self.client.post(
634                    reverse(
635                        "authentik_api:passworddevice-lock", kwargs={"pk": user.password_device.pk}
636                    )
637                )
638                self.assertEqual(response.status_code, 400)
639                device = PasswordDevice.objects.get(user=user)
640                self.assertFalse(device.locked)
641                self.assertEqual(device.failed_attempts, 0)
642                self.assertFalse(
643                    Event.objects.filter(
644                        action=EventAction.AUTHENTICATOR_LOCKED, context__affected_user__pk=user.pk
645                    ).exists()
646                )
647
648    def test_service_account_conversion_bypasses_existing_lock(self):
649        """Converting a locked user to a service account stops enforcing the lock."""
650        PasswordDevice.objects.filter(user=self.user).update(locked_at=now())
651        policy = PasswordLockout(self.stage, RequestFactory().post("/"))
652        for user_type in (UserTypes.SERVICE_ACCOUNT, UserTypes.INTERNAL_SERVICE_ACCOUNT):
653            with self.subTest(user_type=user_type):
654                self.user.type = user_type
655                self.user.save()
656                self.assertEqual(
657                    policy.apply(self.user, self.user, {}), PasswordLockoutResult(self.user)
658                )
659
660
661class TestPasswordLockoutConcurrency(TransactionTestCase):
662    """Password lockout concurrency tests"""
663
664    def test_concurrent_failures(self):
665        """Concurrent failures update one serialized counter"""
666        user = create_test_admin_user()
667        request = RequestFactory().post("/")
668        stage = PasswordStage.objects.create(
669            name=generate_id(), backends=[BACKEND_INBUILT], failed_attempts_before_lockout=3
670        )
671
672        ready = Barrier(3)
673
674        def fail_password():
675            try:
676                ready.wait(timeout=10)
677                return PasswordLockout(stage, request).apply(user, None, {})
678            finally:
679                connection.close()
680
681        connection.close()
682        with patch("authentik.enterprise.license.LicenseKey.cached_summary") as summary:
683            summary.return_value.status.is_valid = True
684            with ThreadPoolExecutor(max_workers=3) as pool:
685                futures = [pool.submit(fail_password) for _ in range(3)]
686                results = [future.result(timeout=10) for future in futures]
687
688        device = PasswordDevice.objects.get(user=user)
689        self.assertTrue(device.locked)
690        self.assertCountEqual(
691            results,
692            [
693                PasswordLockoutResult(),
694                PasswordLockoutResult(last_attempt=True),
695                PasswordLockoutResult(lockout_reached=True),
696            ],
697        )
698        self.assertEqual(
699            Event.objects.filter(
700                action=EventAction.AUTHENTICATOR_LOCKED,
701                context__affected_user__pk=user.pk,
702            ).count(),
703            1,
704        )
MOCK_BACKEND_AUTHENTICATE = <MagicMock id='123519816323088'>
class TestPasswordStage(authentik.flows.tests.APIFlowTestCase):
 58class TestPasswordStage(APIFlowTestCase):
 59    """Password tests"""
 60
 61    def setUp(self):
 62        super().setUp()
 63        self.user = create_test_admin_user()
 64
 65        self.flow = create_test_flow(FlowDesignation.AUTHENTICATION)
 66        self.stage = PasswordStage.objects.create(name=generate_id(), backends=[BACKEND_INBUILT])
 67        self.binding = FlowStageBinding.objects.create(target=self.flow, stage=self.stage, order=2)
 68
 69    @patch(
 70        "authentik.flows.views.executor.to_stage_response",
 71        TO_STAGE_RESPONSE_MOCK,
 72    )
 73    def test_without_user(self):
 74        """Test without user"""
 75        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
 76        session = self.client.session
 77        session[SESSION_KEY_PLAN] = plan
 78        session.save()
 79
 80        response = self.client.post(
 81            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
 82            # Still have to send the password so the form is valid
 83            {"password": self.user.username},
 84        )
 85
 86        self.assertStageResponse(
 87            response,
 88            self.flow,
 89            component="ak-stage-access-denied",
 90            error_message="Unknown error",
 91        )
 92
 93    def test_recovery_flow_link(self):
 94        """Test link to the default recovery flow"""
 95        flow = create_test_flow(designation=FlowDesignation.RECOVERY)
 96        brand = create_test_brand()
 97        brand.flow_recovery = flow
 98        brand.save()
 99
100        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
101        session = self.client.session
102        session[SESSION_KEY_PLAN] = plan
103        session.save()
104
105        response = self.client.get(
106            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
107        )
108        self.assertEqual(response.status_code, 200)
109        self.assertIn(flow.slug, response.content.decode())
110
111    def test_valid_password(self):
112        """Test with a valid pending user and valid password"""
113        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
114        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
115        session = self.client.session
116        session[SESSION_KEY_PLAN] = plan
117        session.save()
118
119        response = self.client.post(
120            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
121            # Form data
122            {"password": self.user.username},
123        )
124
125        self.assertEqual(response.status_code, 200)
126        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
127
128    def test_valid_password_inactive(self):
129        """Test with a valid pending user and valid password"""
130        self.user.is_active = False
131        self.user.save()
132        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
133        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
134        session = self.client.session
135        session[SESSION_KEY_PLAN] = plan
136        session.save()
137
138        response = self.client.post(
139            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
140            # Form data
141            {"password": self.user.username},
142        )
143
144        self.assertEqual(response.status_code, 200)
145        self.assertStageResponse(
146            response,
147            self.flow,
148            response_errors={"password": [{"string": "Invalid password", "code": "invalid"}]},
149        )
150
151    def test_invalid_password(self):
152        """Test with a valid pending user and invalid password"""
153        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
154        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
155        session = self.client.session
156        session[SESSION_KEY_PLAN] = plan
157        session.save()
158
159        response = self.client.post(
160            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
161            # Form data
162            {"password": self.user.username + "test"},
163        )
164        self.assertEqual(response.status_code, 200)
165
166    def test_invalid_password_lockout(self):
167        """Test with a valid pending user and invalid password (trigger logout counter)"""
168        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
169        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
170        session = self.client.session
171        session[SESSION_KEY_PLAN] = plan
172        session.save()
173
174        res = self.client.get(
175            reverse(
176                "authentik_api:flow-executor",
177                kwargs={"flow_slug": self.flow.slug},
178            ),
179        )
180        self.assertEqual(res.status_code, 200)
181        for _ in range(self.stage.failed_attempts_before_cancel - 1):
182            response = self.client.post(
183                reverse(
184                    "authentik_api:flow-executor",
185                    kwargs={"flow_slug": self.flow.slug},
186                ),
187                # Form data
188                {"password": self.user.username + "test"},
189            )
190            self.assertEqual(response.status_code, 200)
191            self.assertStageResponse(
192                response,
193                flow=self.flow,
194                response_errors={"password": [{"string": "Invalid password", "code": "invalid"}]},
195            )
196
197        response = self.client.post(
198            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
199            # Form data
200            {"password": self.user.username + "test"},
201        )
202        self.assertEqual(response.status_code, 200)
203        # To ensure the plan has been cancelled, check SESSION_KEY_PLAN
204        self.assertNotIn(SESSION_KEY_PLAN, self.client.session)
205        self.assertStageResponse(response, flow=self.flow, error_message="Invalid password")
206
207    @patch(
208        "authentik.flows.views.executor.to_stage_response",
209        TO_STAGE_RESPONSE_MOCK,
210    )
211    @patch(
212        "authentik.core.auth.InbuiltBackend.authenticate",
213        MOCK_BACKEND_AUTHENTICATE,
214    )
215    def test_permission_denied(self):
216        """Test with a valid pending user and valid password.
217        Backend is patched to return PermissionError"""
218        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
219        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
220        session = self.client.session
221        session[SESSION_KEY_PLAN] = plan
222        session.save()
223
224        response = self.client.post(
225            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
226            # Form data
227            {"password": self.user.username + "test"},
228        )
229
230        self.assertStageResponse(
231            response,
232            self.flow,
233            component="ak-stage-access-denied",
234            error_message="Unknown error",
235        )

Password tests

def setUp(self):
61    def setUp(self):
62        super().setUp()
63        self.user = create_test_admin_user()
64
65        self.flow = create_test_flow(FlowDesignation.AUTHENTICATION)
66        self.stage = PasswordStage.objects.create(name=generate_id(), backends=[BACKEND_INBUILT])
67        self.binding = FlowStageBinding.objects.create(target=self.flow, stage=self.stage, order=2)

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

@patch('authentik.flows.views.executor.to_stage_response', TO_STAGE_RESPONSE_MOCK)
def test_without_user(self):
69    @patch(
70        "authentik.flows.views.executor.to_stage_response",
71        TO_STAGE_RESPONSE_MOCK,
72    )
73    def test_without_user(self):
74        """Test without user"""
75        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
76        session = self.client.session
77        session[SESSION_KEY_PLAN] = plan
78        session.save()
79
80        response = self.client.post(
81            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
82            # Still have to send the password so the form is valid
83            {"password": self.user.username},
84        )
85
86        self.assertStageResponse(
87            response,
88            self.flow,
89            component="ak-stage-access-denied",
90            error_message="Unknown error",
91        )

Test without user

def test_valid_password(self):
111    def test_valid_password(self):
112        """Test with a valid pending user and valid password"""
113        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
114        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
115        session = self.client.session
116        session[SESSION_KEY_PLAN] = plan
117        session.save()
118
119        response = self.client.post(
120            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
121            # Form data
122            {"password": self.user.username},
123        )
124
125        self.assertEqual(response.status_code, 200)
126        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))

Test with a valid pending user and valid password

def test_valid_password_inactive(self):
128    def test_valid_password_inactive(self):
129        """Test with a valid pending user and valid password"""
130        self.user.is_active = False
131        self.user.save()
132        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
133        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
134        session = self.client.session
135        session[SESSION_KEY_PLAN] = plan
136        session.save()
137
138        response = self.client.post(
139            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
140            # Form data
141            {"password": self.user.username},
142        )
143
144        self.assertEqual(response.status_code, 200)
145        self.assertStageResponse(
146            response,
147            self.flow,
148            response_errors={"password": [{"string": "Invalid password", "code": "invalid"}]},
149        )

Test with a valid pending user and valid password

def test_invalid_password(self):
151    def test_invalid_password(self):
152        """Test with a valid pending user and invalid password"""
153        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
154        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
155        session = self.client.session
156        session[SESSION_KEY_PLAN] = plan
157        session.save()
158
159        response = self.client.post(
160            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
161            # Form data
162            {"password": self.user.username + "test"},
163        )
164        self.assertEqual(response.status_code, 200)

Test with a valid pending user and invalid password

def test_invalid_password_lockout(self):
166    def test_invalid_password_lockout(self):
167        """Test with a valid pending user and invalid password (trigger logout counter)"""
168        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
169        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
170        session = self.client.session
171        session[SESSION_KEY_PLAN] = plan
172        session.save()
173
174        res = self.client.get(
175            reverse(
176                "authentik_api:flow-executor",
177                kwargs={"flow_slug": self.flow.slug},
178            ),
179        )
180        self.assertEqual(res.status_code, 200)
181        for _ in range(self.stage.failed_attempts_before_cancel - 1):
182            response = self.client.post(
183                reverse(
184                    "authentik_api:flow-executor",
185                    kwargs={"flow_slug": self.flow.slug},
186                ),
187                # Form data
188                {"password": self.user.username + "test"},
189            )
190            self.assertEqual(response.status_code, 200)
191            self.assertStageResponse(
192                response,
193                flow=self.flow,
194                response_errors={"password": [{"string": "Invalid password", "code": "invalid"}]},
195            )
196
197        response = self.client.post(
198            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
199            # Form data
200            {"password": self.user.username + "test"},
201        )
202        self.assertEqual(response.status_code, 200)
203        # To ensure the plan has been cancelled, check SESSION_KEY_PLAN
204        self.assertNotIn(SESSION_KEY_PLAN, self.client.session)
205        self.assertStageResponse(response, flow=self.flow, error_message="Invalid password")

Test with a valid pending user and invalid password (trigger logout counter)

@patch('authentik.flows.views.executor.to_stage_response', TO_STAGE_RESPONSE_MOCK)
@patch('authentik.core.auth.InbuiltBackend.authenticate', MOCK_BACKEND_AUTHENTICATE)
def test_permission_denied(self):
207    @patch(
208        "authentik.flows.views.executor.to_stage_response",
209        TO_STAGE_RESPONSE_MOCK,
210    )
211    @patch(
212        "authentik.core.auth.InbuiltBackend.authenticate",
213        MOCK_BACKEND_AUTHENTICATE,
214    )
215    def test_permission_denied(self):
216        """Test with a valid pending user and valid password.
217        Backend is patched to return PermissionError"""
218        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
219        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
220        session = self.client.session
221        session[SESSION_KEY_PLAN] = plan
222        session.save()
223
224        response = self.client.post(
225            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
226            # Form data
227            {"password": self.user.username + "test"},
228        )
229
230        self.assertStageResponse(
231            response,
232            self.flow,
233            component="ak-stage-access-denied",
234            error_message="Unknown error",
235        )

Test with a valid pending user and valid password. Backend is patched to return PermissionError

class TestPasswordDevice(django.test.testcases.TestCase):
238class TestPasswordDevice(TestCase):
239    """Password device tests"""
240
241    def test_not_offered_as_mfa(self):
242        """Test password devices are not usable as a second factor"""
243        user = create_test_admin_user()
244        device = PasswordDevice.objects.get(user=user)
245
246        self.assertNotIn(PasswordDevice, list(device_classes()))
247        self.assertEqual(list(devices_for_user(user)), [])
248        self.assertIsNone(Device.from_persistent_id(device.persistent_id))
249
250    def test_set_password(self):
251        """Test changing a password replaces it on the user's only device"""
252        user = create_test_user()
253        PasswordDevice.set_password(user, "changed")
254
255        device = PasswordDevice.objects.get(user=user)
256        self.assertTrue(device.check_password("changed"))
257        self.assertFalse(device.check_password(user.username))
258        self.assertEqual(user.password, device.password)
259
260    def test_one_device_per_user(self):
261        """Test the database refuses a second password device"""
262        user = create_test_user()
263        with self.assertRaises(IntegrityError), transaction.atomic():
264            PasswordDevice.objects.create(user=user, name="Password", password="second")
265
266    def test_password_write_saves_user(self):
267        """Test password writes save the user, so sync and policy caches see the change"""
268        user = create_test_user()
269        for write in (
270            lambda: PasswordDevice.set_password(user, generate_id()),
271            lambda: PasswordDevice.set_password_from_hash(user, make_password(generate_id())),
272            lambda: PasswordDevice.set_unusable_password(user),
273        ):
274            with self.subTest(write=write), patch.object(post_save, "send") as send:
275                write()
276                self.assertIn(User, [call.kwargs["sender"] for call in send.call_args_list])
277
278    def test_password_change_keeps_lock(self):
279        """Test a new password clears failed attempts without unlocking"""
280        user = create_test_user()
281        locked_at = now()
282        PasswordDevice.objects.filter(user=user).update(failed_attempts=2, locked_at=locked_at)
283
284        PasswordDevice.set_password(user, generate_id())
285
286        device = PasswordDevice.objects.get(user=user)
287        self.assertEqual(device.failed_attempts, 0)
288        self.assertEqual(device.locked_at, locked_at)
289
290    def test_set_unusable_password(self):
291        """Test revoking a password keeps its device state and creates no device"""
292        user = create_test_user()
293        changed_at = user.password_change_date
294        PasswordDevice.objects.filter(user=user).update(failed_attempts=2)
295        PasswordDevice.set_unusable_password(user)
296
297        device = PasswordDevice.objects.get(user=user)
298        self.assertFalse(user.has_usable_password())
299        self.assertEqual(device.failed_attempts, 2)
300        self.assertEqual(device.password_change_date, changed_at)
301
302        without_device = User.objects.create(username=generate_id())
303        PasswordDevice.set_unusable_password(without_device)
304        self.assertFalse(PasswordDevice.objects.filter(user=without_device).exists())
305
306    def test_user_without_device(self):
307        """Test a user without a password device has no usable password"""
308        user = User.objects.create(username=generate_id())
309
310        self.assertFalse(user.has_usable_password())
311        self.assertEqual(user.password_change_date, user.date_joined)
312        self.assertIsNone(
313            InbuiltBackend().authenticate(None, username=user.username, password=user.username)
314        )
315
316    def test_hash_upgrade(self):
317        """Test rehashing keeps the change date, sends no signal and loses to a concurrent reset"""
318        user = create_test_user()
319        old_hash = PBKDF2PasswordHasher().encode("initial", "salt", iterations=1)
320        PasswordDevice.objects.filter(user=user).update(password=old_hash)
321        device = PasswordDevice.objects.get(user=user)
322        changed_at = device.password_change_date
323
324        with patch.object(password_changed, "send") as signal:
325            self.assertTrue(device.check_password("initial"))
326        signal.assert_not_called()
327        upgraded = PasswordDevice.objects.get(user=user)
328        self.assertNotEqual(upgraded.password, old_hash)
329        self.assertEqual(upgraded.password_change_date, changed_at)
330
331        PasswordDevice.objects.filter(user=user).update(password=old_hash)
332        device = PasswordDevice.objects.get(user=user)
333        reset_hash = make_password("reset")
334        PasswordDevice.objects.filter(user=user).update(password=reset_hash)
335        self.assertTrue(device.check_password("initial"))
336        self.assertEqual(PasswordDevice.objects.get(user=user).password, reset_hash)
337
338    def test_async_authenticate(self):
339        """Test async authentication runs the backend's own check"""
340        user = create_test_user()
341        self.assertEqual(
342            async_to_sync(InbuiltBackend().aauthenticate)(
343                None, username=user.username, password=user.username
344            ),
345            user,
346        )
347        self.assertIsNone(
348            async_to_sync(TokenBackend().aauthenticate)(
349                None, username=user.username, password=user.username
350            )
351        )
352
353    def test_changepassword(self):
354        """Test `ak changepassword` stores the password on the device"""
355        user = create_test_user()
356        with patch(
357            "authentik.admin.management.commands.changepassword.getpass", return_value="changed"
358        ):
359            call_command("changepassword", user.username, stdout=StringIO())
360        self.assertTrue(PasswordDevice.objects.get(user=user).check_password("changed"))

Password device tests

def test_not_offered_as_mfa(self):
241    def test_not_offered_as_mfa(self):
242        """Test password devices are not usable as a second factor"""
243        user = create_test_admin_user()
244        device = PasswordDevice.objects.get(user=user)
245
246        self.assertNotIn(PasswordDevice, list(device_classes()))
247        self.assertEqual(list(devices_for_user(user)), [])
248        self.assertIsNone(Device.from_persistent_id(device.persistent_id))

Test password devices are not usable as a second factor

def test_set_password(self):
250    def test_set_password(self):
251        """Test changing a password replaces it on the user's only device"""
252        user = create_test_user()
253        PasswordDevice.set_password(user, "changed")
254
255        device = PasswordDevice.objects.get(user=user)
256        self.assertTrue(device.check_password("changed"))
257        self.assertFalse(device.check_password(user.username))
258        self.assertEqual(user.password, device.password)

Test changing a password replaces it on the user's only device

def test_one_device_per_user(self):
260    def test_one_device_per_user(self):
261        """Test the database refuses a second password device"""
262        user = create_test_user()
263        with self.assertRaises(IntegrityError), transaction.atomic():
264            PasswordDevice.objects.create(user=user, name="Password", password="second")

Test the database refuses a second password device

def test_password_write_saves_user(self):
266    def test_password_write_saves_user(self):
267        """Test password writes save the user, so sync and policy caches see the change"""
268        user = create_test_user()
269        for write in (
270            lambda: PasswordDevice.set_password(user, generate_id()),
271            lambda: PasswordDevice.set_password_from_hash(user, make_password(generate_id())),
272            lambda: PasswordDevice.set_unusable_password(user),
273        ):
274            with self.subTest(write=write), patch.object(post_save, "send") as send:
275                write()
276                self.assertIn(User, [call.kwargs["sender"] for call in send.call_args_list])

Test password writes save the user, so sync and policy caches see the change

def test_password_change_keeps_lock(self):
278    def test_password_change_keeps_lock(self):
279        """Test a new password clears failed attempts without unlocking"""
280        user = create_test_user()
281        locked_at = now()
282        PasswordDevice.objects.filter(user=user).update(failed_attempts=2, locked_at=locked_at)
283
284        PasswordDevice.set_password(user, generate_id())
285
286        device = PasswordDevice.objects.get(user=user)
287        self.assertEqual(device.failed_attempts, 0)
288        self.assertEqual(device.locked_at, locked_at)

Test a new password clears failed attempts without unlocking

def test_set_unusable_password(self):
290    def test_set_unusable_password(self):
291        """Test revoking a password keeps its device state and creates no device"""
292        user = create_test_user()
293        changed_at = user.password_change_date
294        PasswordDevice.objects.filter(user=user).update(failed_attempts=2)
295        PasswordDevice.set_unusable_password(user)
296
297        device = PasswordDevice.objects.get(user=user)
298        self.assertFalse(user.has_usable_password())
299        self.assertEqual(device.failed_attempts, 2)
300        self.assertEqual(device.password_change_date, changed_at)
301
302        without_device = User.objects.create(username=generate_id())
303        PasswordDevice.set_unusable_password(without_device)
304        self.assertFalse(PasswordDevice.objects.filter(user=without_device).exists())

Test revoking a password keeps its device state and creates no device

def test_user_without_device(self):
306    def test_user_without_device(self):
307        """Test a user without a password device has no usable password"""
308        user = User.objects.create(username=generate_id())
309
310        self.assertFalse(user.has_usable_password())
311        self.assertEqual(user.password_change_date, user.date_joined)
312        self.assertIsNone(
313            InbuiltBackend().authenticate(None, username=user.username, password=user.username)
314        )

Test a user without a password device has no usable password

def test_hash_upgrade(self):
316    def test_hash_upgrade(self):
317        """Test rehashing keeps the change date, sends no signal and loses to a concurrent reset"""
318        user = create_test_user()
319        old_hash = PBKDF2PasswordHasher().encode("initial", "salt", iterations=1)
320        PasswordDevice.objects.filter(user=user).update(password=old_hash)
321        device = PasswordDevice.objects.get(user=user)
322        changed_at = device.password_change_date
323
324        with patch.object(password_changed, "send") as signal:
325            self.assertTrue(device.check_password("initial"))
326        signal.assert_not_called()
327        upgraded = PasswordDevice.objects.get(user=user)
328        self.assertNotEqual(upgraded.password, old_hash)
329        self.assertEqual(upgraded.password_change_date, changed_at)
330
331        PasswordDevice.objects.filter(user=user).update(password=old_hash)
332        device = PasswordDevice.objects.get(user=user)
333        reset_hash = make_password("reset")
334        PasswordDevice.objects.filter(user=user).update(password=reset_hash)
335        self.assertTrue(device.check_password("initial"))
336        self.assertEqual(PasswordDevice.objects.get(user=user).password, reset_hash)

Test rehashing keeps the change date, sends no signal and loses to a concurrent reset

def test_async_authenticate(self):
338    def test_async_authenticate(self):
339        """Test async authentication runs the backend's own check"""
340        user = create_test_user()
341        self.assertEqual(
342            async_to_sync(InbuiltBackend().aauthenticate)(
343                None, username=user.username, password=user.username
344            ),
345            user,
346        )
347        self.assertIsNone(
348            async_to_sync(TokenBackend().aauthenticate)(
349                None, username=user.username, password=user.username
350            )
351        )

Test async authentication runs the backend's own check

def test_changepassword(self):
353    def test_changepassword(self):
354        """Test `ak changepassword` stores the password on the device"""
355        user = create_test_user()
356        with patch(
357            "authentik.admin.management.commands.changepassword.getpass", return_value="changed"
358        ):
359            call_command("changepassword", user.username, stdout=StringIO())
360        self.assertTrue(PasswordDevice.objects.get(user=user).check_password("changed"))

Test ak changepassword stores the password on the device

class TestPasswordLockout(authentik.flows.tests.APIFlowTestCase):
363class TestPasswordLockout(APIFlowTestCase):
364    """Password lockout tests"""
365
366    def setUp(self):
367        super().setUp()
368        self.licensed(True).start()
369        self.addCleanup(patch.stopall)
370
371        self.user = create_test_admin_user()
372        self.flow = create_test_flow(FlowDesignation.AUTHENTICATION)
373        self.stage = PasswordStage.objects.create(
374            name=generate_id(),
375            backends=[BACKEND_INBUILT],
376            failed_attempts_before_lockout=2,
377        )
378        self.binding = FlowStageBinding.objects.create(target=self.flow, stage=self.stage, order=2)
379
380    def licensed(self, valid: bool):
381        """Patch the license summary this stage reads to decide whether it may lock"""
382        summary = LicenseSummary(
383            internal_users=100,
384            external_users=100,
385            status=LicenseUsageStatus.VALID if valid else LicenseUsageStatus.UNLICENSED,
386            latest_valid=now(),
387            license_flags=[],
388        )
389        return patch(
390            "authentik.enterprise.stages.password.lockout.LicenseKey.cached_summary",
391            return_value=summary,
392        )
393
394    def start_flow(self):
395        """Put a plan with the test user pending into the session"""
396        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
397        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
398        session = self.client.session
399        session[SESSION_KEY_PLAN] = plan
400        session.save()
401
402    def submit(self, password: str):
403        return self.client.post(
404            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
405            {"password": password},
406        )
407
408    @property
409    def device(self) -> PasswordDevice:
410        return PasswordDevice.objects.get(user=self.user)
411
412    def test_locks_after_limit(self):
413        """Test the password is locked once the stage's limit is reached"""
414        self.start_flow()
415        response = self.submit("wrong")
416        self.assertEqual(self.device.failed_attempts, 1)
417        self.assertFalse(self.device.locked)
418        self.assertStageResponse(
419            response,
420            self.flow,
421            response_errors={"password": [{"string": "Invalid password", "code": "invalid"}]},
422        )
423
424        response = self.submit("wrong")
425        self.assertEqual(self.device.failed_attempts, 0)
426        self.assertTrue(self.device.locked)
427        self.assertStageResponse(
428            response,
429            self.flow,
430            component="ak-stage-access-denied",
431            error_message="Invalid password",
432        )
433        self.assertTrue(
434            Event.objects.filter(
435                action=EventAction.AUTHENTICATOR_LOCKED,
436                context__affected_user__pk=self.user.pk,
437            ).exists()
438        )
439
440    def test_locked_refuses_correct_password(self):
441        """Test a locked password is refused even when the submitted password is correct"""
442        device = self.device
443        device.locked_at = now()
444        device.save()
445
446        self.start_flow()
447        response = self.submit(self.user.username)
448        self.assertStageResponse(
449            response,
450            self.flow,
451            response_errors={"password": [{"string": "Invalid password", "code": "invalid"}]},
452        )
453
454        response = self.submit(self.user.username)
455        self.assertStageResponse(
456            response,
457            self.flow,
458            component="ak-stage-access-denied",
459            error_message="Invalid password",
460        )
461
462    def test_locked_password_refuses_app_password_in_flow(self):
463        """App passwords submitted through a password stage obey the same lock."""
464        token = Token.objects.create(
465            identifier=generate_id(), user=self.user, intent=TokenIntents.INTENT_APP_PASSWORD
466        )
467        self.stage.backends = [BACKEND_APP_PASSWORD]
468        self.stage.save()
469        self.start_flow()
470        self.assertStageRedirects(self.submit(token.key), reverse("authentik_core:root-redirect"))
471
472        PasswordDevice.objects.filter(user=self.user).update(locked_at=now())
473        self.start_flow()
474        self.assertStageResponse(
475            self.submit(token.key),
476            self.flow,
477            response_errors={"password": [{"string": "Invalid password", "code": "invalid"}]},
478        )
479
480    def test_success_resets_failures(self):
481        """Test authenticating successfully forgets earlier failures"""
482        for licensed in (True, False):
483            with self.subTest(licensed=licensed), self.licensed(licensed):
484                PasswordDevice.objects.filter(user=self.user).update(failed_attempts=1)
485                self.start_flow()
486                self.submit(self.user.username)
487                self.assertEqual(self.device.failed_attempts, 0)
488
489    def test_password_hash_upgrade_preserves_lock(self):
490        """Test upgrading a password hash keeps a lock set by another request"""
491        old_hash = PBKDF2PasswordHasher().encode("initial", "salt", iterations=1)
492        PasswordDevice.objects.filter(user=self.user).update(password=old_hash)
493        device = self.device
494        PasswordDevice.objects.filter(pk=device.pk).update(locked_at=now())
495
496        self.assertTrue(device.check_password("initial"))
497
498        device.refresh_from_db()
499        self.assertTrue(device.locked)
500        self.assertNotEqual(device.password, old_hash)
501
502    def test_unlicensed_never_locks(self):
503        """Test passwords are not locked without an enterprise license"""
504        with self.licensed(False):
505            self.start_flow()
506            self.submit("wrong")
507            self.submit("wrong")
508        self.assertFalse(self.device.locked)
509
510    def test_existing_lock_survives_license_expiry(self):
511        """Losing a license cannot re-enable a password an administrator locked."""
512        PasswordDevice.objects.filter(user=self.user).update(locked_at=now())
513        with self.licensed(False):
514            self.start_flow()
515            response = self.submit(self.user.username)
516        self.assertStageResponse(
517            response,
518            self.flow,
519            response_errors={"password": [{"string": "Invalid password", "code": "invalid"}]},
520        )
521
522    def test_locked_password_skips_backends_and_records_failure(self):
523        """Correct and incorrect locked passwords cause the same failed-login signal."""
524        PasswordDevice.objects.filter(user=self.user).update(locked_at=now())
525        for password in (self.user.username, "wrong"):
526            with self.subTest(password=password):
527                self.start_flow()
528                with (
529                    patch("authentik.core.auth.InbuiltBackend.authenticate") as backend,
530                    patch.object(login_failed, "send", wraps=login_failed.send) as failed,
531                    patch(
532                        "authentik.stages.password.stage.make_password", wraps=make_password
533                    ) as hash_password,
534                ):
535                    self.submit(password)
536                backend.assert_not_called()
537                hash_password.assert_called_once_with(password)
538                failed.assert_called_once()
539
540    def test_lock_during_authentication_records_failure(self):
541        """A lock set while a backend runs still rejects and records the attempt."""
542        PasswordDevice.objects.filter(user=self.user).update(locked_at=now())
543        with patch.object(login_failed, "send") as failed:
544            result = PasswordLockout(self.stage, RequestFactory().post("/")).apply(
545                self.user, self.user, {}
546            )
547        self.assertIsNone(result.user)
548        failed.assert_called_once()
549
550    def test_lock_enforcement_without_enterprise(self):
551        """The OSS implementation enforces existing locks but creates none."""
552        policy = PasswordLockoutBase(self.stage, RequestFactory().post("/"))
553        self.assertEqual(policy.apply(self.user, self.user, {}), PasswordLockoutResult(self.user))
554        for _ in range(self.stage.failed_attempts_before_lockout):
555            self.assertEqual(policy.apply(self.user, None, {}), PasswordLockoutResult())
556        self.assertFalse(self.device.locked)
557        PasswordDevice.objects.filter(user=self.user).update(locked_at=now())
558        self.assertIsNone(policy.apply(self.user, self.user, {}).user)
559
560    def test_external_password_exemption_requires_enabled_source(self):
561        """Disabled sources must not exempt locally verified passwords from lockout."""
562        for backend, model in ((BACKEND_LDAP, LDAPSource), (BACKEND_KERBEROS, KerberosSource)):
563            with self.subTest(backend=backend):
564                source = model.objects.create(name=generate_id(), slug=generate_id())
565                if backend == BACKEND_LDAP:
566                    self.user.attributes[LDAP_DISTINGUISHED_NAME] = "cn=user,dc=example,dc=com"
567                    self.user.save()
568                else:
569                    UserKerberosSourceConnection.objects.create(
570                        source=source, user=self.user, identifier="user@EXAMPLE.COM"
571                    )
572                self.stage.backends = [BACKEND_INBUILT, backend]
573                policy = PasswordLockout(self.stage, RequestFactory().post("/"))
574                PasswordDevice.objects.filter(user=self.user).update(failed_attempts=0)
575                policy.apply(self.user, None, {})
576                self.assertEqual(self.device.failed_attempts, 0)
577                source.enabled = False
578                source.save()
579                policy.apply(self.user, None, {})
580                self.assertEqual(self.device.failed_attempts, 1)
581
582    def test_custom_messages(self):
583        """Test custom warning and lockout messages are returned"""
584        self.stage.last_attempt_warning_message = "One attempt remains."
585        self.stage.lockout_message = "Contact support."
586        self.stage.save()
587        self.start_flow()
588
589        response = self.submit("wrong")
590        self.assertStageResponse(
591            response,
592            self.flow,
593            response_errors={"password": [{"string": "One attempt remains.", "code": "invalid"}]},
594        )
595
596        response = self.submit("wrong")
597        self.assertStageResponse(
598            response,
599            self.flow,
600            component="ak-stage-access-denied",
601            error_message="Contact support.",
602        )
603
604    def test_flow_cancel_preserves_last_attempt_warning(self):
605        """Test flow cancellation keeps a warning returned on the same attempt"""
606        self.stage.failed_attempts_before_cancel = 1
607        self.stage.last_attempt_warning_message = "One attempt remains."
608        self.stage.save(
609            update_fields=("failed_attempts_before_cancel", "last_attempt_warning_message")
610        )
611        self.start_flow()
612        self.client.get(
613            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
614        )
615
616        response = self.submit("wrong")
617
618        self.assertNotIn(SESSION_KEY_PLAN, self.client.session)
619        self.assertStageResponse(
620            response,
621            self.flow,
622            error_message="One attempt remains.",
623        )
624
625    def test_service_accounts_are_exempt(self):
626        """Both service account types bypass automatic and explicit locking."""
627        self.client.force_login(self.user)
628        for user_type in (UserTypes.SERVICE_ACCOUNT, UserTypes.INTERNAL_SERVICE_ACCOUNT):
629            with self.subTest(user_type=user_type):
630                user = create_test_admin_user(type=user_type)
631                policy = PasswordLockout(self.stage, RequestFactory().post("/"))
632                for _ in range(self.stage.failed_attempts_before_lockout + 1):
633                    self.assertEqual(policy.apply(user, None, {}), PasswordLockoutResult())
634                response = self.client.post(
635                    reverse(
636                        "authentik_api:passworddevice-lock", kwargs={"pk": user.password_device.pk}
637                    )
638                )
639                self.assertEqual(response.status_code, 400)
640                device = PasswordDevice.objects.get(user=user)
641                self.assertFalse(device.locked)
642                self.assertEqual(device.failed_attempts, 0)
643                self.assertFalse(
644                    Event.objects.filter(
645                        action=EventAction.AUTHENTICATOR_LOCKED, context__affected_user__pk=user.pk
646                    ).exists()
647                )
648
649    def test_service_account_conversion_bypasses_existing_lock(self):
650        """Converting a locked user to a service account stops enforcing the lock."""
651        PasswordDevice.objects.filter(user=self.user).update(locked_at=now())
652        policy = PasswordLockout(self.stage, RequestFactory().post("/"))
653        for user_type in (UserTypes.SERVICE_ACCOUNT, UserTypes.INTERNAL_SERVICE_ACCOUNT):
654            with self.subTest(user_type=user_type):
655                self.user.type = user_type
656                self.user.save()
657                self.assertEqual(
658                    policy.apply(self.user, self.user, {}), PasswordLockoutResult(self.user)
659                )

Password lockout tests

def setUp(self):
366    def setUp(self):
367        super().setUp()
368        self.licensed(True).start()
369        self.addCleanup(patch.stopall)
370
371        self.user = create_test_admin_user()
372        self.flow = create_test_flow(FlowDesignation.AUTHENTICATION)
373        self.stage = PasswordStage.objects.create(
374            name=generate_id(),
375            backends=[BACKEND_INBUILT],
376            failed_attempts_before_lockout=2,
377        )
378        self.binding = FlowStageBinding.objects.create(target=self.flow, stage=self.stage, order=2)

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

def licensed(self, valid: bool):
380    def licensed(self, valid: bool):
381        """Patch the license summary this stage reads to decide whether it may lock"""
382        summary = LicenseSummary(
383            internal_users=100,
384            external_users=100,
385            status=LicenseUsageStatus.VALID if valid else LicenseUsageStatus.UNLICENSED,
386            latest_valid=now(),
387            license_flags=[],
388        )
389        return patch(
390            "authentik.enterprise.stages.password.lockout.LicenseKey.cached_summary",
391            return_value=summary,
392        )

Patch the license summary this stage reads to decide whether it may lock

def start_flow(self):
394    def start_flow(self):
395        """Put a plan with the test user pending into the session"""
396        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
397        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
398        session = self.client.session
399        session[SESSION_KEY_PLAN] = plan
400        session.save()

Put a plan with the test user pending into the session

def submit(self, password: str):
402    def submit(self, password: str):
403        return self.client.post(
404            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
405            {"password": password},
406        )
408    @property
409    def device(self) -> PasswordDevice:
410        return PasswordDevice.objects.get(user=self.user)
def test_locks_after_limit(self):
412    def test_locks_after_limit(self):
413        """Test the password is locked once the stage's limit is reached"""
414        self.start_flow()
415        response = self.submit("wrong")
416        self.assertEqual(self.device.failed_attempts, 1)
417        self.assertFalse(self.device.locked)
418        self.assertStageResponse(
419            response,
420            self.flow,
421            response_errors={"password": [{"string": "Invalid password", "code": "invalid"}]},
422        )
423
424        response = self.submit("wrong")
425        self.assertEqual(self.device.failed_attempts, 0)
426        self.assertTrue(self.device.locked)
427        self.assertStageResponse(
428            response,
429            self.flow,
430            component="ak-stage-access-denied",
431            error_message="Invalid password",
432        )
433        self.assertTrue(
434            Event.objects.filter(
435                action=EventAction.AUTHENTICATOR_LOCKED,
436                context__affected_user__pk=self.user.pk,
437            ).exists()
438        )

Test the password is locked once the stage's limit is reached

def test_locked_refuses_correct_password(self):
440    def test_locked_refuses_correct_password(self):
441        """Test a locked password is refused even when the submitted password is correct"""
442        device = self.device
443        device.locked_at = now()
444        device.save()
445
446        self.start_flow()
447        response = self.submit(self.user.username)
448        self.assertStageResponse(
449            response,
450            self.flow,
451            response_errors={"password": [{"string": "Invalid password", "code": "invalid"}]},
452        )
453
454        response = self.submit(self.user.username)
455        self.assertStageResponse(
456            response,
457            self.flow,
458            component="ak-stage-access-denied",
459            error_message="Invalid password",
460        )

Test a locked password is refused even when the submitted password is correct

def test_locked_password_refuses_app_password_in_flow(self):
462    def test_locked_password_refuses_app_password_in_flow(self):
463        """App passwords submitted through a password stage obey the same lock."""
464        token = Token.objects.create(
465            identifier=generate_id(), user=self.user, intent=TokenIntents.INTENT_APP_PASSWORD
466        )
467        self.stage.backends = [BACKEND_APP_PASSWORD]
468        self.stage.save()
469        self.start_flow()
470        self.assertStageRedirects(self.submit(token.key), reverse("authentik_core:root-redirect"))
471
472        PasswordDevice.objects.filter(user=self.user).update(locked_at=now())
473        self.start_flow()
474        self.assertStageResponse(
475            self.submit(token.key),
476            self.flow,
477            response_errors={"password": [{"string": "Invalid password", "code": "invalid"}]},
478        )

App passwords submitted through a password stage obey the same lock.

def test_success_resets_failures(self):
480    def test_success_resets_failures(self):
481        """Test authenticating successfully forgets earlier failures"""
482        for licensed in (True, False):
483            with self.subTest(licensed=licensed), self.licensed(licensed):
484                PasswordDevice.objects.filter(user=self.user).update(failed_attempts=1)
485                self.start_flow()
486                self.submit(self.user.username)
487                self.assertEqual(self.device.failed_attempts, 0)

Test authenticating successfully forgets earlier failures

def test_password_hash_upgrade_preserves_lock(self):
489    def test_password_hash_upgrade_preserves_lock(self):
490        """Test upgrading a password hash keeps a lock set by another request"""
491        old_hash = PBKDF2PasswordHasher().encode("initial", "salt", iterations=1)
492        PasswordDevice.objects.filter(user=self.user).update(password=old_hash)
493        device = self.device
494        PasswordDevice.objects.filter(pk=device.pk).update(locked_at=now())
495
496        self.assertTrue(device.check_password("initial"))
497
498        device.refresh_from_db()
499        self.assertTrue(device.locked)
500        self.assertNotEqual(device.password, old_hash)

Test upgrading a password hash keeps a lock set by another request

def test_unlicensed_never_locks(self):
502    def test_unlicensed_never_locks(self):
503        """Test passwords are not locked without an enterprise license"""
504        with self.licensed(False):
505            self.start_flow()
506            self.submit("wrong")
507            self.submit("wrong")
508        self.assertFalse(self.device.locked)

Test passwords are not locked without an enterprise license

def test_existing_lock_survives_license_expiry(self):
510    def test_existing_lock_survives_license_expiry(self):
511        """Losing a license cannot re-enable a password an administrator locked."""
512        PasswordDevice.objects.filter(user=self.user).update(locked_at=now())
513        with self.licensed(False):
514            self.start_flow()
515            response = self.submit(self.user.username)
516        self.assertStageResponse(
517            response,
518            self.flow,
519            response_errors={"password": [{"string": "Invalid password", "code": "invalid"}]},
520        )

Losing a license cannot re-enable a password an administrator locked.

def test_locked_password_skips_backends_and_records_failure(self):
522    def test_locked_password_skips_backends_and_records_failure(self):
523        """Correct and incorrect locked passwords cause the same failed-login signal."""
524        PasswordDevice.objects.filter(user=self.user).update(locked_at=now())
525        for password in (self.user.username, "wrong"):
526            with self.subTest(password=password):
527                self.start_flow()
528                with (
529                    patch("authentik.core.auth.InbuiltBackend.authenticate") as backend,
530                    patch.object(login_failed, "send", wraps=login_failed.send) as failed,
531                    patch(
532                        "authentik.stages.password.stage.make_password", wraps=make_password
533                    ) as hash_password,
534                ):
535                    self.submit(password)
536                backend.assert_not_called()
537                hash_password.assert_called_once_with(password)
538                failed.assert_called_once()

Correct and incorrect locked passwords cause the same failed-login signal.

def test_lock_during_authentication_records_failure(self):
540    def test_lock_during_authentication_records_failure(self):
541        """A lock set while a backend runs still rejects and records the attempt."""
542        PasswordDevice.objects.filter(user=self.user).update(locked_at=now())
543        with patch.object(login_failed, "send") as failed:
544            result = PasswordLockout(self.stage, RequestFactory().post("/")).apply(
545                self.user, self.user, {}
546            )
547        self.assertIsNone(result.user)
548        failed.assert_called_once()

A lock set while a backend runs still rejects and records the attempt.

def test_lock_enforcement_without_enterprise(self):
550    def test_lock_enforcement_without_enterprise(self):
551        """The OSS implementation enforces existing locks but creates none."""
552        policy = PasswordLockoutBase(self.stage, RequestFactory().post("/"))
553        self.assertEqual(policy.apply(self.user, self.user, {}), PasswordLockoutResult(self.user))
554        for _ in range(self.stage.failed_attempts_before_lockout):
555            self.assertEqual(policy.apply(self.user, None, {}), PasswordLockoutResult())
556        self.assertFalse(self.device.locked)
557        PasswordDevice.objects.filter(user=self.user).update(locked_at=now())
558        self.assertIsNone(policy.apply(self.user, self.user, {}).user)

The OSS implementation enforces existing locks but creates none.

def test_external_password_exemption_requires_enabled_source(self):
560    def test_external_password_exemption_requires_enabled_source(self):
561        """Disabled sources must not exempt locally verified passwords from lockout."""
562        for backend, model in ((BACKEND_LDAP, LDAPSource), (BACKEND_KERBEROS, KerberosSource)):
563            with self.subTest(backend=backend):
564                source = model.objects.create(name=generate_id(), slug=generate_id())
565                if backend == BACKEND_LDAP:
566                    self.user.attributes[LDAP_DISTINGUISHED_NAME] = "cn=user,dc=example,dc=com"
567                    self.user.save()
568                else:
569                    UserKerberosSourceConnection.objects.create(
570                        source=source, user=self.user, identifier="user@EXAMPLE.COM"
571                    )
572                self.stage.backends = [BACKEND_INBUILT, backend]
573                policy = PasswordLockout(self.stage, RequestFactory().post("/"))
574                PasswordDevice.objects.filter(user=self.user).update(failed_attempts=0)
575                policy.apply(self.user, None, {})
576                self.assertEqual(self.device.failed_attempts, 0)
577                source.enabled = False
578                source.save()
579                policy.apply(self.user, None, {})
580                self.assertEqual(self.device.failed_attempts, 1)

Disabled sources must not exempt locally verified passwords from lockout.

def test_custom_messages(self):
582    def test_custom_messages(self):
583        """Test custom warning and lockout messages are returned"""
584        self.stage.last_attempt_warning_message = "One attempt remains."
585        self.stage.lockout_message = "Contact support."
586        self.stage.save()
587        self.start_flow()
588
589        response = self.submit("wrong")
590        self.assertStageResponse(
591            response,
592            self.flow,
593            response_errors={"password": [{"string": "One attempt remains.", "code": "invalid"}]},
594        )
595
596        response = self.submit("wrong")
597        self.assertStageResponse(
598            response,
599            self.flow,
600            component="ak-stage-access-denied",
601            error_message="Contact support.",
602        )

Test custom warning and lockout messages are returned

def test_flow_cancel_preserves_last_attempt_warning(self):
604    def test_flow_cancel_preserves_last_attempt_warning(self):
605        """Test flow cancellation keeps a warning returned on the same attempt"""
606        self.stage.failed_attempts_before_cancel = 1
607        self.stage.last_attempt_warning_message = "One attempt remains."
608        self.stage.save(
609            update_fields=("failed_attempts_before_cancel", "last_attempt_warning_message")
610        )
611        self.start_flow()
612        self.client.get(
613            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
614        )
615
616        response = self.submit("wrong")
617
618        self.assertNotIn(SESSION_KEY_PLAN, self.client.session)
619        self.assertStageResponse(
620            response,
621            self.flow,
622            error_message="One attempt remains.",
623        )

Test flow cancellation keeps a warning returned on the same attempt

def test_service_accounts_are_exempt(self):
625    def test_service_accounts_are_exempt(self):
626        """Both service account types bypass automatic and explicit locking."""
627        self.client.force_login(self.user)
628        for user_type in (UserTypes.SERVICE_ACCOUNT, UserTypes.INTERNAL_SERVICE_ACCOUNT):
629            with self.subTest(user_type=user_type):
630                user = create_test_admin_user(type=user_type)
631                policy = PasswordLockout(self.stage, RequestFactory().post("/"))
632                for _ in range(self.stage.failed_attempts_before_lockout + 1):
633                    self.assertEqual(policy.apply(user, None, {}), PasswordLockoutResult())
634                response = self.client.post(
635                    reverse(
636                        "authentik_api:passworddevice-lock", kwargs={"pk": user.password_device.pk}
637                    )
638                )
639                self.assertEqual(response.status_code, 400)
640                device = PasswordDevice.objects.get(user=user)
641                self.assertFalse(device.locked)
642                self.assertEqual(device.failed_attempts, 0)
643                self.assertFalse(
644                    Event.objects.filter(
645                        action=EventAction.AUTHENTICATOR_LOCKED, context__affected_user__pk=user.pk
646                    ).exists()
647                )

Both service account types bypass automatic and explicit locking.

def test_service_account_conversion_bypasses_existing_lock(self):
649    def test_service_account_conversion_bypasses_existing_lock(self):
650        """Converting a locked user to a service account stops enforcing the lock."""
651        PasswordDevice.objects.filter(user=self.user).update(locked_at=now())
652        policy = PasswordLockout(self.stage, RequestFactory().post("/"))
653        for user_type in (UserTypes.SERVICE_ACCOUNT, UserTypes.INTERNAL_SERVICE_ACCOUNT):
654            with self.subTest(user_type=user_type):
655                self.user.type = user_type
656                self.user.save()
657                self.assertEqual(
658                    policy.apply(self.user, self.user, {}), PasswordLockoutResult(self.user)
659                )

Converting a locked user to a service account stops enforcing the lock.

class TestPasswordLockoutConcurrency(django.test.testcases.TransactionTestCase):
662class TestPasswordLockoutConcurrency(TransactionTestCase):
663    """Password lockout concurrency tests"""
664
665    def test_concurrent_failures(self):
666        """Concurrent failures update one serialized counter"""
667        user = create_test_admin_user()
668        request = RequestFactory().post("/")
669        stage = PasswordStage.objects.create(
670            name=generate_id(), backends=[BACKEND_INBUILT], failed_attempts_before_lockout=3
671        )
672
673        ready = Barrier(3)
674
675        def fail_password():
676            try:
677                ready.wait(timeout=10)
678                return PasswordLockout(stage, request).apply(user, None, {})
679            finally:
680                connection.close()
681
682        connection.close()
683        with patch("authentik.enterprise.license.LicenseKey.cached_summary") as summary:
684            summary.return_value.status.is_valid = True
685            with ThreadPoolExecutor(max_workers=3) as pool:
686                futures = [pool.submit(fail_password) for _ in range(3)]
687                results = [future.result(timeout=10) for future in futures]
688
689        device = PasswordDevice.objects.get(user=user)
690        self.assertTrue(device.locked)
691        self.assertCountEqual(
692            results,
693            [
694                PasswordLockoutResult(),
695                PasswordLockoutResult(last_attempt=True),
696                PasswordLockoutResult(lockout_reached=True),
697            ],
698        )
699        self.assertEqual(
700            Event.objects.filter(
701                action=EventAction.AUTHENTICATOR_LOCKED,
702                context__affected_user__pk=user.pk,
703            ).count(),
704            1,
705        )

Password lockout concurrency tests

def test_concurrent_failures(self):
665    def test_concurrent_failures(self):
666        """Concurrent failures update one serialized counter"""
667        user = create_test_admin_user()
668        request = RequestFactory().post("/")
669        stage = PasswordStage.objects.create(
670            name=generate_id(), backends=[BACKEND_INBUILT], failed_attempts_before_lockout=3
671        )
672
673        ready = Barrier(3)
674
675        def fail_password():
676            try:
677                ready.wait(timeout=10)
678                return PasswordLockout(stage, request).apply(user, None, {})
679            finally:
680                connection.close()
681
682        connection.close()
683        with patch("authentik.enterprise.license.LicenseKey.cached_summary") as summary:
684            summary.return_value.status.is_valid = True
685            with ThreadPoolExecutor(max_workers=3) as pool:
686                futures = [pool.submit(fail_password) for _ in range(3)]
687                results = [future.result(timeout=10) for future in futures]
688
689        device = PasswordDevice.objects.get(user=user)
690        self.assertTrue(device.locked)
691        self.assertCountEqual(
692            results,
693            [
694                PasswordLockoutResult(),
695                PasswordLockoutResult(last_attempt=True),
696                PasswordLockoutResult(lockout_reached=True),
697            ],
698        )
699        self.assertEqual(
700            Event.objects.filter(
701                action=EventAction.AUTHENTICATOR_LOCKED,
702                context__affected_user__pk=user.pk,
703            ).count(),
704            1,
705        )

Concurrent failures update one serialized counter