authentik.flows.views.executor

authentik multi-stage authentication engine

  1"""authentik multi-stage authentication engine"""
  2
  3from copy import deepcopy
  4from urllib.parse import urlencode, urlsplit, urlunsplit
  5
  6from django.conf import settings
  7from django.contrib.auth.mixins import LoginRequiredMixin
  8from django.core.cache import cache
  9from django.http import Http404, HttpRequest, HttpResponse, HttpResponseRedirect
 10from django.http.request import QueryDict
 11from django.shortcuts import get_object_or_404, redirect
 12from django.template.response import TemplateResponse
 13from django.urls import reverse
 14from django.utils.decorators import method_decorator
 15from django.utils.translation import gettext as _
 16from django.views.decorators.clickjacking import xframe_options_sameorigin
 17from django.views.generic import View
 18from drf_spectacular.types import OpenApiTypes
 19from drf_spectacular.utils import OpenApiParameter, PolymorphicProxySerializer, extend_schema
 20from rest_framework.permissions import AllowAny
 21from rest_framework.views import APIView
 22from structlog.stdlib import BoundLogger, get_logger
 23
 24from authentik.brands.models import Brand
 25from authentik.common.oauth.constants import QS_LOGIN_HINT
 26from authentik.events.models import Event, EventAction, cleanse_dict
 27from authentik.flows.apps import HIST_FLOW_EXECUTION_STAGE_TIME
 28from authentik.flows.challenge import (
 29    Challenge,
 30    ChallengeResponse,
 31    FlowErrorChallenge,
 32    HttpChallengeResponse,
 33    RedirectChallenge,
 34    ShellChallenge,
 35    WithUserInfoChallenge,
 36)
 37from authentik.flows.exceptions import EmptyFlowException, FlowNonApplicableException
 38from authentik.flows.models import (
 39    ConfigurableStage,
 40    Flow,
 41    FlowDeniedAction,
 42    FlowDesignation,
 43    FlowStageBinding,
 44    FlowToken,
 45    InvalidResponseAction,
 46    Stage,
 47)
 48from authentik.flows.planner import (
 49    CACHE_PREFIX,
 50    PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD,
 51    PLAN_CONTEXT_IS_RESTORED,
 52    PLAN_CONTEXT_PENDING_USER,
 53    PLAN_CONTEXT_REDIRECT,
 54    FlowPlan,
 55    FlowPlanner,
 56)
 57from authentik.flows.stage import AccessDeniedStage, StageView
 58from authentik.lib.tracing import (
 59    active_tracer,
 60    record_exception,
 61)
 62from authentik.lib.tracing.exceptions import TracingIgnoredException, should_ignore_exception
 63from authentik.lib.utils.reflection import all_subclasses, class_to_path
 64from authentik.lib.utils.urls import is_url_absolute, redirect_with_qs
 65from authentik.policies.engine import PolicyEngine
 66
 67LOGGER = get_logger()
 68# Argument used to redirect user after login
 69NEXT_ARG_NAME = "next"
 70
 71SESSION_KEY_PLAN = "authentik/flows/plan"
 72SESSION_KEY_GET = "authentik/flows/get"
 73SESSION_KEY_POST = "authentik/flows/post"
 74SESSION_KEY_HISTORY = "authentik/flows/history"
 75QS_KEY_TOKEN = "flow_token"  # nosec
 76QS_QUERY = "query"
 77
 78
 79def challenge_types():
 80    """This function returns a mapping which contains all subclasses of challenges
 81    subclasses of Challenge, and Challenge itself."""
 82    mapping = {}
 83    for cls in all_subclasses(Challenge):
 84        if cls == WithUserInfoChallenge:
 85            continue
 86        mapping[cls().fields["component"].default] = cls
 87    return mapping
 88
 89
 90def challenge_response_types():
 91    """This function returns a mapping which contains all subclasses of challenges
 92    subclasses of Challenge, and Challenge itself."""
 93    mapping = {}
 94    for cls in all_subclasses(ChallengeResponse):
 95        mapping[cls(stage=None).fields["component"].default] = cls
 96    return mapping
 97
 98
 99class InvalidStageError(TracingIgnoredException):
100    """Error raised when a challenge from a stage is not valid"""
101
102
103@method_decorator(xframe_options_sameorigin, name="dispatch")
104class FlowExecutorView(APIView):
105    """Flow executor, passing requests to Stage Views"""
106
107    permission_classes = [AllowAny]
108
109    flow: Flow = None
110
111    plan: FlowPlan | None = None
112    current_binding: FlowStageBinding | None = None
113    current_stage: Stage
114    current_stage_view: View
115    direct_execution = False
116
117    _logger: BoundLogger
118
119    def setup(self, request: HttpRequest, flow_slug: str):
120        super().setup(request, flow_slug=flow_slug)
121        if not self.flow:
122            self.flow = get_object_or_404(Flow.objects.select_related(), slug=flow_slug)
123        self._logger = get_logger().bind(flow_slug=flow_slug)
124        active_tracer().set_tag("authentik.flow", self.flow.slug)
125
126    def handle_invalid_flow(self, exc: FlowNonApplicableException) -> HttpResponse:
127        """When a flow is non-applicable check if user is on the correct domain"""
128        if self.flow.denied_action in [
129            FlowDeniedAction.CONTINUE,
130            FlowDeniedAction.MESSAGE_CONTINUE,
131        ]:
132            next_url = self.request.GET.get(NEXT_ARG_NAME)
133            if next_url and not is_url_absolute(next_url):
134                self._logger.debug("f(exec): Redirecting to next on fail")
135                return to_stage_response(self.request, redirect(next_url))
136        if self.flow.denied_action == FlowDeniedAction.CONTINUE:
137            return to_stage_response(
138                self.request, redirect(reverse("authentik_core:root-redirect"))
139            )
140        return to_stage_response(self.request, self.stage_invalid(error_message=exc.messages))
141
142    def _check_flow_token(self, key: str) -> FlowPlan | None:
143        """Check if the user is using a flow token to restore a plan"""
144        token: FlowToken | None = FlowToken.objects.filter(key=key).first()
145        if not token:
146            return None
147        plan = None
148        try:
149            plan = token.plan
150        except (AttributeError, EOFError, ImportError, IndexError) as exc:
151            LOGGER.warning("f(exec): Failed to restore token plan", exc=exc)
152        finally:
153            if token.revoke_on_execution:
154                token.delete()
155        if not isinstance(plan, FlowPlan):
156            return None
157        if existing_plan := self.request.session.get(SESSION_KEY_PLAN):
158            plan.context.update(existing_plan.context)
159        plan.context[PLAN_CONTEXT_IS_RESTORED] = token
160        self._logger.debug("f(exec): restored flow plan from token", plan=plan)
161        return plan
162
163    def initialize_request(self, request, *args, **kwargs):
164        # Stubbed out `initialize_request` since we call the correct method early on
165        # in `dispatch`, and super().dispatch would call it again
166        return self.request or request
167
168    def dispatch(self, request: HttpRequest, flow_slug: str) -> HttpResponse:
169        self.request = super().initialize_request(request)
170        self.initial(self.request)
171
172        with active_tracer().start_span(
173            op="authentik.flow.executor.dispatch", name=self.flow.slug
174        ) as span:
175            span.set_data("authentik Flow", self.flow.slug)
176            get_params = QueryDict(request.GET.get(QS_QUERY, ""))
177            if QS_KEY_TOKEN in get_params:
178                plan = self._check_flow_token(get_params[QS_KEY_TOKEN])
179                if plan:
180                    self.request.session[SESSION_KEY_PLAN] = plan
181            # Early check if there's an active Plan for the current session
182            if SESSION_KEY_PLAN in self.request.session:
183                self.plan: FlowPlan = self.request.session[SESSION_KEY_PLAN]
184                if self.plan.flow_pk != self.flow.pk.hex:
185                    self._logger.warning(
186                        "f(exec): Found existing plan for other flow, deleting plan",
187                        other_flow=self.plan.flow_pk,
188                    )
189                    # Existing plan is deleted from session and instance
190                    self.plan = None
191                    self.cancel()
192                else:
193                    self._logger.debug("f(exec): Continuing existing plan")
194
195            # Initial flow request, check if we have an upstream query string passed in
196            request.session[SESSION_KEY_GET] = get_params
197            # Don't check session again as we've either already loaded the plan or we need to plan
198            if not self.plan:
199                request.session[SESSION_KEY_HISTORY] = []
200                self._logger.debug("f(exec): No active Plan found, initiating planner")
201                try:
202                    self.plan = self._initiate_plan()
203                except FlowNonApplicableException as exc:
204                    # If we're this flow is for authentication and the user is already authenticated
205                    # continue to the next URL
206                    if (
207                        self.flow.designation == FlowDesignation.AUTHENTICATION
208                        and self.request.user.is_authenticated
209                    ):
210                        return self._flow_done()
211                    self._logger.warning("f(exec): Flow not applicable to current user", exc=exc)
212                    return self.handle_invalid_flow(exc)
213                except EmptyFlowException as exc:
214                    self._logger.warning("f(exec): Flow is empty", exc=exc)
215                    # To match behavior with loading an empty flow plan from cache,
216                    # we don't show an error message here, but rather call _flow_done()
217                    return self._flow_done()
218            # We don't save the Plan after getting the next stage
219            # as it hasn't been successfully passed yet
220            try:
221                # This is the first time we actually access any attribute on the selected plan
222                # if the cached plan is from an older version, it might have different attributes
223                # in which case we just delete the plan and invalidate everything
224                next_binding = self.plan.next(self.request)
225            except Exception as exc:  # noqa
226                self._logger.warning(
227                    "f(exec): found incompatible flow plan, invalidating run", exc=exc
228                )
229                keys = cache.keys(f"{CACHE_PREFIX}*")
230                cache.delete_many(keys)
231                return self.stage_invalid()
232            if not next_binding:
233                self._logger.debug("f(exec): no more stages, flow is done.")
234                return self._flow_done()
235            self.current_binding = next_binding
236            self.current_stage = next_binding.stage
237            self._logger.debug(
238                "f(exec): Current stage",
239                current_stage=self.current_stage,
240                flow_slug=self.flow.slug,
241            )
242            try:
243                stage_cls = self.current_stage.view
244            except NotImplementedError as exc:
245                self._logger.debug("Error getting stage type", exc=exc)
246                return self.stage_invalid()
247            self.current_stage_view = stage_cls(self)
248            self.current_stage_view.args = self.args
249            self.current_stage_view.kwargs = self.kwargs
250            self.current_stage_view.request = request
251            try:
252                return super().dispatch(request)
253            except InvalidStageError as exc:
254                return self.stage_invalid(str(exc))
255
256    def handle_exception(self, exc: Exception) -> HttpResponse:
257        """Handle exception in stage execution"""
258        if settings.DEBUG or settings.TEST:
259            raise exc
260        self._logger.warning(exc)
261        if not should_ignore_exception(exc):
262            record_exception(exc)
263            Event.new(
264                action=EventAction.SYSTEM_EXCEPTION,
265                message="System exception during flow execution.",
266            ).with_exception(exc).from_http(self.request)
267        challenge = FlowErrorChallenge(self.request, exc)
268        challenge.is_valid(raise_exception=True)
269        return to_stage_response(self.request, HttpChallengeResponse(challenge))
270
271    @extend_schema(
272        responses={
273            200: PolymorphicProxySerializer(
274                component_name="ChallengeTypes",
275                serializers=challenge_types,
276                resource_type_field_name="component",
277            ),
278        },
279        request=OpenApiTypes.NONE,
280        parameters=[
281            OpenApiParameter(
282                name="query",
283                location=OpenApiParameter.QUERY,
284                required=True,
285                description="Querystring as received",
286                type=OpenApiTypes.STR,
287            )
288        ],
289        operation_id="flows_executor_get",
290    )
291    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
292        """Get the next pending challenge from the currently active flow."""
293        class_path = class_to_path(self.current_stage_view.__class__)
294        self._logger.debug(
295            "f(exec): Passing GET",
296            view_class=class_path,
297            stage=self.current_stage,
298        )
299        try:
300            with (
301                active_tracer().start_span(
302                    op="authentik.flow.executor.stage",
303                    name=class_path,
304                ) as span,
305                HIST_FLOW_EXECUTION_STAGE_TIME.labels(
306                    method=request.method.upper(),
307                    stage_type=class_path,
308                ).time(),
309            ):
310                span.set_data("Method", request.method.upper())
311                span.set_data("authentik Stage", self.current_stage_view)
312                span.set_data("authentik Flow", self.flow.slug)
313                stage_response = self.current_stage_view.dispatch(request)
314                return to_stage_response(request, stage_response)
315        except Exception as exc:  # noqa
316            return self.handle_exception(exc)
317
318    @extend_schema(
319        responses={
320            200: PolymorphicProxySerializer(
321                component_name="ChallengeTypes",
322                serializers=challenge_types,
323                resource_type_field_name="component",
324            ),
325        },
326        request=PolymorphicProxySerializer(
327            component_name="FlowChallengeResponse",
328            serializers=challenge_response_types,
329            resource_type_field_name="component",
330        ),
331        parameters=[
332            OpenApiParameter(
333                name="query",
334                location=OpenApiParameter.QUERY,
335                required=True,
336                description="Querystring as received",
337                type=OpenApiTypes.STR,
338            )
339        ],
340        operation_id="flows_executor_solve",
341    )
342    def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
343        """Solve the previously retrieved challenge and advanced to the next stage."""
344        class_path = class_to_path(self.current_stage_view.__class__)
345        self._logger.debug(
346            "f(exec): Passing POST",
347            view_class=class_path,
348            stage=self.current_stage,
349        )
350        try:
351            with (
352                active_tracer().start_span(
353                    op="authentik.flow.executor.stage",
354                    name=class_path,
355                ) as span,
356                HIST_FLOW_EXECUTION_STAGE_TIME.labels(
357                    method=request.method.upper(),
358                    stage_type=class_path,
359                ).time(),
360            ):
361                span.set_data("Method", request.method.upper())
362                span.set_data("authentik Stage", self.current_stage_view)
363                span.set_data("authentik Flow", self.flow.slug)
364                stage_response = self.current_stage_view.dispatch(request)
365                return to_stage_response(request, stage_response)
366        except Exception as exc:  # noqa
367            return self.handle_exception(exc)
368
369    def _initiate_plan(self) -> FlowPlan:
370        planner = FlowPlanner(self.flow)
371        plan = planner.plan(self.request)
372        self.request.session[SESSION_KEY_PLAN] = plan
373        try:
374            # Call the has_stages getter to check that
375            # there are no issues with the class we might've gotten
376            # from the cache. If there are errors, just delete all cached flows
377            _ = plan.has_stages
378        except Exception:  # noqa
379            keys = cache.keys(f"{CACHE_PREFIX}*")
380            cache.delete_many(keys)
381            return self._initiate_plan()
382        return plan
383
384    def restart_flow(self, keep_context=False) -> HttpResponse:
385        """Restart the currently active flow, optionally keeping the current context"""
386        planner = FlowPlanner(self.flow)
387        planner.use_cache = False
388        default_context = None
389        if keep_context:
390            default_context = self.plan.context
391        try:
392            plan = planner.plan(self.request, default_context)
393        except FlowNonApplicableException as exc:
394            self._logger.warning("f(exec): Flow restart not applicable to current user", exc=exc)
395            return self.handle_invalid_flow(exc)
396        self.request.session[SESSION_KEY_PLAN] = plan
397        kwargs = self.kwargs
398        kwargs.update({"flow_slug": self.flow.slug})
399        return redirect_with_qs("authentik_api:flow-executor", self.request.GET, **kwargs)
400
401    def _flow_done(self) -> HttpResponse:
402        """User Successfully passed all stages"""
403        # Since this is wrapped by the ExecutorShell, the next argument is saved in the session
404        # extract the next param before cancel as that cleans it
405        continuous_login_hold = None
406        if self.plan:
407            continuous_login_hold = self.plan.context.get(PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD)
408        if self.plan and PLAN_CONTEXT_REDIRECT in self.plan.context:
409            # The context `redirect` variable can only be set by
410            # an expression policy or authentik itself, so we don't
411            # check if its an absolute URL or a relative one
412            self.cancel()
413            return to_stage_response(
414                self.request,
415                redirect(self.plan.context.get(PLAN_CONTEXT_REDIRECT)),
416                final_redirect=True,
417                continuous_login_hold=continuous_login_hold,
418            )
419        next_param = self.request.session.get(SESSION_KEY_GET, {}).get(
420            NEXT_ARG_NAME, "authentik_core:root-redirect"
421        )
422        self.cancel()
423        if next_param and not is_url_absolute(next_param):
424            return to_stage_response(
425                self.request,
426                redirect_with_qs(next_param),
427                final_redirect=True,
428                continuous_login_hold=continuous_login_hold,
429            )
430        return to_stage_response(
431            self.request, self.stage_invalid(error_message=_("Invalid next URL"))
432        )
433
434    def stage_ok(self) -> HttpResponse:
435        """Callback called by stages upon successful completion.
436        Persists updated plan and context to session."""
437        self._logger.debug(
438            "f(exec): Stage ok",
439            stage_class=class_to_path(self.current_stage_view.__class__),
440        )
441        if isinstance(self.current_stage_view, StageView):
442            self.current_stage_view.cleanup()
443        if self.direct_execution:
444            # The stage's own response is returned directly. The plan was never stored in the
445            # session, and the session may hold the plan of a flow running in another tab.
446            self.plan.pop()
447            return HttpResponse()
448        if self.flow.inspector_accessible(self.request):
449            self.request.session.get(SESSION_KEY_HISTORY, []).append(deepcopy(self.plan))
450        self.plan.pop()
451        self.request.session[SESSION_KEY_PLAN] = self.plan
452        if self.plan.bindings:
453            self._logger.debug(
454                "f(exec): Continuing with next stage",
455                remaining=len(self.plan.bindings),
456            )
457            kwargs = self.kwargs
458            kwargs.update({"flow_slug": self.flow.slug})
459            return redirect_with_qs("authentik_api:flow-executor", self.request.GET, **kwargs)
460        # User passed all stages
461        self._logger.debug(
462            "f(exec): User passed all stages",
463            context=cleanse_dict(self.plan.context),
464        )
465        return self._flow_done()
466
467    def stage_invalid(self, error_message: str | None = None) -> HttpResponse:
468        """Callback used stage when data is correct but a policy denies access
469        or the user account is disabled.
470
471        Optionally, an exception can be passed, which will be shown if the current user
472        is a superuser."""
473        self._logger.debug("f(exec): Stage invalid")
474        if self.current_binding and self.current_binding.invalid_response_action in [
475            InvalidResponseAction.RESTART,
476            InvalidResponseAction.RESTART_WITH_CONTEXT,
477        ]:
478            keep_context = (
479                self.current_binding.invalid_response_action
480                == InvalidResponseAction.RESTART_WITH_CONTEXT
481            )
482            self._logger.debug(
483                "f(exec): Invalid response, restarting flow",
484                keep_context=keep_context,
485            )
486            return self.restart_flow(keep_context)
487        challenge_view = AccessDeniedStage(self, error_message)
488        challenge_view.request = self.request
489        # Render the challenge first, because cancel() clears the stored query that its
490        # cancel URL reads `next` from
491        response = challenge_view.get(self.request)
492        self.cancel()
493        return to_stage_response(self.request, response)
494
495    def cancel(self):
496        """Cancel current flow execution"""
497        if self.direct_execution:
498            # Direct execution keeps its plan local to the request, so there is no session
499            # state to clean up, and the session may belong to a flow running in another tab.
500            return
501        keys_to_delete = [
502            SESSION_KEY_PLAN,
503            SESSION_KEY_GET,
504            # We might need the initial POST payloads for later requests
505            # SESSION_KEY_POST,
506            # We don't delete the history on purpose, as a user might
507            # still be inspecting it.
508            # It's only deleted on a fresh executions
509            # SESSION_KEY_HISTORY,
510        ]
511        self._logger.debug("f(exec): cleaning up")
512        for key in keys_to_delete:
513            if key in self.request.session:
514                del self.request.session[key]
515
516
517class CancelView(View):
518    """View which cancels the currently active plan"""
519
520    def clean_next_url(self, url: str) -> str:
521        """Remove any user identifiers from the URL to prevent loops"""
522        qs_to_remove = [QS_LOGIN_HINT]
523        parts = urlsplit(url)
524        if not any(x in parts.query for x in qs_to_remove):
525            return url
526        query = QueryDict(parts.query, mutable=True)
527        for qs in qs_to_remove:
528            query.pop(qs, None)
529        return urlunsplit(parts._replace(query=urlencode(sorted(query.items()), doseq=True)))
530
531    def get(self, request: HttpRequest) -> HttpResponse:
532        """View which canels the currently active plan"""
533        if SESSION_KEY_PLAN in request.session:
534            del request.session[SESSION_KEY_PLAN]
535            LOGGER.debug("Canceled current plan")
536        next_url = self.request.GET.get(NEXT_ARG_NAME)
537        if next_url and not is_url_absolute(next_url):
538            # Ensure that we get rid of any user identifiers from the URL
539            return redirect(self.clean_next_url(next_url))
540        return redirect("authentik_flows:default-invalidation")
541
542
543class ToDefaultFlow(View):
544    """Redirect to default flow matching by designation"""
545
546    designation: FlowDesignation | None = None
547
548    @staticmethod
549    def flow_by_policy(request: HttpRequest, **flow_filter) -> Flow | None:
550        """Get a Flow by `**flow_filter` and check if the request from `request` can access it."""
551        flows = Flow.objects.filter(**flow_filter).order_by("slug")
552        for flow in flows:
553            engine = PolicyEngine(flow, request.user, request)
554            engine.build()
555            result = engine.result
556            if result.passing:
557                LOGGER.debug("flow_by_policy: flow passing", flow=flow)
558                return flow
559            LOGGER.warning("flow_by_policy: flow not passing", flow=flow, messages=result.messages)
560        LOGGER.debug("flow_by_policy: no flow found", filters=flow_filter)
561        return None
562
563    @staticmethod
564    def get_flow(request: HttpRequest, designation: FlowDesignation) -> Flow:
565        """Get a flow for the selected designation"""
566        brand: Brand = request.brand
567        flow = None
568        # First, attempt to get default flow from brand
569        if designation == FlowDesignation.AUTHENTICATION:
570            flow = brand.flow_authentication
571        elif designation == FlowDesignation.INVALIDATION:
572            flow = brand.flow_invalidation
573        if flow:
574            return flow
575        # If no flow was set, get the first based on slug and policy
576        flow = ToDefaultFlow.flow_by_policy(request, designation=designation)
577        if flow:
578            return flow
579        # If we still don't have a flow, 404
580        raise Http404
581
582    def dispatch(self, request: HttpRequest) -> HttpResponse:
583        flow = ToDefaultFlow.get_flow(request, self.designation)
584        # If user already has a pending plan, clear it so we don't have to later.
585        if SESSION_KEY_PLAN in self.request.session:
586            plan: FlowPlan = self.request.session[SESSION_KEY_PLAN]
587            if plan.flow_pk != flow.pk.hex:
588                LOGGER.warning(
589                    "f(def): Found existing plan for other flow, deleting plan",
590                    flow_slug=flow.slug,
591                )
592                del self.request.session[SESSION_KEY_PLAN]
593        return redirect_with_qs("authentik_core:if-flow", request.GET, flow_slug=flow.slug)
594
595
596def to_stage_response(
597    request: HttpRequest,
598    source: HttpResponse,
599    final_redirect: bool = False,
600    continuous_login_hold: bool | None = None,
601) -> HttpResponse:
602    """Convert normal HttpResponse into JSON Response"""
603    if (
604        isinstance(source, HttpResponseRedirect)
605        or source.status_code == HttpResponseRedirect.status_code
606    ):
607        redirect_url = source["Location"]
608        # Redirects to the same URL usually indicate an Error within a form
609        if request.get_full_path() == redirect_url:
610            return source
611        LOGGER.debug(
612            "converting to redirect challenge",
613            to=str(redirect_url),
614            current=request.path,
615        )
616        challenge_data = {
617            "to": str(redirect_url),
618            "final_redirect": final_redirect,
619        }
620        if continuous_login_hold is not None:
621            challenge_data["continuous_login_hold"] = continuous_login_hold
622        return HttpChallengeResponse(RedirectChallenge(challenge_data))
623    if isinstance(source, TemplateResponse):
624        return HttpChallengeResponse(
625            ShellChallenge(
626                {
627                    "body": source.render().content.decode("utf-8"),
628                }
629            )
630        )
631    # Check for actual HttpResponse (without isinstance as we don't want to check inheritance)
632    if source.__class__ == HttpResponse:
633        return HttpChallengeResponse(
634            ShellChallenge(
635                {
636                    "body": source.content.decode("utf-8"),
637                }
638            )
639        )
640    return source
641
642
643class ConfigureFlowInitView(LoginRequiredMixin, View):
644    """Initiate planner for selected change flow and redirect to flow executor,
645    or raise Http404 if no configure_flow has been set."""
646
647    def get(self, request: HttpRequest, stage_uuid: str) -> HttpResponse:
648        """Initiate planner for selected change flow and redirect to flow executor,
649        or raise Http404 if no configure_flow has been set."""
650        try:
651            stage: Stage = Stage.objects.get_subclass(pk=stage_uuid)
652        except Stage.DoesNotExist as exc:
653            raise Http404 from exc
654        if not isinstance(stage, ConfigurableStage):
655            LOGGER.debug("Stage does not inherit ConfigurableStage", stage=stage)
656            raise Http404
657        if not stage.configure_flow:
658            LOGGER.debug("Stage has no configure_flow set", stage=stage)
659            raise Http404
660
661        try:
662            plan = FlowPlanner(stage.configure_flow).plan(
663                request, {PLAN_CONTEXT_PENDING_USER: request.user}
664            )
665        except FlowNonApplicableException:
666            LOGGER.warning("Flow not applicable to user")
667            raise Http404 from None
668        return plan.to_redirect(request, stage.configure_flow)
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
NEXT_ARG_NAME = 'next'
SESSION_KEY_PLAN = 'authentik/flows/plan'
SESSION_KEY_GET = 'authentik/flows/get'
SESSION_KEY_POST = 'authentik/flows/post'
SESSION_KEY_HISTORY = 'authentik/flows/history'
QS_KEY_TOKEN = 'flow_token'
QS_QUERY = 'query'
def challenge_types():
80def challenge_types():
81    """This function returns a mapping which contains all subclasses of challenges
82    subclasses of Challenge, and Challenge itself."""
83    mapping = {}
84    for cls in all_subclasses(Challenge):
85        if cls == WithUserInfoChallenge:
86            continue
87        mapping[cls().fields["component"].default] = cls
88    return mapping

This function returns a mapping which contains all subclasses of challenges subclasses of Challenge, and Challenge itself.

def challenge_response_types():
91def challenge_response_types():
92    """This function returns a mapping which contains all subclasses of challenges
93    subclasses of Challenge, and Challenge itself."""
94    mapping = {}
95    for cls in all_subclasses(ChallengeResponse):
96        mapping[cls(stage=None).fields["component"].default] = cls
97    return mapping

This function returns a mapping which contains all subclasses of challenges subclasses of Challenge, and Challenge itself.

class InvalidStageError(authentik.lib.tracing.exceptions.TracingIgnoredException):
100class InvalidStageError(TracingIgnoredException):
101    """Error raised when a challenge from a stage is not valid"""

Error raised when a challenge from a stage is not valid

@method_decorator(xframe_options_sameorigin, name='dispatch')
class FlowExecutorView(rest_framework.views.APIView):
104@method_decorator(xframe_options_sameorigin, name="dispatch")
105class FlowExecutorView(APIView):
106    """Flow executor, passing requests to Stage Views"""
107
108    permission_classes = [AllowAny]
109
110    flow: Flow = None
111
112    plan: FlowPlan | None = None
113    current_binding: FlowStageBinding | None = None
114    current_stage: Stage
115    current_stage_view: View
116    direct_execution = False
117
118    _logger: BoundLogger
119
120    def setup(self, request: HttpRequest, flow_slug: str):
121        super().setup(request, flow_slug=flow_slug)
122        if not self.flow:
123            self.flow = get_object_or_404(Flow.objects.select_related(), slug=flow_slug)
124        self._logger = get_logger().bind(flow_slug=flow_slug)
125        active_tracer().set_tag("authentik.flow", self.flow.slug)
126
127    def handle_invalid_flow(self, exc: FlowNonApplicableException) -> HttpResponse:
128        """When a flow is non-applicable check if user is on the correct domain"""
129        if self.flow.denied_action in [
130            FlowDeniedAction.CONTINUE,
131            FlowDeniedAction.MESSAGE_CONTINUE,
132        ]:
133            next_url = self.request.GET.get(NEXT_ARG_NAME)
134            if next_url and not is_url_absolute(next_url):
135                self._logger.debug("f(exec): Redirecting to next on fail")
136                return to_stage_response(self.request, redirect(next_url))
137        if self.flow.denied_action == FlowDeniedAction.CONTINUE:
138            return to_stage_response(
139                self.request, redirect(reverse("authentik_core:root-redirect"))
140            )
141        return to_stage_response(self.request, self.stage_invalid(error_message=exc.messages))
142
143    def _check_flow_token(self, key: str) -> FlowPlan | None:
144        """Check if the user is using a flow token to restore a plan"""
145        token: FlowToken | None = FlowToken.objects.filter(key=key).first()
146        if not token:
147            return None
148        plan = None
149        try:
150            plan = token.plan
151        except (AttributeError, EOFError, ImportError, IndexError) as exc:
152            LOGGER.warning("f(exec): Failed to restore token plan", exc=exc)
153        finally:
154            if token.revoke_on_execution:
155                token.delete()
156        if not isinstance(plan, FlowPlan):
157            return None
158        if existing_plan := self.request.session.get(SESSION_KEY_PLAN):
159            plan.context.update(existing_plan.context)
160        plan.context[PLAN_CONTEXT_IS_RESTORED] = token
161        self._logger.debug("f(exec): restored flow plan from token", plan=plan)
162        return plan
163
164    def initialize_request(self, request, *args, **kwargs):
165        # Stubbed out `initialize_request` since we call the correct method early on
166        # in `dispatch`, and super().dispatch would call it again
167        return self.request or request
168
169    def dispatch(self, request: HttpRequest, flow_slug: str) -> HttpResponse:
170        self.request = super().initialize_request(request)
171        self.initial(self.request)
172
173        with active_tracer().start_span(
174            op="authentik.flow.executor.dispatch", name=self.flow.slug
175        ) as span:
176            span.set_data("authentik Flow", self.flow.slug)
177            get_params = QueryDict(request.GET.get(QS_QUERY, ""))
178            if QS_KEY_TOKEN in get_params:
179                plan = self._check_flow_token(get_params[QS_KEY_TOKEN])
180                if plan:
181                    self.request.session[SESSION_KEY_PLAN] = plan
182            # Early check if there's an active Plan for the current session
183            if SESSION_KEY_PLAN in self.request.session:
184                self.plan: FlowPlan = self.request.session[SESSION_KEY_PLAN]
185                if self.plan.flow_pk != self.flow.pk.hex:
186                    self._logger.warning(
187                        "f(exec): Found existing plan for other flow, deleting plan",
188                        other_flow=self.plan.flow_pk,
189                    )
190                    # Existing plan is deleted from session and instance
191                    self.plan = None
192                    self.cancel()
193                else:
194                    self._logger.debug("f(exec): Continuing existing plan")
195
196            # Initial flow request, check if we have an upstream query string passed in
197            request.session[SESSION_KEY_GET] = get_params
198            # Don't check session again as we've either already loaded the plan or we need to plan
199            if not self.plan:
200                request.session[SESSION_KEY_HISTORY] = []
201                self._logger.debug("f(exec): No active Plan found, initiating planner")
202                try:
203                    self.plan = self._initiate_plan()
204                except FlowNonApplicableException as exc:
205                    # If we're this flow is for authentication and the user is already authenticated
206                    # continue to the next URL
207                    if (
208                        self.flow.designation == FlowDesignation.AUTHENTICATION
209                        and self.request.user.is_authenticated
210                    ):
211                        return self._flow_done()
212                    self._logger.warning("f(exec): Flow not applicable to current user", exc=exc)
213                    return self.handle_invalid_flow(exc)
214                except EmptyFlowException as exc:
215                    self._logger.warning("f(exec): Flow is empty", exc=exc)
216                    # To match behavior with loading an empty flow plan from cache,
217                    # we don't show an error message here, but rather call _flow_done()
218                    return self._flow_done()
219            # We don't save the Plan after getting the next stage
220            # as it hasn't been successfully passed yet
221            try:
222                # This is the first time we actually access any attribute on the selected plan
223                # if the cached plan is from an older version, it might have different attributes
224                # in which case we just delete the plan and invalidate everything
225                next_binding = self.plan.next(self.request)
226            except Exception as exc:  # noqa
227                self._logger.warning(
228                    "f(exec): found incompatible flow plan, invalidating run", exc=exc
229                )
230                keys = cache.keys(f"{CACHE_PREFIX}*")
231                cache.delete_many(keys)
232                return self.stage_invalid()
233            if not next_binding:
234                self._logger.debug("f(exec): no more stages, flow is done.")
235                return self._flow_done()
236            self.current_binding = next_binding
237            self.current_stage = next_binding.stage
238            self._logger.debug(
239                "f(exec): Current stage",
240                current_stage=self.current_stage,
241                flow_slug=self.flow.slug,
242            )
243            try:
244                stage_cls = self.current_stage.view
245            except NotImplementedError as exc:
246                self._logger.debug("Error getting stage type", exc=exc)
247                return self.stage_invalid()
248            self.current_stage_view = stage_cls(self)
249            self.current_stage_view.args = self.args
250            self.current_stage_view.kwargs = self.kwargs
251            self.current_stage_view.request = request
252            try:
253                return super().dispatch(request)
254            except InvalidStageError as exc:
255                return self.stage_invalid(str(exc))
256
257    def handle_exception(self, exc: Exception) -> HttpResponse:
258        """Handle exception in stage execution"""
259        if settings.DEBUG or settings.TEST:
260            raise exc
261        self._logger.warning(exc)
262        if not should_ignore_exception(exc):
263            record_exception(exc)
264            Event.new(
265                action=EventAction.SYSTEM_EXCEPTION,
266                message="System exception during flow execution.",
267            ).with_exception(exc).from_http(self.request)
268        challenge = FlowErrorChallenge(self.request, exc)
269        challenge.is_valid(raise_exception=True)
270        return to_stage_response(self.request, HttpChallengeResponse(challenge))
271
272    @extend_schema(
273        responses={
274            200: PolymorphicProxySerializer(
275                component_name="ChallengeTypes",
276                serializers=challenge_types,
277                resource_type_field_name="component",
278            ),
279        },
280        request=OpenApiTypes.NONE,
281        parameters=[
282            OpenApiParameter(
283                name="query",
284                location=OpenApiParameter.QUERY,
285                required=True,
286                description="Querystring as received",
287                type=OpenApiTypes.STR,
288            )
289        ],
290        operation_id="flows_executor_get",
291    )
292    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
293        """Get the next pending challenge from the currently active flow."""
294        class_path = class_to_path(self.current_stage_view.__class__)
295        self._logger.debug(
296            "f(exec): Passing GET",
297            view_class=class_path,
298            stage=self.current_stage,
299        )
300        try:
301            with (
302                active_tracer().start_span(
303                    op="authentik.flow.executor.stage",
304                    name=class_path,
305                ) as span,
306                HIST_FLOW_EXECUTION_STAGE_TIME.labels(
307                    method=request.method.upper(),
308                    stage_type=class_path,
309                ).time(),
310            ):
311                span.set_data("Method", request.method.upper())
312                span.set_data("authentik Stage", self.current_stage_view)
313                span.set_data("authentik Flow", self.flow.slug)
314                stage_response = self.current_stage_view.dispatch(request)
315                return to_stage_response(request, stage_response)
316        except Exception as exc:  # noqa
317            return self.handle_exception(exc)
318
319    @extend_schema(
320        responses={
321            200: PolymorphicProxySerializer(
322                component_name="ChallengeTypes",
323                serializers=challenge_types,
324                resource_type_field_name="component",
325            ),
326        },
327        request=PolymorphicProxySerializer(
328            component_name="FlowChallengeResponse",
329            serializers=challenge_response_types,
330            resource_type_field_name="component",
331        ),
332        parameters=[
333            OpenApiParameter(
334                name="query",
335                location=OpenApiParameter.QUERY,
336                required=True,
337                description="Querystring as received",
338                type=OpenApiTypes.STR,
339            )
340        ],
341        operation_id="flows_executor_solve",
342    )
343    def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
344        """Solve the previously retrieved challenge and advanced to the next stage."""
345        class_path = class_to_path(self.current_stage_view.__class__)
346        self._logger.debug(
347            "f(exec): Passing POST",
348            view_class=class_path,
349            stage=self.current_stage,
350        )
351        try:
352            with (
353                active_tracer().start_span(
354                    op="authentik.flow.executor.stage",
355                    name=class_path,
356                ) as span,
357                HIST_FLOW_EXECUTION_STAGE_TIME.labels(
358                    method=request.method.upper(),
359                    stage_type=class_path,
360                ).time(),
361            ):
362                span.set_data("Method", request.method.upper())
363                span.set_data("authentik Stage", self.current_stage_view)
364                span.set_data("authentik Flow", self.flow.slug)
365                stage_response = self.current_stage_view.dispatch(request)
366                return to_stage_response(request, stage_response)
367        except Exception as exc:  # noqa
368            return self.handle_exception(exc)
369
370    def _initiate_plan(self) -> FlowPlan:
371        planner = FlowPlanner(self.flow)
372        plan = planner.plan(self.request)
373        self.request.session[SESSION_KEY_PLAN] = plan
374        try:
375            # Call the has_stages getter to check that
376            # there are no issues with the class we might've gotten
377            # from the cache. If there are errors, just delete all cached flows
378            _ = plan.has_stages
379        except Exception:  # noqa
380            keys = cache.keys(f"{CACHE_PREFIX}*")
381            cache.delete_many(keys)
382            return self._initiate_plan()
383        return plan
384
385    def restart_flow(self, keep_context=False) -> HttpResponse:
386        """Restart the currently active flow, optionally keeping the current context"""
387        planner = FlowPlanner(self.flow)
388        planner.use_cache = False
389        default_context = None
390        if keep_context:
391            default_context = self.plan.context
392        try:
393            plan = planner.plan(self.request, default_context)
394        except FlowNonApplicableException as exc:
395            self._logger.warning("f(exec): Flow restart not applicable to current user", exc=exc)
396            return self.handle_invalid_flow(exc)
397        self.request.session[SESSION_KEY_PLAN] = plan
398        kwargs = self.kwargs
399        kwargs.update({"flow_slug": self.flow.slug})
400        return redirect_with_qs("authentik_api:flow-executor", self.request.GET, **kwargs)
401
402    def _flow_done(self) -> HttpResponse:
403        """User Successfully passed all stages"""
404        # Since this is wrapped by the ExecutorShell, the next argument is saved in the session
405        # extract the next param before cancel as that cleans it
406        continuous_login_hold = None
407        if self.plan:
408            continuous_login_hold = self.plan.context.get(PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD)
409        if self.plan and PLAN_CONTEXT_REDIRECT in self.plan.context:
410            # The context `redirect` variable can only be set by
411            # an expression policy or authentik itself, so we don't
412            # check if its an absolute URL or a relative one
413            self.cancel()
414            return to_stage_response(
415                self.request,
416                redirect(self.plan.context.get(PLAN_CONTEXT_REDIRECT)),
417                final_redirect=True,
418                continuous_login_hold=continuous_login_hold,
419            )
420        next_param = self.request.session.get(SESSION_KEY_GET, {}).get(
421            NEXT_ARG_NAME, "authentik_core:root-redirect"
422        )
423        self.cancel()
424        if next_param and not is_url_absolute(next_param):
425            return to_stage_response(
426                self.request,
427                redirect_with_qs(next_param),
428                final_redirect=True,
429                continuous_login_hold=continuous_login_hold,
430            )
431        return to_stage_response(
432            self.request, self.stage_invalid(error_message=_("Invalid next URL"))
433        )
434
435    def stage_ok(self) -> HttpResponse:
436        """Callback called by stages upon successful completion.
437        Persists updated plan and context to session."""
438        self._logger.debug(
439            "f(exec): Stage ok",
440            stage_class=class_to_path(self.current_stage_view.__class__),
441        )
442        if isinstance(self.current_stage_view, StageView):
443            self.current_stage_view.cleanup()
444        if self.direct_execution:
445            # The stage's own response is returned directly. The plan was never stored in the
446            # session, and the session may hold the plan of a flow running in another tab.
447            self.plan.pop()
448            return HttpResponse()
449        if self.flow.inspector_accessible(self.request):
450            self.request.session.get(SESSION_KEY_HISTORY, []).append(deepcopy(self.plan))
451        self.plan.pop()
452        self.request.session[SESSION_KEY_PLAN] = self.plan
453        if self.plan.bindings:
454            self._logger.debug(
455                "f(exec): Continuing with next stage",
456                remaining=len(self.plan.bindings),
457            )
458            kwargs = self.kwargs
459            kwargs.update({"flow_slug": self.flow.slug})
460            return redirect_with_qs("authentik_api:flow-executor", self.request.GET, **kwargs)
461        # User passed all stages
462        self._logger.debug(
463            "f(exec): User passed all stages",
464            context=cleanse_dict(self.plan.context),
465        )
466        return self._flow_done()
467
468    def stage_invalid(self, error_message: str | None = None) -> HttpResponse:
469        """Callback used stage when data is correct but a policy denies access
470        or the user account is disabled.
471
472        Optionally, an exception can be passed, which will be shown if the current user
473        is a superuser."""
474        self._logger.debug("f(exec): Stage invalid")
475        if self.current_binding and self.current_binding.invalid_response_action in [
476            InvalidResponseAction.RESTART,
477            InvalidResponseAction.RESTART_WITH_CONTEXT,
478        ]:
479            keep_context = (
480                self.current_binding.invalid_response_action
481                == InvalidResponseAction.RESTART_WITH_CONTEXT
482            )
483            self._logger.debug(
484                "f(exec): Invalid response, restarting flow",
485                keep_context=keep_context,
486            )
487            return self.restart_flow(keep_context)
488        challenge_view = AccessDeniedStage(self, error_message)
489        challenge_view.request = self.request
490        # Render the challenge first, because cancel() clears the stored query that its
491        # cancel URL reads `next` from
492        response = challenge_view.get(self.request)
493        self.cancel()
494        return to_stage_response(self.request, response)
495
496    def cancel(self):
497        """Cancel current flow execution"""
498        if self.direct_execution:
499            # Direct execution keeps its plan local to the request, so there is no session
500            # state to clean up, and the session may belong to a flow running in another tab.
501            return
502        keys_to_delete = [
503            SESSION_KEY_PLAN,
504            SESSION_KEY_GET,
505            # We might need the initial POST payloads for later requests
506            # SESSION_KEY_POST,
507            # We don't delete the history on purpose, as a user might
508            # still be inspecting it.
509            # It's only deleted on a fresh executions
510            # SESSION_KEY_HISTORY,
511        ]
512        self._logger.debug("f(exec): cleaning up")
513        for key in keys_to_delete:
514            if key in self.request.session:
515                del self.request.session[key]

Flow executor, passing requests to Stage Views

permission_classes = [<class 'rest_framework.permissions.AllowAny'>]
plan: authentik.flows.planner.FlowPlan | None = None
current_binding: authentik.flows.models.FlowStageBinding | None = None
current_stage_view: django.views.generic.base.View
direct_execution = False
def setup(self, request: django.http.request.HttpRequest, flow_slug: str):
120    def setup(self, request: HttpRequest, flow_slug: str):
121        super().setup(request, flow_slug=flow_slug)
122        if not self.flow:
123            self.flow = get_object_or_404(Flow.objects.select_related(), slug=flow_slug)
124        self._logger = get_logger().bind(flow_slug=flow_slug)
125        active_tracer().set_tag("authentik.flow", self.flow.slug)

Initialize attributes shared by all view methods.

def handle_invalid_flow( self, exc: authentik.flows.exceptions.FlowNonApplicableException) -> django.http.response.HttpResponse:
127    def handle_invalid_flow(self, exc: FlowNonApplicableException) -> HttpResponse:
128        """When a flow is non-applicable check if user is on the correct domain"""
129        if self.flow.denied_action in [
130            FlowDeniedAction.CONTINUE,
131            FlowDeniedAction.MESSAGE_CONTINUE,
132        ]:
133            next_url = self.request.GET.get(NEXT_ARG_NAME)
134            if next_url and not is_url_absolute(next_url):
135                self._logger.debug("f(exec): Redirecting to next on fail")
136                return to_stage_response(self.request, redirect(next_url))
137        if self.flow.denied_action == FlowDeniedAction.CONTINUE:
138            return to_stage_response(
139                self.request, redirect(reverse("authentik_core:root-redirect"))
140            )
141        return to_stage_response(self.request, self.stage_invalid(error_message=exc.messages))

When a flow is non-applicable check if user is on the correct domain

def initialize_request(self, request, *args, **kwargs):
164    def initialize_request(self, request, *args, **kwargs):
165        # Stubbed out `initialize_request` since we call the correct method early on
166        # in `dispatch`, and super().dispatch would call it again
167        return self.request or request

Returns the initial request object.

def dispatch( self, request: django.http.request.HttpRequest, flow_slug: str) -> django.http.response.HttpResponse:
169    def dispatch(self, request: HttpRequest, flow_slug: str) -> HttpResponse:
170        self.request = super().initialize_request(request)
171        self.initial(self.request)
172
173        with active_tracer().start_span(
174            op="authentik.flow.executor.dispatch", name=self.flow.slug
175        ) as span:
176            span.set_data("authentik Flow", self.flow.slug)
177            get_params = QueryDict(request.GET.get(QS_QUERY, ""))
178            if QS_KEY_TOKEN in get_params:
179                plan = self._check_flow_token(get_params[QS_KEY_TOKEN])
180                if plan:
181                    self.request.session[SESSION_KEY_PLAN] = plan
182            # Early check if there's an active Plan for the current session
183            if SESSION_KEY_PLAN in self.request.session:
184                self.plan: FlowPlan = self.request.session[SESSION_KEY_PLAN]
185                if self.plan.flow_pk != self.flow.pk.hex:
186                    self._logger.warning(
187                        "f(exec): Found existing plan for other flow, deleting plan",
188                        other_flow=self.plan.flow_pk,
189                    )
190                    # Existing plan is deleted from session and instance
191                    self.plan = None
192                    self.cancel()
193                else:
194                    self._logger.debug("f(exec): Continuing existing plan")
195
196            # Initial flow request, check if we have an upstream query string passed in
197            request.session[SESSION_KEY_GET] = get_params
198            # Don't check session again as we've either already loaded the plan or we need to plan
199            if not self.plan:
200                request.session[SESSION_KEY_HISTORY] = []
201                self._logger.debug("f(exec): No active Plan found, initiating planner")
202                try:
203                    self.plan = self._initiate_plan()
204                except FlowNonApplicableException as exc:
205                    # If we're this flow is for authentication and the user is already authenticated
206                    # continue to the next URL
207                    if (
208                        self.flow.designation == FlowDesignation.AUTHENTICATION
209                        and self.request.user.is_authenticated
210                    ):
211                        return self._flow_done()
212                    self._logger.warning("f(exec): Flow not applicable to current user", exc=exc)
213                    return self.handle_invalid_flow(exc)
214                except EmptyFlowException as exc:
215                    self._logger.warning("f(exec): Flow is empty", exc=exc)
216                    # To match behavior with loading an empty flow plan from cache,
217                    # we don't show an error message here, but rather call _flow_done()
218                    return self._flow_done()
219            # We don't save the Plan after getting the next stage
220            # as it hasn't been successfully passed yet
221            try:
222                # This is the first time we actually access any attribute on the selected plan
223                # if the cached plan is from an older version, it might have different attributes
224                # in which case we just delete the plan and invalidate everything
225                next_binding = self.plan.next(self.request)
226            except Exception as exc:  # noqa
227                self._logger.warning(
228                    "f(exec): found incompatible flow plan, invalidating run", exc=exc
229                )
230                keys = cache.keys(f"{CACHE_PREFIX}*")
231                cache.delete_many(keys)
232                return self.stage_invalid()
233            if not next_binding:
234                self._logger.debug("f(exec): no more stages, flow is done.")
235                return self._flow_done()
236            self.current_binding = next_binding
237            self.current_stage = next_binding.stage
238            self._logger.debug(
239                "f(exec): Current stage",
240                current_stage=self.current_stage,
241                flow_slug=self.flow.slug,
242            )
243            try:
244                stage_cls = self.current_stage.view
245            except NotImplementedError as exc:
246                self._logger.debug("Error getting stage type", exc=exc)
247                return self.stage_invalid()
248            self.current_stage_view = stage_cls(self)
249            self.current_stage_view.args = self.args
250            self.current_stage_view.kwargs = self.kwargs
251            self.current_stage_view.request = request
252            try:
253                return super().dispatch(request)
254            except InvalidStageError as exc:
255                return self.stage_invalid(str(exc))

Dispatch the incoming request to the appropriate handler method.

This method implements the core request/response lifecycle for Django REST Framework views:

  1. Wraps the incoming Django HttpRequest in a REST framework Request.
  2. Performs content negotiation, authentication, permission, and throttling checks.
  3. Resolves and calls the appropriate HTTP method handler (e.g. get(), post(), put()).
  4. Handles any exceptions raised during processing and converts them into appropriate Response objects.
  5. Finalizes and returns the response with proper rendering and headers applied.
def handle_exception(self, exc: Exception) -> django.http.response.HttpResponse:
257    def handle_exception(self, exc: Exception) -> HttpResponse:
258        """Handle exception in stage execution"""
259        if settings.DEBUG or settings.TEST:
260            raise exc
261        self._logger.warning(exc)
262        if not should_ignore_exception(exc):
263            record_exception(exc)
264            Event.new(
265                action=EventAction.SYSTEM_EXCEPTION,
266                message="System exception during flow execution.",
267            ).with_exception(exc).from_http(self.request)
268        challenge = FlowErrorChallenge(self.request, exc)
269        challenge.is_valid(raise_exception=True)
270        return to_stage_response(self.request, HttpChallengeResponse(challenge))

Handle exception in stage execution

@extend_schema(responses={200: PolymorphicProxySerializer(component_name='ChallengeTypes', serializers=challenge_types, resource_type_field_name='component')}, request=OpenApiTypes.NONE, parameters=[OpenApiParameter(name='query', location=OpenApiParameter.QUERY, required=True, description='Querystring as received', type=OpenApiTypes.STR)], operation_id='flows_executor_get')
def get( self, request: django.http.request.HttpRequest, *args, **kwargs) -> django.http.response.HttpResponse:
272    @extend_schema(
273        responses={
274            200: PolymorphicProxySerializer(
275                component_name="ChallengeTypes",
276                serializers=challenge_types,
277                resource_type_field_name="component",
278            ),
279        },
280        request=OpenApiTypes.NONE,
281        parameters=[
282            OpenApiParameter(
283                name="query",
284                location=OpenApiParameter.QUERY,
285                required=True,
286                description="Querystring as received",
287                type=OpenApiTypes.STR,
288            )
289        ],
290        operation_id="flows_executor_get",
291    )
292    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
293        """Get the next pending challenge from the currently active flow."""
294        class_path = class_to_path(self.current_stage_view.__class__)
295        self._logger.debug(
296            "f(exec): Passing GET",
297            view_class=class_path,
298            stage=self.current_stage,
299        )
300        try:
301            with (
302                active_tracer().start_span(
303                    op="authentik.flow.executor.stage",
304                    name=class_path,
305                ) as span,
306                HIST_FLOW_EXECUTION_STAGE_TIME.labels(
307                    method=request.method.upper(),
308                    stage_type=class_path,
309                ).time(),
310            ):
311                span.set_data("Method", request.method.upper())
312                span.set_data("authentik Stage", self.current_stage_view)
313                span.set_data("authentik Flow", self.flow.slug)
314                stage_response = self.current_stage_view.dispatch(request)
315                return to_stage_response(request, stage_response)
316        except Exception as exc:  # noqa
317            return self.handle_exception(exc)

Get the next pending challenge from the currently active flow.

@extend_schema(responses={200: PolymorphicProxySerializer(component_name='ChallengeTypes', serializers=challenge_types, resource_type_field_name='component')}, request=PolymorphicProxySerializer(component_name='FlowChallengeResponse', serializers=challenge_response_types, resource_type_field_name='component'), parameters=[OpenApiParameter(name='query', location=OpenApiParameter.QUERY, required=True, description='Querystring as received', type=OpenApiTypes.STR)], operation_id='flows_executor_solve')
def post( self, request: django.http.request.HttpRequest, *args, **kwargs) -> django.http.response.HttpResponse:
319    @extend_schema(
320        responses={
321            200: PolymorphicProxySerializer(
322                component_name="ChallengeTypes",
323                serializers=challenge_types,
324                resource_type_field_name="component",
325            ),
326        },
327        request=PolymorphicProxySerializer(
328            component_name="FlowChallengeResponse",
329            serializers=challenge_response_types,
330            resource_type_field_name="component",
331        ),
332        parameters=[
333            OpenApiParameter(
334                name="query",
335                location=OpenApiParameter.QUERY,
336                required=True,
337                description="Querystring as received",
338                type=OpenApiTypes.STR,
339            )
340        ],
341        operation_id="flows_executor_solve",
342    )
343    def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
344        """Solve the previously retrieved challenge and advanced to the next stage."""
345        class_path = class_to_path(self.current_stage_view.__class__)
346        self._logger.debug(
347            "f(exec): Passing POST",
348            view_class=class_path,
349            stage=self.current_stage,
350        )
351        try:
352            with (
353                active_tracer().start_span(
354                    op="authentik.flow.executor.stage",
355                    name=class_path,
356                ) as span,
357                HIST_FLOW_EXECUTION_STAGE_TIME.labels(
358                    method=request.method.upper(),
359                    stage_type=class_path,
360                ).time(),
361            ):
362                span.set_data("Method", request.method.upper())
363                span.set_data("authentik Stage", self.current_stage_view)
364                span.set_data("authentik Flow", self.flow.slug)
365                stage_response = self.current_stage_view.dispatch(request)
366                return to_stage_response(request, stage_response)
367        except Exception as exc:  # noqa
368            return self.handle_exception(exc)

Solve the previously retrieved challenge and advanced to the next stage.

def restart_flow(self, keep_context=False) -> django.http.response.HttpResponse:
385    def restart_flow(self, keep_context=False) -> HttpResponse:
386        """Restart the currently active flow, optionally keeping the current context"""
387        planner = FlowPlanner(self.flow)
388        planner.use_cache = False
389        default_context = None
390        if keep_context:
391            default_context = self.plan.context
392        try:
393            plan = planner.plan(self.request, default_context)
394        except FlowNonApplicableException as exc:
395            self._logger.warning("f(exec): Flow restart not applicable to current user", exc=exc)
396            return self.handle_invalid_flow(exc)
397        self.request.session[SESSION_KEY_PLAN] = plan
398        kwargs = self.kwargs
399        kwargs.update({"flow_slug": self.flow.slug})
400        return redirect_with_qs("authentik_api:flow-executor", self.request.GET, **kwargs)

Restart the currently active flow, optionally keeping the current context

def stage_ok(self) -> django.http.response.HttpResponse:
435    def stage_ok(self) -> HttpResponse:
436        """Callback called by stages upon successful completion.
437        Persists updated plan and context to session."""
438        self._logger.debug(
439            "f(exec): Stage ok",
440            stage_class=class_to_path(self.current_stage_view.__class__),
441        )
442        if isinstance(self.current_stage_view, StageView):
443            self.current_stage_view.cleanup()
444        if self.direct_execution:
445            # The stage's own response is returned directly. The plan was never stored in the
446            # session, and the session may hold the plan of a flow running in another tab.
447            self.plan.pop()
448            return HttpResponse()
449        if self.flow.inspector_accessible(self.request):
450            self.request.session.get(SESSION_KEY_HISTORY, []).append(deepcopy(self.plan))
451        self.plan.pop()
452        self.request.session[SESSION_KEY_PLAN] = self.plan
453        if self.plan.bindings:
454            self._logger.debug(
455                "f(exec): Continuing with next stage",
456                remaining=len(self.plan.bindings),
457            )
458            kwargs = self.kwargs
459            kwargs.update({"flow_slug": self.flow.slug})
460            return redirect_with_qs("authentik_api:flow-executor", self.request.GET, **kwargs)
461        # User passed all stages
462        self._logger.debug(
463            "f(exec): User passed all stages",
464            context=cleanse_dict(self.plan.context),
465        )
466        return self._flow_done()

Callback called by stages upon successful completion. Persists updated plan and context to session.

def stage_invalid( self, error_message: str | None = None) -> django.http.response.HttpResponse:
468    def stage_invalid(self, error_message: str | None = None) -> HttpResponse:
469        """Callback used stage when data is correct but a policy denies access
470        or the user account is disabled.
471
472        Optionally, an exception can be passed, which will be shown if the current user
473        is a superuser."""
474        self._logger.debug("f(exec): Stage invalid")
475        if self.current_binding and self.current_binding.invalid_response_action in [
476            InvalidResponseAction.RESTART,
477            InvalidResponseAction.RESTART_WITH_CONTEXT,
478        ]:
479            keep_context = (
480                self.current_binding.invalid_response_action
481                == InvalidResponseAction.RESTART_WITH_CONTEXT
482            )
483            self._logger.debug(
484                "f(exec): Invalid response, restarting flow",
485                keep_context=keep_context,
486            )
487            return self.restart_flow(keep_context)
488        challenge_view = AccessDeniedStage(self, error_message)
489        challenge_view.request = self.request
490        # Render the challenge first, because cancel() clears the stored query that its
491        # cancel URL reads `next` from
492        response = challenge_view.get(self.request)
493        self.cancel()
494        return to_stage_response(self.request, response)

Callback used stage when data is correct but a policy denies access or the user account is disabled.

Optionally, an exception can be passed, which will be shown if the current user is a superuser.

def cancel(self):
496    def cancel(self):
497        """Cancel current flow execution"""
498        if self.direct_execution:
499            # Direct execution keeps its plan local to the request, so there is no session
500            # state to clean up, and the session may belong to a flow running in another tab.
501            return
502        keys_to_delete = [
503            SESSION_KEY_PLAN,
504            SESSION_KEY_GET,
505            # We might need the initial POST payloads for later requests
506            # SESSION_KEY_POST,
507            # We don't delete the history on purpose, as a user might
508            # still be inspecting it.
509            # It's only deleted on a fresh executions
510            # SESSION_KEY_HISTORY,
511        ]
512        self._logger.debug("f(exec): cleaning up")
513        for key in keys_to_delete:
514            if key in self.request.session:
515                del self.request.session[key]

Cancel current flow execution

class CancelView(django.views.generic.base.View):
518class CancelView(View):
519    """View which cancels the currently active plan"""
520
521    def clean_next_url(self, url: str) -> str:
522        """Remove any user identifiers from the URL to prevent loops"""
523        qs_to_remove = [QS_LOGIN_HINT]
524        parts = urlsplit(url)
525        if not any(x in parts.query for x in qs_to_remove):
526            return url
527        query = QueryDict(parts.query, mutable=True)
528        for qs in qs_to_remove:
529            query.pop(qs, None)
530        return urlunsplit(parts._replace(query=urlencode(sorted(query.items()), doseq=True)))
531
532    def get(self, request: HttpRequest) -> HttpResponse:
533        """View which canels the currently active plan"""
534        if SESSION_KEY_PLAN in request.session:
535            del request.session[SESSION_KEY_PLAN]
536            LOGGER.debug("Canceled current plan")
537        next_url = self.request.GET.get(NEXT_ARG_NAME)
538        if next_url and not is_url_absolute(next_url):
539            # Ensure that we get rid of any user identifiers from the URL
540            return redirect(self.clean_next_url(next_url))
541        return redirect("authentik_flows:default-invalidation")

View which cancels the currently active plan

def clean_next_url(self, url: str) -> str:
521    def clean_next_url(self, url: str) -> str:
522        """Remove any user identifiers from the URL to prevent loops"""
523        qs_to_remove = [QS_LOGIN_HINT]
524        parts = urlsplit(url)
525        if not any(x in parts.query for x in qs_to_remove):
526            return url
527        query = QueryDict(parts.query, mutable=True)
528        for qs in qs_to_remove:
529            query.pop(qs, None)
530        return urlunsplit(parts._replace(query=urlencode(sorted(query.items()), doseq=True)))

Remove any user identifiers from the URL to prevent loops

def get( self, request: django.http.request.HttpRequest) -> django.http.response.HttpResponse:
532    def get(self, request: HttpRequest) -> HttpResponse:
533        """View which canels the currently active plan"""
534        if SESSION_KEY_PLAN in request.session:
535            del request.session[SESSION_KEY_PLAN]
536            LOGGER.debug("Canceled current plan")
537        next_url = self.request.GET.get(NEXT_ARG_NAME)
538        if next_url and not is_url_absolute(next_url):
539            # Ensure that we get rid of any user identifiers from the URL
540            return redirect(self.clean_next_url(next_url))
541        return redirect("authentik_flows:default-invalidation")

View which canels the currently active plan

class ToDefaultFlow(django.views.generic.base.View):
544class ToDefaultFlow(View):
545    """Redirect to default flow matching by designation"""
546
547    designation: FlowDesignation | None = None
548
549    @staticmethod
550    def flow_by_policy(request: HttpRequest, **flow_filter) -> Flow | None:
551        """Get a Flow by `**flow_filter` and check if the request from `request` can access it."""
552        flows = Flow.objects.filter(**flow_filter).order_by("slug")
553        for flow in flows:
554            engine = PolicyEngine(flow, request.user, request)
555            engine.build()
556            result = engine.result
557            if result.passing:
558                LOGGER.debug("flow_by_policy: flow passing", flow=flow)
559                return flow
560            LOGGER.warning("flow_by_policy: flow not passing", flow=flow, messages=result.messages)
561        LOGGER.debug("flow_by_policy: no flow found", filters=flow_filter)
562        return None
563
564    @staticmethod
565    def get_flow(request: HttpRequest, designation: FlowDesignation) -> Flow:
566        """Get a flow for the selected designation"""
567        brand: Brand = request.brand
568        flow = None
569        # First, attempt to get default flow from brand
570        if designation == FlowDesignation.AUTHENTICATION:
571            flow = brand.flow_authentication
572        elif designation == FlowDesignation.INVALIDATION:
573            flow = brand.flow_invalidation
574        if flow:
575            return flow
576        # If no flow was set, get the first based on slug and policy
577        flow = ToDefaultFlow.flow_by_policy(request, designation=designation)
578        if flow:
579            return flow
580        # If we still don't have a flow, 404
581        raise Http404
582
583    def dispatch(self, request: HttpRequest) -> HttpResponse:
584        flow = ToDefaultFlow.get_flow(request, self.designation)
585        # If user already has a pending plan, clear it so we don't have to later.
586        if SESSION_KEY_PLAN in self.request.session:
587            plan: FlowPlan = self.request.session[SESSION_KEY_PLAN]
588            if plan.flow_pk != flow.pk.hex:
589                LOGGER.warning(
590                    "f(def): Found existing plan for other flow, deleting plan",
591                    flow_slug=flow.slug,
592                )
593                del self.request.session[SESSION_KEY_PLAN]
594        return redirect_with_qs("authentik_core:if-flow", request.GET, flow_slug=flow.slug)

Redirect to default flow matching by designation

designation: authentik.flows.models.FlowDesignation | None = None
@staticmethod
def flow_by_policy( request: django.http.request.HttpRequest, **flow_filter) -> authentik.flows.models.Flow | None:
549    @staticmethod
550    def flow_by_policy(request: HttpRequest, **flow_filter) -> Flow | None:
551        """Get a Flow by `**flow_filter` and check if the request from `request` can access it."""
552        flows = Flow.objects.filter(**flow_filter).order_by("slug")
553        for flow in flows:
554            engine = PolicyEngine(flow, request.user, request)
555            engine.build()
556            result = engine.result
557            if result.passing:
558                LOGGER.debug("flow_by_policy: flow passing", flow=flow)
559                return flow
560            LOGGER.warning("flow_by_policy: flow not passing", flow=flow, messages=result.messages)
561        LOGGER.debug("flow_by_policy: no flow found", filters=flow_filter)
562        return None

Get a Flow by **flow_filter and check if the request from request can access it.

@staticmethod
def get_flow( request: django.http.request.HttpRequest, designation: authentik.flows.models.FlowDesignation) -> authentik.flows.models.Flow:
564    @staticmethod
565    def get_flow(request: HttpRequest, designation: FlowDesignation) -> Flow:
566        """Get a flow for the selected designation"""
567        brand: Brand = request.brand
568        flow = None
569        # First, attempt to get default flow from brand
570        if designation == FlowDesignation.AUTHENTICATION:
571            flow = brand.flow_authentication
572        elif designation == FlowDesignation.INVALIDATION:
573            flow = brand.flow_invalidation
574        if flow:
575            return flow
576        # If no flow was set, get the first based on slug and policy
577        flow = ToDefaultFlow.flow_by_policy(request, designation=designation)
578        if flow:
579            return flow
580        # If we still don't have a flow, 404
581        raise Http404

Get a flow for the selected designation

def dispatch( self, request: django.http.request.HttpRequest) -> django.http.response.HttpResponse:
583    def dispatch(self, request: HttpRequest) -> HttpResponse:
584        flow = ToDefaultFlow.get_flow(request, self.designation)
585        # If user already has a pending plan, clear it so we don't have to later.
586        if SESSION_KEY_PLAN in self.request.session:
587            plan: FlowPlan = self.request.session[SESSION_KEY_PLAN]
588            if plan.flow_pk != flow.pk.hex:
589                LOGGER.warning(
590                    "f(def): Found existing plan for other flow, deleting plan",
591                    flow_slug=flow.slug,
592                )
593                del self.request.session[SESSION_KEY_PLAN]
594        return redirect_with_qs("authentik_core:if-flow", request.GET, flow_slug=flow.slug)
def to_stage_response( request: django.http.request.HttpRequest, source: django.http.response.HttpResponse, final_redirect: bool = False, continuous_login_hold: bool | None = None) -> django.http.response.HttpResponse:
597def to_stage_response(
598    request: HttpRequest,
599    source: HttpResponse,
600    final_redirect: bool = False,
601    continuous_login_hold: bool | None = None,
602) -> HttpResponse:
603    """Convert normal HttpResponse into JSON Response"""
604    if (
605        isinstance(source, HttpResponseRedirect)
606        or source.status_code == HttpResponseRedirect.status_code
607    ):
608        redirect_url = source["Location"]
609        # Redirects to the same URL usually indicate an Error within a form
610        if request.get_full_path() == redirect_url:
611            return source
612        LOGGER.debug(
613            "converting to redirect challenge",
614            to=str(redirect_url),
615            current=request.path,
616        )
617        challenge_data = {
618            "to": str(redirect_url),
619            "final_redirect": final_redirect,
620        }
621        if continuous_login_hold is not None:
622            challenge_data["continuous_login_hold"] = continuous_login_hold
623        return HttpChallengeResponse(RedirectChallenge(challenge_data))
624    if isinstance(source, TemplateResponse):
625        return HttpChallengeResponse(
626            ShellChallenge(
627                {
628                    "body": source.render().content.decode("utf-8"),
629                }
630            )
631        )
632    # Check for actual HttpResponse (without isinstance as we don't want to check inheritance)
633    if source.__class__ == HttpResponse:
634        return HttpChallengeResponse(
635            ShellChallenge(
636                {
637                    "body": source.content.decode("utf-8"),
638                }
639            )
640        )
641    return source

Convert normal HttpResponse into JSON Response

class ConfigureFlowInitView(django.contrib.auth.mixins.LoginRequiredMixin, django.views.generic.base.View):
644class ConfigureFlowInitView(LoginRequiredMixin, View):
645    """Initiate planner for selected change flow and redirect to flow executor,
646    or raise Http404 if no configure_flow has been set."""
647
648    def get(self, request: HttpRequest, stage_uuid: str) -> HttpResponse:
649        """Initiate planner for selected change flow and redirect to flow executor,
650        or raise Http404 if no configure_flow has been set."""
651        try:
652            stage: Stage = Stage.objects.get_subclass(pk=stage_uuid)
653        except Stage.DoesNotExist as exc:
654            raise Http404 from exc
655        if not isinstance(stage, ConfigurableStage):
656            LOGGER.debug("Stage does not inherit ConfigurableStage", stage=stage)
657            raise Http404
658        if not stage.configure_flow:
659            LOGGER.debug("Stage has no configure_flow set", stage=stage)
660            raise Http404
661
662        try:
663            plan = FlowPlanner(stage.configure_flow).plan(
664                request, {PLAN_CONTEXT_PENDING_USER: request.user}
665            )
666        except FlowNonApplicableException:
667            LOGGER.warning("Flow not applicable to user")
668            raise Http404 from None
669        return plan.to_redirect(request, stage.configure_flow)

Initiate planner for selected change flow and redirect to flow executor, or raise Http404 if no configure_flow has been set.

def get( self, request: django.http.request.HttpRequest, stage_uuid: str) -> django.http.response.HttpResponse:
648    def get(self, request: HttpRequest, stage_uuid: str) -> HttpResponse:
649        """Initiate planner for selected change flow and redirect to flow executor,
650        or raise Http404 if no configure_flow has been set."""
651        try:
652            stage: Stage = Stage.objects.get_subclass(pk=stage_uuid)
653        except Stage.DoesNotExist as exc:
654            raise Http404 from exc
655        if not isinstance(stage, ConfigurableStage):
656            LOGGER.debug("Stage does not inherit ConfigurableStage", stage=stage)
657            raise Http404
658        if not stage.configure_flow:
659            LOGGER.debug("Stage has no configure_flow set", stage=stage)
660            raise Http404
661
662        try:
663            plan = FlowPlanner(stage.configure_flow).plan(
664                request, {PLAN_CONTEXT_PENDING_USER: request.user}
665            )
666        except FlowNonApplicableException:
667            LOGGER.warning("Flow not applicable to user")
668            raise Http404 from None
669        return plan.to_redirect(request, stage.configure_flow)

Initiate planner for selected change flow and redirect to flow executor, or raise Http404 if no configure_flow has been set.