authentik.stages.authenticator_validate.stage

Authenticator Validation

  1"""Authenticator Validation"""
  2
  3from datetime import datetime
  4from hashlib import sha256
  5
  6from django.conf import settings
  7from django.http import HttpRequest, HttpResponse
  8from django.utils.timezone import now
  9from django.utils.translation import gettext_lazy as _
 10from jwt import PyJWTError, decode, encode
 11from rest_framework.fields import CharField, IntegerField, ListField, UUIDField
 12from rest_framework.serializers import ValidationError
 13
 14from authentik.core.api.utils import JSONDictField, PassiveSerializer
 15from authentik.core.models import User
 16from authentik.events.middleware import audit_ignore
 17from authentik.events.models import Event, EventAction
 18from authentik.flows.challenge import ChallengeResponse, WithUserInfoChallenge
 19from authentik.flows.exceptions import FlowSkipStageException, StageInvalidException
 20from authentik.flows.models import FlowDesignation, NotConfiguredAction, Stage
 21from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER
 22from authentik.flows.stage import ChallengeStageView
 23from authentik.lib.utils.time import timedelta_from_string
 24from authentik.policies.reputation.signals import update_score
 25from authentik.root.install_id import get_install_id
 26from authentik.stages.authenticator import devices_for_user
 27from authentik.stages.authenticator.models import Device
 28from authentik.stages.authenticator_email.models import EmailDevice
 29from authentik.stages.authenticator_sms.models import SMSDevice
 30from authentik.stages.authenticator_validate.challenge import (
 31    DeviceChallenge,
 32    get_challenge_for_device,
 33    get_webauthn_challenge_without_user,
 34    select_challenge,
 35    validate_challenge_code,
 36    validate_challenge_duo,
 37    validate_challenge_webauthn,
 38)
 39from authentik.stages.authenticator_validate.models import AuthenticatorValidateStage, DeviceClasses
 40from authentik.stages.authenticator_webauthn.models import WebAuthnDevice
 41from authentik.stages.authenticator_webauthn.stage import PLAN_CONTEXT_WEBAUTHN_CHALLENGE
 42from authentik.stages.password.stage import PLAN_CONTEXT_METHOD, PLAN_CONTEXT_METHOD_ARGS
 43
 44COOKIE_NAME_MFA = "authentik_mfa"
 45
 46PLAN_CONTEXT_STAGES = "goauthentik.io/stages/authenticator_validate/stages"
 47PLAN_CONTEXT_SELECTED_STAGE = "goauthentik.io/stages/authenticator_validate/selected_stage"
 48PLAN_CONTEXT_DEVICE_CHALLENGES = "goauthentik.io/stages/authenticator_validate/device_challenges"
 49
 50
 51class SelectableStageSerializer(PassiveSerializer):
 52    """Serializer for stages which can be selected by users"""
 53
 54    pk = UUIDField()
 55    name = CharField()
 56    verbose_name = CharField()
 57    meta_model_name = CharField()
 58
 59
 60class AuthenticatorValidationChallenge(WithUserInfoChallenge):
 61    """Authenticator challenge"""
 62
 63    device_challenges = ListField(child=DeviceChallenge())
 64    component = CharField(default="ak-stage-authenticator-validate")
 65    configuration_stages = ListField(child=SelectableStageSerializer())
 66
 67
 68class AuthenticatorValidationChallengeResponse(ChallengeResponse):
 69    """Challenge used for Code-based and WebAuthn authenticators"""
 70
 71    device: Device | None
 72
 73    selected_challenge = DeviceChallenge(required=False)
 74    selected_stage = CharField(required=False)
 75
 76    code = CharField(required=False)
 77    webauthn = JSONDictField(required=False)
 78    duo = IntegerField(required=False)
 79    component = CharField(default="ak-stage-authenticator-validate")
 80
 81    def _challenge_allowed(self, classes: list):
 82        device_challenges: list[dict] = self.stage.executor.plan.context.get(
 83            PLAN_CONTEXT_DEVICE_CHALLENGES, []
 84        )
 85        if not any(x["device_class"] in classes for x in device_challenges):
 86            raise ValidationError("No compatible device class allowed")
 87
 88    def validate_code(self, code: str) -> str:
 89        """Validate code-based response, raise error if code isn't allowed"""
 90        self._challenge_allowed(
 91            [DeviceClasses.TOTP, DeviceClasses.STATIC, DeviceClasses.SMS, DeviceClasses.EMAIL]
 92        )
 93        challenges = self.stage.executor.plan.context.get(PLAN_CONTEXT_DEVICE_CHALLENGES, [])
 94        self.device = validate_challenge_code(
 95            code, self.stage, self.stage.get_pending_user(), challenges
 96        )
 97        return code
 98
 99    def validate_webauthn(self, webauthn: dict) -> dict:
100        """Validate webauthn response, raise error if webauthn wasn't allowed
101        or response is invalid"""
102        self._challenge_allowed([DeviceClasses.WEBAUTHN])
103        self.device = validate_challenge_webauthn(
104            webauthn, self.stage, self.stage.get_pending_user()
105        )
106        return webauthn
107
108    def validate_duo(self, duo: int) -> int:
109        """Initiate Duo authentication"""
110        self._challenge_allowed([DeviceClasses.DUO])
111        self.device = validate_challenge_duo(duo, self.stage, self.stage.get_pending_user())
112        return duo
113
114    def validate_selected_challenge(self, challenge: dict) -> dict:
115        """Check which challenge the user has selected. Actual logic only used for SMS stage."""
116        # First check if the challenge is valid
117        allowed = False
118        for device_challenge in self.stage.executor.plan.context.get(
119            PLAN_CONTEXT_DEVICE_CHALLENGES, []
120        ):
121            if device_challenge.get("device_class", "") == challenge.get(
122                "device_class", ""
123            ) and device_challenge.get("device_uid", "") == challenge.get("device_uid", ""):
124                allowed = True
125        if not allowed:
126            raise ValidationError("invalid challenge selected")
127
128        device_class = challenge.get("device_class", "")
129        if device_class == "sms":
130            devices = SMSDevice.objects.filter(pk=int(challenge.get("device_uid", "0")))
131            if not devices.exists():
132                raise ValidationError("invalid challenge selected")
133            select_challenge(self.stage.request, devices.first())
134        elif device_class == "email":
135            devices = EmailDevice.objects.filter(pk=int(challenge.get("device_uid", "0")))
136            if not devices.exists():
137                raise ValidationError("invalid challenge selected")
138            select_challenge(self.stage.request, devices.first())
139        return challenge
140
141    def validate_selected_stage(self, stage_pk: str) -> str:
142        """Check that the selected stage is valid"""
143        stages = self.stage.executor.plan.context.get(PLAN_CONTEXT_STAGES, [])
144        if not any(str(stage.pk) == stage_pk for stage in stages):
145            raise ValidationError("Selected stage is invalid")
146        self.stage.logger.debug("Setting selected stage to ", stage=stage_pk)
147        self.stage.executor.plan.context[PLAN_CONTEXT_SELECTED_STAGE] = stage_pk
148        return stage_pk
149
150    def validate(self, attrs: dict):
151        # Checking if the given data is from a valid device class is done above
152        # Here we only check if the any data was sent at all
153        if "code" not in attrs and "webauthn" not in attrs and "duo" not in attrs:
154            raise ValidationError("Empty response")
155        self.stage.executor.plan.context.setdefault(PLAN_CONTEXT_METHOD, "auth_mfa")
156        self.stage.executor.plan.context.setdefault(PLAN_CONTEXT_METHOD_ARGS, {})
157        self.stage.executor.plan.context[PLAN_CONTEXT_METHOD_ARGS].setdefault("mfa_devices", [])
158        self.stage.executor.plan.context[PLAN_CONTEXT_METHOD_ARGS]["mfa_devices"].append(
159            self.device
160        )
161        with audit_ignore():
162            self.device.last_used = now()
163            self.device.save()
164        return attrs
165
166
167class AuthenticatorValidateStageView(ChallengeStageView):
168    """Authenticator Validation"""
169
170    response_class = AuthenticatorValidationChallengeResponse
171
172    def get_device_challenges(self) -> list[dict]:
173        """Get a list of all device challenges applicable for the current stage"""
174        challenges = []
175        pending_user = self.get_pending_user()
176        if pending_user.is_anonymous:
177            # We shouldn't get here without any kind of authentication data
178            raise StageInvalidException()
179        # When `pretend_user_exists` is enabled in the identification stage,
180        # `pending_user` will be a user model that isn't save to the DB
181        # hence it doesn't have a PK. In that case we just return an empty list of
182        # authenticators
183        if not pending_user.pk:
184            return []
185        # Convert to a list to have usable log output instead of just <generator ...>
186        user_devices = list(devices_for_user(self.get_pending_user()))
187        self.logger.debug("Got devices for user", devices=user_devices)
188
189        # static and totp are only shown once
190        # since their challenges are device-independent
191        seen_classes = []
192
193        stage: AuthenticatorValidateStage = self.executor.current_stage
194
195        threshold = timedelta_from_string(stage.last_auth_threshold)
196        allowed_devices = []
197
198        has_webauthn_filters_set = stage.webauthn_allowed_device_types.exists()
199
200        for device in user_devices:
201            device_class = device.__class__.__name__.lower().replace("device", "")
202            if device_class not in stage.device_classes:
203                self.logger.debug("device class not allowed", device_class=device_class)
204                continue
205            if isinstance(device, SMSDevice) and device.is_hashed:
206                self.logger.debug("Hashed SMS device, skipping", device=device)
207                continue
208            allowed_devices.append(device)
209            # Ignore WebAuthn devices which are not in the allowed types
210            if (
211                isinstance(device, WebAuthnDevice)
212                and device.device_type
213                and has_webauthn_filters_set
214            ):
215                if not stage.webauthn_allowed_device_types.filter(
216                    pk=device.device_type.pk
217                ).exists():
218                    self.logger.debug(
219                        "WebAuthn device type not allowed", device=device, type=device.device_type
220                    )
221                    continue
222            # Ensure only one challenge per device class
223            # WebAuthn does another device loop to find all WebAuthn devices
224            if device_class in seen_classes:
225                continue
226            if device_class not in seen_classes:
227                seen_classes.append(device_class)
228            challenge = DeviceChallenge(
229                data={
230                    "device_class": device_class,
231                    "device_uid": device.pk,
232                    "challenge": get_challenge_for_device(self, stage, device),
233                    "last_used": device.last_used,
234                }
235            )
236            challenge.is_valid()
237            challenges.append(challenge.data)
238            self.logger.debug("adding challenge for device", challenge=challenge)
239        # check if we have an MFA cookie and if it's valid
240        if threshold.total_seconds() > 0:
241            self.check_mfa_cookie(allowed_devices)
242        return challenges
243
244    def get_webauthn_challenge_without_user(self) -> list[dict]:
245        """Get a WebAuthn challenge when no pending user is set."""
246        challenge = DeviceChallenge(
247            data={
248                "device_class": DeviceClasses.WEBAUTHN,
249                "device_uid": -1,
250                "challenge": get_webauthn_challenge_without_user(
251                    self,
252                    self.executor.current_stage,
253                ),
254                "last_used": None,
255            }
256        )
257        challenge.is_valid()
258        return [challenge.data]
259
260    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:  # noqa: PLR0911
261        """Check if a user is set, and check if the user has any devices
262        if not, we can skip this entire stage"""
263        user = self.get_pending_user()
264        stage: AuthenticatorValidateStage = self.executor.current_stage
265        if user and not user.is_anonymous:
266            try:
267                challenges = self.get_device_challenges()
268            except FlowSkipStageException:
269                self.executor.plan.context.pop(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, None)
270                return self.executor.stage_ok()
271        else:
272            if self.executor.flow.designation != FlowDesignation.AUTHENTICATION:
273                self.logger.debug("Refusing passwordless flow in non-authentication flow")
274                return self.executor.stage_ok()
275            # Passwordless auth, with just webauthn
276            if DeviceClasses.WEBAUTHN in stage.device_classes:
277                self.logger.debug("Flow without user, getting generic webauthn challenge")
278                challenges = self.get_webauthn_challenge_without_user()
279            else:
280                self.logger.debug("No pending user, continuing")
281                return self.executor.stage_ok()
282        self.executor.plan.context[PLAN_CONTEXT_DEVICE_CHALLENGES] = challenges
283
284        # No allowed devices
285        if len(challenges) < 1:
286            if stage.not_configured_action == NotConfiguredAction.SKIP:
287                self.logger.debug("Authenticator not configured, skipping stage")
288                return self.executor.stage_ok()
289            if stage.not_configured_action == NotConfiguredAction.DENY:
290                self.logger.debug("Authenticator not configured, denying")
291                return self.executor.stage_invalid(_("No (allowed) MFA authenticator configured."))
292            if stage.not_configured_action == NotConfiguredAction.CONFIGURE:
293                self.logger.debug("Authenticator not configured, forcing configure")
294                return self.prepare_stages(user)
295        return super().get(request, *args, **kwargs)
296
297    def prepare_stages(self, user: User, *args, **kwargs) -> HttpResponse:
298        """Check how the user can configure themselves. If no stages are set, return an error.
299        If a single stage is set, insert that stage directly. If multiple are selected, include
300        them in the challenge."""
301        stage: AuthenticatorValidateStage = self.executor.current_stage
302        if not stage.configuration_stages.exists():
303            Event.new(
304                EventAction.CONFIGURATION_ERROR,
305                message=(
306                    "Authenticator validation stage is set to configure user "
307                    "but no configuration flow is set."
308                ),
309                stage=self,
310            ).from_http(self.request).set_user(user).save()
311            return self.executor.stage_invalid()
312        if stage.configuration_stages.count() == 1:
313            next_stage = Stage.objects.get_subclass(pk=stage.configuration_stages.first().pk)
314            self.logger.debug("Single stage configured, auto-selecting", stage=next_stage)
315            self.executor.plan.context[PLAN_CONTEXT_SELECTED_STAGE] = next_stage
316            # Because that normal execution only happens on post, we directly inject it here and
317            # return it
318            self.executor.plan.insert_stage(next_stage)
319            return self.executor.stage_ok()
320        stages = Stage.objects.filter(pk__in=stage.configuration_stages.all()).select_subclasses()
321        self.executor.plan.context[PLAN_CONTEXT_STAGES] = stages
322        return super().get(self.request, *args, **kwargs)
323
324    def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
325        res = super().post(request, *args, **kwargs)
326        if (
327            PLAN_CONTEXT_SELECTED_STAGE in self.executor.plan.context
328            and self.executor.current_stage.not_configured_action == NotConfiguredAction.CONFIGURE
329        ):
330            self.logger.debug("Got selected stage in context, running that")
331            stage_pk = self.executor.plan.context.get(PLAN_CONTEXT_SELECTED_STAGE)
332            # Because the foreign key to stage.configuration_stage points to
333            # a base stage class, we need to do another lookup
334            stage = Stage.objects.get_subclass(pk=stage_pk)
335            # plan.insert inserts at 1 index, so when stage_ok pops 0,
336            # the configuration stage is next
337            self.executor.plan.insert_stage(stage)
338            return self.executor.stage_ok()
339        return res
340
341    def get_challenge(self) -> AuthenticatorValidationChallenge:
342        challenges = self.executor.plan.context.get(PLAN_CONTEXT_DEVICE_CHALLENGES, [])
343        stages = self.executor.plan.context.get(PLAN_CONTEXT_STAGES, [])
344        stage_challenges = []
345        for stage in stages:
346            serializer = SelectableStageSerializer(
347                data={
348                    "pk": stage.pk,
349                    "name": getattr(stage, "friendly_name", stage.name) or stage.name,
350                    "verbose_name": str(stage._meta.verbose_name)
351                    .replace("Setup Stage", "")
352                    .strip(),
353                    "meta_model_name": f"{stage._meta.app_label}.{stage._meta.model_name}",
354                }
355            )
356            serializer.is_valid()
357            stage_challenges.append(serializer.data)
358        return AuthenticatorValidationChallenge(
359            data={
360                "component": "ak-stage-authenticator-validate",
361                "device_challenges": challenges,
362                "configuration_stages": stage_challenges,
363            }
364        )
365
366    @property
367    def cookie_jwt_key(self) -> str:
368        """Signing key for MFA Cookie for this stage"""
369        return sha256(
370            f"{get_install_id()}:{self.executor.current_stage.pk.hex}".encode("ascii")
371        ).hexdigest()
372
373    def check_mfa_cookie(self, allowed_devices: list[Device]):
374        """Check if an MFA cookie has been set, whether it's valid and applies
375        to the current stage and device.
376
377        The list of devices passed to this function must only contain devices for the
378        correct user and with an allowed class"""
379        if COOKIE_NAME_MFA not in self.request.COOKIES:
380            return
381        stage: AuthenticatorValidateStage = self.executor.current_stage
382        threshold = timedelta_from_string(stage.last_auth_threshold)
383        latest_allowed = datetime.now() + threshold
384        try:
385            payload = decode(self.request.COOKIES[COOKIE_NAME_MFA], self.cookie_jwt_key, ["HS256"])
386            if payload["stage"] != stage.pk.hex:
387                self.logger.warning("Invalid stage PK")
388                return
389            if datetime.fromtimestamp(payload["exp"]) > latest_allowed:
390                self.logger.warning("Expired MFA cookie")
391                return
392            if not any(device.pk == payload["device"] for device in allowed_devices):
393                self.logger.warning("Invalid device PK")
394                return
395            self.logger.info("MFA has been used within threshold")
396            raise FlowSkipStageException()
397        except (PyJWTError, ValueError, TypeError) as exc:
398            self.logger.info("Invalid mfa cookie for device", exc=exc)
399
400    def set_valid_mfa_cookie(self, device: Device) -> HttpResponse:
401        """Set an MFA cookie to allow users to skip MFA validation in this context (browser)
402
403        The cookie is JWT which is signed with a hash of the secret key and the UID of the stage"""
404        stage: AuthenticatorValidateStage = self.executor.current_stage
405        delta = timedelta_from_string(stage.last_auth_threshold)
406        if delta.total_seconds() < 1:
407            self.logger.info("Not setting MFA cookie since threshold is not set.")
408            return self.executor.stage_ok()
409        expiry = datetime.now() + delta
410        cookie_payload = {
411            "device": device.pk,
412            "stage": stage.pk.hex,
413            "exp": expiry.timestamp(),
414        }
415        response = self.executor.stage_ok()
416        cookie = encode(cookie_payload, self.cookie_jwt_key)
417        response.set_cookie(
418            COOKIE_NAME_MFA,
419            cookie,
420            expires=expiry,
421            path=settings.SESSION_COOKIE_PATH,
422            domain=settings.SESSION_COOKIE_DOMAIN,
423            samesite=settings.SESSION_COOKIE_SAMESITE,
424        )
425        return response
426
427    def challenge_invalid(self, response: AuthenticatorValidationChallengeResponse) -> HttpResponse:
428        update_score(self.request, self.get_pending_user().username, -1)
429        return super().challenge_invalid(response)
430
431    def challenge_valid(self, response: AuthenticatorValidationChallengeResponse) -> HttpResponse:
432        # All validation is done by the serializer
433        # The WebAuthn challenge has been answered, don't allow it to be answered again
434        self.executor.plan.context.pop(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, None)
435        user = self.executor.plan.context.get(PLAN_CONTEXT_PENDING_USER)
436        if not user and "webauthn" in response.data:
437            webauthn_device: WebAuthnDevice = response.device
438            self.logger.debug("Set user from user-less flow", user=webauthn_device.user)
439            self.executor.plan.context[PLAN_CONTEXT_PENDING_USER] = webauthn_device.user
440            # We already set a default method in the validator above
441            # so this needs to have higher priority
442            self.executor.plan.context[PLAN_CONTEXT_METHOD] = "auth_webauthn_pwl"
443            self.executor.plan.context.setdefault(PLAN_CONTEXT_METHOD_ARGS, {})
444            self.executor.plan.context[PLAN_CONTEXT_METHOD_ARGS].update(
445                {
446                    "device": webauthn_device,
447                    "device_type": webauthn_device.device_type,
448                }
449            )
450        return self.set_valid_mfa_cookie(response.device)
PLAN_CONTEXT_STAGES = 'goauthentik.io/stages/authenticator_validate/stages'
PLAN_CONTEXT_SELECTED_STAGE = 'goauthentik.io/stages/authenticator_validate/selected_stage'
PLAN_CONTEXT_DEVICE_CHALLENGES = 'goauthentik.io/stages/authenticator_validate/device_challenges'
class SelectableStageSerializer(authentik.core.api.utils.PassiveSerializer):
52class SelectableStageSerializer(PassiveSerializer):
53    """Serializer for stages which can be selected by users"""
54
55    pk = UUIDField()
56    name = CharField()
57    verbose_name = CharField()
58    meta_model_name = CharField()

Serializer for stages which can be selected by users

pk
name
verbose_name
meta_model_name
class AuthenticatorValidationChallenge(authentik.flows.challenge.WithUserInfoChallenge):
61class AuthenticatorValidationChallenge(WithUserInfoChallenge):
62    """Authenticator challenge"""
63
64    device_challenges = ListField(child=DeviceChallenge())
65    component = CharField(default="ak-stage-authenticator-validate")
66    configuration_stages = ListField(child=SelectableStageSerializer())

Authenticator challenge

device_challenges
component
configuration_stages
class AuthenticatorValidationChallengeResponse(authentik.flows.challenge.ChallengeResponse):
 69class AuthenticatorValidationChallengeResponse(ChallengeResponse):
 70    """Challenge used for Code-based and WebAuthn authenticators"""
 71
 72    device: Device | None
 73
 74    selected_challenge = DeviceChallenge(required=False)
 75    selected_stage = CharField(required=False)
 76
 77    code = CharField(required=False)
 78    webauthn = JSONDictField(required=False)
 79    duo = IntegerField(required=False)
 80    component = CharField(default="ak-stage-authenticator-validate")
 81
 82    def _challenge_allowed(self, classes: list):
 83        device_challenges: list[dict] = self.stage.executor.plan.context.get(
 84            PLAN_CONTEXT_DEVICE_CHALLENGES, []
 85        )
 86        if not any(x["device_class"] in classes for x in device_challenges):
 87            raise ValidationError("No compatible device class allowed")
 88
 89    def validate_code(self, code: str) -> str:
 90        """Validate code-based response, raise error if code isn't allowed"""
 91        self._challenge_allowed(
 92            [DeviceClasses.TOTP, DeviceClasses.STATIC, DeviceClasses.SMS, DeviceClasses.EMAIL]
 93        )
 94        challenges = self.stage.executor.plan.context.get(PLAN_CONTEXT_DEVICE_CHALLENGES, [])
 95        self.device = validate_challenge_code(
 96            code, self.stage, self.stage.get_pending_user(), challenges
 97        )
 98        return code
 99
100    def validate_webauthn(self, webauthn: dict) -> dict:
101        """Validate webauthn response, raise error if webauthn wasn't allowed
102        or response is invalid"""
103        self._challenge_allowed([DeviceClasses.WEBAUTHN])
104        self.device = validate_challenge_webauthn(
105            webauthn, self.stage, self.stage.get_pending_user()
106        )
107        return webauthn
108
109    def validate_duo(self, duo: int) -> int:
110        """Initiate Duo authentication"""
111        self._challenge_allowed([DeviceClasses.DUO])
112        self.device = validate_challenge_duo(duo, self.stage, self.stage.get_pending_user())
113        return duo
114
115    def validate_selected_challenge(self, challenge: dict) -> dict:
116        """Check which challenge the user has selected. Actual logic only used for SMS stage."""
117        # First check if the challenge is valid
118        allowed = False
119        for device_challenge in self.stage.executor.plan.context.get(
120            PLAN_CONTEXT_DEVICE_CHALLENGES, []
121        ):
122            if device_challenge.get("device_class", "") == challenge.get(
123                "device_class", ""
124            ) and device_challenge.get("device_uid", "") == challenge.get("device_uid", ""):
125                allowed = True
126        if not allowed:
127            raise ValidationError("invalid challenge selected")
128
129        device_class = challenge.get("device_class", "")
130        if device_class == "sms":
131            devices = SMSDevice.objects.filter(pk=int(challenge.get("device_uid", "0")))
132            if not devices.exists():
133                raise ValidationError("invalid challenge selected")
134            select_challenge(self.stage.request, devices.first())
135        elif device_class == "email":
136            devices = EmailDevice.objects.filter(pk=int(challenge.get("device_uid", "0")))
137            if not devices.exists():
138                raise ValidationError("invalid challenge selected")
139            select_challenge(self.stage.request, devices.first())
140        return challenge
141
142    def validate_selected_stage(self, stage_pk: str) -> str:
143        """Check that the selected stage is valid"""
144        stages = self.stage.executor.plan.context.get(PLAN_CONTEXT_STAGES, [])
145        if not any(str(stage.pk) == stage_pk for stage in stages):
146            raise ValidationError("Selected stage is invalid")
147        self.stage.logger.debug("Setting selected stage to ", stage=stage_pk)
148        self.stage.executor.plan.context[PLAN_CONTEXT_SELECTED_STAGE] = stage_pk
149        return stage_pk
150
151    def validate(self, attrs: dict):
152        # Checking if the given data is from a valid device class is done above
153        # Here we only check if the any data was sent at all
154        if "code" not in attrs and "webauthn" not in attrs and "duo" not in attrs:
155            raise ValidationError("Empty response")
156        self.stage.executor.plan.context.setdefault(PLAN_CONTEXT_METHOD, "auth_mfa")
157        self.stage.executor.plan.context.setdefault(PLAN_CONTEXT_METHOD_ARGS, {})
158        self.stage.executor.plan.context[PLAN_CONTEXT_METHOD_ARGS].setdefault("mfa_devices", [])
159        self.stage.executor.plan.context[PLAN_CONTEXT_METHOD_ARGS]["mfa_devices"].append(
160            self.device
161        )
162        with audit_ignore():
163            self.device.last_used = now()
164            self.device.save()
165        return attrs

Challenge used for Code-based and WebAuthn authenticators

selected_challenge
selected_stage
code
webauthn
duo
component
def validate_code(self, code: str) -> str:
89    def validate_code(self, code: str) -> str:
90        """Validate code-based response, raise error if code isn't allowed"""
91        self._challenge_allowed(
92            [DeviceClasses.TOTP, DeviceClasses.STATIC, DeviceClasses.SMS, DeviceClasses.EMAIL]
93        )
94        challenges = self.stage.executor.plan.context.get(PLAN_CONTEXT_DEVICE_CHALLENGES, [])
95        self.device = validate_challenge_code(
96            code, self.stage, self.stage.get_pending_user(), challenges
97        )
98        return code

Validate code-based response, raise error if code isn't allowed

def validate_webauthn(self, webauthn: dict) -> dict:
100    def validate_webauthn(self, webauthn: dict) -> dict:
101        """Validate webauthn response, raise error if webauthn wasn't allowed
102        or response is invalid"""
103        self._challenge_allowed([DeviceClasses.WEBAUTHN])
104        self.device = validate_challenge_webauthn(
105            webauthn, self.stage, self.stage.get_pending_user()
106        )
107        return webauthn

Validate webauthn response, raise error if webauthn wasn't allowed or response is invalid

def validate_duo(self, duo: int) -> int:
109    def validate_duo(self, duo: int) -> int:
110        """Initiate Duo authentication"""
111        self._challenge_allowed([DeviceClasses.DUO])
112        self.device = validate_challenge_duo(duo, self.stage, self.stage.get_pending_user())
113        return duo

Initiate Duo authentication

def validate_selected_challenge(self, challenge: dict) -> dict:
115    def validate_selected_challenge(self, challenge: dict) -> dict:
116        """Check which challenge the user has selected. Actual logic only used for SMS stage."""
117        # First check if the challenge is valid
118        allowed = False
119        for device_challenge in self.stage.executor.plan.context.get(
120            PLAN_CONTEXT_DEVICE_CHALLENGES, []
121        ):
122            if device_challenge.get("device_class", "") == challenge.get(
123                "device_class", ""
124            ) and device_challenge.get("device_uid", "") == challenge.get("device_uid", ""):
125                allowed = True
126        if not allowed:
127            raise ValidationError("invalid challenge selected")
128
129        device_class = challenge.get("device_class", "")
130        if device_class == "sms":
131            devices = SMSDevice.objects.filter(pk=int(challenge.get("device_uid", "0")))
132            if not devices.exists():
133                raise ValidationError("invalid challenge selected")
134            select_challenge(self.stage.request, devices.first())
135        elif device_class == "email":
136            devices = EmailDevice.objects.filter(pk=int(challenge.get("device_uid", "0")))
137            if not devices.exists():
138                raise ValidationError("invalid challenge selected")
139            select_challenge(self.stage.request, devices.first())
140        return challenge

Check which challenge the user has selected. Actual logic only used for SMS stage.

def validate_selected_stage(self, stage_pk: str) -> str:
142    def validate_selected_stage(self, stage_pk: str) -> str:
143        """Check that the selected stage is valid"""
144        stages = self.stage.executor.plan.context.get(PLAN_CONTEXT_STAGES, [])
145        if not any(str(stage.pk) == stage_pk for stage in stages):
146            raise ValidationError("Selected stage is invalid")
147        self.stage.logger.debug("Setting selected stage to ", stage=stage_pk)
148        self.stage.executor.plan.context[PLAN_CONTEXT_SELECTED_STAGE] = stage_pk
149        return stage_pk

Check that the selected stage is valid

def validate(self, attrs: dict):
151    def validate(self, attrs: dict):
152        # Checking if the given data is from a valid device class is done above
153        # Here we only check if the any data was sent at all
154        if "code" not in attrs and "webauthn" not in attrs and "duo" not in attrs:
155            raise ValidationError("Empty response")
156        self.stage.executor.plan.context.setdefault(PLAN_CONTEXT_METHOD, "auth_mfa")
157        self.stage.executor.plan.context.setdefault(PLAN_CONTEXT_METHOD_ARGS, {})
158        self.stage.executor.plan.context[PLAN_CONTEXT_METHOD_ARGS].setdefault("mfa_devices", [])
159        self.stage.executor.plan.context[PLAN_CONTEXT_METHOD_ARGS]["mfa_devices"].append(
160            self.device
161        )
162        with audit_ignore():
163            self.device.last_used = now()
164            self.device.save()
165        return attrs
class AuthenticatorValidateStageView(authentik.flows.stage.ChallengeStageView):
168class AuthenticatorValidateStageView(ChallengeStageView):
169    """Authenticator Validation"""
170
171    response_class = AuthenticatorValidationChallengeResponse
172
173    def get_device_challenges(self) -> list[dict]:
174        """Get a list of all device challenges applicable for the current stage"""
175        challenges = []
176        pending_user = self.get_pending_user()
177        if pending_user.is_anonymous:
178            # We shouldn't get here without any kind of authentication data
179            raise StageInvalidException()
180        # When `pretend_user_exists` is enabled in the identification stage,
181        # `pending_user` will be a user model that isn't save to the DB
182        # hence it doesn't have a PK. In that case we just return an empty list of
183        # authenticators
184        if not pending_user.pk:
185            return []
186        # Convert to a list to have usable log output instead of just <generator ...>
187        user_devices = list(devices_for_user(self.get_pending_user()))
188        self.logger.debug("Got devices for user", devices=user_devices)
189
190        # static and totp are only shown once
191        # since their challenges are device-independent
192        seen_classes = []
193
194        stage: AuthenticatorValidateStage = self.executor.current_stage
195
196        threshold = timedelta_from_string(stage.last_auth_threshold)
197        allowed_devices = []
198
199        has_webauthn_filters_set = stage.webauthn_allowed_device_types.exists()
200
201        for device in user_devices:
202            device_class = device.__class__.__name__.lower().replace("device", "")
203            if device_class not in stage.device_classes:
204                self.logger.debug("device class not allowed", device_class=device_class)
205                continue
206            if isinstance(device, SMSDevice) and device.is_hashed:
207                self.logger.debug("Hashed SMS device, skipping", device=device)
208                continue
209            allowed_devices.append(device)
210            # Ignore WebAuthn devices which are not in the allowed types
211            if (
212                isinstance(device, WebAuthnDevice)
213                and device.device_type
214                and has_webauthn_filters_set
215            ):
216                if not stage.webauthn_allowed_device_types.filter(
217                    pk=device.device_type.pk
218                ).exists():
219                    self.logger.debug(
220                        "WebAuthn device type not allowed", device=device, type=device.device_type
221                    )
222                    continue
223            # Ensure only one challenge per device class
224            # WebAuthn does another device loop to find all WebAuthn devices
225            if device_class in seen_classes:
226                continue
227            if device_class not in seen_classes:
228                seen_classes.append(device_class)
229            challenge = DeviceChallenge(
230                data={
231                    "device_class": device_class,
232                    "device_uid": device.pk,
233                    "challenge": get_challenge_for_device(self, stage, device),
234                    "last_used": device.last_used,
235                }
236            )
237            challenge.is_valid()
238            challenges.append(challenge.data)
239            self.logger.debug("adding challenge for device", challenge=challenge)
240        # check if we have an MFA cookie and if it's valid
241        if threshold.total_seconds() > 0:
242            self.check_mfa_cookie(allowed_devices)
243        return challenges
244
245    def get_webauthn_challenge_without_user(self) -> list[dict]:
246        """Get a WebAuthn challenge when no pending user is set."""
247        challenge = DeviceChallenge(
248            data={
249                "device_class": DeviceClasses.WEBAUTHN,
250                "device_uid": -1,
251                "challenge": get_webauthn_challenge_without_user(
252                    self,
253                    self.executor.current_stage,
254                ),
255                "last_used": None,
256            }
257        )
258        challenge.is_valid()
259        return [challenge.data]
260
261    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:  # noqa: PLR0911
262        """Check if a user is set, and check if the user has any devices
263        if not, we can skip this entire stage"""
264        user = self.get_pending_user()
265        stage: AuthenticatorValidateStage = self.executor.current_stage
266        if user and not user.is_anonymous:
267            try:
268                challenges = self.get_device_challenges()
269            except FlowSkipStageException:
270                self.executor.plan.context.pop(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, None)
271                return self.executor.stage_ok()
272        else:
273            if self.executor.flow.designation != FlowDesignation.AUTHENTICATION:
274                self.logger.debug("Refusing passwordless flow in non-authentication flow")
275                return self.executor.stage_ok()
276            # Passwordless auth, with just webauthn
277            if DeviceClasses.WEBAUTHN in stage.device_classes:
278                self.logger.debug("Flow without user, getting generic webauthn challenge")
279                challenges = self.get_webauthn_challenge_without_user()
280            else:
281                self.logger.debug("No pending user, continuing")
282                return self.executor.stage_ok()
283        self.executor.plan.context[PLAN_CONTEXT_DEVICE_CHALLENGES] = challenges
284
285        # No allowed devices
286        if len(challenges) < 1:
287            if stage.not_configured_action == NotConfiguredAction.SKIP:
288                self.logger.debug("Authenticator not configured, skipping stage")
289                return self.executor.stage_ok()
290            if stage.not_configured_action == NotConfiguredAction.DENY:
291                self.logger.debug("Authenticator not configured, denying")
292                return self.executor.stage_invalid(_("No (allowed) MFA authenticator configured."))
293            if stage.not_configured_action == NotConfiguredAction.CONFIGURE:
294                self.logger.debug("Authenticator not configured, forcing configure")
295                return self.prepare_stages(user)
296        return super().get(request, *args, **kwargs)
297
298    def prepare_stages(self, user: User, *args, **kwargs) -> HttpResponse:
299        """Check how the user can configure themselves. If no stages are set, return an error.
300        If a single stage is set, insert that stage directly. If multiple are selected, include
301        them in the challenge."""
302        stage: AuthenticatorValidateStage = self.executor.current_stage
303        if not stage.configuration_stages.exists():
304            Event.new(
305                EventAction.CONFIGURATION_ERROR,
306                message=(
307                    "Authenticator validation stage is set to configure user "
308                    "but no configuration flow is set."
309                ),
310                stage=self,
311            ).from_http(self.request).set_user(user).save()
312            return self.executor.stage_invalid()
313        if stage.configuration_stages.count() == 1:
314            next_stage = Stage.objects.get_subclass(pk=stage.configuration_stages.first().pk)
315            self.logger.debug("Single stage configured, auto-selecting", stage=next_stage)
316            self.executor.plan.context[PLAN_CONTEXT_SELECTED_STAGE] = next_stage
317            # Because that normal execution only happens on post, we directly inject it here and
318            # return it
319            self.executor.plan.insert_stage(next_stage)
320            return self.executor.stage_ok()
321        stages = Stage.objects.filter(pk__in=stage.configuration_stages.all()).select_subclasses()
322        self.executor.plan.context[PLAN_CONTEXT_STAGES] = stages
323        return super().get(self.request, *args, **kwargs)
324
325    def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
326        res = super().post(request, *args, **kwargs)
327        if (
328            PLAN_CONTEXT_SELECTED_STAGE in self.executor.plan.context
329            and self.executor.current_stage.not_configured_action == NotConfiguredAction.CONFIGURE
330        ):
331            self.logger.debug("Got selected stage in context, running that")
332            stage_pk = self.executor.plan.context.get(PLAN_CONTEXT_SELECTED_STAGE)
333            # Because the foreign key to stage.configuration_stage points to
334            # a base stage class, we need to do another lookup
335            stage = Stage.objects.get_subclass(pk=stage_pk)
336            # plan.insert inserts at 1 index, so when stage_ok pops 0,
337            # the configuration stage is next
338            self.executor.plan.insert_stage(stage)
339            return self.executor.stage_ok()
340        return res
341
342    def get_challenge(self) -> AuthenticatorValidationChallenge:
343        challenges = self.executor.plan.context.get(PLAN_CONTEXT_DEVICE_CHALLENGES, [])
344        stages = self.executor.plan.context.get(PLAN_CONTEXT_STAGES, [])
345        stage_challenges = []
346        for stage in stages:
347            serializer = SelectableStageSerializer(
348                data={
349                    "pk": stage.pk,
350                    "name": getattr(stage, "friendly_name", stage.name) or stage.name,
351                    "verbose_name": str(stage._meta.verbose_name)
352                    .replace("Setup Stage", "")
353                    .strip(),
354                    "meta_model_name": f"{stage._meta.app_label}.{stage._meta.model_name}",
355                }
356            )
357            serializer.is_valid()
358            stage_challenges.append(serializer.data)
359        return AuthenticatorValidationChallenge(
360            data={
361                "component": "ak-stage-authenticator-validate",
362                "device_challenges": challenges,
363                "configuration_stages": stage_challenges,
364            }
365        )
366
367    @property
368    def cookie_jwt_key(self) -> str:
369        """Signing key for MFA Cookie for this stage"""
370        return sha256(
371            f"{get_install_id()}:{self.executor.current_stage.pk.hex}".encode("ascii")
372        ).hexdigest()
373
374    def check_mfa_cookie(self, allowed_devices: list[Device]):
375        """Check if an MFA cookie has been set, whether it's valid and applies
376        to the current stage and device.
377
378        The list of devices passed to this function must only contain devices for the
379        correct user and with an allowed class"""
380        if COOKIE_NAME_MFA not in self.request.COOKIES:
381            return
382        stage: AuthenticatorValidateStage = self.executor.current_stage
383        threshold = timedelta_from_string(stage.last_auth_threshold)
384        latest_allowed = datetime.now() + threshold
385        try:
386            payload = decode(self.request.COOKIES[COOKIE_NAME_MFA], self.cookie_jwt_key, ["HS256"])
387            if payload["stage"] != stage.pk.hex:
388                self.logger.warning("Invalid stage PK")
389                return
390            if datetime.fromtimestamp(payload["exp"]) > latest_allowed:
391                self.logger.warning("Expired MFA cookie")
392                return
393            if not any(device.pk == payload["device"] for device in allowed_devices):
394                self.logger.warning("Invalid device PK")
395                return
396            self.logger.info("MFA has been used within threshold")
397            raise FlowSkipStageException()
398        except (PyJWTError, ValueError, TypeError) as exc:
399            self.logger.info("Invalid mfa cookie for device", exc=exc)
400
401    def set_valid_mfa_cookie(self, device: Device) -> HttpResponse:
402        """Set an MFA cookie to allow users to skip MFA validation in this context (browser)
403
404        The cookie is JWT which is signed with a hash of the secret key and the UID of the stage"""
405        stage: AuthenticatorValidateStage = self.executor.current_stage
406        delta = timedelta_from_string(stage.last_auth_threshold)
407        if delta.total_seconds() < 1:
408            self.logger.info("Not setting MFA cookie since threshold is not set.")
409            return self.executor.stage_ok()
410        expiry = datetime.now() + delta
411        cookie_payload = {
412            "device": device.pk,
413            "stage": stage.pk.hex,
414            "exp": expiry.timestamp(),
415        }
416        response = self.executor.stage_ok()
417        cookie = encode(cookie_payload, self.cookie_jwt_key)
418        response.set_cookie(
419            COOKIE_NAME_MFA,
420            cookie,
421            expires=expiry,
422            path=settings.SESSION_COOKIE_PATH,
423            domain=settings.SESSION_COOKIE_DOMAIN,
424            samesite=settings.SESSION_COOKIE_SAMESITE,
425        )
426        return response
427
428    def challenge_invalid(self, response: AuthenticatorValidationChallengeResponse) -> HttpResponse:
429        update_score(self.request, self.get_pending_user().username, -1)
430        return super().challenge_invalid(response)
431
432    def challenge_valid(self, response: AuthenticatorValidationChallengeResponse) -> HttpResponse:
433        # All validation is done by the serializer
434        # The WebAuthn challenge has been answered, don't allow it to be answered again
435        self.executor.plan.context.pop(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, None)
436        user = self.executor.plan.context.get(PLAN_CONTEXT_PENDING_USER)
437        if not user and "webauthn" in response.data:
438            webauthn_device: WebAuthnDevice = response.device
439            self.logger.debug("Set user from user-less flow", user=webauthn_device.user)
440            self.executor.plan.context[PLAN_CONTEXT_PENDING_USER] = webauthn_device.user
441            # We already set a default method in the validator above
442            # so this needs to have higher priority
443            self.executor.plan.context[PLAN_CONTEXT_METHOD] = "auth_webauthn_pwl"
444            self.executor.plan.context.setdefault(PLAN_CONTEXT_METHOD_ARGS, {})
445            self.executor.plan.context[PLAN_CONTEXT_METHOD_ARGS].update(
446                {
447                    "device": webauthn_device,
448                    "device_type": webauthn_device.device_type,
449                }
450            )
451        return self.set_valid_mfa_cookie(response.device)

Authenticator Validation

response_class = <class 'AuthenticatorValidationChallengeResponse'>
def get_device_challenges(self) -> list[dict]:
173    def get_device_challenges(self) -> list[dict]:
174        """Get a list of all device challenges applicable for the current stage"""
175        challenges = []
176        pending_user = self.get_pending_user()
177        if pending_user.is_anonymous:
178            # We shouldn't get here without any kind of authentication data
179            raise StageInvalidException()
180        # When `pretend_user_exists` is enabled in the identification stage,
181        # `pending_user` will be a user model that isn't save to the DB
182        # hence it doesn't have a PK. In that case we just return an empty list of
183        # authenticators
184        if not pending_user.pk:
185            return []
186        # Convert to a list to have usable log output instead of just <generator ...>
187        user_devices = list(devices_for_user(self.get_pending_user()))
188        self.logger.debug("Got devices for user", devices=user_devices)
189
190        # static and totp are only shown once
191        # since their challenges are device-independent
192        seen_classes = []
193
194        stage: AuthenticatorValidateStage = self.executor.current_stage
195
196        threshold = timedelta_from_string(stage.last_auth_threshold)
197        allowed_devices = []
198
199        has_webauthn_filters_set = stage.webauthn_allowed_device_types.exists()
200
201        for device in user_devices:
202            device_class = device.__class__.__name__.lower().replace("device", "")
203            if device_class not in stage.device_classes:
204                self.logger.debug("device class not allowed", device_class=device_class)
205                continue
206            if isinstance(device, SMSDevice) and device.is_hashed:
207                self.logger.debug("Hashed SMS device, skipping", device=device)
208                continue
209            allowed_devices.append(device)
210            # Ignore WebAuthn devices which are not in the allowed types
211            if (
212                isinstance(device, WebAuthnDevice)
213                and device.device_type
214                and has_webauthn_filters_set
215            ):
216                if not stage.webauthn_allowed_device_types.filter(
217                    pk=device.device_type.pk
218                ).exists():
219                    self.logger.debug(
220                        "WebAuthn device type not allowed", device=device, type=device.device_type
221                    )
222                    continue
223            # Ensure only one challenge per device class
224            # WebAuthn does another device loop to find all WebAuthn devices
225            if device_class in seen_classes:
226                continue
227            if device_class not in seen_classes:
228                seen_classes.append(device_class)
229            challenge = DeviceChallenge(
230                data={
231                    "device_class": device_class,
232                    "device_uid": device.pk,
233                    "challenge": get_challenge_for_device(self, stage, device),
234                    "last_used": device.last_used,
235                }
236            )
237            challenge.is_valid()
238            challenges.append(challenge.data)
239            self.logger.debug("adding challenge for device", challenge=challenge)
240        # check if we have an MFA cookie and if it's valid
241        if threshold.total_seconds() > 0:
242            self.check_mfa_cookie(allowed_devices)
243        return challenges

Get a list of all device challenges applicable for the current stage

def get_webauthn_challenge_without_user(self) -> list[dict]:
245    def get_webauthn_challenge_without_user(self) -> list[dict]:
246        """Get a WebAuthn challenge when no pending user is set."""
247        challenge = DeviceChallenge(
248            data={
249                "device_class": DeviceClasses.WEBAUTHN,
250                "device_uid": -1,
251                "challenge": get_webauthn_challenge_without_user(
252                    self,
253                    self.executor.current_stage,
254                ),
255                "last_used": None,
256            }
257        )
258        challenge.is_valid()
259        return [challenge.data]

Get a WebAuthn challenge when no pending user is set.

def get( self, request: django.http.request.HttpRequest, *args, **kwargs) -> django.http.response.HttpResponse:
261    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:  # noqa: PLR0911
262        """Check if a user is set, and check if the user has any devices
263        if not, we can skip this entire stage"""
264        user = self.get_pending_user()
265        stage: AuthenticatorValidateStage = self.executor.current_stage
266        if user and not user.is_anonymous:
267            try:
268                challenges = self.get_device_challenges()
269            except FlowSkipStageException:
270                self.executor.plan.context.pop(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, None)
271                return self.executor.stage_ok()
272        else:
273            if self.executor.flow.designation != FlowDesignation.AUTHENTICATION:
274                self.logger.debug("Refusing passwordless flow in non-authentication flow")
275                return self.executor.stage_ok()
276            # Passwordless auth, with just webauthn
277            if DeviceClasses.WEBAUTHN in stage.device_classes:
278                self.logger.debug("Flow without user, getting generic webauthn challenge")
279                challenges = self.get_webauthn_challenge_without_user()
280            else:
281                self.logger.debug("No pending user, continuing")
282                return self.executor.stage_ok()
283        self.executor.plan.context[PLAN_CONTEXT_DEVICE_CHALLENGES] = challenges
284
285        # No allowed devices
286        if len(challenges) < 1:
287            if stage.not_configured_action == NotConfiguredAction.SKIP:
288                self.logger.debug("Authenticator not configured, skipping stage")
289                return self.executor.stage_ok()
290            if stage.not_configured_action == NotConfiguredAction.DENY:
291                self.logger.debug("Authenticator not configured, denying")
292                return self.executor.stage_invalid(_("No (allowed) MFA authenticator configured."))
293            if stage.not_configured_action == NotConfiguredAction.CONFIGURE:
294                self.logger.debug("Authenticator not configured, forcing configure")
295                return self.prepare_stages(user)
296        return super().get(request, *args, **kwargs)

Check if a user is set, and check if the user has any devices if not, we can skip this entire stage

def prepare_stages( self, user: authentik.core.models.User, *args, **kwargs) -> django.http.response.HttpResponse:
298    def prepare_stages(self, user: User, *args, **kwargs) -> HttpResponse:
299        """Check how the user can configure themselves. If no stages are set, return an error.
300        If a single stage is set, insert that stage directly. If multiple are selected, include
301        them in the challenge."""
302        stage: AuthenticatorValidateStage = self.executor.current_stage
303        if not stage.configuration_stages.exists():
304            Event.new(
305                EventAction.CONFIGURATION_ERROR,
306                message=(
307                    "Authenticator validation stage is set to configure user "
308                    "but no configuration flow is set."
309                ),
310                stage=self,
311            ).from_http(self.request).set_user(user).save()
312            return self.executor.stage_invalid()
313        if stage.configuration_stages.count() == 1:
314            next_stage = Stage.objects.get_subclass(pk=stage.configuration_stages.first().pk)
315            self.logger.debug("Single stage configured, auto-selecting", stage=next_stage)
316            self.executor.plan.context[PLAN_CONTEXT_SELECTED_STAGE] = next_stage
317            # Because that normal execution only happens on post, we directly inject it here and
318            # return it
319            self.executor.plan.insert_stage(next_stage)
320            return self.executor.stage_ok()
321        stages = Stage.objects.filter(pk__in=stage.configuration_stages.all()).select_subclasses()
322        self.executor.plan.context[PLAN_CONTEXT_STAGES] = stages
323        return super().get(self.request, *args, **kwargs)

Check how the user can configure themselves. If no stages are set, return an error. If a single stage is set, insert that stage directly. If multiple are selected, include them in the challenge.

def post( self, request: django.http.request.HttpRequest, *args, **kwargs) -> django.http.response.HttpResponse:
325    def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
326        res = super().post(request, *args, **kwargs)
327        if (
328            PLAN_CONTEXT_SELECTED_STAGE in self.executor.plan.context
329            and self.executor.current_stage.not_configured_action == NotConfiguredAction.CONFIGURE
330        ):
331            self.logger.debug("Got selected stage in context, running that")
332            stage_pk = self.executor.plan.context.get(PLAN_CONTEXT_SELECTED_STAGE)
333            # Because the foreign key to stage.configuration_stage points to
334            # a base stage class, we need to do another lookup
335            stage = Stage.objects.get_subclass(pk=stage_pk)
336            # plan.insert inserts at 1 index, so when stage_ok pops 0,
337            # the configuration stage is next
338            self.executor.plan.insert_stage(stage)
339            return self.executor.stage_ok()
340        return res

Handle challenge response

def get_challenge( self) -> AuthenticatorValidationChallenge:
342    def get_challenge(self) -> AuthenticatorValidationChallenge:
343        challenges = self.executor.plan.context.get(PLAN_CONTEXT_DEVICE_CHALLENGES, [])
344        stages = self.executor.plan.context.get(PLAN_CONTEXT_STAGES, [])
345        stage_challenges = []
346        for stage in stages:
347            serializer = SelectableStageSerializer(
348                data={
349                    "pk": stage.pk,
350                    "name": getattr(stage, "friendly_name", stage.name) or stage.name,
351                    "verbose_name": str(stage._meta.verbose_name)
352                    .replace("Setup Stage", "")
353                    .strip(),
354                    "meta_model_name": f"{stage._meta.app_label}.{stage._meta.model_name}",
355                }
356            )
357            serializer.is_valid()
358            stage_challenges.append(serializer.data)
359        return AuthenticatorValidationChallenge(
360            data={
361                "component": "ak-stage-authenticator-validate",
362                "device_challenges": challenges,
363                "configuration_stages": stage_challenges,
364            }
365        )

Return the challenge that the client should solve

cookie_jwt_key: str
367    @property
368    def cookie_jwt_key(self) -> str:
369        """Signing key for MFA Cookie for this stage"""
370        return sha256(
371            f"{get_install_id()}:{self.executor.current_stage.pk.hex}".encode("ascii")
372        ).hexdigest()

Signing key for MFA Cookie for this stage

def challenge_invalid( self, response: AuthenticatorValidationChallengeResponse) -> django.http.response.HttpResponse:
428    def challenge_invalid(self, response: AuthenticatorValidationChallengeResponse) -> HttpResponse:
429        update_score(self.request, self.get_pending_user().username, -1)
430        return super().challenge_invalid(response)

Callback when the challenge has the incorrect format

def challenge_valid( self, response: AuthenticatorValidationChallengeResponse) -> django.http.response.HttpResponse:
432    def challenge_valid(self, response: AuthenticatorValidationChallengeResponse) -> HttpResponse:
433        # All validation is done by the serializer
434        # The WebAuthn challenge has been answered, don't allow it to be answered again
435        self.executor.plan.context.pop(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, None)
436        user = self.executor.plan.context.get(PLAN_CONTEXT_PENDING_USER)
437        if not user and "webauthn" in response.data:
438            webauthn_device: WebAuthnDevice = response.device
439            self.logger.debug("Set user from user-less flow", user=webauthn_device.user)
440            self.executor.plan.context[PLAN_CONTEXT_PENDING_USER] = webauthn_device.user
441            # We already set a default method in the validator above
442            # so this needs to have higher priority
443            self.executor.plan.context[PLAN_CONTEXT_METHOD] = "auth_webauthn_pwl"
444            self.executor.plan.context.setdefault(PLAN_CONTEXT_METHOD_ARGS, {})
445            self.executor.plan.context[PLAN_CONTEXT_METHOD_ARGS].update(
446                {
447                    "device": webauthn_device,
448                    "device_type": webauthn_device.device_type,
449                }
450            )
451        return self.set_valid_mfa_cookie(response.device)

Callback when the challenge has the correct format